(savehist-mode): Don't bother with `custom-set-minor-mode.
[emacs.git] / src / macterm.c
blob5ac3255daca8ddd1c5c62353208ca6338c327674
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"
92 /* Non-nil means Emacs uses toolkit scroll bars. */
94 Lisp_Object Vx_toolkit_scroll_bars;
96 /* If Non-nil, the text will be rendered using Core Graphics text rendering which may anti-alias the text. */
97 Lisp_Object Vmac_use_core_graphics;
100 /* Non-zero means that a HELP_EVENT has been generated since Emacs
101 start. */
103 static int any_help_event_p;
105 /* Last window where we saw the mouse. Used by mouse-autoselect-window. */
106 static Lisp_Object last_window;
108 /* This is a chain of structures for all the X displays currently in
109 use. */
111 struct x_display_info *x_display_list;
113 /* This is a list of cons cells, each of the form (NAME
114 FONT-LIST-CACHE . RESOURCE-DATABASE), one for each element of
115 x_display_list and in the same order. NAME is the name of the
116 frame. FONT-LIST-CACHE records previous values returned by
117 x-list-fonts. RESOURCE-DATABASE preserves the X Resource Database
118 equivalent, which is implemented with a Lisp object, for the
119 display. */
121 Lisp_Object x_display_name_list;
123 /* This is display since Mac does not support multiple ones. */
124 struct mac_display_info one_mac_display_info;
126 /* Frame being updated by update_frame. This is declared in term.c.
127 This is set by update_begin and looked at by all the XT functions.
128 It is zero while not inside an update. In that case, the XT
129 functions assume that `selected_frame' is the frame to apply to. */
131 extern struct frame *updating_frame;
133 /* This is a frame waiting to be auto-raised, within XTread_socket. */
135 struct frame *pending_autoraise_frame;
137 /* Mouse movement.
139 Formerly, we used PointerMotionHintMask (in standard_event_mask)
140 so that we would have to call XQueryPointer after each MotionNotify
141 event to ask for another such event. However, this made mouse tracking
142 slow, and there was a bug that made it eventually stop.
144 Simply asking for MotionNotify all the time seems to work better.
146 In order to avoid asking for motion events and then throwing most
147 of them away or busy-polling the server for mouse positions, we ask
148 the server for pointer motion hints. This means that we get only
149 one event per group of mouse movements. "Groups" are delimited by
150 other kinds of events (focus changes and button clicks, for
151 example), or by XQueryPointer calls; when one of these happens, we
152 get another MotionNotify event the next time the mouse moves. This
153 is at least as efficient as getting motion events when mouse
154 tracking is on, and I suspect only negligibly worse when tracking
155 is off. */
157 /* Where the mouse was last time we reported a mouse event. */
159 static Rect last_mouse_glyph;
160 static FRAME_PTR last_mouse_glyph_frame;
162 /* The scroll bar in which the last X motion event occurred.
164 If the last X motion event occurred in a scroll bar, we set this so
165 XTmouse_position can know whether to report a scroll bar motion or
166 an ordinary motion.
168 If the last X motion event didn't occur in a scroll bar, we set
169 this to Qnil, to tell XTmouse_position to return an ordinary motion
170 event. */
172 static Lisp_Object last_mouse_scroll_bar;
174 /* This is a hack. We would really prefer that XTmouse_position would
175 return the time associated with the position it returns, but there
176 doesn't seem to be any way to wrest the time-stamp from the server
177 along with the position query. So, we just keep track of the time
178 of the last movement we received, and return that in hopes that
179 it's somewhat accurate. */
181 static Time last_mouse_movement_time;
183 struct scroll_bar *tracked_scroll_bar = NULL;
185 /* Incremented by XTread_socket whenever it really tries to read
186 events. */
188 #ifdef __STDC__
189 static int volatile input_signal_count;
190 #else
191 static int input_signal_count;
192 #endif
194 extern Lisp_Object Vsystem_name;
196 /* A mask of extra modifier bits to put into every keyboard char. */
198 extern EMACS_INT extra_keyboard_modifiers;
200 /* The keysyms to use for the various modifiers. */
202 static Lisp_Object Qalt, Qhyper, Qsuper, Qctrl,
203 Qmeta, Qmodifier_value;
205 extern int inhibit_window_system;
207 #if __MRC__ && !TARGET_API_MAC_CARBON
208 QDGlobals qd; /* QuickDraw global information structure. */
209 #endif
211 #define mac_window_to_frame(wp) (((mac_output *) GetWRefCon (wp))->mFP)
213 struct mac_display_info *mac_display_info_for_display (Display *);
214 static void x_update_window_end P_ ((struct window *, int, int));
215 static int x_io_error_quitter P_ ((Display *));
216 int x_catch_errors P_ ((Display *));
217 void x_uncatch_errors P_ ((Display *, int));
218 void x_lower_frame P_ ((struct frame *));
219 void x_scroll_bar_clear P_ ((struct frame *));
220 int x_had_errors_p P_ ((Display *));
221 void x_wm_set_size_hint P_ ((struct frame *, long, int));
222 void x_raise_frame P_ ((struct frame *));
223 void x_set_window_size P_ ((struct frame *, int, int, int));
224 void x_wm_set_window_state P_ ((struct frame *, int));
225 void x_wm_set_icon_pixmap P_ ((struct frame *, int));
226 void mac_initialize P_ ((void));
227 static void x_font_min_bounds P_ ((XFontStruct *, int *, int *));
228 static int x_compute_min_glyph_bounds P_ ((struct frame *));
229 static void x_update_end P_ ((struct frame *));
230 static void XTframe_up_to_date P_ ((struct frame *));
231 static void XTset_terminal_modes P_ ((void));
232 static void XTreset_terminal_modes P_ ((void));
233 static void x_clear_frame P_ ((void));
234 static void frame_highlight P_ ((struct frame *));
235 static void frame_unhighlight P_ ((struct frame *));
236 static void x_new_focus_frame P_ ((struct x_display_info *, struct frame *));
237 static void mac_focus_changed P_ ((int, struct mac_display_info *,
238 struct frame *, struct input_event *));
239 static void x_detect_focus_change P_ ((struct mac_display_info *,
240 EventRecord *, struct input_event *));
241 static void XTframe_rehighlight P_ ((struct frame *));
242 static void x_frame_rehighlight P_ ((struct x_display_info *));
243 static void x_draw_hollow_cursor P_ ((struct window *, struct glyph_row *));
244 static void x_draw_bar_cursor P_ ((struct window *, struct glyph_row *, int,
245 enum text_cursor_kinds));
247 static void x_clip_to_row P_ ((struct window *, struct glyph_row *, int, GC));
248 static void x_flush P_ ((struct frame *f));
249 static void x_update_begin P_ ((struct frame *));
250 static void x_update_window_begin P_ ((struct window *));
251 static void x_after_update_window_line P_ ((struct glyph_row *));
252 static void x_scroll_bar_report_motion P_ ((struct frame **, Lisp_Object *,
253 enum scroll_bar_part *,
254 Lisp_Object *, Lisp_Object *,
255 unsigned long *));
257 static int is_emacs_window P_ ((WindowPtr));
259 static void XSetFont P_ ((Display *, GC, XFontStruct *));
261 /* Defined in macmenu.h. */
262 extern void menubar_selection_callback (FRAME_PTR, int);
264 #define GC_FORE_COLOR(gc) (&(gc)->fore_color)
265 #define GC_BACK_COLOR(gc) (&(gc)->back_color)
266 #define GC_FONT(gc) ((gc)->xgcv.font)
267 #define GC_CLIP_REGION(gc) ((gc)->clip_region)
268 #define FRAME_NORMAL_GC(f) ((f)->output_data.mac->normal_gc)
270 static RgnHandle saved_port_clip_region = NULL;
272 static void
273 mac_begin_clip (region)
274 RgnHandle region;
276 static RgnHandle new_region = NULL;
278 if (saved_port_clip_region == NULL)
279 saved_port_clip_region = NewRgn ();
280 if (new_region == NULL)
281 new_region = NewRgn ();
283 if (region)
285 GetClip (saved_port_clip_region);
286 SectRgn (saved_port_clip_region, region, new_region);
287 SetClip (new_region);
291 static void
292 mac_end_clip (region)
293 RgnHandle region;
295 if (region)
296 SetClip (saved_port_clip_region);
300 /* X display function emulation */
302 void
303 XFreePixmap (display, pixmap)
304 Display *display; /* not used */
305 Pixmap pixmap;
307 DisposeGWorld (pixmap);
311 /* Mac version of XDrawLine. */
313 static void
314 mac_draw_line (f, gc, x1, y1, x2, y2)
315 struct frame *f;
316 GC gc;
317 int x1, y1, x2, y2;
319 SetPortWindowPort (FRAME_MAC_WINDOW (f));
321 RGBForeColor (GC_FORE_COLOR (gc));
323 mac_begin_clip (GC_CLIP_REGION (gc));
324 MoveTo (x1, y1);
325 LineTo (x2, y2);
326 mac_end_clip (GC_CLIP_REGION (gc));
329 void
330 mac_draw_line_to_pixmap (display, p, gc, x1, y1, x2, y2)
331 Display *display;
332 Pixmap p;
333 GC gc;
334 int x1, y1, x2, y2;
336 CGrafPtr old_port;
337 GDHandle old_gdh;
339 GetGWorld (&old_port, &old_gdh);
340 SetGWorld (p, NULL);
342 RGBForeColor (GC_FORE_COLOR (gc));
344 LockPixels (GetGWorldPixMap (p));
345 MoveTo (x1, y1);
346 LineTo (x2, y2);
347 UnlockPixels (GetGWorldPixMap (p));
349 SetGWorld (old_port, old_gdh);
353 static void
354 mac_erase_rectangle (f, gc, x, y, width, height)
355 struct frame *f;
356 GC gc;
357 int x, y;
358 unsigned int width, height;
360 Rect r;
362 SetPortWindowPort (FRAME_MAC_WINDOW (f));
364 RGBBackColor (GC_BACK_COLOR (gc));
365 SetRect (&r, x, y, x + width, y + height);
367 mac_begin_clip (GC_CLIP_REGION (gc));
368 EraseRect (&r);
369 mac_end_clip (GC_CLIP_REGION (gc));
371 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
375 /* Mac version of XClearArea. */
377 void
378 mac_clear_area (f, x, y, width, height)
379 struct frame *f;
380 int x, y;
381 unsigned int width, height;
383 mac_erase_rectangle (f, FRAME_NORMAL_GC (f), x, y, width, height);
386 /* Mac version of XClearWindow. */
388 static void
389 mac_clear_window (f)
390 struct frame *f;
392 SetPortWindowPort (FRAME_MAC_WINDOW (f));
394 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
396 #if TARGET_API_MAC_CARBON
398 Rect r;
400 GetWindowPortBounds (FRAME_MAC_WINDOW (f), &r);
401 EraseRect (&r);
403 #else /* not TARGET_API_MAC_CARBON */
404 EraseRect (&(FRAME_MAC_WINDOW (f)->portRect));
405 #endif /* not TARGET_API_MAC_CARBON */
409 /* Mac replacement for XCopyArea. */
411 static void
412 mac_draw_bitmap (f, gc, x, y, width, height, bits, overlay_p)
413 struct frame *f;
414 GC gc;
415 int x, y, width, height;
416 unsigned short *bits;
417 int overlay_p;
419 BitMap bitmap;
420 Rect r;
422 bitmap.rowBytes = sizeof(unsigned short);
423 bitmap.baseAddr = (char *)bits;
424 SetRect (&(bitmap.bounds), 0, 0, width, height);
426 SetPortWindowPort (FRAME_MAC_WINDOW (f));
428 RGBForeColor (GC_FORE_COLOR (gc));
429 RGBBackColor (GC_BACK_COLOR (gc));
430 SetRect (&r, x, y, x + width, y + height);
432 mac_begin_clip (GC_CLIP_REGION (gc));
433 #if TARGET_API_MAC_CARBON
435 CGrafPtr port;
437 GetPort (&port);
438 LockPortBits (port);
439 CopyBits (&bitmap, GetPortBitMapForCopyBits (port),
440 &(bitmap.bounds), &r, overlay_p ? srcOr : srcCopy, 0);
441 UnlockPortBits (port);
443 #else /* not TARGET_API_MAC_CARBON */
444 CopyBits (&bitmap, &(FRAME_MAC_WINDOW (f)->portBits), &(bitmap.bounds), &r,
445 overlay_p ? srcOr : srcCopy, 0);
446 #endif /* not TARGET_API_MAC_CARBON */
447 mac_end_clip (GC_CLIP_REGION (gc));
449 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
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 mac_fill_rectangle (f, gc, x, y, width, height)
567 struct frame *f;
568 GC gc;
569 int x, y;
570 unsigned int width, height;
572 Rect r;
574 SetPortWindowPort (FRAME_MAC_WINDOW (f));
576 RGBForeColor (GC_FORE_COLOR (gc));
577 SetRect (&r, x, y, x + width, y + height);
579 mac_begin_clip (GC_CLIP_REGION (gc));
580 PaintRect (&r); /* using foreground color of gc */
581 mac_end_clip (GC_CLIP_REGION (gc));
585 /* Mac replacement for XDrawRectangle: dest is a window. */
587 static void
588 mac_draw_rectangle (f, gc, x, y, width, height)
589 struct frame *f;
590 GC gc;
591 int x, y;
592 unsigned int width, height;
594 Rect r;
596 SetPortWindowPort (FRAME_MAC_WINDOW (f));
598 RGBForeColor (GC_FORE_COLOR (gc));
599 SetRect (&r, x, y, x + width + 1, y + height + 1);
601 mac_begin_clip (GC_CLIP_REGION (gc));
602 FrameRect (&r); /* using foreground color of gc */
603 mac_end_clip (GC_CLIP_REGION (gc));
607 #if USE_ATSUI
608 static OSStatus
609 atsu_get_text_layout_with_text_ptr (text, text_length, style, text_layout)
610 ConstUniCharArrayPtr text;
611 UniCharCount text_length;
612 ATSUStyle style;
613 ATSUTextLayout *text_layout;
615 OSStatus err;
616 static ATSUTextLayout saved_text_layout = NULL; /* not reentrant */
618 if (saved_text_layout == NULL)
620 UniCharCount lengths[] = {kATSUToTextEnd};
621 ATSUAttributeTag tags[] = {kATSULineLayoutOptionsTag};
622 ByteCount sizes[] = {sizeof (ATSLineLayoutOptions)};
623 static ATSLineLayoutOptions line_layout =
624 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
625 kATSLineDisableAllLayoutOperations | kATSLineUseDeviceMetrics
626 #else
627 kATSLineIsDisplayOnly | kATSLineFractDisable
628 #endif
630 ATSUAttributeValuePtr values[] = {&line_layout};
632 err = ATSUCreateTextLayoutWithTextPtr (text,
633 kATSUFromTextBeginning,
634 kATSUToTextEnd,
635 text_length,
636 1, lengths, &style,
637 &saved_text_layout);
638 if (err == noErr)
639 err = ATSUSetLayoutControls (saved_text_layout,
640 sizeof (tags) / sizeof (tags[0]),
641 tags, sizes, values);
642 /* XXX: Should we do this? */
643 if (err == noErr)
644 err = ATSUSetTransientFontMatching (saved_text_layout, true);
646 else
648 err = ATSUSetRunStyle (saved_text_layout, style,
649 kATSUFromTextBeginning, kATSUToTextEnd);
650 if (err == noErr)
651 err = ATSUSetTextPointerLocation (saved_text_layout, text,
652 kATSUFromTextBeginning,
653 kATSUToTextEnd,
654 text_length);
657 if (err == noErr)
658 *text_layout = saved_text_layout;
659 return err;
661 #endif
664 static void
665 mac_invert_rectangle (f, x, y, width, height)
666 struct frame *f;
667 int x, y;
668 unsigned int width, height;
670 Rect r;
672 SetPortWindowPort (FRAME_MAC_WINDOW (f));
674 SetRect (&r, x, y, x + width, y + height);
676 InvertRect (&r);
680 static void
681 mac_draw_string_common (f, gc, x, y, buf, nchars, mode, bytes_per_char)
682 struct frame *f;
683 GC gc;
684 int x, y;
685 char *buf;
686 int nchars, mode, bytes_per_char;
688 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
689 UInt32 textFlags, savedFlags;
690 if (!NILP(Vmac_use_core_graphics)) {
691 textFlags = kQDUseCGTextRendering;
692 savedFlags = SwapQDTextFlags(textFlags);
694 #endif
696 SetPortWindowPort (FRAME_MAC_WINDOW (f));
698 RGBForeColor (GC_FORE_COLOR (gc));
699 if (mode != srcOr)
700 RGBBackColor (GC_BACK_COLOR (gc));
702 #if USE_ATSUI
703 if (GC_FONT (gc)->mac_style)
705 OSErr err;
706 ATSUTextLayout text_layout;
708 xassert (bytes_per_char == 2);
710 #ifndef WORDS_BIG_ENDIAN
712 int i;
713 UniChar *text = (UniChar *)buf;
715 for (i = 0; i < nchars; i++)
716 text[i] = EndianU16_BtoN (text[i]);
718 #endif
719 err = atsu_get_text_layout_with_text_ptr ((ConstUniCharArrayPtr)buf,
720 nchars,
721 GC_FONT (gc)->mac_style,
722 &text_layout);
723 if (err == noErr)
725 #ifdef MAC_OSX
726 if (NILP (Vmac_use_core_graphics))
728 #endif
729 mac_begin_clip (GC_CLIP_REGION (gc));
730 MoveTo (x, y);
731 ATSUDrawText (text_layout,
732 kATSUFromTextBeginning, kATSUToTextEnd,
733 kATSUUseGrafPortPenLoc, kATSUUseGrafPortPenLoc);
734 mac_end_clip (GC_CLIP_REGION (gc));
735 #ifdef MAC_OSX
737 else
739 CGrafPtr port;
740 CGContextRef context;
741 float port_height = FRAME_PIXEL_HEIGHT (f);
742 ATSUAttributeTag tags[] = {kATSUCGContextTag};
743 ByteCount sizes[] = {sizeof (CGContextRef)};
744 ATSUAttributeValuePtr values[] = {&context};
746 GetPort (&port);
747 QDBeginCGContext (port, &context);
748 if (gc->n_clip_rects)
750 CGContextTranslateCTM (context, 0, port_height);
751 CGContextScaleCTM (context, 1, -1);
752 CGContextClipToRects (context, gc->clip_rects,
753 gc->n_clip_rects);
754 CGContextScaleCTM (context, 1, -1);
755 CGContextTranslateCTM (context, 0, -port_height);
757 CGContextSetRGBFillColor
758 (context,
759 RED_FROM_ULONG (gc->xgcv.foreground) / 255.0,
760 GREEN_FROM_ULONG (gc->xgcv.foreground) / 255.0,
761 BLUE_FROM_ULONG (gc->xgcv.foreground) / 255.0,
762 1.0);
763 err = ATSUSetLayoutControls (text_layout,
764 sizeof (tags) / sizeof (tags[0]),
765 tags, sizes, values);
766 if (err == noErr)
767 ATSUDrawText (text_layout,
768 kATSUFromTextBeginning, kATSUToTextEnd,
769 Long2Fix (x), Long2Fix (port_height - y));
770 CGContextSynchronize (context);
771 QDEndCGContext (port, &context);
772 #if 0
773 /* This doesn't work on Mac OS X 10.1. */
774 ATSUClearLayoutControls (text_layout,
775 sizeof (tags) / sizeof (tags[0]),
776 tags);
777 #else
778 ATSUSetLayoutControls (text_layout,
779 sizeof (tags) / sizeof (tags[0]),
780 tags, sizes, values);
781 #endif
783 #endif
786 else
788 #endif
789 TextFont (GC_FONT (gc)->mac_fontnum);
790 TextSize (GC_FONT (gc)->mac_fontsize);
791 TextFace (GC_FONT (gc)->mac_fontface);
792 TextMode (mode);
794 mac_begin_clip (GC_CLIP_REGION (gc));
795 MoveTo (x, y);
796 DrawText (buf, 0, nchars * bytes_per_char);
797 mac_end_clip (GC_CLIP_REGION (gc));
798 #if USE_ATSUI
800 #endif
802 if (mode != srcOr)
803 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
804 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
805 if (!NILP(Vmac_use_core_graphics))
806 SwapQDTextFlags(savedFlags);
807 #endif
811 /* Mac replacement for XDrawString. */
813 static void
814 mac_draw_string (f, gc, x, y, buf, nchars)
815 struct frame *f;
816 GC gc;
817 int x, y;
818 char *buf;
819 int nchars;
821 mac_draw_string_common (f, gc, x, y, buf, nchars, srcOr, 1);
825 /* Mac replacement for XDrawString16. */
827 static void
828 mac_draw_string_16 (f, gc, x, y, buf, nchars)
829 struct frame *f;
830 GC gc;
831 int x, y;
832 XChar2b *buf;
833 int nchars;
835 mac_draw_string_common (f, gc, x, y, (char *) buf, nchars, srcOr, 2);
839 /* Mac replacement for XDrawImageString. */
841 static void
842 mac_draw_image_string (f, gc, x, y, buf, nchars)
843 struct frame *f;
844 GC gc;
845 int x, y;
846 char *buf;
847 int nchars;
849 mac_draw_string_common (f, gc, x, y, buf, nchars, srcCopy, 1);
853 /* Mac replacement for XDrawString16. */
855 static void
856 mac_draw_image_string_16 (f, gc, x, y, buf, nchars)
857 struct frame *f;
858 GC gc;
859 int x, y;
860 XChar2b *buf;
861 int nchars;
863 mac_draw_string_common (f, gc, x, y, (char *) buf, nchars, srcCopy, 2);
867 #if USE_CG_TEXT_DRAWING
868 static XCharStruct *x_per_char_metric P_ ((XFontStruct *, XChar2b *));
870 static int
871 mac_draw_string_cg (f, gc, x, y, buf, nchars)
872 struct frame *f;
873 GC gc;
874 int x, y;
875 XChar2b *buf;
876 int nchars;
878 CGrafPtr port;
879 float port_height, gx, gy;
880 int i;
881 CGContextRef context;
882 CGGlyph *glyphs;
883 CGSize *advances;
885 if (NILP (Vmac_use_core_graphics) || GC_FONT (gc)->cg_font == NULL)
886 return 0;
888 port = GetWindowPort (FRAME_MAC_WINDOW (f));
889 port_height = FRAME_PIXEL_HEIGHT (f);
890 gx = x;
891 gy = port_height - y;
892 glyphs = (CGGlyph *)buf;
893 advances = xmalloc (sizeof (CGSize) * nchars);
894 for (i = 0; i < nchars; i++)
896 advances[i].width = x_per_char_metric (GC_FONT (gc), buf)->width;
897 advances[i].height = 0;
898 glyphs[i] = GC_FONT (gc)->cg_glyphs[buf->byte2];
899 buf++;
902 QDBeginCGContext (port, &context);
903 if (gc->n_clip_rects)
905 CGContextTranslateCTM (context, 0, port_height);
906 CGContextScaleCTM (context, 1, -1);
907 CGContextClipToRects (context, gc->clip_rects, gc->n_clip_rects);
908 CGContextScaleCTM (context, 1, -1);
909 CGContextTranslateCTM (context, 0, -port_height);
911 CGContextSetRGBFillColor (context,
912 RED_FROM_ULONG (gc->xgcv.foreground) / 255.0,
913 GREEN_FROM_ULONG (gc->xgcv.foreground) / 255.0,
914 BLUE_FROM_ULONG (gc->xgcv.foreground) / 255.0,
915 1.0);
916 CGContextSetFont (context, GC_FONT (gc)->cg_font);
917 CGContextSetFontSize (context, GC_FONT (gc)->mac_fontsize);
918 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1030
919 CGContextSetTextPosition (context, gx, gy);
920 CGContextShowGlyphsWithAdvances (context, glyphs, advances, nchars);
921 #else
922 for (i = 0; i < nchars; i++)
924 CGContextShowGlyphsAtPoint (context, gx, gy, glyphs + i, 1);
925 gx += advances[i].width;
927 #endif
928 CGContextSynchronize (context);
929 QDEndCGContext (port, &context);
931 xfree (advances);
933 return 1;
935 #endif
938 /* Mac replacement for XCopyArea: dest must be window. */
940 static void
941 mac_copy_area (src, f, gc, src_x, src_y, width, height, dest_x, dest_y)
942 Pixmap src;
943 struct frame *f;
944 GC gc;
945 int src_x, src_y;
946 unsigned int width, height;
947 int dest_x, dest_y;
949 Rect src_r, dest_r;
951 SetPortWindowPort (FRAME_MAC_WINDOW (f));
953 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
954 SetRect (&dest_r, dest_x, dest_y, dest_x + width, dest_y + height);
956 ForeColor (blackColor);
957 BackColor (whiteColor);
959 mac_begin_clip (GC_CLIP_REGION (gc));
960 LockPixels (GetGWorldPixMap (src));
961 #if TARGET_API_MAC_CARBON
963 CGrafPtr port;
965 GetPort (&port);
966 LockPortBits (port);
967 CopyBits (GetPortBitMapForCopyBits (src),
968 GetPortBitMapForCopyBits (port),
969 &src_r, &dest_r, srcCopy, 0);
970 UnlockPortBits (port);
972 #else /* not TARGET_API_MAC_CARBON */
973 CopyBits (&(((GrafPtr)src)->portBits), &(FRAME_MAC_WINDOW (f)->portBits),
974 &src_r, &dest_r, srcCopy, 0);
975 #endif /* not TARGET_API_MAC_CARBON */
976 UnlockPixels (GetGWorldPixMap (src));
977 mac_end_clip (GC_CLIP_REGION (gc));
979 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
983 static void
984 mac_copy_area_with_mask (src, mask, f, gc, src_x, src_y,
985 width, height, dest_x, dest_y)
986 Pixmap src, mask;
987 struct frame *f;
988 GC gc;
989 int src_x, src_y;
990 unsigned int width, height;
991 int dest_x, dest_y;
993 Rect src_r, dest_r;
995 SetPortWindowPort (FRAME_MAC_WINDOW (f));
997 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
998 SetRect (&dest_r, dest_x, dest_y, dest_x + width, dest_y + height);
1000 ForeColor (blackColor);
1001 BackColor (whiteColor);
1003 mac_begin_clip (GC_CLIP_REGION (gc));
1004 LockPixels (GetGWorldPixMap (src));
1005 LockPixels (GetGWorldPixMap (mask));
1006 #if TARGET_API_MAC_CARBON
1008 CGrafPtr port;
1010 GetPort (&port);
1011 LockPortBits (port);
1012 CopyMask (GetPortBitMapForCopyBits (src), GetPortBitMapForCopyBits (mask),
1013 GetPortBitMapForCopyBits (port),
1014 &src_r, &src_r, &dest_r);
1015 UnlockPortBits (port);
1017 #else /* not TARGET_API_MAC_CARBON */
1018 CopyMask (&(((GrafPtr)src)->portBits), &(((GrafPtr)mask)->portBits),
1019 &(FRAME_MAC_WINDOW (f)->portBits), &src_r, &src_r, &dest_r);
1020 #endif /* not TARGET_API_MAC_CARBON */
1021 UnlockPixels (GetGWorldPixMap (mask));
1022 UnlockPixels (GetGWorldPixMap (src));
1023 mac_end_clip (GC_CLIP_REGION (gc));
1025 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
1029 /* Mac replacement for XCopyArea: used only for scrolling. */
1031 static void
1032 mac_scroll_area (f, gc, src_x, src_y, width, height, dest_x, dest_y)
1033 struct frame *f;
1034 GC gc;
1035 int src_x, src_y;
1036 unsigned int width, height;
1037 int dest_x, dest_y;
1039 #if TARGET_API_MAC_CARBON
1040 Rect src_r;
1041 RgnHandle dummy = NewRgn (); /* For avoiding update events. */
1043 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
1044 ScrollWindowRect (FRAME_MAC_WINDOW (f),
1045 &src_r, dest_x - src_x, dest_y - src_y,
1046 kScrollWindowNoOptions, dummy);
1047 DisposeRgn (dummy);
1048 #else /* not TARGET_API_MAC_CARBON */
1049 Rect src_r, dest_r;
1050 WindowPtr w = FRAME_MAC_WINDOW (f);
1052 SetPort (w);
1054 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
1055 SetRect (&dest_r, dest_x, dest_y, dest_x + width, dest_y + height);
1057 /* In Color QuickDraw, set ForeColor and BackColor as follows to avoid
1058 color mapping in CopyBits. Otherwise, it will be slow. */
1059 ForeColor (blackColor);
1060 BackColor (whiteColor);
1061 mac_begin_clip (GC_CLIP_REGION (gc));
1062 CopyBits (&(w->portBits), &(w->portBits), &src_r, &dest_r, srcCopy, 0);
1063 mac_end_clip (GC_CLIP_REGION (gc));
1065 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
1066 #endif /* not TARGET_API_MAC_CARBON */
1070 /* Mac replacement for XChangeGC. */
1072 static void
1073 XChangeGC (display, gc, mask, xgcv)
1074 Display *display;
1075 GC gc;
1076 unsigned long mask;
1077 XGCValues *xgcv;
1079 if (mask & GCForeground)
1080 XSetForeground (display, gc, xgcv->foreground);
1081 if (mask & GCBackground)
1082 XSetBackground (display, gc, xgcv->background);
1083 if (mask & GCFont)
1084 XSetFont (display, gc, xgcv->font);
1088 /* Mac replacement for XCreateGC. */
1091 XCreateGC (display, window, mask, xgcv)
1092 Display *display;
1093 Window window;
1094 unsigned long mask;
1095 XGCValues *xgcv;
1097 GC gc = xmalloc (sizeof (*gc));
1099 if (gc)
1101 bzero (gc, sizeof (*gc));
1102 XChangeGC (display, gc, mask, xgcv);
1105 return gc;
1109 /* Used in xfaces.c. */
1111 void
1112 XFreeGC (display, gc)
1113 Display *display;
1114 GC gc;
1116 if (gc->clip_region)
1117 DisposeRgn (gc->clip_region);
1118 xfree (gc);
1122 /* Mac replacement for XGetGCValues. */
1124 static void
1125 XGetGCValues (display, gc, mask, xgcv)
1126 Display *display;
1127 GC gc;
1128 unsigned long mask;
1129 XGCValues *xgcv;
1131 if (mask & GCForeground)
1132 xgcv->foreground = gc->xgcv.foreground;
1133 if (mask & GCBackground)
1134 xgcv->background = gc->xgcv.background;
1135 if (mask & GCFont)
1136 xgcv->font = gc->xgcv.font;
1140 /* Mac replacement for XSetForeground. */
1142 void
1143 XSetForeground (display, gc, color)
1144 Display *display;
1145 GC gc;
1146 unsigned long color;
1148 if (gc->xgcv.foreground != color)
1150 gc->xgcv.foreground = color;
1151 gc->fore_color.red = RED16_FROM_ULONG (color);
1152 gc->fore_color.green = GREEN16_FROM_ULONG (color);
1153 gc->fore_color.blue = BLUE16_FROM_ULONG (color);
1158 /* Mac replacement for XSetBackground. */
1160 void
1161 XSetBackground (display, gc, color)
1162 Display *display;
1163 GC gc;
1164 unsigned long color;
1166 if (gc->xgcv.background != color)
1168 gc->xgcv.background = color;
1169 gc->back_color.red = RED16_FROM_ULONG (color);
1170 gc->back_color.green = GREEN16_FROM_ULONG (color);
1171 gc->back_color.blue = BLUE16_FROM_ULONG (color);
1176 /* Mac replacement for XSetFont. */
1178 static void
1179 XSetFont (display, gc, font)
1180 Display *display;
1181 GC gc;
1182 XFontStruct *font;
1184 gc->xgcv.font = font;
1188 /* Mac replacement for XSetClipRectangles. */
1190 static void
1191 mac_set_clip_rectangles (display, gc, rectangles, n)
1192 Display *display;
1193 GC gc;
1194 Rect *rectangles;
1195 int n;
1197 int i;
1199 if (n < 0 || n > MAX_CLIP_RECTS)
1200 abort ();
1201 if (n == 0)
1203 if (gc->clip_region)
1205 DisposeRgn (gc->clip_region);
1206 gc->clip_region = NULL;
1209 else
1211 if (gc->clip_region == NULL)
1212 gc->clip_region = NewRgn ();
1213 RectRgn (gc->clip_region, rectangles);
1214 if (n > 1)
1216 RgnHandle region = NewRgn ();
1218 for (i = 1; i < n; i++)
1220 RectRgn (region, rectangles + i);
1221 UnionRgn (gc->clip_region, region, gc->clip_region);
1223 DisposeRgn (region);
1226 #if defined (MAC_OSX) && USE_ATSUI
1227 gc->n_clip_rects = n;
1229 for (i = 0; i < n; i++)
1231 Rect *rect = rectangles + i;
1233 gc->clip_rects[i] = CGRectMake (rect->left, rect->top,
1234 rect->right - rect->left,
1235 rect->bottom - rect->top);
1237 #endif
1241 /* Mac replacement for XSetClipMask. */
1243 static INLINE void
1244 mac_reset_clip_rectangles (display, gc)
1245 Display *display;
1246 GC gc;
1248 mac_set_clip_rectangles (display, gc, NULL, 0);
1252 /* Mac replacement for XSetWindowBackground. */
1254 void
1255 XSetWindowBackground (display, w, color)
1256 Display *display;
1257 WindowPtr w;
1258 unsigned long color;
1260 #if !TARGET_API_MAC_CARBON
1261 AuxWinHandle aw_handle;
1262 CTabHandle ctab_handle;
1263 ColorSpecPtr ct_table;
1264 short ct_size;
1265 #endif
1266 RGBColor bg_color;
1268 bg_color.red = RED16_FROM_ULONG (color);
1269 bg_color.green = GREEN16_FROM_ULONG (color);
1270 bg_color.blue = BLUE16_FROM_ULONG (color);
1272 #if TARGET_API_MAC_CARBON
1273 SetWindowContentColor (w, &bg_color);
1274 #else
1275 if (GetAuxWin (w, &aw_handle))
1277 ctab_handle = (*aw_handle)->awCTable;
1278 HandToHand ((Handle *) &ctab_handle);
1279 ct_table = (*ctab_handle)->ctTable;
1280 ct_size = (*ctab_handle)->ctSize;
1281 while (ct_size > -1)
1283 if (ct_table->value == 0)
1285 ct_table->rgb = bg_color;
1286 CTabChanged (ctab_handle);
1287 SetWinColor (w, (WCTabHandle) ctab_handle);
1289 ct_size--;
1292 #endif
1295 /* x_sync is a no-op on Mac. */
1296 void
1297 x_sync (f)
1298 void *f;
1303 /* Flush display of frame F, or of all frames if F is null. */
1305 static void
1306 x_flush (f)
1307 struct frame *f;
1309 #if TARGET_API_MAC_CARBON
1310 BLOCK_INPUT;
1311 if (f)
1312 QDFlushPortBuffer (GetWindowPort (FRAME_MAC_WINDOW (f)), NULL);
1313 else
1314 QDFlushPortBuffer (GetQDGlobalsThePort (), NULL);
1315 UNBLOCK_INPUT;
1316 #endif
1320 /* Remove calls to XFlush by defining XFlush to an empty replacement.
1321 Calls to XFlush should be unnecessary because the X output buffer
1322 is flushed automatically as needed by calls to XPending,
1323 XNextEvent, or XWindowEvent according to the XFlush man page.
1324 XTread_socket calls XPending. Removing XFlush improves
1325 performance. */
1327 #define XFlush(DISPLAY) (void) 0
1330 /* Return the struct mac_display_info corresponding to DPY. There's
1331 only one. */
1333 struct mac_display_info *
1334 mac_display_info_for_display (dpy)
1335 Display *dpy;
1337 return &one_mac_display_info;
1342 /***********************************************************************
1343 Starting and ending an update
1344 ***********************************************************************/
1346 /* Start an update of frame F. This function is installed as a hook
1347 for update_begin, i.e. it is called when update_begin is called.
1348 This function is called prior to calls to x_update_window_begin for
1349 each window being updated. */
1351 static void
1352 x_update_begin (f)
1353 struct frame *f;
1355 #if TARGET_API_MAC_CARBON
1356 /* During update of a frame, availability of input events is
1357 periodically checked with ReceiveNextEvent if
1358 redisplay-dont-pause is nil. That normally flushes window buffer
1359 changes for every check, and thus screen update looks waving even
1360 if no input is available. So we disable screen updates during
1361 update of a frame. */
1362 BLOCK_INPUT;
1363 DisableScreenUpdates ();
1364 UNBLOCK_INPUT;
1365 #endif
1369 /* Start update of window W. Set the global variable updated_window
1370 to the window being updated and set output_cursor to the cursor
1371 position of W. */
1373 static void
1374 x_update_window_begin (w)
1375 struct window *w;
1377 struct frame *f = XFRAME (WINDOW_FRAME (w));
1378 struct mac_display_info *display_info = FRAME_MAC_DISPLAY_INFO (f);
1380 updated_window = w;
1381 set_output_cursor (&w->cursor);
1383 BLOCK_INPUT;
1385 if (f == display_info->mouse_face_mouse_frame)
1387 /* Don't do highlighting for mouse motion during the update. */
1388 display_info->mouse_face_defer = 1;
1390 /* If F needs to be redrawn, simply forget about any prior mouse
1391 highlighting. */
1392 if (FRAME_GARBAGED_P (f))
1393 display_info->mouse_face_window = Qnil;
1395 #if 0 /* Rows in a current matrix containing glyphs in mouse-face have
1396 their mouse_face_p flag set, which means that they are always
1397 unequal to rows in a desired matrix which never have that
1398 flag set. So, rows containing mouse-face glyphs are never
1399 scrolled, and we don't have to switch the mouse highlight off
1400 here to prevent it from being scrolled. */
1402 /* Can we tell that this update does not affect the window
1403 where the mouse highlight is? If so, no need to turn off.
1404 Likewise, don't do anything if the frame is garbaged;
1405 in that case, the frame's current matrix that we would use
1406 is all wrong, and we will redisplay that line anyway. */
1407 if (!NILP (display_info->mouse_face_window)
1408 && w == XWINDOW (display_info->mouse_face_window))
1410 int i;
1412 for (i = 0; i < w->desired_matrix->nrows; ++i)
1413 if (MATRIX_ROW_ENABLED_P (w->desired_matrix, i))
1414 break;
1416 if (i < w->desired_matrix->nrows)
1417 clear_mouse_face (display_info);
1419 #endif /* 0 */
1422 UNBLOCK_INPUT;
1426 /* Draw a vertical window border from (x,y0) to (x,y1) */
1428 static void
1429 mac_draw_vertical_window_border (w, x, y0, y1)
1430 struct window *w;
1431 int x, y0, y1;
1433 struct frame *f = XFRAME (WINDOW_FRAME (w));
1434 struct face *face;
1436 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
1437 if (face)
1438 XSetForeground (FRAME_MAC_DISPLAY (f), f->output_data.mac->normal_gc,
1439 face->foreground);
1441 mac_draw_line (f, f->output_data.mac->normal_gc, x, y0, x, y1);
1444 /* End update of window W (which is equal to updated_window).
1446 Draw vertical borders between horizontally adjacent windows, and
1447 display W's cursor if CURSOR_ON_P is non-zero.
1449 MOUSE_FACE_OVERWRITTEN_P non-zero means that some row containing
1450 glyphs in mouse-face were overwritten. In that case we have to
1451 make sure that the mouse-highlight is properly redrawn.
1453 W may be a menu bar pseudo-window in case we don't have X toolkit
1454 support. Such windows don't have a cursor, so don't display it
1455 here. */
1457 static void
1458 x_update_window_end (w, cursor_on_p, mouse_face_overwritten_p)
1459 struct window *w;
1460 int cursor_on_p, mouse_face_overwritten_p;
1462 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (XFRAME (w->frame));
1464 if (!w->pseudo_window_p)
1466 BLOCK_INPUT;
1468 if (cursor_on_p)
1469 display_and_set_cursor (w, 1, output_cursor.hpos,
1470 output_cursor.vpos,
1471 output_cursor.x, output_cursor.y);
1473 if (draw_window_fringes (w, 1))
1474 x_draw_vertical_border (w);
1476 UNBLOCK_INPUT;
1479 /* If a row with mouse-face was overwritten, arrange for
1480 XTframe_up_to_date to redisplay the mouse highlight. */
1481 if (mouse_face_overwritten_p)
1483 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
1484 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
1485 dpyinfo->mouse_face_window = Qnil;
1488 updated_window = NULL;
1492 /* End update of frame F. This function is installed as a hook in
1493 update_end. */
1495 static void
1496 x_update_end (f)
1497 struct frame *f;
1499 /* Mouse highlight may be displayed again. */
1500 FRAME_MAC_DISPLAY_INFO (f)->mouse_face_defer = 0;
1502 BLOCK_INPUT;
1503 #if TARGET_API_MAC_CARBON
1504 EnableScreenUpdates ();
1505 #endif
1506 XFlush (FRAME_MAC_DISPLAY (f));
1507 UNBLOCK_INPUT;
1511 /* This function is called from various places in xdisp.c whenever a
1512 complete update has been performed. The global variable
1513 updated_window is not available here. */
1515 static void
1516 XTframe_up_to_date (f)
1517 struct frame *f;
1519 if (FRAME_MAC_P (f))
1521 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
1523 if (dpyinfo->mouse_face_deferred_gc
1524 || f == dpyinfo->mouse_face_mouse_frame)
1526 BLOCK_INPUT;
1527 if (dpyinfo->mouse_face_mouse_frame)
1528 note_mouse_highlight (dpyinfo->mouse_face_mouse_frame,
1529 dpyinfo->mouse_face_mouse_x,
1530 dpyinfo->mouse_face_mouse_y);
1531 dpyinfo->mouse_face_deferred_gc = 0;
1532 UNBLOCK_INPUT;
1538 /* Draw truncation mark bitmaps, continuation mark bitmaps, overlay
1539 arrow bitmaps, or clear the fringes if no bitmaps are required
1540 before DESIRED_ROW is made current. The window being updated is
1541 found in updated_window. This function is called from
1542 update_window_line only if it is known that there are differences
1543 between bitmaps to be drawn between current row and DESIRED_ROW. */
1545 static void
1546 x_after_update_window_line (desired_row)
1547 struct glyph_row *desired_row;
1549 struct window *w = updated_window;
1550 struct frame *f;
1551 int width, height;
1553 xassert (w);
1555 if (!desired_row->mode_line_p && !w->pseudo_window_p)
1556 desired_row->redraw_fringe_bitmaps_p = 1;
1558 /* When a window has disappeared, make sure that no rest of
1559 full-width rows stays visible in the internal border. Could
1560 check here if updated_window is the leftmost/rightmost window,
1561 but I guess it's not worth doing since vertically split windows
1562 are almost never used, internal border is rarely set, and the
1563 overhead is very small. */
1564 if (windows_or_buffers_changed
1565 && desired_row->full_width_p
1566 && (f = XFRAME (w->frame),
1567 width = FRAME_INTERNAL_BORDER_WIDTH (f),
1568 width != 0)
1569 && (height = desired_row->visible_height,
1570 height > 0))
1572 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
1574 /* Internal border is drawn below the tool bar. */
1575 if (WINDOWP (f->tool_bar_window)
1576 && w == XWINDOW (f->tool_bar_window))
1577 y -= width;
1579 BLOCK_INPUT;
1580 mac_clear_area (f, 0, y, width, height);
1581 mac_clear_area (f, FRAME_PIXEL_WIDTH (f) - width, y, width, height);
1582 UNBLOCK_INPUT;
1587 /* Draw the bitmap WHICH in one of the left or right fringes of
1588 window W. ROW is the glyph row for which to display the bitmap; it
1589 determines the vertical position at which the bitmap has to be
1590 drawn. */
1592 static void
1593 x_draw_fringe_bitmap (w, row, p)
1594 struct window *w;
1595 struct glyph_row *row;
1596 struct draw_fringe_bitmap_params *p;
1598 struct frame *f = XFRAME (WINDOW_FRAME (w));
1599 Display *display = FRAME_MAC_DISPLAY (f);
1600 struct face *face = p->face;
1601 int rowY;
1603 /* Must clip because of partially visible lines. */
1604 rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
1605 if (p->y < rowY)
1607 /* Adjust position of "bottom aligned" bitmap on partially
1608 visible last row. */
1609 int oldY = row->y;
1610 int oldVH = row->visible_height;
1611 row->visible_height = p->h;
1612 row->y -= rowY - p->y;
1613 x_clip_to_row (w, row, -1, face->gc);
1614 row->y = oldY;
1615 row->visible_height = oldVH;
1617 else
1618 x_clip_to_row (w, row, -1, face->gc);
1620 if (p->bx >= 0 && !p->overlay_p)
1622 #if 0 /* MAC_TODO: stipple */
1623 /* In case the same realized face is used for fringes and
1624 for something displayed in the text (e.g. face `region' on
1625 mono-displays, the fill style may have been changed to
1626 FillSolid in x_draw_glyph_string_background. */
1627 if (face->stipple)
1628 XSetFillStyle (FRAME_X_DISPLAY (f), face->gc, FillOpaqueStippled);
1629 else
1630 XSetForeground (FRAME_X_DISPLAY (f), face->gc, face->background);
1631 #endif
1633 mac_erase_rectangle (f, face->gc, p->bx, p->by, p->nx, p->ny);
1635 #if 0 /* MAC_TODO: stipple */
1636 if (!face->stipple)
1637 XSetForeground (FRAME_X_DISPLAY (f), face->gc, face->foreground);
1638 #endif
1641 if (p->which)
1643 unsigned short *bits = p->bits + p->dh;
1644 XGCValues gcv;
1646 XGetGCValues (display, face->gc, GCForeground, &gcv);
1647 XSetForeground (display, face->gc,
1648 (p->cursor_p
1649 ? (p->overlay_p ? face->background
1650 : f->output_data.mac->cursor_pixel)
1651 : face->foreground));
1652 mac_draw_bitmap (f, face->gc, p->x, p->y,
1653 p->wd, p->h, bits, p->overlay_p);
1654 XSetForeground (display, face->gc, gcv.foreground);
1657 mac_reset_clip_rectangles (display, face->gc);
1662 /* This is called when starting Emacs and when restarting after
1663 suspend. When starting Emacs, no window is mapped. And nothing
1664 must be done to Emacs's own window if it is suspended (though that
1665 rarely happens). */
1667 static void
1668 XTset_terminal_modes ()
1672 /* This is called when exiting or suspending Emacs. Exiting will make
1673 the windows go away, and suspending requires no action. */
1675 static void
1676 XTreset_terminal_modes ()
1682 /***********************************************************************
1683 Display Iterator
1684 ***********************************************************************/
1686 /* Function prototypes of this page. */
1688 static XCharStruct *x_per_char_metric P_ ((XFontStruct *, XChar2b *));
1689 static int mac_encode_char P_ ((int, XChar2b *, struct font_info *, int *));
1692 /* Get metrics of character CHAR2B in FONT. Value is null if CHAR2B
1693 is not contained in the font. */
1695 static INLINE XCharStruct *
1696 x_per_char_metric (font, char2b)
1697 XFontStruct *font;
1698 XChar2b *char2b;
1700 /* The result metric information. */
1701 XCharStruct *pcm = NULL;
1703 xassert (font && char2b);
1705 #if USE_ATSUI
1706 if (font->mac_style)
1708 if (char2b->byte1 >= font->min_byte1
1709 && char2b->byte1 <= font->max_byte1
1710 && char2b->byte2 >= font->min_char_or_byte2
1711 && char2b->byte2 <= font->max_char_or_byte2)
1713 pcm = (font->per_char
1714 + ((font->max_char_or_byte2 - font->min_char_or_byte2 + 1)
1715 * (char2b->byte1 - font->min_byte1))
1716 + (char2b->byte2 - font->min_char_or_byte2));
1719 if (pcm && !pcm->valid_p)
1721 OSErr err;
1722 ATSUTextLayout text_layout;
1723 UniChar c;
1724 int char_width;
1725 ATSTrapezoid glyph_bounds;
1726 Rect char_bounds;
1728 c = (char2b->byte1 << 8) + char2b->byte2;
1729 BLOCK_INPUT;
1730 err = atsu_get_text_layout_with_text_ptr (&c, 1,
1731 font->mac_style,
1732 &text_layout);
1733 if (err == noErr)
1734 err = ATSUMeasureTextImage (text_layout,
1735 kATSUFromTextBeginning, kATSUToTextEnd,
1736 0, 0, &char_bounds);
1738 if (err == noErr)
1739 err = ATSUGetGlyphBounds (text_layout, 0, 0,
1740 kATSUFromTextBeginning, kATSUToTextEnd,
1741 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
1742 kATSUseFractionalOrigins,
1743 #else
1744 kATSUseDeviceOrigins,
1745 #endif
1746 1, &glyph_bounds, NULL);
1747 UNBLOCK_INPUT;
1748 if (err != noErr)
1749 pcm = NULL;
1750 else
1752 xassert (glyph_bounds.lowerRight.x - glyph_bounds.lowerLeft.x
1753 == glyph_bounds.upperRight.x - glyph_bounds.upperLeft.x);
1755 char_width = Fix2Long (glyph_bounds.upperRight.x
1756 - glyph_bounds.upperLeft.x);
1757 STORE_XCHARSTRUCT (*pcm, char_width, char_bounds);
1761 else
1763 #endif
1764 if (font->per_char != NULL)
1766 if (font->min_byte1 == 0 && font->max_byte1 == 0)
1768 /* min_char_or_byte2 specifies the linear character index
1769 corresponding to the first element of the per_char array,
1770 max_char_or_byte2 is the index of the last character. A
1771 character with non-zero CHAR2B->byte1 is not in the font.
1772 A character with byte2 less than min_char_or_byte2 or
1773 greater max_char_or_byte2 is not in the font. */
1774 if (char2b->byte1 == 0
1775 && char2b->byte2 >= font->min_char_or_byte2
1776 && char2b->byte2 <= font->max_char_or_byte2)
1777 pcm = font->per_char + char2b->byte2 - font->min_char_or_byte2;
1779 else
1781 /* If either min_byte1 or max_byte1 are nonzero, both
1782 min_char_or_byte2 and max_char_or_byte2 are less than
1783 256, and the 2-byte character index values corresponding
1784 to the per_char array element N (counting from 0) are:
1786 byte1 = N/D + min_byte1
1787 byte2 = N\D + min_char_or_byte2
1789 where:
1791 D = max_char_or_byte2 - min_char_or_byte2 + 1
1792 / = integer division
1793 \ = integer modulus */
1794 if (char2b->byte1 >= font->min_byte1
1795 && char2b->byte1 <= font->max_byte1
1796 && char2b->byte2 >= font->min_char_or_byte2
1797 && char2b->byte2 <= font->max_char_or_byte2)
1799 pcm = (font->per_char
1800 + ((font->max_char_or_byte2 - font->min_char_or_byte2 + 1)
1801 * (char2b->byte1 - font->min_byte1))
1802 + (char2b->byte2 - font->min_char_or_byte2));
1806 else
1808 /* If the per_char pointer is null, all glyphs between the first
1809 and last character indexes inclusive have the same
1810 information, as given by both min_bounds and max_bounds. */
1811 if (char2b->byte2 >= font->min_char_or_byte2
1812 && char2b->byte2 <= font->max_char_or_byte2)
1813 pcm = &font->max_bounds;
1815 #if USE_ATSUI
1817 #endif
1819 return ((pcm == NULL
1820 || (pcm->width == 0 && (pcm->rbearing - pcm->lbearing) == 0))
1821 ? NULL : pcm);
1824 /* RIF:
1827 static XCharStruct *
1828 mac_per_char_metric (font, char2b, font_type)
1829 XFontStruct *font;
1830 XChar2b *char2b;
1831 int font_type;
1833 return x_per_char_metric (font, char2b);
1836 /* RIF:
1837 Encode CHAR2B using encoding information from FONT_INFO. CHAR2B is
1838 the two-byte form of C. Encoding is returned in *CHAR2B. */
1840 static int
1841 mac_encode_char (c, char2b, font_info, two_byte_p)
1842 int c;
1843 XChar2b *char2b;
1844 struct font_info *font_info;
1845 int *two_byte_p;
1847 int charset = CHAR_CHARSET (c);
1848 XFontStruct *font = font_info->font;
1850 /* FONT_INFO may define a scheme by which to encode byte1 and byte2.
1851 This may be either a program in a special encoder language or a
1852 fixed encoding. */
1853 if (font_info->font_encoder)
1855 /* It's a program. */
1856 struct ccl_program *ccl = font_info->font_encoder;
1858 check_ccl_update (ccl);
1859 if (CHARSET_DIMENSION (charset) == 1)
1861 ccl->reg[0] = charset;
1862 ccl->reg[1] = char2b->byte2;
1863 ccl->reg[2] = -1;
1865 else
1867 ccl->reg[0] = charset;
1868 ccl->reg[1] = char2b->byte1;
1869 ccl->reg[2] = char2b->byte2;
1872 ccl_driver (ccl, NULL, NULL, 0, 0, NULL);
1874 /* We assume that MSBs are appropriately set/reset by CCL
1875 program. */
1876 if (font->max_byte1 == 0) /* 1-byte font */
1877 char2b->byte1 = 0, char2b->byte2 = ccl->reg[1];
1878 else
1879 char2b->byte1 = ccl->reg[1], char2b->byte2 = ccl->reg[2];
1881 else if (font_info->encoding[charset])
1883 /* Fixed encoding scheme. See fontset.h for the meaning of the
1884 encoding numbers. */
1885 int enc = font_info->encoding[charset];
1887 if ((enc == 1 || enc == 2)
1888 && CHARSET_DIMENSION (charset) == 2)
1889 char2b->byte1 |= 0x80;
1891 if (enc == 1 || enc == 3)
1892 char2b->byte2 |= 0x80;
1894 if (enc == 4)
1896 int sjis1, sjis2;
1898 ENCODE_SJIS (char2b->byte1, char2b->byte2, sjis1, sjis2);
1899 char2b->byte1 = sjis1;
1900 char2b->byte2 = sjis2;
1904 if (two_byte_p)
1905 *two_byte_p = ((XFontStruct *) (font_info->font))->max_byte1 > 0;
1907 return FONT_TYPE_UNKNOWN;
1912 /***********************************************************************
1913 Glyph display
1914 ***********************************************************************/
1918 static void x_set_glyph_string_clipping P_ ((struct glyph_string *));
1919 static void x_set_glyph_string_gc P_ ((struct glyph_string *));
1920 static void x_draw_glyph_string_background P_ ((struct glyph_string *,
1921 int));
1922 static void x_draw_glyph_string_foreground P_ ((struct glyph_string *));
1923 static void x_draw_composite_glyph_string_foreground P_ ((struct glyph_string *));
1924 static void x_draw_glyph_string_box P_ ((struct glyph_string *));
1925 static void x_draw_glyph_string P_ ((struct glyph_string *));
1926 static void mac_compute_glyph_string_overhangs P_ ((struct glyph_string *));
1927 static void x_set_cursor_gc P_ ((struct glyph_string *));
1928 static void x_set_mode_line_face_gc P_ ((struct glyph_string *));
1929 static void x_set_mouse_face_gc P_ ((struct glyph_string *));
1930 /*static int x_alloc_lighter_color P_ ((struct frame *, Display *, Colormap,
1931 unsigned long *, double, int));*/
1932 static void x_setup_relief_color P_ ((struct frame *, struct relief *,
1933 double, int, unsigned long));
1934 static void x_setup_relief_colors P_ ((struct glyph_string *));
1935 static void x_draw_image_glyph_string P_ ((struct glyph_string *));
1936 static void x_draw_image_relief P_ ((struct glyph_string *));
1937 static void x_draw_image_foreground P_ ((struct glyph_string *));
1938 static void x_draw_image_foreground_1 P_ ((struct glyph_string *, Pixmap));
1939 static void x_clear_glyph_string_rect P_ ((struct glyph_string *, int,
1940 int, int, int));
1941 static void x_draw_relief_rect P_ ((struct frame *, int, int, int, int,
1942 int, int, int, int, int, int,
1943 Rect *));
1944 static void x_draw_box_rect P_ ((struct glyph_string *, int, int, int, int,
1945 int, int, int, Rect *));
1947 #if GLYPH_DEBUG
1948 static void x_check_font P_ ((struct frame *, XFontStruct *));
1949 #endif
1952 /* Set S->gc to a suitable GC for drawing glyph string S in cursor
1953 face. */
1955 static void
1956 x_set_cursor_gc (s)
1957 struct glyph_string *s;
1959 if (s->font == FRAME_FONT (s->f)
1960 && s->face->background == FRAME_BACKGROUND_PIXEL (s->f)
1961 && s->face->foreground == FRAME_FOREGROUND_PIXEL (s->f)
1962 && !s->cmp)
1963 s->gc = s->f->output_data.mac->cursor_gc;
1964 else
1966 /* Cursor on non-default face: must merge. */
1967 XGCValues xgcv;
1968 unsigned long mask;
1970 xgcv.background = s->f->output_data.mac->cursor_pixel;
1971 xgcv.foreground = s->face->background;
1973 /* If the glyph would be invisible, try a different foreground. */
1974 if (xgcv.foreground == xgcv.background)
1975 xgcv.foreground = s->face->foreground;
1976 if (xgcv.foreground == xgcv.background)
1977 xgcv.foreground = s->f->output_data.mac->cursor_foreground_pixel;
1978 if (xgcv.foreground == xgcv.background)
1979 xgcv.foreground = s->face->foreground;
1981 /* Make sure the cursor is distinct from text in this face. */
1982 if (xgcv.background == s->face->background
1983 && xgcv.foreground == s->face->foreground)
1985 xgcv.background = s->face->foreground;
1986 xgcv.foreground = s->face->background;
1989 IF_DEBUG (x_check_font (s->f, s->font));
1990 xgcv.font = s->font;
1991 mask = GCForeground | GCBackground | GCFont;
1993 if (FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc)
1994 XChangeGC (s->display, FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc,
1995 mask, &xgcv);
1996 else
1997 FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc
1998 = XCreateGC (s->display, s->window, mask, &xgcv);
2000 s->gc = FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc;
2005 /* Set up S->gc of glyph string S for drawing text in mouse face. */
2007 static void
2008 x_set_mouse_face_gc (s)
2009 struct glyph_string *s;
2011 int face_id;
2012 struct face *face;
2014 /* What face has to be used last for the mouse face? */
2015 face_id = FRAME_X_DISPLAY_INFO (s->f)->mouse_face_face_id;
2016 face = FACE_FROM_ID (s->f, face_id);
2017 if (face == NULL)
2018 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2020 if (s->first_glyph->type == CHAR_GLYPH)
2021 face_id = FACE_FOR_CHAR (s->f, face, s->first_glyph->u.ch);
2022 else
2023 face_id = FACE_FOR_CHAR (s->f, face, 0);
2024 s->face = FACE_FROM_ID (s->f, face_id);
2025 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
2027 /* If font in this face is same as S->font, use it. */
2028 if (s->font == s->face->font)
2029 s->gc = s->face->gc;
2030 else
2032 /* Otherwise construct scratch_cursor_gc with values from FACE
2033 but font FONT. */
2034 XGCValues xgcv;
2035 unsigned long mask;
2037 xgcv.background = s->face->background;
2038 xgcv.foreground = s->face->foreground;
2039 IF_DEBUG (x_check_font (s->f, s->font));
2040 xgcv.font = s->font;
2041 mask = GCForeground | GCBackground | GCFont;
2043 if (FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc)
2044 XChangeGC (s->display, FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc,
2045 mask, &xgcv);
2046 else
2047 FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc
2048 = XCreateGC (s->display, s->window, mask, &xgcv);
2050 s->gc = FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc;
2053 xassert (s->gc != 0);
2057 /* Set S->gc of glyph string S to a GC suitable for drawing a mode line.
2058 Faces to use in the mode line have already been computed when the
2059 matrix was built, so there isn't much to do, here. */
2061 static INLINE void
2062 x_set_mode_line_face_gc (s)
2063 struct glyph_string *s;
2065 s->gc = s->face->gc;
2069 /* Set S->gc of glyph string S for drawing that glyph string. Set
2070 S->stippled_p to a non-zero value if the face of S has a stipple
2071 pattern. */
2073 static INLINE void
2074 x_set_glyph_string_gc (s)
2075 struct glyph_string *s;
2077 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
2079 if (s->hl == DRAW_NORMAL_TEXT)
2081 s->gc = s->face->gc;
2082 s->stippled_p = s->face->stipple != 0;
2084 else if (s->hl == DRAW_INVERSE_VIDEO)
2086 x_set_mode_line_face_gc (s);
2087 s->stippled_p = s->face->stipple != 0;
2089 else if (s->hl == DRAW_CURSOR)
2091 x_set_cursor_gc (s);
2092 s->stippled_p = 0;
2094 else if (s->hl == DRAW_MOUSE_FACE)
2096 x_set_mouse_face_gc (s);
2097 s->stippled_p = s->face->stipple != 0;
2099 else if (s->hl == DRAW_IMAGE_RAISED
2100 || s->hl == DRAW_IMAGE_SUNKEN)
2102 s->gc = s->face->gc;
2103 s->stippled_p = s->face->stipple != 0;
2105 else
2107 s->gc = s->face->gc;
2108 s->stippled_p = s->face->stipple != 0;
2111 /* GC must have been set. */
2112 xassert (s->gc != 0);
2116 /* Set clipping for output of glyph string S. S may be part of a mode
2117 line or menu if we don't have X toolkit support. */
2119 static INLINE void
2120 x_set_glyph_string_clipping (s)
2121 struct glyph_string *s;
2123 Rect rects[MAX_CLIP_RECTS];
2124 int n;
2126 n = get_glyph_string_clip_rects (s, rects, MAX_CLIP_RECTS);
2127 mac_set_clip_rectangles (s->display, s->gc, rects, n);
2131 /* RIF:
2132 Compute left and right overhang of glyph string S. If S is a glyph
2133 string for a composition, assume overhangs don't exist. */
2135 static void
2136 mac_compute_glyph_string_overhangs (s)
2137 struct glyph_string *s;
2139 if (s->cmp == NULL
2140 && s->first_glyph->type == CHAR_GLYPH)
2142 Rect r;
2143 MacFontStruct *font = s->font;
2145 #if USE_ATSUI
2146 if (font->mac_style)
2148 OSErr err;
2149 ATSUTextLayout text_layout;
2150 UniChar *buf;
2151 int i;
2153 SetRect (&r, 0, 0, 0, 0);
2154 buf = xmalloc (sizeof (UniChar) * s->nchars);
2155 if (buf)
2157 for (i = 0; i < s->nchars; i++)
2158 buf[i] = (s->char2b[i].byte1 << 8) + s->char2b[i].byte2;
2160 err = atsu_get_text_layout_with_text_ptr (buf, s->nchars,
2161 font->mac_style,
2162 &text_layout);
2163 if (err == noErr)
2164 err = ATSUMeasureTextImage (text_layout,
2165 kATSUFromTextBeginning,
2166 kATSUToTextEnd,
2167 0, 0, &r);
2168 xfree (buf);
2171 else
2173 #endif
2174 TextFont (font->mac_fontnum);
2175 TextSize (font->mac_fontsize);
2176 TextFace (font->mac_fontface);
2178 if (s->two_byte_p)
2179 QDTextBounds (s->nchars * 2, (char *)s->char2b, &r);
2180 else
2182 int i;
2183 char *buf = xmalloc (s->nchars);
2185 if (buf == NULL)
2186 SetRect (&r, 0, 0, 0, 0);
2187 else
2189 for (i = 0; i < s->nchars; ++i)
2190 buf[i] = s->char2b[i].byte2;
2191 QDTextBounds (s->nchars, buf, &r);
2192 xfree (buf);
2195 #if USE_ATSUI
2197 #endif
2199 s->right_overhang = r.right > s->width ? r.right - s->width : 0;
2200 s->left_overhang = r.left < 0 ? -r.left : 0;
2205 /* Fill rectangle X, Y, W, H with background color of glyph string S. */
2207 static INLINE void
2208 x_clear_glyph_string_rect (s, x, y, w, h)
2209 struct glyph_string *s;
2210 int x, y, w, h;
2212 mac_erase_rectangle (s->f, s->gc, x, y, w, h);
2216 /* We prefer not to use XDrawImageString (srcCopy text transfer mode)
2217 on Mac OS X because:
2218 - Screen is double-buffered. (In srcCopy mode, a text is drawn
2219 into an offscreen graphics world first. So performance gain
2220 cannot be expected.)
2221 - It lowers rendering quality.
2222 - Some fonts leave garbage on cursor movement. */
2224 /* Draw the background of glyph_string S. If S->background_filled_p
2225 is non-zero don't draw it. FORCE_P non-zero means draw the
2226 background even if it wouldn't be drawn normally. This is used
2227 when a string preceding S draws into the background of S, or S
2228 contains the first component of a composition. */
2230 static void
2231 x_draw_glyph_string_background (s, force_p)
2232 struct glyph_string *s;
2233 int force_p;
2235 /* Nothing to do if background has already been drawn or if it
2236 shouldn't be drawn in the first place. */
2237 if (!s->background_filled_p)
2239 int box_line_width = max (s->face->box_line_width, 0);
2241 #if 0 /* MAC_TODO: stipple */
2242 if (s->stippled_p)
2244 /* Fill background with a stipple pattern. */
2245 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2246 XFillRectangle (s->display, s->window, s->gc, s->x,
2247 s->y + box_line_width,
2248 s->background_width,
2249 s->height - 2 * box_line_width);
2250 XSetFillStyle (s->display, s->gc, FillSolid);
2251 s->background_filled_p = 1;
2253 else
2254 #endif
2255 #if defined (MAC_OS8) && !USE_ATSUI
2256 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2257 || s->font_not_found_p
2258 || s->extends_to_end_of_line_p
2259 || force_p)
2260 #endif
2262 x_clear_glyph_string_rect (s, s->x, s->y + box_line_width,
2263 s->background_width,
2264 s->height - 2 * box_line_width);
2265 s->background_filled_p = 1;
2271 /* Draw the foreground of glyph string S. */
2273 static void
2274 x_draw_glyph_string_foreground (s)
2275 struct glyph_string *s;
2277 int i, x;
2279 /* If first glyph of S has a left box line, start drawing the text
2280 of S to the right of that box line. */
2281 if (s->face->box != FACE_NO_BOX
2282 && s->first_glyph->left_box_line_p)
2283 x = s->x + abs (s->face->box_line_width);
2284 else
2285 x = s->x;
2287 /* Draw characters of S as rectangles if S's font could not be
2288 loaded. */
2289 if (s->font_not_found_p)
2291 for (i = 0; i < s->nchars; ++i)
2293 struct glyph *g = s->first_glyph + i;
2294 mac_draw_rectangle (s->f, s->gc, x, s->y,
2295 g->pixel_width - 1, s->height - 1);
2296 x += g->pixel_width;
2299 else
2301 char *char1b = (char *) s->char2b;
2302 int boff = s->font_info->baseline_offset;
2304 if (s->font_info->vertical_centering)
2305 boff = VCENTER_BASELINE_OFFSET (s->font, s->f) - boff;
2307 /* If we can use 8-bit functions, condense S->char2b. */
2308 if (!s->two_byte_p
2309 #if USE_ATSUI
2310 && GC_FONT (s->gc)->mac_style == NULL
2311 #endif
2313 for (i = 0; i < s->nchars; ++i)
2314 char1b[i] = s->char2b[i].byte2;
2316 #if defined (MAC_OS8) && !USE_ATSUI
2317 /* Draw text with XDrawString if background has already been
2318 filled. Otherwise, use XDrawImageString. (Note that
2319 XDrawImageString is usually faster than XDrawString.) Always
2320 use XDrawImageString when drawing the cursor so that there is
2321 no chance that characters under a box cursor are invisible. */
2322 if (s->for_overlaps
2323 || (s->background_filled_p && s->hl != DRAW_CURSOR))
2324 #endif
2326 /* Draw characters with 16-bit or 8-bit functions. */
2327 if (s->two_byte_p
2328 #if USE_ATSUI
2329 || GC_FONT (s->gc)->mac_style
2330 #endif
2332 #if USE_CG_TEXT_DRAWING
2333 if (!s->two_byte_p
2334 && mac_draw_string_cg (s->f, s->gc, x, s->ybase - boff,
2335 s->char2b, s->nchars))
2337 else
2338 #endif
2339 mac_draw_string_16 (s->f, s->gc, x, s->ybase - boff,
2340 s->char2b, s->nchars);
2341 else
2342 mac_draw_string (s->f, s->gc, x, s->ybase - boff,
2343 char1b, s->nchars);
2345 #if defined (MAC_OS8) && !USE_ATSUI
2346 else
2348 if (s->two_byte_p)
2349 mac_draw_image_string_16 (s->f, s->gc, x, s->ybase - boff,
2350 s->char2b, s->nchars);
2351 else
2352 mac_draw_image_string (s->f, s->gc, x, s->ybase - boff,
2353 char1b, s->nchars);
2355 #endif
2359 /* Draw the foreground of composite glyph string S. */
2361 static void
2362 x_draw_composite_glyph_string_foreground (s)
2363 struct glyph_string *s;
2365 int i, x;
2367 /* If first glyph of S has a left box line, start drawing the text
2368 of S to the right of that box line. */
2369 if (s->face->box != FACE_NO_BOX
2370 && s->first_glyph->left_box_line_p)
2371 x = s->x + abs (s->face->box_line_width);
2372 else
2373 x = s->x;
2375 /* S is a glyph string for a composition. S->gidx is the index of
2376 the first character drawn for glyphs of this composition.
2377 S->gidx == 0 means we are drawing the very first character of
2378 this composition. */
2380 /* Draw a rectangle for the composition if the font for the very
2381 first character of the composition could not be loaded. */
2382 if (s->font_not_found_p)
2384 if (s->gidx == 0)
2385 mac_draw_rectangle (s->f, s->gc, x, s->y,
2386 s->width - 1, s->height - 1);
2388 else
2390 for (i = 0; i < s->nchars; i++, ++s->gidx)
2391 mac_draw_string_16 (s->f, s->gc,
2392 x + s->cmp->offsets[s->gidx * 2],
2393 s->ybase - s->cmp->offsets[s->gidx * 2 + 1],
2394 s->char2b + i, 1);
2399 #ifdef USE_X_TOOLKIT
2401 static struct frame *x_frame_of_widget P_ ((Widget));
2404 /* Return the frame on which widget WIDGET is used.. Abort if frame
2405 cannot be determined. */
2407 static struct frame *
2408 x_frame_of_widget (widget)
2409 Widget widget;
2411 struct x_display_info *dpyinfo;
2412 Lisp_Object tail;
2413 struct frame *f;
2415 dpyinfo = x_display_info_for_display (XtDisplay (widget));
2417 /* Find the top-level shell of the widget. Note that this function
2418 can be called when the widget is not yet realized, so XtWindow
2419 (widget) == 0. That's the reason we can't simply use
2420 x_any_window_to_frame. */
2421 while (!XtIsTopLevelShell (widget))
2422 widget = XtParent (widget);
2424 /* Look for a frame with that top-level widget. Allocate the color
2425 on that frame to get the right gamma correction value. */
2426 for (tail = Vframe_list; GC_CONSP (tail); tail = XCDR (tail))
2427 if (GC_FRAMEP (XCAR (tail))
2428 && (f = XFRAME (XCAR (tail)),
2429 (f->output_data.nothing != 1
2430 && FRAME_X_DISPLAY_INFO (f) == dpyinfo))
2431 && f->output_data.x->widget == widget)
2432 return f;
2434 abort ();
2438 /* Allocate the color COLOR->pixel on the screen and display of
2439 widget WIDGET in colormap CMAP. If an exact match cannot be
2440 allocated, try the nearest color available. Value is non-zero
2441 if successful. This is called from lwlib. */
2444 x_alloc_nearest_color_for_widget (widget, cmap, color)
2445 Widget widget;
2446 Colormap cmap;
2447 XColor *color;
2449 struct frame *f = x_frame_of_widget (widget);
2450 return x_alloc_nearest_color (f, cmap, color);
2454 #endif /* USE_X_TOOLKIT */
2456 #if 0 /* MAC_TODO */
2458 /* Allocate the color COLOR->pixel on SCREEN of DISPLAY, colormap
2459 CMAP. If an exact match can't be allocated, try the nearest color
2460 available. Value is non-zero if successful. Set *COLOR to the
2461 color allocated. */
2464 x_alloc_nearest_color (f, cmap, color)
2465 struct frame *f;
2466 Colormap cmap;
2467 XColor *color;
2469 Display *display = FRAME_X_DISPLAY (f);
2470 Screen *screen = FRAME_X_SCREEN (f);
2471 int rc;
2473 gamma_correct (f, color);
2474 rc = XAllocColor (display, cmap, color);
2475 if (rc == 0)
2477 /* If we got to this point, the colormap is full, so we're going
2478 to try to get the next closest color. The algorithm used is
2479 a least-squares matching, which is what X uses for closest
2480 color matching with StaticColor visuals. */
2481 int nearest, i;
2482 unsigned long nearest_delta = ~0;
2483 int ncells = XDisplayCells (display, XScreenNumberOfScreen (screen));
2484 XColor *cells = (XColor *) alloca (ncells * sizeof *cells);
2486 for (i = 0; i < ncells; ++i)
2487 cells[i].pixel = i;
2488 XQueryColors (display, cmap, cells, ncells);
2490 for (nearest = i = 0; i < ncells; ++i)
2492 long dred = (color->red >> 8) - (cells[i].red >> 8);
2493 long dgreen = (color->green >> 8) - (cells[i].green >> 8);
2494 long dblue = (color->blue >> 8) - (cells[i].blue >> 8);
2495 unsigned long delta = dred * dred + dgreen * dgreen + dblue * dblue;
2497 if (delta < nearest_delta)
2499 nearest = i;
2500 nearest_delta = delta;
2504 color->red = cells[nearest].red;
2505 color->green = cells[nearest].green;
2506 color->blue = cells[nearest].blue;
2507 rc = XAllocColor (display, cmap, color);
2510 #ifdef DEBUG_X_COLORS
2511 if (rc)
2512 register_color (color->pixel);
2513 #endif /* DEBUG_X_COLORS */
2515 return rc;
2519 /* Allocate color PIXEL on frame F. PIXEL must already be allocated.
2520 It's necessary to do this instead of just using PIXEL directly to
2521 get color reference counts right. */
2523 unsigned long
2524 x_copy_color (f, pixel)
2525 struct frame *f;
2526 unsigned long pixel;
2528 XColor color;
2530 color.pixel = pixel;
2531 BLOCK_INPUT;
2532 XQueryColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
2533 XAllocColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
2534 UNBLOCK_INPUT;
2535 #ifdef DEBUG_X_COLORS
2536 register_color (pixel);
2537 #endif
2538 return color.pixel;
2542 /* Allocate color PIXEL on display DPY. PIXEL must already be allocated.
2543 It's necessary to do this instead of just using PIXEL directly to
2544 get color reference counts right. */
2546 unsigned long
2547 x_copy_dpy_color (dpy, cmap, pixel)
2548 Display *dpy;
2549 Colormap cmap;
2550 unsigned long pixel;
2552 XColor color;
2554 color.pixel = pixel;
2555 BLOCK_INPUT;
2556 XQueryColor (dpy, cmap, &color);
2557 XAllocColor (dpy, cmap, &color);
2558 UNBLOCK_INPUT;
2559 #ifdef DEBUG_X_COLORS
2560 register_color (pixel);
2561 #endif
2562 return color.pixel;
2565 #endif /* MAC_TODO */
2568 /* Brightness beyond which a color won't have its highlight brightness
2569 boosted.
2571 Nominally, highlight colors for `3d' faces are calculated by
2572 brightening an object's color by a constant scale factor, but this
2573 doesn't yield good results for dark colors, so for colors who's
2574 brightness is less than this value (on a scale of 0-255) have to
2575 use an additional additive factor.
2577 The value here is set so that the default menu-bar/mode-line color
2578 (grey75) will not have its highlights changed at all. */
2579 #define HIGHLIGHT_COLOR_DARK_BOOST_LIMIT 187
2582 /* Allocate a color which is lighter or darker than *COLOR by FACTOR
2583 or DELTA. Try a color with RGB values multiplied by FACTOR first.
2584 If this produces the same color as COLOR, try a color where all RGB
2585 values have DELTA added. Return the allocated color in *COLOR.
2586 DISPLAY is the X display, CMAP is the colormap to operate on.
2587 Value is non-zero if successful. */
2589 static int
2590 mac_alloc_lighter_color (f, color, factor, delta)
2591 struct frame *f;
2592 unsigned long *color;
2593 double factor;
2594 int delta;
2596 unsigned long new;
2597 long bright;
2599 /* On Mac, RGB values are 0-255, not 0-65535, so scale delta. */
2600 delta /= 256;
2602 /* Change RGB values by specified FACTOR. Avoid overflow! */
2603 xassert (factor >= 0);
2604 new = RGB_TO_ULONG (min (0xff, (int) (factor * RED_FROM_ULONG (*color))),
2605 min (0xff, (int) (factor * GREEN_FROM_ULONG (*color))),
2606 min (0xff, (int) (factor * BLUE_FROM_ULONG (*color))));
2608 /* Calculate brightness of COLOR. */
2609 bright = (2 * RED_FROM_ULONG (*color) + 3 * GREEN_FROM_ULONG (*color)
2610 + BLUE_FROM_ULONG (*color)) / 6;
2612 /* We only boost colors that are darker than
2613 HIGHLIGHT_COLOR_DARK_BOOST_LIMIT. */
2614 if (bright < HIGHLIGHT_COLOR_DARK_BOOST_LIMIT)
2615 /* Make an additive adjustment to NEW, because it's dark enough so
2616 that scaling by FACTOR alone isn't enough. */
2618 /* How far below the limit this color is (0 - 1, 1 being darker). */
2619 double dimness = 1 - (double)bright / HIGHLIGHT_COLOR_DARK_BOOST_LIMIT;
2620 /* The additive adjustment. */
2621 int min_delta = delta * dimness * factor / 2;
2623 if (factor < 1)
2624 new = RGB_TO_ULONG (max (0, min (0xff, (int) (RED_FROM_ULONG (*color)) - min_delta)),
2625 max (0, min (0xff, (int) (GREEN_FROM_ULONG (*color)) - min_delta)),
2626 max (0, min (0xff, (int) (BLUE_FROM_ULONG (*color)) - min_delta)));
2627 else
2628 new = RGB_TO_ULONG (max (0, min (0xff, (int) (min_delta + RED_FROM_ULONG (*color)))),
2629 max (0, min (0xff, (int) (min_delta + GREEN_FROM_ULONG (*color)))),
2630 max (0, min (0xff, (int) (min_delta + BLUE_FROM_ULONG (*color)))));
2633 if (new == *color)
2634 new = RGB_TO_ULONG (max (0, min (0xff, (int) (delta + RED_FROM_ULONG (*color)))),
2635 max (0, min (0xff, (int) (delta + GREEN_FROM_ULONG (*color)))),
2636 max (0, min (0xff, (int) (delta + BLUE_FROM_ULONG (*color)))));
2638 /* MAC_TODO: Map to palette and retry with delta if same? */
2639 /* MAC_TODO: Free colors (if using palette)? */
2641 if (new == *color)
2642 return 0;
2644 *color = new;
2646 return 1;
2650 /* Set up the foreground color for drawing relief lines of glyph
2651 string S. RELIEF is a pointer to a struct relief containing the GC
2652 with which lines will be drawn. Use a color that is FACTOR or
2653 DELTA lighter or darker than the relief's background which is found
2654 in S->f->output_data.x->relief_background. If such a color cannot
2655 be allocated, use DEFAULT_PIXEL, instead. */
2657 static void
2658 x_setup_relief_color (f, relief, factor, delta, default_pixel)
2659 struct frame *f;
2660 struct relief *relief;
2661 double factor;
2662 int delta;
2663 unsigned long default_pixel;
2665 XGCValues xgcv;
2666 struct mac_output *di = f->output_data.mac;
2667 unsigned long mask = GCForeground;
2668 unsigned long pixel;
2669 unsigned long background = di->relief_background;
2670 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
2672 /* MAC_TODO: Free colors (if using palette)? */
2674 /* Allocate new color. */
2675 xgcv.foreground = default_pixel;
2676 pixel = background;
2677 if (dpyinfo->n_planes != 1
2678 && mac_alloc_lighter_color (f, &pixel, factor, delta))
2680 relief->allocated_p = 1;
2681 xgcv.foreground = relief->pixel = pixel;
2684 if (relief->gc == 0)
2686 #if 0 /* MAC_TODO: stipple */
2687 xgcv.stipple = dpyinfo->gray;
2688 mask |= GCStipple;
2689 #endif
2690 relief->gc = XCreateGC (NULL, FRAME_MAC_WINDOW (f), mask, &xgcv);
2692 else
2693 XChangeGC (NULL, relief->gc, mask, &xgcv);
2697 /* Set up colors for the relief lines around glyph string S. */
2699 static void
2700 x_setup_relief_colors (s)
2701 struct glyph_string *s;
2703 struct mac_output *di = s->f->output_data.mac;
2704 unsigned long color;
2706 if (s->face->use_box_color_for_shadows_p)
2707 color = s->face->box_color;
2708 else if (s->first_glyph->type == IMAGE_GLYPH
2709 && s->img->pixmap
2710 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2711 color = IMAGE_BACKGROUND (s->img, s->f, 0);
2712 else
2714 XGCValues xgcv;
2716 /* Get the background color of the face. */
2717 XGetGCValues (s->display, s->gc, GCBackground, &xgcv);
2718 color = xgcv.background;
2721 if (di->white_relief.gc == 0
2722 || color != di->relief_background)
2724 di->relief_background = color;
2725 x_setup_relief_color (s->f, &di->white_relief, 1.2, 0x8000,
2726 WHITE_PIX_DEFAULT (s->f));
2727 x_setup_relief_color (s->f, &di->black_relief, 0.6, 0x4000,
2728 BLACK_PIX_DEFAULT (s->f));
2733 /* Draw a relief on frame F inside the rectangle given by LEFT_X,
2734 TOP_Y, RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the relief
2735 to draw, it must be >= 0. RAISED_P non-zero means draw a raised
2736 relief. LEFT_P non-zero means draw a relief on the left side of
2737 the rectangle. RIGHT_P non-zero means draw a relief on the right
2738 side of the rectangle. CLIP_RECT is the clipping rectangle to use
2739 when drawing. */
2741 static void
2742 x_draw_relief_rect (f, left_x, top_y, right_x, bottom_y, width,
2743 raised_p, top_p, bot_p, left_p, right_p, clip_rect)
2744 struct frame *f;
2745 int left_x, top_y, right_x, bottom_y, width;
2746 int top_p, bot_p, left_p, right_p, raised_p;
2747 Rect *clip_rect;
2749 Display *dpy = FRAME_MAC_DISPLAY (f);
2750 int i;
2751 GC gc;
2753 if (raised_p)
2754 gc = f->output_data.mac->white_relief.gc;
2755 else
2756 gc = f->output_data.mac->black_relief.gc;
2757 mac_set_clip_rectangles (dpy, gc, clip_rect, 1);
2759 /* Top. */
2760 if (top_p)
2761 for (i = 0; i < width; ++i)
2762 mac_draw_line (f, gc,
2763 left_x + i * left_p, top_y + i,
2764 right_x - i * right_p, top_y + i);
2766 /* Left. */
2767 if (left_p)
2768 for (i = 0; i < width; ++i)
2769 mac_draw_line (f, gc,
2770 left_x + i, top_y + i, left_x + i, bottom_y - i);
2772 mac_reset_clip_rectangles (dpy, gc);
2773 if (raised_p)
2774 gc = f->output_data.mac->black_relief.gc;
2775 else
2776 gc = f->output_data.mac->white_relief.gc;
2777 mac_set_clip_rectangles (dpy, gc, clip_rect, 1);
2779 /* Bottom. */
2780 if (bot_p)
2781 for (i = 0; i < width; ++i)
2782 mac_draw_line (f, gc,
2783 left_x + i * left_p, bottom_y - i,
2784 right_x - i * right_p, bottom_y - i);
2786 /* Right. */
2787 if (right_p)
2788 for (i = 0; i < width; ++i)
2789 mac_draw_line (f, gc,
2790 right_x - i, top_y + i + 1, right_x - i, bottom_y - i - 1);
2792 mac_reset_clip_rectangles (dpy, gc);
2796 /* Draw a box on frame F inside the rectangle given by LEFT_X, TOP_Y,
2797 RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the lines to
2798 draw, it must be >= 0. LEFT_P non-zero means draw a line on the
2799 left side of the rectangle. RIGHT_P non-zero means draw a line
2800 on the right side of the rectangle. CLIP_RECT is the clipping
2801 rectangle to use when drawing. */
2803 static void
2804 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
2805 left_p, right_p, clip_rect)
2806 struct glyph_string *s;
2807 int left_x, top_y, right_x, bottom_y, width, left_p, right_p;
2808 Rect *clip_rect;
2810 XGCValues xgcv;
2812 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2813 XSetForeground (s->display, s->gc, s->face->box_color);
2814 mac_set_clip_rectangles (s->display, s->gc, clip_rect, 1);
2816 /* Top. */
2817 mac_fill_rectangle (s->f, s->gc, left_x, top_y,
2818 right_x - left_x + 1, width);
2820 /* Left. */
2821 if (left_p)
2822 mac_fill_rectangle (s->f, s->gc, left_x, top_y,
2823 width, bottom_y - top_y + 1);
2825 /* Bottom. */
2826 mac_fill_rectangle (s->f, s->gc, left_x, bottom_y - width + 1,
2827 right_x - left_x + 1, width);
2829 /* Right. */
2830 if (right_p)
2831 mac_fill_rectangle (s->f, s->gc, right_x - width + 1,
2832 top_y, width, bottom_y - top_y + 1);
2834 XSetForeground (s->display, s->gc, xgcv.foreground);
2835 mac_reset_clip_rectangles (s->display, s->gc);
2839 /* Draw a box around glyph string S. */
2841 static void
2842 x_draw_glyph_string_box (s)
2843 struct glyph_string *s;
2845 int width, left_x, right_x, top_y, bottom_y, last_x, raised_p;
2846 int left_p, right_p;
2847 struct glyph *last_glyph;
2848 Rect clip_rect;
2850 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2851 ? WINDOW_RIGHT_EDGE_X (s->w)
2852 : window_box_right (s->w, s->area));
2854 /* The glyph that may have a right box line. */
2855 last_glyph = (s->cmp || s->img
2856 ? s->first_glyph
2857 : s->first_glyph + s->nchars - 1);
2859 width = abs (s->face->box_line_width);
2860 raised_p = s->face->box == FACE_RAISED_BOX;
2861 left_x = s->x;
2862 right_x = (s->row->full_width_p && s->extends_to_end_of_line_p
2863 ? last_x - 1
2864 : min (last_x, s->x + s->background_width) - 1);
2865 top_y = s->y;
2866 bottom_y = top_y + s->height - 1;
2868 left_p = (s->first_glyph->left_box_line_p
2869 || (s->hl == DRAW_MOUSE_FACE
2870 && (s->prev == NULL
2871 || s->prev->hl != s->hl)));
2872 right_p = (last_glyph->right_box_line_p
2873 || (s->hl == DRAW_MOUSE_FACE
2874 && (s->next == NULL
2875 || s->next->hl != s->hl)));
2877 get_glyph_string_clip_rect (s, &clip_rect);
2879 if (s->face->box == FACE_SIMPLE_BOX)
2880 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
2881 left_p, right_p, &clip_rect);
2882 else
2884 x_setup_relief_colors (s);
2885 x_draw_relief_rect (s->f, left_x, top_y, right_x, bottom_y,
2886 width, raised_p, 1, 1, left_p, right_p, &clip_rect);
2891 /* Draw foreground of image glyph string S. */
2893 static void
2894 x_draw_image_foreground (s)
2895 struct glyph_string *s;
2897 int x = s->x;
2898 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2900 /* If first glyph of S has a left box line, start drawing it to the
2901 right of that line. */
2902 if (s->face->box != FACE_NO_BOX
2903 && s->first_glyph->left_box_line_p
2904 && s->slice.x == 0)
2905 x += abs (s->face->box_line_width);
2907 /* If there is a margin around the image, adjust x- and y-position
2908 by that margin. */
2909 if (s->slice.x == 0)
2910 x += s->img->hmargin;
2911 if (s->slice.y == 0)
2912 y += s->img->vmargin;
2914 if (s->img->pixmap)
2916 x_set_glyph_string_clipping (s);
2918 if (s->img->mask)
2919 mac_copy_area_with_mask (s->img->pixmap, s->img->mask,
2920 s->f, s->gc, s->slice.x, s->slice.y,
2921 s->slice.width, s->slice.height, x, y);
2922 else
2924 mac_copy_area (s->img->pixmap,
2925 s->f, s->gc, s->slice.x, s->slice.y,
2926 s->slice.width, s->slice.height, x, y);
2928 /* When the image has a mask, we can expect that at
2929 least part of a mouse highlight or a block cursor will
2930 be visible. If the image doesn't have a mask, make
2931 a block cursor visible by drawing a rectangle around
2932 the image. I believe it's looking better if we do
2933 nothing here for mouse-face. */
2934 if (s->hl == DRAW_CURSOR)
2936 int r = s->img->relief;
2937 if (r < 0) r = -r;
2938 mac_draw_rectangle (s->f, s->gc, x - r, y - r,
2939 s->slice.width + r*2 - 1,
2940 s->slice.height + r*2 - 1);
2944 else
2945 /* Draw a rectangle if image could not be loaded. */
2946 mac_draw_rectangle (s->f, s->gc, x, y,
2947 s->slice.width - 1, s->slice.height - 1);
2951 /* Draw a relief around the image glyph string S. */
2953 static void
2954 x_draw_image_relief (s)
2955 struct glyph_string *s;
2957 int x0, y0, x1, y1, thick, raised_p;
2958 Rect r;
2959 int x = s->x;
2960 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2962 /* If first glyph of S has a left box line, start drawing it to the
2963 right of that line. */
2964 if (s->face->box != FACE_NO_BOX
2965 && s->first_glyph->left_box_line_p
2966 && s->slice.x == 0)
2967 x += abs (s->face->box_line_width);
2969 /* If there is a margin around the image, adjust x- and y-position
2970 by that margin. */
2971 if (s->slice.x == 0)
2972 x += s->img->hmargin;
2973 if (s->slice.y == 0)
2974 y += s->img->vmargin;
2976 if (s->hl == DRAW_IMAGE_SUNKEN
2977 || s->hl == DRAW_IMAGE_RAISED)
2979 thick = tool_bar_button_relief >= 0 ? tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2980 raised_p = s->hl == DRAW_IMAGE_RAISED;
2982 else
2984 thick = abs (s->img->relief);
2985 raised_p = s->img->relief > 0;
2988 x0 = x - thick;
2989 y0 = y - thick;
2990 x1 = x + s->slice.width + thick - 1;
2991 y1 = y + s->slice.height + thick - 1;
2993 x_setup_relief_colors (s);
2994 get_glyph_string_clip_rect (s, &r);
2995 x_draw_relief_rect (s->f, x0, y0, x1, y1, thick, raised_p,
2996 s->slice.y == 0,
2997 s->slice.y + s->slice.height == s->img->height,
2998 s->slice.x == 0,
2999 s->slice.x + s->slice.width == s->img->width,
3000 &r);
3004 /* Draw part of the background of glyph string S. X, Y, W, and H
3005 give the rectangle to draw. */
3007 static void
3008 x_draw_glyph_string_bg_rect (s, x, y, w, h)
3009 struct glyph_string *s;
3010 int x, y, w, h;
3012 #if 0 /* MAC_TODO: stipple */
3013 if (s->stippled_p)
3015 /* Fill background with a stipple pattern. */
3016 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
3017 XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
3018 XSetFillStyle (s->display, s->gc, FillSolid);
3020 else
3021 #endif /* MAC_TODO */
3022 x_clear_glyph_string_rect (s, x, y, w, h);
3026 /* Draw image glyph string S.
3028 s->y
3029 s->x +-------------------------
3030 | s->face->box
3032 | +-------------------------
3033 | | s->img->margin
3035 | | +-------------------
3036 | | | the image
3040 static void
3041 x_draw_image_glyph_string (s)
3042 struct glyph_string *s;
3044 int x, y;
3045 int box_line_hwidth = abs (s->face->box_line_width);
3046 int box_line_vwidth = max (s->face->box_line_width, 0);
3047 int height;
3048 Pixmap pixmap = 0;
3050 height = s->height - 2 * box_line_vwidth;
3053 /* Fill background with face under the image. Do it only if row is
3054 taller than image or if image has a clip mask to reduce
3055 flickering. */
3056 s->stippled_p = s->face->stipple != 0;
3057 if (height > s->slice.height
3058 || s->img->hmargin
3059 || s->img->vmargin
3060 || s->img->mask
3061 || s->img->pixmap == 0
3062 || s->width != s->background_width)
3064 x = s->x;
3065 if (s->first_glyph->left_box_line_p
3066 && s->slice.x == 0)
3067 x += box_line_hwidth;
3069 y = s->y;
3070 if (s->slice.y == 0)
3071 y += box_line_vwidth;
3073 x_draw_glyph_string_bg_rect (s, x, y, s->background_width, height);
3075 s->background_filled_p = 1;
3078 /* Draw the foreground. */
3079 x_draw_image_foreground (s);
3081 /* If we must draw a relief around the image, do it. */
3082 if (s->img->relief
3083 || s->hl == DRAW_IMAGE_RAISED
3084 || s->hl == DRAW_IMAGE_SUNKEN)
3085 x_draw_image_relief (s);
3089 /* Draw stretch glyph string S. */
3091 static void
3092 x_draw_stretch_glyph_string (s)
3093 struct glyph_string *s;
3095 xassert (s->first_glyph->type == STRETCH_GLYPH);
3096 s->stippled_p = s->face->stipple != 0;
3098 if (s->hl == DRAW_CURSOR
3099 && !x_stretch_cursor_p)
3101 /* If `x-stretch-block-cursor' is nil, don't draw a block cursor
3102 as wide as the stretch glyph. */
3103 int width = min (FRAME_COLUMN_WIDTH (s->f), s->background_width);
3105 /* Draw cursor. */
3106 x_draw_glyph_string_bg_rect (s, s->x, s->y, width, s->height);
3108 /* Clear rest using the GC of the original non-cursor face. */
3109 if (width < s->background_width)
3111 int x = s->x + width, y = s->y;
3112 int w = s->background_width - width, h = s->height;
3113 Rect r;
3114 GC gc;
3116 if (s->row->mouse_face_p
3117 && cursor_in_mouse_face_p (s->w))
3119 x_set_mouse_face_gc (s);
3120 gc = s->gc;
3122 else
3123 gc = s->face->gc;
3125 get_glyph_string_clip_rect (s, &r);
3126 mac_set_clip_rectangles (s->display, gc, &r, 1);
3128 #if 0 /* MAC_TODO: stipple */
3129 if (s->face->stipple)
3131 /* Fill background with a stipple pattern. */
3132 XSetFillStyle (s->display, gc, FillOpaqueStippled);
3133 XFillRectangle (s->display, s->window, gc, x, y, w, h);
3134 XSetFillStyle (s->display, gc, FillSolid);
3136 else
3137 #endif /* MAC_TODO */
3138 mac_erase_rectangle (s->f, gc, x, y, w, h);
3141 else if (!s->background_filled_p)
3142 x_draw_glyph_string_bg_rect (s, s->x, s->y, s->background_width,
3143 s->height);
3145 s->background_filled_p = 1;
3149 /* Draw glyph string S. */
3151 static void
3152 x_draw_glyph_string (s)
3153 struct glyph_string *s;
3155 int relief_drawn_p = 0;
3157 /* If S draws into the background of its successor that does not
3158 draw a cursor, draw the background of the successor first so that
3159 S can draw into it. This makes S->next use XDrawString instead
3160 of XDrawImageString. */
3161 if (s->next && s->right_overhang && !s->for_overlaps
3162 && s->next->hl != DRAW_CURSOR)
3164 xassert (s->next->img == NULL);
3165 x_set_glyph_string_gc (s->next);
3166 x_set_glyph_string_clipping (s->next);
3167 x_draw_glyph_string_background (s->next, 1);
3170 /* Set up S->gc, set clipping and draw S. */
3171 x_set_glyph_string_gc (s);
3173 /* Draw relief (if any) in advance for char/composition so that the
3174 glyph string can be drawn over it. */
3175 if (!s->for_overlaps
3176 && s->face->box != FACE_NO_BOX
3177 && (s->first_glyph->type == CHAR_GLYPH
3178 || s->first_glyph->type == COMPOSITE_GLYPH))
3181 x_set_glyph_string_clipping (s);
3182 x_draw_glyph_string_background (s, 1);
3183 x_draw_glyph_string_box (s);
3184 x_set_glyph_string_clipping (s);
3185 relief_drawn_p = 1;
3187 else
3188 x_set_glyph_string_clipping (s);
3190 switch (s->first_glyph->type)
3192 case IMAGE_GLYPH:
3193 x_draw_image_glyph_string (s);
3194 break;
3196 case STRETCH_GLYPH:
3197 x_draw_stretch_glyph_string (s);
3198 break;
3200 case CHAR_GLYPH:
3201 if (s->for_overlaps)
3202 s->background_filled_p = 1;
3203 else
3204 x_draw_glyph_string_background (s, 0);
3205 x_draw_glyph_string_foreground (s);
3206 break;
3208 case COMPOSITE_GLYPH:
3209 if (s->for_overlaps || s->gidx > 0)
3210 s->background_filled_p = 1;
3211 else
3212 x_draw_glyph_string_background (s, 1);
3213 x_draw_composite_glyph_string_foreground (s);
3214 break;
3216 default:
3217 abort ();
3220 if (!s->for_overlaps)
3222 /* Draw underline. */
3223 if (s->face->underline_p)
3225 unsigned long h = 1;
3226 unsigned long dy = s->height - h;
3228 if (s->face->underline_defaulted_p)
3229 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3230 s->width, h);
3231 else
3233 XGCValues xgcv;
3234 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3235 XSetForeground (s->display, s->gc, s->face->underline_color);
3236 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3237 s->width, h);
3238 XSetForeground (s->display, s->gc, xgcv.foreground);
3242 /* Draw overline. */
3243 if (s->face->overline_p)
3245 unsigned long dy = 0, h = 1;
3247 if (s->face->overline_color_defaulted_p)
3248 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3249 s->width, h);
3250 else
3252 XGCValues xgcv;
3253 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3254 XSetForeground (s->display, s->gc, s->face->overline_color);
3255 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3256 s->width, h);
3257 XSetForeground (s->display, s->gc, xgcv.foreground);
3261 /* Draw strike-through. */
3262 if (s->face->strike_through_p)
3264 unsigned long h = 1;
3265 unsigned long dy = (s->height - h) / 2;
3267 if (s->face->strike_through_color_defaulted_p)
3268 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3269 s->width, h);
3270 else
3272 XGCValues xgcv;
3273 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3274 XSetForeground (s->display, s->gc, s->face->strike_through_color);
3275 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3276 s->width, h);
3277 XSetForeground (s->display, s->gc, xgcv.foreground);
3281 /* Draw relief if not yet drawn. */
3282 if (!relief_drawn_p && s->face->box != FACE_NO_BOX)
3283 x_draw_glyph_string_box (s);
3286 /* Reset clipping. */
3287 mac_reset_clip_rectangles (s->display, s->gc);
3290 /* Shift display to make room for inserted glyphs. */
3292 void
3293 mac_shift_glyphs_for_insert (f, x, y, width, height, shift_by)
3294 struct frame *f;
3295 int x, y, width, height, shift_by;
3297 mac_scroll_area (f, f->output_data.mac->normal_gc,
3298 x, y, width, height,
3299 x + shift_by, y);
3302 /* Delete N glyphs at the nominal cursor position. Not implemented
3303 for X frames. */
3305 static void
3306 x_delete_glyphs (n)
3307 register int n;
3309 abort ();
3313 /* Clear entire frame. If updating_frame is non-null, clear that
3314 frame. Otherwise clear the selected frame. */
3316 static void
3317 x_clear_frame ()
3319 struct frame *f;
3321 if (updating_frame)
3322 f = updating_frame;
3323 else
3324 f = SELECTED_FRAME ();
3326 /* Clearing the frame will erase any cursor, so mark them all as no
3327 longer visible. */
3328 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
3329 output_cursor.hpos = output_cursor.vpos = 0;
3330 output_cursor.x = -1;
3332 /* We don't set the output cursor here because there will always
3333 follow an explicit cursor_to. */
3334 BLOCK_INPUT;
3335 mac_clear_window (f);
3337 /* We have to clear the scroll bars, too. If we have changed
3338 colors or something like that, then they should be notified. */
3339 x_scroll_bar_clear (f);
3341 XFlush (FRAME_MAC_DISPLAY (f));
3342 UNBLOCK_INPUT;
3347 /* Invert the middle quarter of the frame for .15 sec. */
3349 /* We use the select system call to do the waiting, so we have to make
3350 sure it's available. If it isn't, we just won't do visual bells. */
3352 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
3355 /* Subtract the `struct timeval' values X and Y, storing the result in
3356 *RESULT. Return 1 if the difference is negative, otherwise 0. */
3358 static int
3359 timeval_subtract (result, x, y)
3360 struct timeval *result, x, y;
3362 /* Perform the carry for the later subtraction by updating y. This
3363 is safer because on some systems the tv_sec member is unsigned. */
3364 if (x.tv_usec < y.tv_usec)
3366 int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
3367 y.tv_usec -= 1000000 * nsec;
3368 y.tv_sec += nsec;
3371 if (x.tv_usec - y.tv_usec > 1000000)
3373 int nsec = (y.tv_usec - x.tv_usec) / 1000000;
3374 y.tv_usec += 1000000 * nsec;
3375 y.tv_sec -= nsec;
3378 /* Compute the time remaining to wait. tv_usec is certainly
3379 positive. */
3380 result->tv_sec = x.tv_sec - y.tv_sec;
3381 result->tv_usec = x.tv_usec - y.tv_usec;
3383 /* Return indication of whether the result should be considered
3384 negative. */
3385 return x.tv_sec < y.tv_sec;
3388 void
3389 XTflash (f)
3390 struct frame *f;
3392 /* Get the height not including a menu bar widget. */
3393 int height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, FRAME_LINES (f));
3394 /* Height of each line to flash. */
3395 int flash_height = FRAME_LINE_HEIGHT (f);
3396 /* These will be the left and right margins of the rectangles. */
3397 int flash_left = FRAME_INTERNAL_BORDER_WIDTH (f);
3398 int flash_right = FRAME_PIXEL_WIDTH (f) - FRAME_INTERNAL_BORDER_WIDTH (f);
3400 int width;
3402 /* Don't flash the area between a scroll bar and the frame
3403 edge it is next to. */
3404 switch (FRAME_VERTICAL_SCROLL_BAR_TYPE (f))
3406 case vertical_scroll_bar_left:
3407 flash_left += VERTICAL_SCROLL_BAR_WIDTH_TRIM;
3408 break;
3410 case vertical_scroll_bar_right:
3411 flash_right -= VERTICAL_SCROLL_BAR_WIDTH_TRIM;
3412 break;
3414 default:
3415 break;
3418 width = flash_right - flash_left;
3420 BLOCK_INPUT;
3422 /* If window is tall, flash top and bottom line. */
3423 if (height > 3 * FRAME_LINE_HEIGHT (f))
3425 mac_invert_rectangle (f, flash_left,
3426 (FRAME_INTERNAL_BORDER_WIDTH (f)
3427 + FRAME_TOOL_BAR_LINES (f) * FRAME_LINE_HEIGHT (f)),
3428 width, flash_height);
3429 mac_invert_rectangle (f, flash_left,
3430 (height - flash_height
3431 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3432 width, flash_height);
3434 else
3435 /* If it is short, flash it all. */
3436 mac_invert_rectangle (f, flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3437 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3439 x_flush (f);
3442 struct timeval wakeup;
3444 EMACS_GET_TIME (wakeup);
3446 /* Compute time to wait until, propagating carry from usecs. */
3447 wakeup.tv_usec += 150000;
3448 wakeup.tv_sec += (wakeup.tv_usec / 1000000);
3449 wakeup.tv_usec %= 1000000;
3451 /* Keep waiting until past the time wakeup or any input gets
3452 available. */
3453 while (! detect_input_pending ())
3455 struct timeval current;
3456 struct timeval timeout;
3458 EMACS_GET_TIME (current);
3460 /* Break if result would be negative. */
3461 if (timeval_subtract (&current, wakeup, current))
3462 break;
3464 /* How long `select' should wait. */
3465 timeout.tv_sec = 0;
3466 timeout.tv_usec = 10000;
3468 /* Try to wait that long--but we might wake up sooner. */
3469 select (0, NULL, NULL, NULL, &timeout);
3473 /* If window is tall, flash top and bottom line. */
3474 if (height > 3 * FRAME_LINE_HEIGHT (f))
3476 mac_invert_rectangle (f, flash_left,
3477 (FRAME_INTERNAL_BORDER_WIDTH (f)
3478 + FRAME_TOOL_BAR_LINES (f) * FRAME_LINE_HEIGHT (f)),
3479 width, flash_height);
3480 mac_invert_rectangle (f, flash_left,
3481 (height - flash_height
3482 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3483 width, flash_height);
3485 else
3486 /* If it is short, flash it all. */
3487 mac_invert_rectangle (f, flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3488 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3490 x_flush (f);
3492 UNBLOCK_INPUT;
3495 #endif /* defined (HAVE_TIMEVAL) && defined (HAVE_SELECT) */
3498 /* Make audible bell. */
3500 void
3501 XTring_bell ()
3503 struct frame *f = SELECTED_FRAME ();
3505 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
3506 if (visible_bell)
3507 XTflash (f);
3508 else
3509 #endif
3511 BLOCK_INPUT;
3512 SysBeep (1);
3513 XFlush (FRAME_MAC_DISPLAY (f));
3514 UNBLOCK_INPUT;
3519 /* Specify how many text lines, from the top of the window,
3520 should be affected by insert-lines and delete-lines operations.
3521 This, and those operations, are used only within an update
3522 that is bounded by calls to x_update_begin and x_update_end. */
3524 static void
3525 XTset_terminal_window (n)
3526 register int n;
3528 /* This function intentionally left blank. */
3533 /***********************************************************************
3534 Line Dance
3535 ***********************************************************************/
3537 /* Perform an insert-lines or delete-lines operation, inserting N
3538 lines or deleting -N lines at vertical position VPOS. */
3540 static void
3541 x_ins_del_lines (vpos, n)
3542 int vpos, n;
3544 abort ();
3548 /* Scroll part of the display as described by RUN. */
3550 static void
3551 x_scroll_run (w, run)
3552 struct window *w;
3553 struct run *run;
3555 struct frame *f = XFRAME (w->frame);
3556 int x, y, width, height, from_y, to_y, bottom_y;
3558 /* Get frame-relative bounding box of the text display area of W,
3559 without mode lines. Include in this box the left and right
3560 fringe of W. */
3561 window_box (w, -1, &x, &y, &width, &height);
3563 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
3564 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
3565 bottom_y = y + height;
3567 if (to_y < from_y)
3569 /* Scrolling up. Make sure we don't copy part of the mode
3570 line at the bottom. */
3571 if (from_y + run->height > bottom_y)
3572 height = bottom_y - from_y;
3573 else
3574 height = run->height;
3576 else
3578 /* Scolling down. Make sure we don't copy over the mode line.
3579 at the bottom. */
3580 if (to_y + run->height > bottom_y)
3581 height = bottom_y - to_y;
3582 else
3583 height = run->height;
3586 BLOCK_INPUT;
3588 /* Cursor off. Will be switched on again in x_update_window_end. */
3589 updated_window = w;
3590 x_clear_cursor (w);
3592 mac_scroll_area (f, f->output_data.mac->normal_gc,
3593 x, from_y,
3594 width, height,
3595 x, to_y);
3597 UNBLOCK_INPUT;
3602 /***********************************************************************
3603 Exposure Events
3604 ***********************************************************************/
3607 static void
3608 frame_highlight (f)
3609 struct frame *f;
3611 OSErr err;
3612 ControlRef root_control;
3614 BLOCK_INPUT;
3615 err = GetRootControl (FRAME_MAC_WINDOW (f), &root_control);
3616 if (err == noErr)
3617 ActivateControl (root_control);
3618 UNBLOCK_INPUT;
3619 x_update_cursor (f, 1);
3622 static void
3623 frame_unhighlight (f)
3624 struct frame *f;
3626 OSErr err;
3627 ControlRef root_control;
3629 BLOCK_INPUT;
3630 err = GetRootControl (FRAME_MAC_WINDOW (f), &root_control);
3631 if (err == noErr)
3632 DeactivateControl (root_control);
3633 UNBLOCK_INPUT;
3634 x_update_cursor (f, 1);
3637 /* The focus has changed. Update the frames as necessary to reflect
3638 the new situation. Note that we can't change the selected frame
3639 here, because the Lisp code we are interrupting might become confused.
3640 Each event gets marked with the frame in which it occurred, so the
3641 Lisp code can tell when the switch took place by examining the events. */
3643 static void
3644 x_new_focus_frame (dpyinfo, frame)
3645 struct x_display_info *dpyinfo;
3646 struct frame *frame;
3648 struct frame *old_focus = dpyinfo->x_focus_frame;
3650 if (frame != dpyinfo->x_focus_frame)
3652 /* Set this before calling other routines, so that they see
3653 the correct value of x_focus_frame. */
3654 dpyinfo->x_focus_frame = frame;
3656 if (old_focus && old_focus->auto_lower)
3657 x_lower_frame (old_focus);
3659 #if 0
3660 selected_frame = frame;
3661 XSETFRAME (XWINDOW (selected_frame->selected_window)->frame,
3662 selected_frame);
3663 Fselect_window (selected_frame->selected_window, Qnil);
3664 choose_minibuf_frame ();
3665 #endif /* ! 0 */
3667 if (dpyinfo->x_focus_frame && dpyinfo->x_focus_frame->auto_raise)
3668 pending_autoraise_frame = dpyinfo->x_focus_frame;
3669 else
3670 pending_autoraise_frame = 0;
3673 x_frame_rehighlight (dpyinfo);
3676 /* Handle FocusIn and FocusOut state changes for FRAME.
3677 If FRAME has focus and there exists more than one frame, puts
3678 a FOCUS_IN_EVENT into *BUFP. */
3680 static void
3681 mac_focus_changed (type, dpyinfo, frame, bufp)
3682 int type;
3683 struct mac_display_info *dpyinfo;
3684 struct frame *frame;
3685 struct input_event *bufp;
3687 if (type == activeFlag)
3689 if (dpyinfo->x_focus_event_frame != frame)
3691 x_new_focus_frame (dpyinfo, frame);
3692 dpyinfo->x_focus_event_frame = frame;
3694 /* Don't stop displaying the initial startup message
3695 for a switch-frame event we don't need. */
3696 if (GC_NILP (Vterminal_frame)
3697 && GC_CONSP (Vframe_list)
3698 && !GC_NILP (XCDR (Vframe_list)))
3700 bufp->kind = FOCUS_IN_EVENT;
3701 XSETFRAME (bufp->frame_or_window, frame);
3705 else
3707 if (dpyinfo->x_focus_event_frame == frame)
3709 dpyinfo->x_focus_event_frame = 0;
3710 x_new_focus_frame (dpyinfo, 0);
3715 /* The focus may have changed. Figure out if it is a real focus change,
3716 by checking both FocusIn/Out and Enter/LeaveNotify events.
3718 Returns FOCUS_IN_EVENT event in *BUFP. */
3720 static void
3721 x_detect_focus_change (dpyinfo, event, bufp)
3722 struct mac_display_info *dpyinfo;
3723 EventRecord *event;
3724 struct input_event *bufp;
3726 struct frame *frame;
3728 frame = mac_window_to_frame ((WindowPtr) event->message);
3729 if (! frame)
3730 return;
3732 /* On Mac, this is only called from focus events, so no switch needed. */
3733 mac_focus_changed ((event->modifiers & activeFlag),
3734 dpyinfo, frame, bufp);
3738 /* Handle an event saying the mouse has moved out of an Emacs frame. */
3740 void
3741 x_mouse_leave (dpyinfo)
3742 struct x_display_info *dpyinfo;
3744 x_new_focus_frame (dpyinfo, dpyinfo->x_focus_event_frame);
3747 /* The focus has changed, or we have redirected a frame's focus to
3748 another frame (this happens when a frame uses a surrogate
3749 mini-buffer frame). Shift the highlight as appropriate.
3751 The FRAME argument doesn't necessarily have anything to do with which
3752 frame is being highlighted or un-highlighted; we only use it to find
3753 the appropriate X display info. */
3755 static void
3756 XTframe_rehighlight (frame)
3757 struct frame *frame;
3759 x_frame_rehighlight (FRAME_X_DISPLAY_INFO (frame));
3762 static void
3763 x_frame_rehighlight (dpyinfo)
3764 struct x_display_info *dpyinfo;
3766 struct frame *old_highlight = dpyinfo->x_highlight_frame;
3768 if (dpyinfo->x_focus_frame)
3770 dpyinfo->x_highlight_frame
3771 = ((GC_FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame)))
3772 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
3773 : dpyinfo->x_focus_frame);
3774 if (! FRAME_LIVE_P (dpyinfo->x_highlight_frame))
3776 FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
3777 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
3780 else
3781 dpyinfo->x_highlight_frame = 0;
3783 if (dpyinfo->x_highlight_frame != old_highlight)
3785 if (old_highlight)
3786 frame_unhighlight (old_highlight);
3787 if (dpyinfo->x_highlight_frame)
3788 frame_highlight (dpyinfo->x_highlight_frame);
3794 /* Keyboard processing - modifier keys, vendor-specific keysyms, etc. */
3796 #if 0 /* MAC_TODO */
3797 /* Initialize mode_switch_bit and modifier_meaning. */
3798 static void
3799 x_find_modifier_meanings (dpyinfo)
3800 struct x_display_info *dpyinfo;
3802 int min_code, max_code;
3803 KeySym *syms;
3804 int syms_per_code;
3805 XModifierKeymap *mods;
3807 dpyinfo->meta_mod_mask = 0;
3808 dpyinfo->shift_lock_mask = 0;
3809 dpyinfo->alt_mod_mask = 0;
3810 dpyinfo->super_mod_mask = 0;
3811 dpyinfo->hyper_mod_mask = 0;
3813 #ifdef HAVE_X11R4
3814 XDisplayKeycodes (dpyinfo->display, &min_code, &max_code);
3815 #else
3816 min_code = dpyinfo->display->min_keycode;
3817 max_code = dpyinfo->display->max_keycode;
3818 #endif
3820 syms = XGetKeyboardMapping (dpyinfo->display,
3821 min_code, max_code - min_code + 1,
3822 &syms_per_code);
3823 mods = XGetModifierMapping (dpyinfo->display);
3825 /* Scan the modifier table to see which modifier bits the Meta and
3826 Alt keysyms are on. */
3828 int row, col; /* The row and column in the modifier table. */
3830 for (row = 3; row < 8; row++)
3831 for (col = 0; col < mods->max_keypermod; col++)
3833 KeyCode code
3834 = mods->modifiermap[(row * mods->max_keypermod) + col];
3836 /* Zeroes are used for filler. Skip them. */
3837 if (code == 0)
3838 continue;
3840 /* Are any of this keycode's keysyms a meta key? */
3842 int code_col;
3844 for (code_col = 0; code_col < syms_per_code; code_col++)
3846 int sym = syms[((code - min_code) * syms_per_code) + code_col];
3848 switch (sym)
3850 case XK_Meta_L:
3851 case XK_Meta_R:
3852 dpyinfo->meta_mod_mask |= (1 << row);
3853 break;
3855 case XK_Alt_L:
3856 case XK_Alt_R:
3857 dpyinfo->alt_mod_mask |= (1 << row);
3858 break;
3860 case XK_Hyper_L:
3861 case XK_Hyper_R:
3862 dpyinfo->hyper_mod_mask |= (1 << row);
3863 break;
3865 case XK_Super_L:
3866 case XK_Super_R:
3867 dpyinfo->super_mod_mask |= (1 << row);
3868 break;
3870 case XK_Shift_Lock:
3871 /* Ignore this if it's not on the lock modifier. */
3872 if ((1 << row) == LockMask)
3873 dpyinfo->shift_lock_mask = LockMask;
3874 break;
3881 /* If we couldn't find any meta keys, accept any alt keys as meta keys. */
3882 if (! dpyinfo->meta_mod_mask)
3884 dpyinfo->meta_mod_mask = dpyinfo->alt_mod_mask;
3885 dpyinfo->alt_mod_mask = 0;
3888 /* If some keys are both alt and meta,
3889 make them just meta, not alt. */
3890 if (dpyinfo->alt_mod_mask & dpyinfo->meta_mod_mask)
3892 dpyinfo->alt_mod_mask &= ~dpyinfo->meta_mod_mask;
3895 XFree ((char *) syms);
3896 XFreeModifiermap (mods);
3899 #endif /* MAC_TODO */
3901 /* Convert between the modifier bits X uses and the modifier bits
3902 Emacs uses. */
3904 static unsigned int
3905 x_mac_to_emacs_modifiers (dpyinfo, state)
3906 struct x_display_info *dpyinfo;
3907 unsigned short state;
3909 return (((state & shiftKey) ? shift_modifier : 0)
3910 | ((state & controlKey) ? ctrl_modifier : 0)
3911 | ((state & cmdKey) ? meta_modifier : 0)
3912 | ((state & optionKey) ? alt_modifier : 0));
3915 #if 0 /* MAC_TODO */
3916 static unsigned short
3917 x_emacs_to_x_modifiers (dpyinfo, state)
3918 struct x_display_info *dpyinfo;
3919 unsigned int state;
3921 return ( ((state & alt_modifier) ? dpyinfo->alt_mod_mask : 0)
3922 | ((state & super_modifier) ? dpyinfo->super_mod_mask : 0)
3923 | ((state & hyper_modifier) ? dpyinfo->hyper_mod_mask : 0)
3924 | ((state & shift_modifier) ? ShiftMask : 0)
3925 | ((state & ctrl_modifier) ? ControlMask : 0)
3926 | ((state & meta_modifier) ? dpyinfo->meta_mod_mask : 0));
3928 #endif /* MAC_TODO */
3930 /* Convert a keysym to its name. */
3932 char *
3933 x_get_keysym_name (keysym)
3934 int keysym;
3936 char *value;
3938 BLOCK_INPUT;
3939 #if 0
3940 value = XKeysymToString (keysym);
3941 #else
3942 value = 0;
3943 #endif
3944 UNBLOCK_INPUT;
3946 return value;
3951 /* Function to report a mouse movement to the mainstream Emacs code.
3952 The input handler calls this.
3954 We have received a mouse movement event, which is given in *event.
3955 If the mouse is over a different glyph than it was last time, tell
3956 the mainstream emacs code by setting mouse_moved. If not, ask for
3957 another motion event, so we can check again the next time it moves. */
3959 static Point last_mouse_motion_position;
3960 static Lisp_Object last_mouse_motion_frame;
3962 static int
3963 note_mouse_movement (frame, pos)
3964 FRAME_PTR frame;
3965 Point *pos;
3967 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (frame);
3968 #if TARGET_API_MAC_CARBON
3969 Rect r;
3970 #endif
3972 last_mouse_movement_time = TickCount () * (1000 / 60); /* to milliseconds */
3973 last_mouse_motion_position = *pos;
3974 XSETFRAME (last_mouse_motion_frame, frame);
3976 #if TARGET_API_MAC_CARBON
3977 if (!PtInRect (*pos, GetWindowPortBounds (FRAME_MAC_WINDOW (frame), &r)))
3978 #else
3979 if (!PtInRect (*pos, &FRAME_MAC_WINDOW (frame)->portRect))
3980 #endif
3982 if (frame == dpyinfo->mouse_face_mouse_frame)
3983 /* This case corresponds to LeaveNotify in X11. */
3985 /* If we move outside the frame, then we're certainly no
3986 longer on any text in the frame. */
3987 clear_mouse_face (dpyinfo);
3988 dpyinfo->mouse_face_mouse_frame = 0;
3989 if (!dpyinfo->grabbed)
3990 rif->define_frame_cursor (frame,
3991 frame->output_data.mac->nontext_cursor);
3993 return 1;
3995 /* Has the mouse moved off the glyph it was on at the last sighting? */
3996 if (frame != last_mouse_glyph_frame
3997 || !PtInRect (*pos, &last_mouse_glyph))
3999 frame->mouse_moved = 1;
4000 last_mouse_scroll_bar = Qnil;
4001 note_mouse_highlight (frame, pos->h, pos->v);
4002 /* Remember which glyph we're now on. */
4003 remember_mouse_glyph (frame, pos->h, pos->v, &last_mouse_glyph);
4004 last_mouse_glyph_frame = frame;
4005 return 1;
4008 return 0;
4012 /************************************************************************
4013 Mouse Face
4014 ************************************************************************/
4016 /* MAC TODO: This should be called from somewhere (or removed) ++KFS */
4018 static void
4019 redo_mouse_highlight ()
4021 if (!NILP (last_mouse_motion_frame)
4022 && FRAME_LIVE_P (XFRAME (last_mouse_motion_frame)))
4023 note_mouse_highlight (XFRAME (last_mouse_motion_frame),
4024 last_mouse_motion_position.h,
4025 last_mouse_motion_position.v);
4029 static struct frame *
4030 mac_focus_frame (dpyinfo)
4031 struct mac_display_info *dpyinfo;
4033 if (dpyinfo->x_focus_frame)
4034 return dpyinfo->x_focus_frame;
4035 else
4036 /* Mac version may get events, such as a menu bar click, even when
4037 all the frames are invisible. In this case, we regard the
4038 event came to the selected frame. */
4039 return SELECTED_FRAME ();
4043 /* Return the current position of the mouse.
4044 *FP should be a frame which indicates which display to ask about.
4046 If the mouse movement started in a scroll bar, set *FP, *BAR_WINDOW,
4047 and *PART to the frame, window, and scroll bar part that the mouse
4048 is over. Set *X and *Y to the portion and whole of the mouse's
4049 position on the scroll bar.
4051 If the mouse movement started elsewhere, set *FP to the frame the
4052 mouse is on, *BAR_WINDOW to nil, and *X and *Y to the character cell
4053 the mouse is over.
4055 Set *TIME to the server time-stamp for the time at which the mouse
4056 was at this position.
4058 Don't store anything if we don't have a valid set of values to report.
4060 This clears the mouse_moved flag, so we can wait for the next mouse
4061 movement. */
4063 static void
4064 XTmouse_position (fp, insist, bar_window, part, x, y, time)
4065 FRAME_PTR *fp;
4066 int insist;
4067 Lisp_Object *bar_window;
4068 enum scroll_bar_part *part;
4069 Lisp_Object *x, *y;
4070 unsigned long *time;
4072 FRAME_PTR f1;
4074 BLOCK_INPUT;
4076 if (! NILP (last_mouse_scroll_bar) && insist == 0)
4077 x_scroll_bar_report_motion (fp, bar_window, part, x, y, time);
4078 else
4080 Lisp_Object frame, tail;
4082 /* Clear the mouse-moved flag for every frame on this display. */
4083 FOR_EACH_FRAME (tail, frame)
4084 XFRAME (frame)->mouse_moved = 0;
4086 last_mouse_scroll_bar = Qnil;
4088 if (FRAME_MAC_DISPLAY_INFO (*fp)->grabbed && last_mouse_frame
4089 && FRAME_LIVE_P (last_mouse_frame))
4090 f1 = last_mouse_frame;
4091 else
4092 f1 = mac_focus_frame (FRAME_MAC_DISPLAY_INFO (*fp));
4094 if (f1)
4096 /* Ok, we found a frame. Store all the values.
4097 last_mouse_glyph is a rectangle used to reduce the
4098 generation of mouse events. To not miss any motion
4099 events, we must divide the frame into rectangles of the
4100 size of the smallest character that could be displayed
4101 on it, i.e. into the same rectangles that matrices on
4102 the frame are divided into. */
4103 Point mouse_pos;
4105 SetPortWindowPort (FRAME_MAC_WINDOW (f1));
4106 GetMouse (&mouse_pos);
4107 remember_mouse_glyph (f1, mouse_pos.h, mouse_pos.v,
4108 &last_mouse_glyph);
4109 last_mouse_glyph_frame = f1;
4111 *bar_window = Qnil;
4112 *part = 0;
4113 *fp = f1;
4114 XSETINT (*x, mouse_pos.h);
4115 XSETINT (*y, mouse_pos.v);
4116 *time = last_mouse_movement_time;
4120 UNBLOCK_INPUT;
4124 /************************************************************************
4125 Toolkit scroll bars
4126 ************************************************************************/
4128 #ifdef USE_TOOLKIT_SCROLL_BARS
4130 static pascal void scroll_bar_timer_callback P_ ((EventLoopTimerRef, void *));
4131 static OSStatus install_scroll_bar_timer P_ ((void));
4132 static OSStatus set_scroll_bar_timer P_ ((EventTimerInterval));
4133 static int control_part_code_to_scroll_bar_part P_ ((ControlPartCode));
4134 static void construct_scroll_bar_click P_ ((struct scroll_bar *, int,
4135 struct input_event *));
4136 static OSErr get_control_part_bounds P_ ((ControlHandle, ControlPartCode,
4137 Rect *));
4138 static void x_scroll_bar_handle_press P_ ((struct scroll_bar *,
4139 ControlPartCode,
4140 struct input_event *));
4141 static void x_scroll_bar_handle_release P_ ((struct scroll_bar *,
4142 struct input_event *));
4143 static void x_scroll_bar_handle_drag P_ ((WindowPtr, struct scroll_bar *,
4144 Point, struct input_event *));
4145 static void x_set_toolkit_scroll_bar_thumb P_ ((struct scroll_bar *,
4146 int, int, int));
4148 /* Last scroll bar part sent in x_scroll_bar_handle_*. */
4150 static int last_scroll_bar_part;
4152 static EventLoopTimerRef scroll_bar_timer;
4154 static int scroll_bar_timer_event_posted_p;
4156 #define SCROLL_BAR_FIRST_DELAY 0.5
4157 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
4159 static pascal void
4160 scroll_bar_timer_callback (timer, data)
4161 EventLoopTimerRef timer;
4162 void *data;
4164 EventRef event = NULL;
4165 OSErr err;
4167 err = CreateEvent (NULL, kEventClassMouse, kEventMouseMoved, 0,
4168 kEventAttributeNone, &event);
4169 if (err == noErr)
4171 Point mouse_pos;
4173 GetMouse (&mouse_pos);
4174 LocalToGlobal (&mouse_pos);
4175 err = SetEventParameter (event, kEventParamMouseLocation, typeQDPoint,
4176 sizeof (Point), &mouse_pos);
4178 if (err == noErr)
4180 UInt32 modifiers = GetCurrentKeyModifiers ();
4182 err = SetEventParameter (event, kEventParamKeyModifiers, typeUInt32,
4183 sizeof (UInt32), &modifiers);
4185 if (err == noErr)
4186 err = PostEventToQueue (GetCurrentEventQueue (), event,
4187 kEventPriorityStandard);
4188 if (err == noErr)
4189 scroll_bar_timer_event_posted_p = 1;
4191 if (event)
4192 ReleaseEvent (event);
4195 static OSStatus
4196 install_scroll_bar_timer ()
4198 static EventLoopTimerUPP scroll_bar_timer_callbackUPP = NULL;
4200 if (scroll_bar_timer_callbackUPP == NULL)
4201 scroll_bar_timer_callbackUPP =
4202 NewEventLoopTimerUPP (scroll_bar_timer_callback);
4204 if (scroll_bar_timer == NULL)
4205 /* Mac OS X and CarbonLib 1.5 and later allow us to specify
4206 kEventDurationForever as delays. */
4207 return
4208 InstallEventLoopTimer (GetCurrentEventLoop (),
4209 kEventDurationForever, kEventDurationForever,
4210 scroll_bar_timer_callbackUPP, NULL,
4211 &scroll_bar_timer);
4214 static OSStatus
4215 set_scroll_bar_timer (delay)
4216 EventTimerInterval delay;
4218 if (scroll_bar_timer == NULL)
4219 install_scroll_bar_timer ();
4221 scroll_bar_timer_event_posted_p = 0;
4223 return SetEventLoopTimerNextFireTime (scroll_bar_timer, delay);
4226 static int
4227 control_part_code_to_scroll_bar_part (part_code)
4228 ControlPartCode part_code;
4230 switch (part_code)
4232 case kControlUpButtonPart: return scroll_bar_up_arrow;
4233 case kControlDownButtonPart: return scroll_bar_down_arrow;
4234 case kControlPageUpPart: return scroll_bar_above_handle;
4235 case kControlPageDownPart: return scroll_bar_below_handle;
4236 case kControlIndicatorPart: return scroll_bar_handle;
4239 return -1;
4242 static void
4243 construct_scroll_bar_click (bar, part, bufp)
4244 struct scroll_bar *bar;
4245 int part;
4246 struct input_event *bufp;
4248 bufp->kind = SCROLL_BAR_CLICK_EVENT;
4249 bufp->frame_or_window = bar->window;
4250 bufp->arg = Qnil;
4251 bufp->part = part;
4252 bufp->code = 0;
4253 XSETINT (bufp->x, 0);
4254 XSETINT (bufp->y, 0);
4255 bufp->modifiers = 0;
4258 static OSErr
4259 get_control_part_bounds (ch, part_code, rect)
4260 ControlHandle ch;
4261 ControlPartCode part_code;
4262 Rect *rect;
4264 RgnHandle region = NewRgn ();
4265 OSStatus err;
4267 err = GetControlRegion (ch, part_code, region);
4268 if (err == noErr)
4269 GetRegionBounds (region, rect);
4270 DisposeRgn (region);
4272 return err;
4275 static void
4276 x_scroll_bar_handle_press (bar, part_code, bufp)
4277 struct scroll_bar *bar;
4278 ControlPartCode part_code;
4279 struct input_event *bufp;
4281 int part = control_part_code_to_scroll_bar_part (part_code);
4283 if (part < 0)
4284 return;
4286 if (part != scroll_bar_handle)
4288 construct_scroll_bar_click (bar, part, bufp);
4289 HiliteControl (SCROLL_BAR_CONTROL_HANDLE (bar), part_code);
4290 set_scroll_bar_timer (SCROLL_BAR_FIRST_DELAY);
4293 last_scroll_bar_part = part;
4294 bar->dragging = Qnil;
4295 tracked_scroll_bar = bar;
4298 static void
4299 x_scroll_bar_handle_release (bar, bufp)
4300 struct scroll_bar *bar;
4301 struct input_event *bufp;
4303 if (last_scroll_bar_part != scroll_bar_handle
4304 || !GC_NILP (bar->dragging))
4305 construct_scroll_bar_click (bar, scroll_bar_end_scroll, bufp);
4307 HiliteControl (SCROLL_BAR_CONTROL_HANDLE (bar), 0);
4308 set_scroll_bar_timer (kEventDurationForever);
4310 last_scroll_bar_part = -1;
4311 bar->dragging = Qnil;
4312 tracked_scroll_bar = NULL;
4315 static void
4316 x_scroll_bar_handle_drag (win, bar, mouse_pos, bufp)
4317 WindowPtr win;
4318 struct scroll_bar *bar;
4319 Point mouse_pos;
4320 struct input_event *bufp;
4322 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4324 if (last_scroll_bar_part == scroll_bar_handle)
4326 int top, top_range;
4327 Rect r;
4329 get_control_part_bounds (SCROLL_BAR_CONTROL_HANDLE (bar),
4330 kControlIndicatorPart, &r);
4332 if (GC_NILP (bar->dragging))
4333 XSETINT (bar->dragging, mouse_pos.v - r.top);
4335 top = mouse_pos.v - XINT (bar->dragging) - XINT (bar->track_top);
4336 top_range = (XINT (bar->track_height) - (r.bottom - r.top)) *
4337 (1.0 + (float) GetControlViewSize (ch) / GetControl32BitMaximum (ch))
4338 + .5;
4340 if (top < 0)
4341 top = 0;
4342 if (top > top_range)
4343 top = top_range;
4345 construct_scroll_bar_click (bar, scroll_bar_handle, bufp);
4346 XSETINT (bufp->x, top);
4347 XSETINT (bufp->y, top_range);
4349 else
4351 ControlPartCode part_code;
4352 int unhilite_p = 0, part;
4354 if (ch != FindControlUnderMouse (mouse_pos, win, &part_code))
4355 unhilite_p = 1;
4356 else
4358 part = control_part_code_to_scroll_bar_part (part_code);
4360 switch (last_scroll_bar_part)
4362 case scroll_bar_above_handle:
4363 case scroll_bar_below_handle:
4364 if (part != scroll_bar_above_handle
4365 && part != scroll_bar_below_handle)
4366 unhilite_p = 1;
4367 break;
4369 case scroll_bar_up_arrow:
4370 case scroll_bar_down_arrow:
4371 if (part != scroll_bar_up_arrow
4372 && part != scroll_bar_down_arrow)
4373 unhilite_p = 1;
4374 break;
4378 if (unhilite_p)
4379 HiliteControl (SCROLL_BAR_CONTROL_HANDLE (bar), 0);
4380 else if (part != last_scroll_bar_part
4381 || scroll_bar_timer_event_posted_p)
4383 construct_scroll_bar_click (bar, part, bufp);
4384 last_scroll_bar_part = part;
4385 HiliteControl (SCROLL_BAR_CONTROL_HANDLE (bar), part_code);
4386 set_scroll_bar_timer (SCROLL_BAR_CONTINUOUS_DELAY);
4391 /* Set the thumb size and position of scroll bar BAR. We are currently
4392 displaying PORTION out of a whole WHOLE, and our position POSITION. */
4394 static void
4395 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole)
4396 struct scroll_bar *bar;
4397 int portion, position, whole;
4399 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4401 int value, viewsize, maximum;
4403 if (whole == 0 || XINT (bar->track_height) == 0)
4404 value = 0, viewsize = 1, maximum = 0;
4405 else
4407 value = position;
4408 viewsize = portion;
4409 maximum = max (0, whole - portion);
4412 BLOCK_INPUT;
4414 SetControl32BitMinimum (ch, 0);
4415 SetControl32BitMaximum (ch, maximum);
4416 SetControl32BitValue (ch, value);
4417 SetControlViewSize (ch, viewsize);
4419 UNBLOCK_INPUT;
4422 #endif /* USE_TOOLKIT_SCROLL_BARS */
4426 /************************************************************************
4427 Scroll bars, general
4428 ************************************************************************/
4430 /* Create a scroll bar and return the scroll bar vector for it. W is
4431 the Emacs window on which to create the scroll bar. TOP, LEFT,
4432 WIDTH and HEIGHT are the pixel coordinates and dimensions of the
4433 scroll bar. */
4435 static struct scroll_bar *
4436 x_scroll_bar_create (w, top, left, width, height, disp_top, disp_height)
4437 struct window *w;
4438 int top, left, width, height, disp_top, disp_height;
4440 struct frame *f = XFRAME (w->frame);
4441 struct scroll_bar *bar
4442 = XSCROLL_BAR (Fmake_vector (make_number (SCROLL_BAR_VEC_SIZE), Qnil));
4443 Rect r;
4444 ControlHandle ch;
4446 BLOCK_INPUT;
4448 r.left = left;
4449 r.top = disp_top;
4450 r.right = left + width;
4451 r.bottom = disp_top + disp_height;
4453 #if TARGET_API_MAC_CARBON
4454 ch = NewControl (FRAME_MAC_WINDOW (f), &r, "\p", width < disp_height,
4455 0, 0, 0, kControlScrollBarProc, (long) bar);
4456 #else
4457 ch = NewControl (FRAME_MAC_WINDOW (f), &r, "\p", width < disp_height,
4458 0, 0, 0, scrollBarProc, (long) bar);
4459 #endif
4460 SET_SCROLL_BAR_CONTROL_HANDLE (bar, ch);
4462 XSETWINDOW (bar->window, w);
4463 XSETINT (bar->top, top);
4464 XSETINT (bar->left, left);
4465 XSETINT (bar->width, width);
4466 XSETINT (bar->height, height);
4467 XSETINT (bar->start, 0);
4468 XSETINT (bar->end, 0);
4469 bar->dragging = Qnil;
4470 #ifdef USE_TOOLKIT_SCROLL_BARS
4471 bar->track_top = Qnil;
4472 bar->track_height = Qnil;
4473 #endif
4475 /* Add bar to its frame's list of scroll bars. */
4476 bar->next = FRAME_SCROLL_BARS (f);
4477 bar->prev = Qnil;
4478 XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
4479 if (!NILP (bar->next))
4480 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
4482 UNBLOCK_INPUT;
4483 return bar;
4487 /* Draw BAR's handle in the proper position.
4489 If the handle is already drawn from START to END, don't bother
4490 redrawing it, unless REBUILD is non-zero; in that case, always
4491 redraw it. (REBUILD is handy for drawing the handle after expose
4492 events.)
4494 Normally, we want to constrain the start and end of the handle to
4495 fit inside its rectangle, but if the user is dragging the scroll
4496 bar handle, we want to let them drag it down all the way, so that
4497 the bar's top is as far down as it goes; otherwise, there's no way
4498 to move to the very end of the buffer. */
4500 #ifndef USE_TOOLKIT_SCROLL_BARS
4502 static void
4503 x_scroll_bar_set_handle (bar, start, end, rebuild)
4504 struct scroll_bar *bar;
4505 int start, end;
4506 int rebuild;
4508 int dragging = ! NILP (bar->dragging);
4509 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4510 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4511 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, XINT (bar->height));
4512 int length = end - start;
4514 /* If the display is already accurate, do nothing. */
4515 if (! rebuild
4516 && start == XINT (bar->start)
4517 && end == XINT (bar->end))
4518 return;
4520 BLOCK_INPUT;
4522 /* Make sure the values are reasonable, and try to preserve the
4523 distance between start and end. */
4524 if (start < 0)
4525 start = 0;
4526 else if (start > top_range)
4527 start = top_range;
4528 end = start + length;
4530 if (end < start)
4531 end = start;
4532 else if (end > top_range && ! dragging)
4533 end = top_range;
4535 /* Store the adjusted setting in the scroll bar. */
4536 XSETINT (bar->start, start);
4537 XSETINT (bar->end, end);
4539 /* Clip the end position, just for display. */
4540 if (end > top_range)
4541 end = top_range;
4543 /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels below
4544 top positions, to make sure the handle is always at least that
4545 many pixels tall. */
4546 end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
4548 SetControlMinimum (ch, 0);
4549 /* Don't inadvertently activate deactivated scroll bars */
4550 if (GetControlMaximum (ch) != -1)
4551 SetControlMaximum (ch, top_range + VERTICAL_SCROLL_BAR_MIN_HANDLE
4552 - (end - start));
4553 SetControlValue (ch, start);
4554 #if TARGET_API_MAC_CARBON
4555 SetControlViewSize (ch, end - start);
4556 #endif
4558 UNBLOCK_INPUT;
4561 #endif /* !USE_TOOLKIT_SCROLL_BARS */
4563 /* Destroy scroll bar BAR, and set its Emacs window's scroll bar to
4564 nil. */
4566 static void
4567 x_scroll_bar_remove (bar)
4568 struct scroll_bar *bar;
4570 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4572 BLOCK_INPUT;
4574 /* Destroy the Mac scroll bar control */
4575 DisposeControl (SCROLL_BAR_CONTROL_HANDLE (bar));
4577 /* Disassociate this scroll bar from its window. */
4578 XWINDOW (bar->window)->vertical_scroll_bar = Qnil;
4580 UNBLOCK_INPUT;
4584 /* Set the handle of the vertical scroll bar for WINDOW to indicate
4585 that we are displaying PORTION characters out of a total of WHOLE
4586 characters, starting at POSITION. If WINDOW has no scroll bar,
4587 create one. */
4589 static void
4590 XTset_vertical_scroll_bar (w, portion, whole, position)
4591 struct window *w;
4592 int portion, whole, position;
4594 struct frame *f = XFRAME (w->frame);
4595 struct scroll_bar *bar;
4596 int top, height, left, sb_left, width, sb_width, disp_top, disp_height;
4597 int window_y, window_height;
4599 /* Get window dimensions. */
4600 window_box (w, -1, 0, &window_y, 0, &window_height);
4601 top = window_y;
4602 width = WINDOW_CONFIG_SCROLL_BAR_COLS (w) * FRAME_COLUMN_WIDTH (f);
4603 height = window_height;
4605 /* Compute the left edge of the scroll bar area. */
4606 left = WINDOW_SCROLL_BAR_AREA_X (w);
4608 /* Compute the width of the scroll bar which might be less than
4609 the width of the area reserved for the scroll bar. */
4610 if (WINDOW_CONFIG_SCROLL_BAR_WIDTH (w) > 0)
4611 sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
4612 else
4613 sb_width = width;
4615 /* Compute the left edge of the scroll bar. */
4616 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
4617 sb_left = left;
4618 else
4619 sb_left = left + width - sb_width;
4621 /* Adjustments according to Inside Macintosh to make it look nice */
4622 disp_top = top;
4623 disp_height = height;
4624 if (disp_top == 0)
4626 disp_top = -1;
4627 disp_height++;
4629 else if (disp_top == FRAME_PIXEL_HEIGHT (f) - 16)
4631 disp_top++;
4632 disp_height--;
4635 if (sb_left + sb_width == FRAME_PIXEL_WIDTH (f))
4636 sb_left++;
4638 /* Does the scroll bar exist yet? */
4639 if (NILP (w->vertical_scroll_bar))
4641 BLOCK_INPUT;
4642 mac_clear_area (f, left, top, width, height);
4643 UNBLOCK_INPUT;
4644 bar = x_scroll_bar_create (w, top, sb_left, sb_width, height, disp_top,
4645 disp_height);
4646 XSETVECTOR (w->vertical_scroll_bar, bar);
4648 else
4650 /* It may just need to be moved and resized. */
4651 ControlHandle ch;
4653 bar = XSCROLL_BAR (w->vertical_scroll_bar);
4654 ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4656 BLOCK_INPUT;
4658 /* If already correctly positioned, do nothing. */
4659 if (!(XINT (bar->left) == sb_left
4660 && XINT (bar->top) == top
4661 && XINT (bar->width) == sb_width
4662 && XINT (bar->height) == height))
4664 /* Since toolkit scroll bars are smaller than the space reserved
4665 for them on the frame, we have to clear "under" them. */
4666 mac_clear_area (f, left, top, width, height);
4668 HideControl (ch);
4669 MoveControl (ch, sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM, disp_top);
4670 SizeControl (ch, sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
4671 disp_height);
4672 if (sb_width < disp_height)
4673 ShowControl (ch);
4675 /* Remember new settings. */
4676 XSETINT (bar->left, sb_left);
4677 XSETINT (bar->top, top);
4678 XSETINT (bar->width, sb_width);
4679 XSETINT (bar->height, height);
4680 #ifdef USE_TOOLKIT_SCROLL_BARS
4681 bar->track_top = Qnil;
4682 bar->track_height = Qnil;
4683 #endif
4686 UNBLOCK_INPUT;
4689 #ifdef USE_TOOLKIT_SCROLL_BARS
4690 if (NILP (bar->track_top))
4692 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4693 Rect r0, r1;
4695 BLOCK_INPUT;
4697 SetControl32BitMinimum (ch, 0);
4698 SetControl32BitMaximum (ch, 1);
4699 SetControlViewSize (ch, 1);
4701 /* Move the scroll bar thumb to the top. */
4702 SetControl32BitValue (ch, 0);
4703 get_control_part_bounds (ch, kControlIndicatorPart, &r0);
4705 /* Move the scroll bar thumb to the bottom. */
4706 SetControl32BitValue (ch, 1);
4707 get_control_part_bounds (ch, kControlIndicatorPart, &r1);
4709 UnionRect (&r0, &r1, &r0);
4710 XSETINT (bar->track_top, r0.top);
4711 XSETINT (bar->track_height, r0.bottom - r0.top);
4713 UNBLOCK_INPUT;
4716 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
4717 #else /* not USE_TOOLKIT_SCROLL_BARS */
4718 /* Set the scroll bar's current state, unless we're currently being
4719 dragged. */
4720 if (NILP (bar->dragging))
4722 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, height);
4724 if (whole == 0)
4725 x_scroll_bar_set_handle (bar, 0, top_range, 0);
4726 else
4728 int start = ((double) position * top_range) / whole;
4729 int end = ((double) (position + portion) * top_range) / whole;
4730 x_scroll_bar_set_handle (bar, start, end, 0);
4733 #endif /* not USE_TOOLKIT_SCROLL_BARS */
4737 /* The following three hooks are used when we're doing a thorough
4738 redisplay of the frame. We don't explicitly know which scroll bars
4739 are going to be deleted, because keeping track of when windows go
4740 away is a real pain - "Can you say set-window-configuration, boys
4741 and girls?" Instead, we just assert at the beginning of redisplay
4742 that *all* scroll bars are to be removed, and then save a scroll bar
4743 from the fiery pit when we actually redisplay its window. */
4745 /* Arrange for all scroll bars on FRAME to be removed at the next call
4746 to `*judge_scroll_bars_hook'. A scroll bar may be spared if
4747 `*redeem_scroll_bar_hook' is applied to its window before the judgment. */
4749 static void
4750 XTcondemn_scroll_bars (frame)
4751 FRAME_PTR frame;
4753 /* Transfer all the scroll bars to FRAME_CONDEMNED_SCROLL_BARS. */
4754 while (! NILP (FRAME_SCROLL_BARS (frame)))
4756 Lisp_Object bar;
4757 bar = FRAME_SCROLL_BARS (frame);
4758 FRAME_SCROLL_BARS (frame) = XSCROLL_BAR (bar)->next;
4759 XSCROLL_BAR (bar)->next = FRAME_CONDEMNED_SCROLL_BARS (frame);
4760 XSCROLL_BAR (bar)->prev = Qnil;
4761 if (! NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
4762 XSCROLL_BAR (FRAME_CONDEMNED_SCROLL_BARS (frame))->prev = bar;
4763 FRAME_CONDEMNED_SCROLL_BARS (frame) = bar;
4768 /* Un-mark WINDOW's scroll bar for deletion in this judgment cycle.
4769 Note that WINDOW isn't necessarily condemned at all. */
4771 static void
4772 XTredeem_scroll_bar (window)
4773 struct window *window;
4775 struct scroll_bar *bar;
4776 struct frame *f;
4778 /* We can't redeem this window's scroll bar if it doesn't have one. */
4779 if (NILP (window->vertical_scroll_bar))
4780 abort ();
4782 bar = XSCROLL_BAR (window->vertical_scroll_bar);
4784 /* Unlink it from the condemned list. */
4785 f = XFRAME (WINDOW_FRAME (window));
4786 if (NILP (bar->prev))
4788 /* If the prev pointer is nil, it must be the first in one of
4789 the lists. */
4790 if (EQ (FRAME_SCROLL_BARS (f), window->vertical_scroll_bar))
4791 /* It's not condemned. Everything's fine. */
4792 return;
4793 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
4794 window->vertical_scroll_bar))
4795 FRAME_CONDEMNED_SCROLL_BARS (f) = bar->next;
4796 else
4797 /* If its prev pointer is nil, it must be at the front of
4798 one or the other! */
4799 abort ();
4801 else
4802 XSCROLL_BAR (bar->prev)->next = bar->next;
4804 if (! NILP (bar->next))
4805 XSCROLL_BAR (bar->next)->prev = bar->prev;
4807 bar->next = FRAME_SCROLL_BARS (f);
4808 bar->prev = Qnil;
4809 XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
4810 if (! NILP (bar->next))
4811 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
4814 /* Remove all scroll bars on FRAME that haven't been saved since the
4815 last call to `*condemn_scroll_bars_hook'. */
4817 static void
4818 XTjudge_scroll_bars (f)
4819 FRAME_PTR f;
4821 Lisp_Object bar, next;
4823 bar = FRAME_CONDEMNED_SCROLL_BARS (f);
4825 /* Clear out the condemned list now so we won't try to process any
4826 more events on the hapless scroll bars. */
4827 FRAME_CONDEMNED_SCROLL_BARS (f) = Qnil;
4829 for (; ! NILP (bar); bar = next)
4831 struct scroll_bar *b = XSCROLL_BAR (bar);
4833 x_scroll_bar_remove (b);
4835 next = b->next;
4836 b->next = b->prev = Qnil;
4839 /* Now there should be no references to the condemned scroll bars,
4840 and they should get garbage-collected. */
4844 /* Handle a mouse click on the scroll bar BAR. If *EMACS_EVENT's kind
4845 is set to something other than NO_EVENT, it is enqueued.
4847 This may be called from a signal handler, so we have to ignore GC
4848 mark bits. */
4850 static void
4851 x_scroll_bar_handle_click (bar, part_code, er, bufp)
4852 struct scroll_bar *bar;
4853 ControlPartCode part_code;
4854 EventRecord *er;
4855 struct input_event *bufp;
4857 int win_y, top_range;
4859 if (! GC_WINDOWP (bar->window))
4860 abort ();
4862 bufp->kind = SCROLL_BAR_CLICK_EVENT;
4863 bufp->frame_or_window = bar->window;
4864 bufp->arg = Qnil;
4866 bar->dragging = Qnil;
4868 switch (part_code)
4870 case kControlUpButtonPart:
4871 bufp->part = scroll_bar_up_arrow;
4872 break;
4873 case kControlDownButtonPart:
4874 bufp->part = scroll_bar_down_arrow;
4875 break;
4876 case kControlPageUpPart:
4877 bufp->part = scroll_bar_above_handle;
4878 break;
4879 case kControlPageDownPart:
4880 bufp->part = scroll_bar_below_handle;
4881 break;
4882 #if TARGET_API_MAC_CARBON
4883 default:
4884 #else
4885 case kControlIndicatorPart:
4886 #endif
4887 if (er->what == mouseDown)
4888 bar->dragging = make_number (0);
4889 XSETVECTOR (last_mouse_scroll_bar, bar);
4890 bufp->part = scroll_bar_handle;
4891 break;
4894 win_y = XINT (bufp->y) - XINT (bar->top);
4895 top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (0/*dummy*/, XINT (bar->height));
4897 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
4899 win_y -= 24;
4901 if (! NILP (bar->dragging))
4902 win_y -= XINT (bar->dragging);
4904 if (win_y < 0)
4905 win_y = 0;
4906 if (win_y > top_range)
4907 win_y = top_range;
4909 XSETINT (bufp->x, win_y);
4910 XSETINT (bufp->y, top_range);
4913 #ifndef USE_TOOLKIT_SCROLL_BARS
4915 /* Handle some mouse motion while someone is dragging the scroll bar.
4917 This may be called from a signal handler, so we have to ignore GC
4918 mark bits. */
4920 static void
4921 x_scroll_bar_note_movement (bar, y_pos, t)
4922 struct scroll_bar *bar;
4923 int y_pos;
4924 Time t;
4926 FRAME_PTR f = XFRAME (XWINDOW (bar->window)->frame);
4928 last_mouse_movement_time = t;
4930 f->mouse_moved = 1;
4931 XSETVECTOR (last_mouse_scroll_bar, bar);
4933 /* If we're dragging the bar, display it. */
4934 if (! GC_NILP (bar->dragging))
4936 /* Where should the handle be now? */
4937 int new_start = y_pos - 24;
4939 if (new_start != XINT (bar->start))
4941 int new_end = new_start + (XINT (bar->end) - XINT (bar->start));
4943 x_scroll_bar_set_handle (bar, new_start, new_end, 0);
4948 #endif /* !USE_TOOLKIT_SCROLL_BARS */
4950 /* Return information to the user about the current position of the mouse
4951 on the scroll bar. */
4953 static void
4954 x_scroll_bar_report_motion (fp, bar_window, part, x, y, time)
4955 FRAME_PTR *fp;
4956 Lisp_Object *bar_window;
4957 enum scroll_bar_part *part;
4958 Lisp_Object *x, *y;
4959 unsigned long *time;
4961 struct scroll_bar *bar = XSCROLL_BAR (last_mouse_scroll_bar);
4962 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4963 #if TARGET_API_MAC_CARBON
4964 WindowPtr wp = GetControlOwner (ch);
4965 #else
4966 WindowPtr wp = (*ch)->contrlOwner;
4967 #endif
4968 Point mouse_pos;
4969 struct frame *f = mac_window_to_frame (wp);
4970 int win_y, top_range;
4972 SetPortWindowPort (wp);
4974 GetMouse (&mouse_pos);
4976 win_y = mouse_pos.v - XINT (bar->top);
4977 top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, XINT (bar->height));
4979 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
4981 win_y -= 24;
4983 if (! NILP (bar->dragging))
4984 win_y -= XINT (bar->dragging);
4986 if (win_y < 0)
4987 win_y = 0;
4988 if (win_y > top_range)
4989 win_y = top_range;
4991 *fp = f;
4992 *bar_window = bar->window;
4994 if (! NILP (bar->dragging))
4995 *part = scroll_bar_handle;
4996 else if (win_y < XINT (bar->start))
4997 *part = scroll_bar_above_handle;
4998 else if (win_y < XINT (bar->end) + VERTICAL_SCROLL_BAR_MIN_HANDLE)
4999 *part = scroll_bar_handle;
5000 else
5001 *part = scroll_bar_below_handle;
5003 XSETINT (*x, win_y);
5004 XSETINT (*y, top_range);
5006 f->mouse_moved = 0;
5007 last_mouse_scroll_bar = Qnil;
5009 *time = last_mouse_movement_time;
5013 /* The screen has been cleared so we may have changed foreground or
5014 background colors, and the scroll bars may need to be redrawn.
5015 Clear out the scroll bars, and ask for expose events, so we can
5016 redraw them. */
5018 void
5019 x_scroll_bar_clear (f)
5020 FRAME_PTR f;
5022 XTcondemn_scroll_bars (f);
5023 XTjudge_scroll_bars (f);
5027 /***********************************************************************
5028 Text Cursor
5029 ***********************************************************************/
5031 /* Set clipping for output in glyph row ROW. W is the window in which
5032 we operate. GC is the graphics context to set clipping in.
5034 ROW may be a text row or, e.g., a mode line. Text rows must be
5035 clipped to the interior of the window dedicated to text display,
5036 mode lines must be clipped to the whole window. */
5038 static void
5039 x_clip_to_row (w, row, area, gc)
5040 struct window *w;
5041 struct glyph_row *row;
5042 int area;
5043 GC gc;
5045 struct frame *f = XFRAME (WINDOW_FRAME (w));
5046 Rect clip_rect;
5047 int window_x, window_y, window_width;
5049 window_box (w, area, &window_x, &window_y, &window_width, 0);
5051 clip_rect.left = window_x;
5052 clip_rect.top = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
5053 clip_rect.top = max (clip_rect.top, window_y);
5054 clip_rect.right = clip_rect.left + window_width;
5055 clip_rect.bottom = clip_rect.top + row->visible_height;
5057 mac_set_clip_rectangles (FRAME_MAC_DISPLAY (f), gc, &clip_rect, 1);
5061 /* Draw a hollow box cursor on window W in glyph row ROW. */
5063 static void
5064 x_draw_hollow_cursor (w, row)
5065 struct window *w;
5066 struct glyph_row *row;
5068 struct frame *f = XFRAME (WINDOW_FRAME (w));
5069 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
5070 Display *dpy = FRAME_MAC_DISPLAY (f);
5071 int x, y, wd, h;
5072 XGCValues xgcv;
5073 struct glyph *cursor_glyph;
5074 GC gc;
5076 /* Get the glyph the cursor is on. If we can't tell because
5077 the current matrix is invalid or such, give up. */
5078 cursor_glyph = get_phys_cursor_glyph (w);
5079 if (cursor_glyph == NULL)
5080 return;
5082 /* Compute frame-relative coordinates for phys cursor. */
5083 x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
5084 y = get_phys_cursor_geometry (w, row, cursor_glyph, &h);
5085 wd = w->phys_cursor_width;
5087 /* The foreground of cursor_gc is typically the same as the normal
5088 background color, which can cause the cursor box to be invisible. */
5089 xgcv.foreground = f->output_data.mac->cursor_pixel;
5090 if (dpyinfo->scratch_cursor_gc)
5091 XChangeGC (dpy, dpyinfo->scratch_cursor_gc, GCForeground, &xgcv);
5092 else
5093 dpyinfo->scratch_cursor_gc = XCreateGC (dpy, FRAME_MAC_WINDOW (f),
5094 GCForeground, &xgcv);
5095 gc = dpyinfo->scratch_cursor_gc;
5097 /* Set clipping, draw the rectangle, and reset clipping again. */
5098 x_clip_to_row (w, row, TEXT_AREA, gc);
5099 mac_draw_rectangle (f, gc, x, y, wd, h);
5100 mac_reset_clip_rectangles (dpy, gc);
5104 /* Draw a bar cursor on window W in glyph row ROW.
5106 Implementation note: One would like to draw a bar cursor with an
5107 angle equal to the one given by the font property XA_ITALIC_ANGLE.
5108 Unfortunately, I didn't find a font yet that has this property set.
5109 --gerd. */
5111 static void
5112 x_draw_bar_cursor (w, row, width, kind)
5113 struct window *w;
5114 struct glyph_row *row;
5115 int width;
5116 enum text_cursor_kinds kind;
5118 struct frame *f = XFRAME (w->frame);
5119 struct glyph *cursor_glyph;
5121 /* If cursor is out of bounds, don't draw garbage. This can happen
5122 in mini-buffer windows when switching between echo area glyphs
5123 and mini-buffer. */
5124 cursor_glyph = get_phys_cursor_glyph (w);
5125 if (cursor_glyph == NULL)
5126 return;
5128 /* If on an image, draw like a normal cursor. That's usually better
5129 visible than drawing a bar, esp. if the image is large so that
5130 the bar might not be in the window. */
5131 if (cursor_glyph->type == IMAGE_GLYPH)
5133 struct glyph_row *row;
5134 row = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos);
5135 draw_phys_cursor_glyph (w, row, DRAW_CURSOR);
5137 else
5139 Display *dpy = FRAME_MAC_DISPLAY (f);
5140 Window window = FRAME_MAC_WINDOW (f);
5141 GC gc = FRAME_MAC_DISPLAY_INFO (f)->scratch_cursor_gc;
5142 unsigned long mask = GCForeground | GCBackground;
5143 struct face *face = FACE_FROM_ID (f, cursor_glyph->face_id);
5144 XGCValues xgcv;
5146 /* If the glyph's background equals the color we normally draw
5147 the bar cursor in, the bar cursor in its normal color is
5148 invisible. Use the glyph's foreground color instead in this
5149 case, on the assumption that the glyph's colors are chosen so
5150 that the glyph is legible. */
5151 if (face->background == f->output_data.mac->cursor_pixel)
5152 xgcv.background = xgcv.foreground = face->foreground;
5153 else
5154 xgcv.background = xgcv.foreground = f->output_data.mac->cursor_pixel;
5156 if (gc)
5157 XChangeGC (dpy, gc, mask, &xgcv);
5158 else
5160 gc = XCreateGC (dpy, window, mask, &xgcv);
5161 FRAME_MAC_DISPLAY_INFO (f)->scratch_cursor_gc = gc;
5164 if (width < 0)
5165 width = FRAME_CURSOR_WIDTH (f);
5166 width = min (cursor_glyph->pixel_width, width);
5168 w->phys_cursor_width = width;
5169 x_clip_to_row (w, row, TEXT_AREA, gc);
5171 if (kind == BAR_CURSOR)
5172 mac_fill_rectangle (f, gc,
5173 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x),
5174 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
5175 width, row->height);
5176 else
5177 mac_fill_rectangle (f, gc,
5178 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x),
5179 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y +
5180 row->height - width),
5181 cursor_glyph->pixel_width,
5182 width);
5184 mac_reset_clip_rectangles (dpy, gc);
5189 /* RIF: Define cursor CURSOR on frame F. */
5191 static void
5192 mac_define_frame_cursor (f, cursor)
5193 struct frame *f;
5194 Cursor cursor;
5196 SetThemeCursor (cursor);
5200 /* RIF: Clear area on frame F. */
5202 static void
5203 mac_clear_frame_area (f, x, y, width, height)
5204 struct frame *f;
5205 int x, y, width, height;
5207 mac_clear_area (f, x, y, width, height);
5211 /* RIF: Draw cursor on window W. */
5213 static void
5214 mac_draw_window_cursor (w, glyph_row, x, y, cursor_type, cursor_width, on_p, active_p)
5215 struct window *w;
5216 struct glyph_row *glyph_row;
5217 int x, y;
5218 int cursor_type, cursor_width;
5219 int on_p, active_p;
5221 if (on_p)
5223 w->phys_cursor_type = cursor_type;
5224 w->phys_cursor_on_p = 1;
5226 if (glyph_row->exact_window_width_line_p
5227 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
5229 glyph_row->cursor_in_fringe_p = 1;
5230 draw_fringe_bitmap (w, glyph_row, 0);
5232 else
5233 switch (cursor_type)
5235 case HOLLOW_BOX_CURSOR:
5236 x_draw_hollow_cursor (w, glyph_row);
5237 break;
5239 case FILLED_BOX_CURSOR:
5240 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
5241 break;
5243 case BAR_CURSOR:
5244 x_draw_bar_cursor (w, glyph_row, cursor_width, BAR_CURSOR);
5245 break;
5247 case HBAR_CURSOR:
5248 x_draw_bar_cursor (w, glyph_row, cursor_width, HBAR_CURSOR);
5249 break;
5251 case NO_CURSOR:
5252 w->phys_cursor_width = 0;
5253 break;
5255 default:
5256 abort ();
5262 /* Icons. */
5264 #if 0 /* MAC_TODO: no icon support yet. */
5266 x_bitmap_icon (f, icon)
5267 struct frame *f;
5268 Lisp_Object icon;
5270 HANDLE hicon;
5272 if (FRAME_W32_WINDOW (f) == 0)
5273 return 1;
5275 if (NILP (icon))
5276 hicon = LoadIcon (hinst, EMACS_CLASS);
5277 else if (STRINGP (icon))
5278 hicon = LoadImage (NULL, (LPCTSTR) SDATA (icon), IMAGE_ICON, 0, 0,
5279 LR_DEFAULTSIZE | LR_LOADFROMFILE);
5280 else if (SYMBOLP (icon))
5282 LPCTSTR name;
5284 if (EQ (icon, intern ("application")))
5285 name = (LPCTSTR) IDI_APPLICATION;
5286 else if (EQ (icon, intern ("hand")))
5287 name = (LPCTSTR) IDI_HAND;
5288 else if (EQ (icon, intern ("question")))
5289 name = (LPCTSTR) IDI_QUESTION;
5290 else if (EQ (icon, intern ("exclamation")))
5291 name = (LPCTSTR) IDI_EXCLAMATION;
5292 else if (EQ (icon, intern ("asterisk")))
5293 name = (LPCTSTR) IDI_ASTERISK;
5294 else if (EQ (icon, intern ("winlogo")))
5295 name = (LPCTSTR) IDI_WINLOGO;
5296 else
5297 return 1;
5299 hicon = LoadIcon (NULL, name);
5301 else
5302 return 1;
5304 if (hicon == NULL)
5305 return 1;
5307 PostMessage (FRAME_W32_WINDOW (f), WM_SETICON, (WPARAM) ICON_BIG,
5308 (LPARAM) hicon);
5310 return 0;
5312 #endif /* MAC_TODO */
5314 /************************************************************************
5315 Handling X errors
5316 ************************************************************************/
5318 /* Display Error Handling functions not used on W32. Listing them here
5319 helps diff stay in step when comparing w32term.c with xterm.c.
5321 x_error_catcher (display, error)
5322 x_catch_errors (dpy)
5323 x_catch_errors_unwind (old_val)
5324 x_check_errors (dpy, format)
5325 x_had_errors_p (dpy)
5326 x_clear_errors (dpy)
5327 x_uncatch_errors (dpy, count)
5328 x_trace_wire ()
5329 x_connection_signal (signalnum)
5330 x_connection_closed (dpy, error_message)
5331 x_error_quitter (display, error)
5332 x_error_handler (display, error)
5333 x_io_error_quitter (display)
5338 /* Changing the font of the frame. */
5340 /* Give frame F the font named FONTNAME as its default font, and
5341 return the full name of that font. FONTNAME may be a wildcard
5342 pattern; in that case, we choose some font that fits the pattern.
5343 The return value shows which font we chose. */
5345 Lisp_Object
5346 x_new_font (f, fontname)
5347 struct frame *f;
5348 register char *fontname;
5350 struct font_info *fontp
5351 = FS_LOAD_FONT (f, 0, fontname, -1);
5353 if (!fontp)
5354 return Qnil;
5356 FRAME_FONT (f) = (XFontStruct *) (fontp->font);
5357 FRAME_BASELINE_OFFSET (f) = fontp->baseline_offset;
5358 FRAME_FONTSET (f) = -1;
5360 FRAME_COLUMN_WIDTH (f) = fontp->average_width;
5361 FRAME_SPACE_WIDTH (f) = fontp->space_width;
5362 FRAME_LINE_HEIGHT (f) = FONT_HEIGHT (FRAME_FONT (f));
5364 compute_fringe_widths (f, 1);
5366 /* Compute the scroll bar width in character columns. */
5367 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
5369 int wid = FRAME_COLUMN_WIDTH (f);
5370 FRAME_CONFIG_SCROLL_BAR_COLS (f)
5371 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid-1) / wid;
5373 else
5375 int wid = FRAME_COLUMN_WIDTH (f);
5376 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
5379 /* Now make the frame display the given font. */
5380 if (FRAME_MAC_WINDOW (f) != 0)
5382 XSetFont (FRAME_MAC_DISPLAY (f), f->output_data.mac->normal_gc,
5383 FRAME_FONT (f));
5384 XSetFont (FRAME_MAC_DISPLAY (f), f->output_data.mac->reverse_gc,
5385 FRAME_FONT (f));
5386 XSetFont (FRAME_MAC_DISPLAY (f), f->output_data.mac->cursor_gc,
5387 FRAME_FONT (f));
5389 /* Don't change the size of a tip frame; there's no point in
5390 doing it because it's done in Fx_show_tip, and it leads to
5391 problems because the tip frame has no widget. */
5392 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
5393 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
5396 return build_string (fontp->full_name);
5399 /* Give frame F the fontset named FONTSETNAME as its default font, and
5400 return the full name of that fontset. FONTSETNAME may be a wildcard
5401 pattern; in that case, we choose some fontset that fits the pattern.
5402 The return value shows which fontset we chose. */
5404 Lisp_Object
5405 x_new_fontset (f, fontsetname)
5406 struct frame *f;
5407 char *fontsetname;
5409 int fontset = fs_query_fontset (build_string (fontsetname), 0);
5410 Lisp_Object result;
5412 if (fontset < 0)
5413 return Qnil;
5415 if (FRAME_FONTSET (f) == fontset)
5416 /* This fontset is already set in frame F. There's nothing more
5417 to do. */
5418 return fontset_name (fontset);
5420 result = x_new_font (f, (SDATA (fontset_ascii (fontset))));
5422 if (!STRINGP (result))
5423 /* Can't load ASCII font. */
5424 return Qnil;
5426 /* Since x_new_font doesn't update any fontset information, do it now. */
5427 FRAME_FONTSET (f) = fontset;
5429 return build_string (fontsetname);
5433 /***********************************************************************
5434 TODO: W32 Input Methods
5435 ***********************************************************************/
5436 /* Listing missing functions from xterm.c helps diff stay in step.
5438 xim_destroy_callback (xim, client_data, call_data)
5439 xim_open_dpy (dpyinfo, resource_name)
5440 struct xim_inst_t
5441 xim_instantiate_callback (display, client_data, call_data)
5442 xim_initialize (dpyinfo, resource_name)
5443 xim_close_dpy (dpyinfo)
5448 void
5449 mac_get_window_bounds (f, inner, outer)
5450 struct frame *f;
5451 Rect *inner, *outer;
5453 #if TARGET_API_MAC_CARBON
5454 GetWindowBounds (FRAME_MAC_WINDOW (f), kWindowContentRgn, inner);
5455 GetWindowBounds (FRAME_MAC_WINDOW (f), kWindowStructureRgn, outer);
5456 #else /* not TARGET_API_MAC_CARBON */
5457 RgnHandle region = NewRgn ();
5459 GetWindowRegion (FRAME_MAC_WINDOW (f), kWindowContentRgn, region);
5460 *inner = (*region)->rgnBBox;
5461 GetWindowRegion (FRAME_MAC_WINDOW (f), kWindowStructureRgn, region);
5462 *outer = (*region)->rgnBBox;
5463 DisposeRgn (region);
5464 #endif /* not TARGET_API_MAC_CARBON */
5469 /* Calculate the absolute position in frame F
5470 from its current recorded position values and gravity. */
5472 void
5473 x_calc_absolute_position (f)
5474 struct frame *f;
5476 int width_diff = 0, height_diff = 0;
5477 int flags = f->size_hint_flags;
5478 Rect inner, outer;
5480 /* We have nothing to do if the current position
5481 is already for the top-left corner. */
5482 if (! ((flags & XNegative) || (flags & YNegative)))
5483 return;
5485 /* Find the offsets of the outside upper-left corner of
5486 the inner window, with respect to the outer window. */
5487 mac_get_window_bounds (f, &inner, &outer);
5489 width_diff = (outer.right - outer.left) - (inner.right - inner.left);
5490 height_diff = (outer.bottom - outer.top) - (inner.bottom - inner.top);
5492 /* Treat negative positions as relative to the leftmost bottommost
5493 position that fits on the screen. */
5494 if (flags & XNegative)
5495 f->left_pos = (FRAME_MAC_DISPLAY_INFO (f)->width
5496 - width_diff
5497 - FRAME_PIXEL_WIDTH (f)
5498 + f->left_pos);
5500 if (flags & YNegative)
5501 f->top_pos = (FRAME_MAC_DISPLAY_INFO (f)->height
5502 - height_diff
5503 - FRAME_PIXEL_HEIGHT (f)
5504 + f->top_pos);
5506 /* The left_pos and top_pos
5507 are now relative to the top and left screen edges,
5508 so the flags should correspond. */
5509 f->size_hint_flags &= ~ (XNegative | YNegative);
5512 /* CHANGE_GRAVITY is 1 when calling from Fset_frame_position,
5513 to really change the position, and 0 when calling from
5514 x_make_frame_visible (in that case, XOFF and YOFF are the current
5515 position values). It is -1 when calling from x_set_frame_parameters,
5516 which means, do adjust for borders but don't change the gravity. */
5518 void
5519 x_set_offset (f, xoff, yoff, change_gravity)
5520 struct frame *f;
5521 register int xoff, yoff;
5522 int change_gravity;
5524 if (change_gravity > 0)
5526 f->top_pos = yoff;
5527 f->left_pos = xoff;
5528 f->size_hint_flags &= ~ (XNegative | YNegative);
5529 if (xoff < 0)
5530 f->size_hint_flags |= XNegative;
5531 if (yoff < 0)
5532 f->size_hint_flags |= YNegative;
5533 f->win_gravity = NorthWestGravity;
5535 x_calc_absolute_position (f);
5537 BLOCK_INPUT;
5538 x_wm_set_size_hint (f, (long) 0, 0);
5540 #if TARGET_API_MAC_CARBON
5541 MoveWindowStructure (FRAME_MAC_WINDOW (f), f->left_pos, f->top_pos);
5542 /* If the title bar is completely outside the screen, adjust the
5543 position. */
5544 ConstrainWindowToScreen (FRAME_MAC_WINDOW (f), kWindowTitleBarRgn,
5545 kWindowConstrainMoveRegardlessOfFit
5546 | kWindowConstrainAllowPartial, NULL, NULL);
5547 x_real_positions (f, &f->left_pos, &f->top_pos);
5548 #else
5550 Rect inner, outer, screen_rect, dummy;
5551 RgnHandle region = NewRgn ();
5553 mac_get_window_bounds (f, &inner, &outer);
5554 f->x_pixels_diff = inner.left - outer.left;
5555 f->y_pixels_diff = inner.top - outer.top;
5556 MoveWindow (FRAME_MAC_WINDOW (f), f->left_pos + f->x_pixels_diff,
5557 f->top_pos + f->y_pixels_diff, false);
5559 /* If the title bar is completely outside the screen, adjust the
5560 position. The variable `outer' holds the title bar rectangle.
5561 The variable `inner' holds slightly smaller one than `outer',
5562 so that the calculation of overlapping may not become too
5563 strict. */
5564 GetWindowRegion (FRAME_MAC_WINDOW (f), kWindowTitleBarRgn, region);
5565 outer = (*region)->rgnBBox;
5566 DisposeRgn (region);
5567 inner = outer;
5568 InsetRect (&inner, 8, 8);
5569 screen_rect = qd.screenBits.bounds;
5570 screen_rect.top += GetMBarHeight ();
5572 if (!SectRect (&inner, &screen_rect, &dummy))
5574 if (inner.right <= screen_rect.left)
5575 f->left_pos = screen_rect.left;
5576 else if (inner.left >= screen_rect.right)
5577 f->left_pos = screen_rect.right - (outer.right - outer.left);
5579 if (inner.bottom <= screen_rect.top)
5580 f->top_pos = screen_rect.top;
5581 else if (inner.top >= screen_rect.bottom)
5582 f->top_pos = screen_rect.bottom - (outer.bottom - outer.top);
5584 MoveWindow (FRAME_MAC_WINDOW (f), f->left_pos + f->x_pixels_diff,
5585 f->top_pos + f->y_pixels_diff, false);
5588 #endif
5590 UNBLOCK_INPUT;
5593 /* Call this to change the size of frame F's x-window.
5594 If CHANGE_GRAVITY is 1, we change to top-left-corner window gravity
5595 for this size change and subsequent size changes.
5596 Otherwise we leave the window gravity unchanged. */
5598 void
5599 x_set_window_size (f, change_gravity, cols, rows)
5600 struct frame *f;
5601 int change_gravity;
5602 int cols, rows;
5604 int pixelwidth, pixelheight;
5606 BLOCK_INPUT;
5608 check_frame_size (f, &rows, &cols);
5609 f->scroll_bar_actual_width
5610 = FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f);
5612 compute_fringe_widths (f, 0);
5614 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols);
5615 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
5617 f->win_gravity = NorthWestGravity;
5618 x_wm_set_size_hint (f, (long) 0, 0);
5620 SizeWindow (FRAME_MAC_WINDOW (f), pixelwidth, pixelheight, 0);
5621 #if TARGET_API_MAC_CARBON
5622 if (f->output_data.mac->hourglass_control)
5623 MoveControl (f->output_data.mac->hourglass_control,
5624 pixelwidth - HOURGLASS_WIDTH, 0);
5625 #endif
5627 /* Now, strictly speaking, we can't be sure that this is accurate,
5628 but the window manager will get around to dealing with the size
5629 change request eventually, and we'll hear how it went when the
5630 ConfigureNotify event gets here.
5632 We could just not bother storing any of this information here,
5633 and let the ConfigureNotify event set everything up, but that
5634 might be kind of confusing to the Lisp code, since size changes
5635 wouldn't be reported in the frame parameters until some random
5636 point in the future when the ConfigureNotify event arrives.
5638 We pass 1 for DELAY since we can't run Lisp code inside of
5639 a BLOCK_INPUT. */
5640 change_frame_size (f, rows, cols, 0, 1, 0);
5641 FRAME_PIXEL_WIDTH (f) = pixelwidth;
5642 FRAME_PIXEL_HEIGHT (f) = pixelheight;
5644 /* We've set {FRAME,PIXEL}_{WIDTH,HEIGHT} to the values we hope to
5645 receive in the ConfigureNotify event; if we get what we asked
5646 for, then the event won't cause the screen to become garbaged, so
5647 we have to make sure to do it here. */
5648 SET_FRAME_GARBAGED (f);
5650 XFlush (FRAME_X_DISPLAY (f));
5652 /* If cursor was outside the new size, mark it as off. */
5653 mark_window_cursors_off (XWINDOW (f->root_window));
5655 /* Clear out any recollection of where the mouse highlighting was,
5656 since it might be in a place that's outside the new frame size.
5657 Actually checking whether it is outside is a pain in the neck,
5658 so don't try--just let the highlighting be done afresh with new size. */
5659 cancel_mouse_face (f);
5661 UNBLOCK_INPUT;
5664 /* Mouse warping. */
5666 void x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y);
5668 void
5669 x_set_mouse_position (f, x, y)
5670 struct frame *f;
5671 int x, y;
5673 int pix_x, pix_y;
5675 pix_x = FRAME_COL_TO_PIXEL_X (f, x) + FRAME_COLUMN_WIDTH (f) / 2;
5676 pix_y = FRAME_LINE_TO_PIXEL_Y (f, y) + FRAME_LINE_HEIGHT (f) / 2;
5678 if (pix_x < 0) pix_x = 0;
5679 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
5681 if (pix_y < 0) pix_y = 0;
5682 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
5684 x_set_mouse_pixel_position (f, pix_x, pix_y);
5687 void
5688 x_set_mouse_pixel_position (f, pix_x, pix_y)
5689 struct frame *f;
5690 int pix_x, pix_y;
5692 #if 0 /* MAC_TODO: CursorDeviceMoveTo is non-Carbon */
5693 BLOCK_INPUT;
5695 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
5696 0, 0, 0, 0, pix_x, pix_y);
5697 UNBLOCK_INPUT;
5698 #endif
5701 /* focus shifting, raising and lowering. */
5703 void
5704 x_focus_on_frame (f)
5705 struct frame *f;
5707 #if 0 /* This proves to be unpleasant. */
5708 x_raise_frame (f);
5709 #endif
5710 #if 0
5711 /* I don't think that the ICCCM allows programs to do things like this
5712 without the interaction of the window manager. Whatever you end up
5713 doing with this code, do it to x_unfocus_frame too. */
5714 XSetInputFocus (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5715 RevertToPointerRoot, CurrentTime);
5716 #endif /* ! 0 */
5719 void
5720 x_unfocus_frame (f)
5721 struct frame *f;
5725 /* Raise frame F. */
5727 void
5728 x_raise_frame (f)
5729 struct frame *f;
5731 if (f->async_visible)
5733 BLOCK_INPUT;
5734 SelectWindow (FRAME_MAC_WINDOW (f));
5735 UNBLOCK_INPUT;
5739 /* Lower frame F. */
5741 void
5742 x_lower_frame (f)
5743 struct frame *f;
5745 if (f->async_visible)
5747 BLOCK_INPUT;
5748 SendBehind (FRAME_MAC_WINDOW (f), nil);
5749 UNBLOCK_INPUT;
5753 static void
5754 XTframe_raise_lower (f, raise_flag)
5755 FRAME_PTR f;
5756 int raise_flag;
5758 if (raise_flag)
5759 x_raise_frame (f);
5760 else
5761 x_lower_frame (f);
5764 /* Change of visibility. */
5766 static void
5767 mac_handle_visibility_change (f)
5768 struct frame *f;
5770 WindowPtr wp = FRAME_MAC_WINDOW (f);
5771 int visible = 0, iconified = 0;
5772 struct input_event buf;
5774 if (IsWindowVisible (wp))
5775 if (IsWindowCollapsed (wp))
5776 iconified = 1;
5777 else
5778 visible = 1;
5780 if (!f->async_visible && visible)
5782 if (f->iconified)
5784 /* wait_reading_process_output will notice this and update
5785 the frame's display structures. If we were made
5786 invisible, we should not set garbaged, because that stops
5787 redrawing on Update events. */
5788 SET_FRAME_GARBAGED (f);
5790 EVENT_INIT (buf);
5791 buf.kind = DEICONIFY_EVENT;
5792 XSETFRAME (buf.frame_or_window, f);
5793 kbd_buffer_store_event (&buf);
5795 else if (! NILP (Vframe_list) && ! NILP (XCDR (Vframe_list)))
5796 /* Force a redisplay sooner or later to update the
5797 frame titles in case this is the second frame. */
5798 record_asynch_buffer_change ();
5800 else if (f->async_visible && !visible)
5801 if (iconified)
5803 EVENT_INIT (buf);
5804 buf.kind = ICONIFY_EVENT;
5805 XSETFRAME (buf.frame_or_window, f);
5806 kbd_buffer_store_event (&buf);
5809 f->async_visible = visible;
5810 f->async_iconified = iconified;
5813 /* This tries to wait until the frame is really visible.
5814 However, if the window manager asks the user where to position
5815 the frame, this will return before the user finishes doing that.
5816 The frame will not actually be visible at that time,
5817 but it will become visible later when the window manager
5818 finishes with it. */
5820 void
5821 x_make_frame_visible (f)
5822 struct frame *f;
5824 Lisp_Object type;
5825 int original_top, original_left;
5827 BLOCK_INPUT;
5829 if (! FRAME_VISIBLE_P (f))
5831 /* We test FRAME_GARBAGED_P here to make sure we don't
5832 call x_set_offset a second time
5833 if we get to x_make_frame_visible a second time
5834 before the window gets really visible. */
5835 if (! FRAME_ICONIFIED_P (f)
5836 && ! f->output_data.mac->asked_for_visible)
5837 #if TARGET_API_MAC_CARBON
5838 if (!(FRAME_SIZE_HINTS (f)->flags & (USPosition | PPosition)))
5840 struct frame *sf = SELECTED_FRAME ();
5841 if (!FRAME_MAC_P (sf))
5842 RepositionWindow (FRAME_MAC_WINDOW (f), NULL,
5843 kWindowCenterOnMainScreen);
5844 else
5845 RepositionWindow (FRAME_MAC_WINDOW (f),
5846 FRAME_MAC_WINDOW (sf),
5847 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
5848 kWindowCascadeStartAtParentWindowScreen
5849 #else
5850 kWindowCascadeOnParentWindowScreen
5851 #endif
5853 x_real_positions (f, &f->left_pos, &f->top_pos);
5855 else
5856 #endif
5857 x_set_offset (f, f->left_pos, f->top_pos, 0);
5859 f->output_data.mac->asked_for_visible = 1;
5861 SelectWindow (FRAME_MAC_WINDOW (f));
5862 CollapseWindow (FRAME_MAC_WINDOW (f), false);
5863 ShowWindow (FRAME_MAC_WINDOW (f));
5866 XFlush (FRAME_MAC_DISPLAY (f));
5868 /* Synchronize to ensure Emacs knows the frame is visible
5869 before we do anything else. We do this loop with input not blocked
5870 so that incoming events are handled. */
5872 Lisp_Object frame;
5873 int count;
5875 /* This must come after we set COUNT. */
5876 UNBLOCK_INPUT;
5878 XSETFRAME (frame, f);
5880 /* Wait until the frame is visible. Process X events until a
5881 MapNotify event has been seen, or until we think we won't get a
5882 MapNotify at all.. */
5883 for (count = input_signal_count + 10;
5884 input_signal_count < count && !FRAME_VISIBLE_P (f);)
5886 /* Force processing of queued events. */
5887 x_sync (f);
5889 /* Machines that do polling rather than SIGIO have been
5890 observed to go into a busy-wait here. So we'll fake an
5891 alarm signal to let the handler know that there's something
5892 to be read. We used to raise a real alarm, but it seems
5893 that the handler isn't always enabled here. This is
5894 probably a bug. */
5895 if (input_polling_used ())
5897 /* It could be confusing if a real alarm arrives while
5898 processing the fake one. Turn it off and let the
5899 handler reset it. */
5900 extern void poll_for_input_1 P_ ((void));
5901 int old_poll_suppress_count = poll_suppress_count;
5902 poll_suppress_count = 1;
5903 poll_for_input_1 ();
5904 poll_suppress_count = old_poll_suppress_count;
5907 /* See if a MapNotify event has been processed. */
5908 FRAME_SAMPLE_VISIBILITY (f);
5913 /* Change from mapped state to withdrawn state. */
5915 /* Make the frame visible (mapped and not iconified). */
5917 void
5918 x_make_frame_invisible (f)
5919 struct frame *f;
5921 /* A deactivate event does not occur when the last visible frame is
5922 made invisible. So if we clear the highlight here, it will not
5923 be rehighlighted when it is made visible. */
5924 #if 0
5925 /* Don't keep the highlight on an invisible frame. */
5926 if (FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame == f)
5927 FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame = 0;
5928 #endif
5930 BLOCK_INPUT;
5932 /* Before unmapping the window, update the WM_SIZE_HINTS property to claim
5933 that the current position of the window is user-specified, rather than
5934 program-specified, so that when the window is mapped again, it will be
5935 placed at the same location, without forcing the user to position it
5936 by hand again (they have already done that once for this window.) */
5937 x_wm_set_size_hint (f, (long) 0, 1);
5939 HideWindow (FRAME_MAC_WINDOW (f));
5941 UNBLOCK_INPUT;
5943 #if !USE_CARBON_EVENTS
5944 mac_handle_visibility_change (f);
5945 #endif
5948 /* Change window state from mapped to iconified. */
5950 void
5951 x_iconify_frame (f)
5952 struct frame *f;
5954 OSErr err;
5956 /* A deactivate event does not occur when the last visible frame is
5957 iconified. So if we clear the highlight here, it will not be
5958 rehighlighted when it is deiconified. */
5959 #if 0
5960 /* Don't keep the highlight on an invisible frame. */
5961 if (FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame == f)
5962 FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame = 0;
5963 #endif
5965 if (f->async_iconified)
5966 return;
5968 BLOCK_INPUT;
5970 FRAME_SAMPLE_VISIBILITY (f);
5972 if (! FRAME_VISIBLE_P (f))
5973 ShowWindow (FRAME_MAC_WINDOW (f));
5975 err = CollapseWindow (FRAME_MAC_WINDOW (f), true);
5977 UNBLOCK_INPUT;
5979 if (err != noErr)
5980 error ("Can't notify window manager of iconification");
5982 #if !USE_CARBON_EVENTS
5983 mac_handle_visibility_change (f);
5984 #endif
5988 /* Free X resources of frame F. */
5990 void
5991 x_free_frame_resources (f)
5992 struct frame *f;
5994 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
5995 WindowPtr wp = FRAME_MAC_WINDOW (f);
5997 BLOCK_INPUT;
5999 if (wp != tip_window)
6000 remove_window_handler (wp);
6002 DisposeWindow (wp);
6003 if (wp == tip_window)
6004 /* Neither WaitNextEvent nor ReceiveNextEvent receives `window
6005 closed' event. So we reset tip_window here. */
6006 tip_window = NULL;
6008 free_frame_menubar (f);
6010 if (FRAME_FACE_CACHE (f))
6011 free_frame_faces (f);
6013 x_free_gcs (f);
6015 if (FRAME_SIZE_HINTS (f))
6016 xfree (FRAME_SIZE_HINTS (f));
6018 xfree (f->output_data.mac);
6019 f->output_data.mac = NULL;
6021 if (f == dpyinfo->x_focus_frame)
6022 dpyinfo->x_focus_frame = 0;
6023 if (f == dpyinfo->x_focus_event_frame)
6024 dpyinfo->x_focus_event_frame = 0;
6025 if (f == dpyinfo->x_highlight_frame)
6026 dpyinfo->x_highlight_frame = 0;
6028 if (f == dpyinfo->mouse_face_mouse_frame)
6030 dpyinfo->mouse_face_beg_row
6031 = dpyinfo->mouse_face_beg_col = -1;
6032 dpyinfo->mouse_face_end_row
6033 = dpyinfo->mouse_face_end_col = -1;
6034 dpyinfo->mouse_face_window = Qnil;
6035 dpyinfo->mouse_face_deferred_gc = 0;
6036 dpyinfo->mouse_face_mouse_frame = 0;
6039 UNBLOCK_INPUT;
6043 /* Destroy the X window of frame F. */
6045 void
6046 x_destroy_window (f)
6047 struct frame *f;
6049 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
6051 x_free_frame_resources (f);
6053 dpyinfo->reference_count--;
6057 /* Setting window manager hints. */
6059 /* Set the normal size hints for the window manager, for frame F.
6060 FLAGS is the flags word to use--or 0 meaning preserve the flags
6061 that the window now has.
6062 If USER_POSITION is nonzero, we set the USPosition
6063 flag (this is useful when FLAGS is 0). */
6064 void
6065 x_wm_set_size_hint (f, flags, user_position)
6066 struct frame *f;
6067 long flags;
6068 int user_position;
6070 int base_width, base_height, width_inc, height_inc;
6071 int min_rows = 0, min_cols = 0;
6072 XSizeHints *size_hints;
6074 base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
6075 base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
6076 width_inc = FRAME_COLUMN_WIDTH (f);
6077 height_inc = FRAME_LINE_HEIGHT (f);
6079 check_frame_size (f, &min_rows, &min_cols);
6081 size_hints = FRAME_SIZE_HINTS (f);
6082 if (size_hints == NULL)
6084 size_hints = FRAME_SIZE_HINTS (f) = xmalloc (sizeof (XSizeHints));
6085 bzero (size_hints, sizeof (XSizeHints));
6088 size_hints->flags |= PResizeInc | PMinSize | PBaseSize ;
6089 size_hints->width_inc = width_inc;
6090 size_hints->height_inc = height_inc;
6091 size_hints->min_width = base_width + min_cols * width_inc;
6092 size_hints->min_height = base_height + min_rows * height_inc;
6093 size_hints->base_width = base_width;
6094 size_hints->base_height = base_height;
6096 if (flags)
6097 size_hints->flags = flags;
6098 else if (user_position)
6100 size_hints->flags &= ~ PPosition;
6101 size_hints->flags |= USPosition;
6105 #if 0 /* MAC_TODO: hide application instead of iconify? */
6106 /* Used for IconicState or NormalState */
6108 void
6109 x_wm_set_window_state (f, state)
6110 struct frame *f;
6111 int state;
6113 #ifdef USE_X_TOOLKIT
6114 Arg al[1];
6116 XtSetArg (al[0], XtNinitialState, state);
6117 XtSetValues (f->output_data.x->widget, al, 1);
6118 #else /* not USE_X_TOOLKIT */
6119 Window window = FRAME_X_WINDOW (f);
6121 f->output_data.x->wm_hints.flags |= StateHint;
6122 f->output_data.x->wm_hints.initial_state = state;
6124 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
6125 #endif /* not USE_X_TOOLKIT */
6128 void
6129 x_wm_set_icon_pixmap (f, pixmap_id)
6130 struct frame *f;
6131 int pixmap_id;
6133 Pixmap icon_pixmap;
6135 #ifndef USE_X_TOOLKIT
6136 Window window = FRAME_X_WINDOW (f);
6137 #endif
6139 if (pixmap_id > 0)
6141 icon_pixmap = x_bitmap_pixmap (f, pixmap_id);
6142 f->output_data.x->wm_hints.icon_pixmap = icon_pixmap;
6144 else
6146 /* It seems there is no way to turn off use of an icon pixmap.
6147 The following line does it, only if no icon has yet been created,
6148 for some window managers. But with mwm it crashes.
6149 Some people say it should clear the IconPixmapHint bit in this case,
6150 but that doesn't work, and the X consortium said it isn't the
6151 right thing at all. Since there is no way to win,
6152 best to explicitly give up. */
6153 #if 0
6154 f->output_data.x->wm_hints.icon_pixmap = None;
6155 #else
6156 return;
6157 #endif
6160 #ifdef USE_X_TOOLKIT /* same as in x_wm_set_window_state. */
6163 Arg al[1];
6164 XtSetArg (al[0], XtNiconPixmap, icon_pixmap);
6165 XtSetValues (f->output_data.x->widget, al, 1);
6168 #else /* not USE_X_TOOLKIT */
6170 f->output_data.x->wm_hints.flags |= IconPixmapHint;
6171 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
6173 #endif /* not USE_X_TOOLKIT */
6176 #endif /* MAC_TODO */
6178 void
6179 x_wm_set_icon_position (f, icon_x, icon_y)
6180 struct frame *f;
6181 int icon_x, icon_y;
6183 #if 0 /* MAC_TODO: no icons on Mac */
6184 #ifdef USE_X_TOOLKIT
6185 Window window = XtWindow (f->output_data.x->widget);
6186 #else
6187 Window window = FRAME_X_WINDOW (f);
6188 #endif
6190 f->output_data.x->wm_hints.flags |= IconPositionHint;
6191 f->output_data.x->wm_hints.icon_x = icon_x;
6192 f->output_data.x->wm_hints.icon_y = icon_y;
6194 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
6195 #endif /* MAC_TODO */
6199 /***********************************************************************
6200 XLFD Pattern Match
6201 ***********************************************************************/
6203 /* An XLFD pattern is divided into blocks delimited by '*'. This
6204 structure holds information for each block. */
6205 struct xlfdpat_block
6207 /* Length of the pattern string in this block. Non-zero except for
6208 the first and the last blocks. */
6209 int len;
6211 /* Pattern string except the last character in this block. The last
6212 character is replaced with NUL in order to use it as a
6213 sentinel. */
6214 unsigned char *pattern;
6216 /* Last character of the pattern string. Must not be '?'. */
6217 unsigned char last_char;
6219 /* One of the tables for the Boyer-Moore string search. It
6220 specifies the number of positions to proceed for each character
6221 with which the match fails. */
6222 int skip[256];
6224 /* The skip value for the last character in the above `skip' is
6225 assigned to `infinity' in order to simplify a loop condition.
6226 The original value is saved here. */
6227 int last_char_skip;
6230 struct xlfdpat
6232 /* Normalized pattern string. "Normalized" means that capital
6233 letters are lowered, blocks are not empty except the first and
6234 the last ones, and trailing '?'s in a block that is not the last
6235 one are moved to the next one. The last character in each block
6236 is replaced with NUL. */
6237 unsigned char *buf;
6239 /* Number of characters except '*'s and trailing '?'s in the
6240 normalized pattern string. */
6241 int nchars;
6243 /* Number of trailing '?'s in the normalized pattern string. */
6244 int trailing_anychars;
6246 /* Number of blocks and information for each block. The latter is
6247 NULL if the pattern is exact (no '*' or '?' in it). */
6248 int nblocks;
6249 struct xlfdpat_block *blocks;
6252 static void
6253 xlfdpat_destroy (pat)
6254 struct xlfdpat *pat;
6256 if (pat)
6258 if (pat->buf)
6260 if (pat->blocks)
6261 xfree (pat->blocks);
6262 xfree (pat->buf);
6264 xfree (pat);
6268 static struct xlfdpat *
6269 xlfdpat_create (pattern)
6270 char *pattern;
6272 struct xlfdpat *pat;
6273 int nblocks, i, skip;
6274 unsigned char last_char, *p, *q, *anychar_head;
6275 struct xlfdpat_block *blk;
6277 pat = xmalloc (sizeof (struct xlfdpat));
6278 if (pat == NULL)
6279 goto error;
6281 pat->buf = xmalloc (strlen (pattern) + 1);
6282 if (pat->buf == NULL)
6283 goto error;
6285 /* Normalize the pattern string and store it to `pat->buf'. */
6286 nblocks = 0;
6287 anychar_head = NULL;
6288 q = pat->buf;
6289 last_char = '\0';
6290 for (p = pattern; *p; p++)
6292 unsigned char c = *p;
6294 if (c == '*')
6295 if (last_char == '*')
6296 /* ...a** -> ...a* */
6297 continue;
6298 else
6300 if (last_char == '?')
6301 if (anychar_head > pat->buf && *(anychar_head - 1) == '*')
6302 /* ...*??* -> ...*?? */
6303 continue;
6304 else
6305 /* ...a??* -> ...a*?? */
6307 *anychar_head++ = '*';
6308 c = '?';
6310 nblocks++;
6312 else if (c == '?')
6314 if (last_char != '?')
6315 anychar_head = q;
6317 else
6318 /* On Mac OS X 10.3, tolower also converts non-ASCII
6319 characters for some locales. */
6320 if (isascii (c))
6321 c = tolower (c);
6323 *q++ = last_char = c;
6325 *q = '\0';
6326 nblocks++;
6327 pat->nblocks = nblocks;
6328 if (last_char != '?')
6329 pat->trailing_anychars = 0;
6330 else
6332 pat->trailing_anychars = q - anychar_head;
6333 q = anychar_head;
6335 pat->nchars = q - pat->buf - (nblocks - 1);
6337 if (anychar_head == NULL && nblocks == 1)
6339 /* The pattern is exact. */
6340 pat->blocks = NULL;
6341 return pat;
6344 pat->blocks = xmalloc (sizeof (struct xlfdpat_block) * nblocks);
6345 if (pat->blocks == NULL)
6346 goto error;
6348 /* Divide the normalized pattern into blocks. */
6349 p = pat->buf;
6350 for (blk = pat->blocks; blk < pat->blocks + nblocks - 1; blk++)
6352 blk->pattern = p;
6353 while (*p != '*')
6354 p++;
6355 blk->len = p - blk->pattern;
6356 p++;
6358 blk->pattern = p;
6359 blk->len = q - blk->pattern;
6361 /* Setup a table for the Boyer-Moore string search. */
6362 for (blk = pat->blocks; blk < pat->blocks + nblocks; blk++)
6363 if (blk->len != 0)
6365 blk->last_char = blk->pattern[blk->len - 1];
6366 blk->pattern[blk->len - 1] = '\0';
6368 for (skip = 1; skip < blk->len; skip++)
6369 if (blk->pattern[blk->len - skip - 1] == '?')
6370 break;
6372 for (i = 0; i < 256; i++)
6373 blk->skip[i] = skip;
6375 p = blk->pattern + (blk->len - skip);
6376 while (--skip > 0)
6377 blk->skip[*p++] = skip;
6379 blk->last_char_skip = blk->skip[blk->last_char];
6382 return pat;
6384 error:
6385 xlfdpat_destroy (pat);
6386 return NULL;
6389 static INLINE int
6390 xlfdpat_exact_p (pat)
6391 struct xlfdpat *pat;
6393 return pat->blocks == NULL;
6396 /* Return the first string in STRING + 0, ..., STRING + START_MAX such
6397 that the pattern in *BLK matches with its prefix. Return NULL
6398 there is no such strings. STRING must be lowered in advance. */
6400 static char *
6401 xlfdpat_block_match_1 (blk, string, start_max)
6402 struct xlfdpat_block *blk;
6403 unsigned char *string;
6404 int start_max;
6406 int start, infinity;
6407 unsigned char *p, *s;
6409 xassert (blk->len > 0);
6410 xassert (start_max + blk->len <= strlen (string));
6411 xassert (blk->last_char != '?');
6413 /* See the comments in the function `boyer_moore' (search.c) for the
6414 use of `infinity'. */
6415 infinity = start_max + blk->len + 1;
6416 blk->skip[blk->last_char] = infinity;
6418 start = 0;
6421 /* Check the last character of the pattern. */
6422 s = string + blk->len - 1;
6425 start += blk->skip[*(s + start)];
6427 while (start <= start_max);
6429 if (start < infinity)
6430 /* Couldn't find the last character. */
6431 return NULL;
6433 /* No less than `infinity' means we could find the last
6434 character at `s[start - infinity]'. */
6435 start -= infinity;
6437 /* Check the remaining characters. We prefer making no-'?'
6438 cases faster because the use of '?' is really rare. */
6439 p = blk->pattern;
6440 s = string + start;
6443 while (*p++ == *s++)
6446 while (*(p - 1) == '?');
6448 if (*(p - 1) == '\0')
6449 /* Matched. */
6450 return string + start;
6452 /* Didn't match. */
6453 start += blk->last_char_skip;
6455 while (start <= start_max);
6457 return NULL;
6460 #define xlfdpat_block_match(b, s, m) \
6461 ((b)->len == 1 ? memchr ((s), (b)->last_char, (m) + 1) \
6462 : xlfdpat_block_match_1 (b, s, m))
6464 /* Check if XLFD pattern PAT, which is generated by `xfldpat_create',
6465 matches with STRING. STRING must be lowered in advance. */
6467 static int
6468 xlfdpat_match (pat, string)
6469 struct xlfdpat *pat;
6470 unsigned char *string;
6472 int str_len, nblocks, i, start_max;
6473 struct xlfdpat_block *blk;
6474 unsigned char *s;
6476 xassert (pat->nblocks > 0);
6478 if (xlfdpat_exact_p (pat))
6479 return strcmp (pat->buf, string) == 0;
6481 /* The number of the characters in the string must not be smaller
6482 than that in the pattern. */
6483 str_len = strlen (string);
6484 if (str_len < pat->nchars + pat->trailing_anychars)
6485 return 0;
6487 /* Chop off the trailing '?'s. */
6488 str_len -= pat->trailing_anychars;
6490 /* The last block. When it is non-empty, it must match at the end
6491 of the string. */
6492 nblocks = pat->nblocks;
6493 blk = pat->blocks + (nblocks - 1);
6494 if (nblocks == 1)
6495 /* The last block is also the first one. */
6496 return (str_len == blk->len
6497 && (blk->len == 0 || xlfdpat_block_match (blk, string, 0)));
6498 else if (blk->len != 0)
6499 if (!xlfdpat_block_match (blk, string + (str_len - blk->len), 0))
6500 return 0;
6502 /* The first block. When it is non-empty, it must match at the
6503 beginning of the string. */
6504 blk = pat->blocks;
6505 if (blk->len != 0)
6507 s = xlfdpat_block_match (blk, string, 0);
6508 if (s == NULL)
6509 return 0;
6510 string = s + blk->len;
6513 /* The rest of the blocks. */
6514 start_max = str_len - pat->nchars;
6515 for (i = 1, blk++; i < nblocks - 1; i++, blk++)
6517 s = xlfdpat_block_match (blk, string, start_max);
6518 if (s == NULL)
6519 return 0;
6520 start_max -= s - string;
6521 string = s + blk->len;
6524 return 1;
6528 /***********************************************************************
6529 Fonts
6530 ***********************************************************************/
6532 /* Return a pointer to struct font_info of font FONT_IDX of frame F. */
6534 struct font_info *
6535 x_get_font_info (f, font_idx)
6536 FRAME_PTR f;
6537 int font_idx;
6539 return (FRAME_MAC_FONT_TABLE (f) + font_idx);
6542 /* the global font name table */
6543 static char **font_name_table = NULL;
6544 static int font_name_table_size = 0;
6545 static int font_name_count = 0;
6547 /* Alist linking font family names to Font Manager font family
6548 references (which can also be used as QuickDraw font IDs). We use
6549 an alist because hash tables are not ready when the terminal frame
6550 for Mac OS Classic is created. */
6551 static Lisp_Object fm_font_family_alist;
6552 #if USE_ATSUI
6553 /* Hash table linking font family names to ATSU font IDs. */
6554 static Lisp_Object atsu_font_id_hash;
6555 #endif
6557 /* Alist linking character set strings to Mac text encoding and Emacs
6558 coding system. */
6559 static Lisp_Object Vmac_charset_info_alist;
6561 static Lisp_Object
6562 create_text_encoding_info_alist ()
6564 Lisp_Object result = Qnil, rest;
6566 for (rest = Vmac_charset_info_alist; CONSP (rest); rest = XCDR (rest))
6568 Lisp_Object charset_info = XCAR (rest);
6569 Lisp_Object charset, coding_system, text_encoding;
6570 Lisp_Object existing_info;
6572 if (!(CONSP (charset_info)
6573 && STRINGP (charset = XCAR (charset_info))
6574 && CONSP (XCDR (charset_info))
6575 && INTEGERP (text_encoding = XCAR (XCDR (charset_info)))
6576 && CONSP (XCDR (XCDR (charset_info)))
6577 && SYMBOLP (coding_system = XCAR (XCDR (XCDR (charset_info))))))
6578 continue;
6580 existing_info = assq_no_quit (text_encoding, result);
6581 if (NILP (existing_info))
6582 result = Fcons (list3 (text_encoding, coding_system, charset),
6583 result);
6584 else
6585 if (NILP (Fmember (charset, XCDR (XCDR (existing_info)))))
6586 XSETCDR (XCDR (existing_info),
6587 Fcons (charset, XCDR (XCDR (existing_info))));
6590 return result;
6594 static void
6595 decode_mac_font_name (name, size, coding_system)
6596 char *name;
6597 int size;
6598 Lisp_Object coding_system;
6600 struct coding_system coding;
6601 char *buf, *p;
6603 if (!NILP (coding_system) && !NILP (Fcoding_system_p (coding_system)))
6605 for (p = name; *p; p++)
6606 if (!isascii (*p) || iscntrl (*p))
6607 break;
6609 if (*p)
6611 setup_coding_system (coding_system, &coding);
6612 coding.src_multibyte = 0;
6613 coding.dst_multibyte = 1;
6614 coding.mode |= CODING_MODE_LAST_BLOCK;
6615 coding.composing = COMPOSITION_DISABLED;
6616 buf = (char *) alloca (size);
6618 decode_coding (&coding, name, buf, strlen (name), size - 1);
6619 bcopy (buf, name, coding.produced);
6620 name[coding.produced] = '\0';
6624 /* If there's just one occurrence of '-' in the family name, it is
6625 replaced with '_'. (More than one occurrence of '-' means a
6626 "FOUNDRY-FAMILY-CHARSET"-style name.) */
6627 p = strchr (name, '-');
6628 if (p && strchr (p + 1, '-') == NULL)
6629 *p = '_';
6631 for (p = name; *p; p++)
6632 /* On Mac OS X 10.3, tolower also converts non-ASCII characters
6633 for some locales. */
6634 if (isascii (*p))
6635 *p = tolower (*p);
6639 static char *
6640 mac_to_x_fontname (name, size, style, charset)
6641 char *name;
6642 int size;
6643 Style style;
6644 char *charset;
6646 Str31 foundry, cs;
6647 Str255 family;
6648 char xf[256], *result;
6649 unsigned char *p;
6651 if (sscanf (name, "%31[^-]-%255[^-]-%31s", foundry, family, cs) == 3)
6652 charset = cs;
6653 else
6655 strcpy(foundry, "Apple");
6656 strcpy(family, name);
6659 sprintf (xf, "%s-%c-normal--%d-%d-%d-%d-m-%d-%s",
6660 style & bold ? "bold" : "medium", style & italic ? 'i' : 'r',
6661 size, size * 10, size ? 72 : 0, size ? 72 : 0, size * 10, charset);
6663 result = xmalloc (strlen (foundry) + strlen (family) + strlen (xf) + 3 + 1);
6664 sprintf (result, "-%s-%s-%s", foundry, family, xf);
6665 for (p = result; *p; p++)
6666 /* On Mac OS X 10.3, tolower also converts non-ASCII characters
6667 for some locales. */
6668 if (isascii (*p))
6669 *p = tolower (*p);
6670 return result;
6674 /* Parse fully-specified and instantiated X11 font spec XF, and store
6675 the results to FAMILY, *SIZE, *STYLE, and CHARSET. Return 1 if the
6676 parsing succeeded, and 0 otherwise. For FAMILY and CHARSET, the
6677 caller must allocate at least 256 and 32 bytes respectively. For
6678 ordinary Mac fonts, the value stored to FAMILY should just be their
6679 names, like "monaco", "Taipei", etc. Fonts converted from the GNU
6680 intlfonts collection contain their charset designation in their
6681 names, like "ETL-Fixed-iso8859-1", "ETL-Fixed-koi8-r", etc. Both
6682 types of font names are handled accordingly. */
6684 const int kDefaultFontSize = 12;
6686 static int
6687 parse_x_font_name (xf, family, size, style, charset)
6688 char *xf, *family;
6689 int *size;
6690 Style *style;
6691 char *charset;
6693 Str31 foundry, weight;
6694 int point_size, avgwidth;
6695 char slant[2], *p;
6697 if (sscanf (xf, "-%31[^-]-%255[^-]-%31[^-]-%1[^-]-%*[^-]-%*[^-]-%d-%d-%*[^-]-%*[^-]-%*c-%d-%31s",
6698 foundry, family, weight, slant, size,
6699 &point_size, &avgwidth, charset) != 8
6700 && sscanf (xf, "-%31[^-]-%255[^-]-%31[^-]-%1[^-]-%*[^-]--%d-%d-%*[^-]-%*[^-]-%*c-%d-%31s",
6701 foundry, family, weight, slant, size,
6702 &point_size, &avgwidth, charset) != 8)
6703 return 0;
6705 if (*size == 0)
6707 if (point_size > 0)
6708 *size = point_size / 10;
6709 else if (avgwidth > 0)
6710 *size = avgwidth / 10;
6712 if (*size == 0)
6713 *size = kDefaultFontSize;
6715 *style = normal;
6716 if (strcmp (weight, "bold") == 0)
6717 *style |= bold;
6718 if (*slant == 'i')
6719 *style |= italic;
6721 if (NILP (Fassoc (build_string (charset), Vmac_charset_info_alist)))
6723 int foundry_len = strlen (foundry), family_len = strlen (family);
6725 if (foundry_len + family_len + strlen (charset) + 2 < sizeof (Str255))
6727 /* Like sprintf (family, "%s-%s-%s", foundry, family, charset),
6728 but take overlap into account. */
6729 memmove (family + foundry_len + 1, family, family_len);
6730 memcpy (family, foundry, foundry_len);
6731 family[foundry_len] = '-';
6732 family[foundry_len + 1 + family_len] = '-';
6733 strcpy (family + foundry_len + 1 + family_len + 1, charset);
6735 else
6736 return 0;
6739 for (p = family; *p; p++)
6740 /* On Mac OS X 10.3, tolower also converts non-ASCII characters
6741 for some locales. */
6742 if (isascii (*p))
6743 *p = tolower (*p);
6745 return 1;
6749 static void
6750 add_font_name_table_entry (char *font_name)
6752 if (font_name_table_size == 0)
6754 font_name_table_size = 256;
6755 font_name_table = (char **)
6756 xmalloc (font_name_table_size * sizeof (char *));
6758 else if (font_name_count + 1 >= font_name_table_size)
6760 font_name_table_size *= 2;
6761 font_name_table = (char **)
6762 xrealloc (font_name_table,
6763 font_name_table_size * sizeof (char *));
6766 font_name_table[font_name_count++] = font_name;
6769 /* Sets up the table font_name_table to contain the list of all fonts
6770 in the system the first time the table is used so that the Resource
6771 Manager need not be accessed every time this information is
6772 needed. */
6774 static void
6775 init_font_name_table ()
6777 #if TARGET_API_MAC_CARBON
6778 FMFontFamilyIterator ffi;
6779 FMFontFamilyInstanceIterator ffii;
6780 FMFontFamily ff;
6781 Lisp_Object text_encoding_info_alist;
6782 struct gcpro gcpro1;
6784 text_encoding_info_alist = create_text_encoding_info_alist ();
6786 #if USE_ATSUI
6787 if (!NILP (assq_no_quit (make_number (kTextEncodingMacUnicode),
6788 text_encoding_info_alist)))
6790 OSErr err;
6791 ItemCount nfonts, i;
6792 ATSUFontID *font_ids = NULL;
6793 Ptr name, prev_name = NULL;
6794 ByteCount name_len;
6796 atsu_font_id_hash =
6797 make_hash_table (Qequal, make_number (DEFAULT_HASH_SIZE),
6798 make_float (DEFAULT_REHASH_SIZE),
6799 make_float (DEFAULT_REHASH_THRESHOLD),
6800 Qnil, Qnil, Qnil);;
6801 err = ATSUFontCount (&nfonts);
6802 if (err == noErr)
6803 font_ids = xmalloc (sizeof (ATSUFontID) * nfonts);
6804 if (font_ids)
6805 err = ATSUGetFontIDs (font_ids, nfonts, NULL);
6806 if (err == noErr)
6807 for (i = 0; i < nfonts; i++)
6809 err = ATSUFindFontName (font_ids[i], kFontFamilyName,
6810 kFontMacintoshPlatform, kFontNoScript,
6811 kFontNoLanguage, 0, NULL, &name_len, NULL);
6812 if (err != noErr)
6813 continue;
6814 name = xmalloc (name_len + 1);
6815 if (name == NULL)
6816 continue;
6817 name[name_len] = '\0';
6818 err = ATSUFindFontName (font_ids[i], kFontFamilyName,
6819 kFontMacintoshPlatform, kFontNoScript,
6820 kFontNoLanguage, name_len, name,
6821 NULL, NULL);
6822 if (err == noErr)
6823 decode_mac_font_name (name, name_len + 1, Qnil);
6824 if (err == noErr
6825 && *name != '.'
6826 && (prev_name == NULL
6827 || strcmp (name, prev_name) != 0))
6829 static char *cs = "iso10646-1";
6831 add_font_name_table_entry (mac_to_x_fontname (name, 0,
6832 normal, cs));
6833 add_font_name_table_entry (mac_to_x_fontname (name, 0,
6834 italic, cs));
6835 add_font_name_table_entry (mac_to_x_fontname (name, 0,
6836 bold, cs));
6837 add_font_name_table_entry (mac_to_x_fontname (name, 0,
6838 italic | bold, cs));
6839 Fputhash (make_unibyte_string (name, name_len),
6840 long_to_cons (font_ids[i]), atsu_font_id_hash);
6841 xfree (prev_name);
6842 prev_name = name;
6844 else
6845 xfree (name);
6847 if (prev_name)
6848 xfree (prev_name);
6849 if (font_ids)
6850 xfree (font_ids);
6852 #endif
6854 /* Create a dummy instance iterator here to avoid creating and
6855 destroying it in the loop. */
6856 if (FMCreateFontFamilyInstanceIterator (0, &ffii) != noErr)
6857 return;
6858 /* Create an iterator to enumerate the font families. */
6859 if (FMCreateFontFamilyIterator (NULL, NULL, kFMDefaultOptions, &ffi)
6860 != noErr)
6862 FMDisposeFontFamilyInstanceIterator (&ffii);
6863 return;
6866 GCPRO1 (text_encoding_info_alist);
6868 while (FMGetNextFontFamily (&ffi, &ff) == noErr)
6870 Str255 name;
6871 FMFont font;
6872 FMFontStyle style;
6873 FMFontSize size;
6874 TextEncoding encoding;
6875 TextEncodingBase sc;
6876 Lisp_Object text_encoding_info;
6878 if (FMGetFontFamilyName (ff, name) != noErr)
6879 break;
6880 p2cstr (name);
6881 if (*name == '.')
6882 continue;
6884 if (FMGetFontFamilyTextEncoding (ff, &encoding) != noErr)
6885 break;
6886 sc = GetTextEncodingBase (encoding);
6887 text_encoding_info = assq_no_quit (make_number (sc),
6888 text_encoding_info_alist);
6889 if (NILP (text_encoding_info))
6890 text_encoding_info = assq_no_quit (make_number (kTextEncodingMacRoman),
6891 text_encoding_info_alist);
6892 decode_mac_font_name (name, sizeof (name),
6893 XCAR (XCDR (text_encoding_info)));
6894 fm_font_family_alist = Fcons (Fcons (build_string (name),
6895 make_number (ff)),
6896 fm_font_family_alist);
6898 /* Point the instance iterator at the current font family. */
6899 if (FMResetFontFamilyInstanceIterator (ff, &ffii) != noErr)
6900 break;
6902 while (FMGetNextFontFamilyInstance (&ffii, &font, &style, &size)
6903 == noErr)
6905 Lisp_Object rest = XCDR (XCDR (text_encoding_info));
6907 if (size > 0 || style == normal)
6908 for (; !NILP (rest); rest = XCDR (rest))
6910 char *cs = SDATA (XCAR (rest));
6912 if (size == 0)
6914 add_font_name_table_entry (mac_to_x_fontname (name, size,
6915 style, cs));
6916 add_font_name_table_entry (mac_to_x_fontname (name, size,
6917 italic, cs));
6918 add_font_name_table_entry (mac_to_x_fontname (name, size,
6919 bold, cs));
6920 add_font_name_table_entry (mac_to_x_fontname (name, size,
6921 italic | bold,
6922 cs));
6924 else
6926 add_font_name_table_entry (mac_to_x_fontname (name, size,
6927 style, cs));
6933 UNGCPRO;
6935 /* Dispose of the iterators. */
6936 FMDisposeFontFamilyIterator (&ffi);
6937 FMDisposeFontFamilyInstanceIterator (&ffii);
6938 #else /* !TARGET_API_MAC_CARBON */
6939 GrafPtr port;
6940 SInt16 fontnum, old_fontnum;
6941 int num_mac_fonts = CountResources('FOND');
6942 int i, j;
6943 Handle font_handle, font_handle_2;
6944 short id, scriptcode;
6945 ResType type;
6946 Str255 name;
6947 struct FontAssoc *fat;
6948 struct AsscEntry *assc_entry;
6949 Lisp_Object text_encoding_info_alist, text_encoding_info;
6950 struct gcpro gcpro1;
6952 GetPort (&port); /* save the current font number used */
6953 old_fontnum = port->txFont;
6955 text_encoding_info_alist = create_text_encoding_info_alist ();
6957 GCPRO1 (text_encoding_info_alist);
6959 for (i = 1; i <= num_mac_fonts; i++) /* get all available fonts */
6961 font_handle = GetIndResource ('FOND', i);
6962 if (!font_handle)
6963 continue;
6965 GetResInfo (font_handle, &id, &type, name);
6966 GetFNum (name, &fontnum);
6967 p2cstr (name);
6968 if (fontnum == 0)
6969 continue;
6971 TextFont (fontnum);
6972 scriptcode = FontToScript (fontnum);
6973 text_encoding_info = assq_no_quit (make_number (scriptcode),
6974 text_encoding_info_alist);
6975 if (NILP (text_encoding_info))
6976 text_encoding_info = assq_no_quit (make_number (smRoman),
6977 text_encoding_info_alist);
6978 decode_mac_font_name (name, sizeof (name),
6979 XCAR (XCDR (text_encoding_info)));
6980 fm_font_family_alist = Fcons (Fcons (build_string (name),
6981 make_number (fontnum)),
6982 fm_font_family_alist);
6985 HLock (font_handle);
6987 if (GetResourceSizeOnDisk (font_handle)
6988 >= sizeof (struct FamRec))
6990 fat = (struct FontAssoc *) (*font_handle
6991 + sizeof (struct FamRec));
6992 assc_entry
6993 = (struct AsscEntry *) (*font_handle
6994 + sizeof (struct FamRec)
6995 + sizeof (struct FontAssoc));
6997 for (j = 0; j <= fat->numAssoc; j++, assc_entry++)
6999 Lisp_Object rest = XCDR (XCDR (text_encoding_info));
7001 for (; !NILP (rest); rest = XCDR (rest))
7003 char *cs = SDATA (XCAR (rest));
7005 add_font_name_table_entry (mac_to_x_fontname (name,
7006 assc_entry->fontSize,
7007 assc_entry->fontStyle,
7008 cs));
7013 HUnlock (font_handle);
7014 font_handle_2 = GetNextFOND (font_handle);
7015 ReleaseResource (font_handle);
7016 font_handle = font_handle_2;
7018 while (ResError () == noErr && font_handle);
7021 UNGCPRO;
7023 TextFont (old_fontnum);
7024 #endif /* !TARGET_API_MAC_CARBON */
7028 void
7029 mac_clear_font_name_table ()
7031 int i;
7033 for (i = 0; i < font_name_count; i++)
7034 xfree (font_name_table[i]);
7035 xfree (font_name_table);
7036 font_name_table = NULL;
7037 font_name_table_size = font_name_count = 0;
7038 fm_font_family_alist = Qnil;
7042 enum xlfd_scalable_field_index
7044 XLFD_SCL_PIXEL_SIZE,
7045 XLFD_SCL_POINT_SIZE,
7046 XLFD_SCL_AVGWIDTH,
7047 XLFD_SCL_LAST
7050 static int xlfd_scalable_fields[] =
7052 6, /* PIXEL_SIZE */
7053 7, /* POINT_SIZE */
7054 11, /* AVGWIDTH */
7058 static Lisp_Object
7059 mac_do_list_fonts (pattern, maxnames)
7060 char *pattern;
7061 int maxnames;
7063 int i, n_fonts = 0;
7064 Lisp_Object font_list = Qnil;
7065 struct xlfdpat *pat;
7066 char *scaled, *ptr;
7067 int scl_val[XLFD_SCL_LAST], *field, *val;
7068 int exact;
7070 if (font_name_table == NULL) /* Initialize when first used. */
7071 init_font_name_table ();
7073 for (i = 0; i < XLFD_SCL_LAST; i++)
7074 scl_val[i] = -1;
7076 /* If the pattern contains 14 dashes and one of PIXEL_SIZE,
7077 POINT_SIZE, and AVGWIDTH fields is explicitly specified, scalable
7078 fonts are scaled according to the specified size. */
7079 ptr = pattern;
7080 i = 0;
7081 field = xlfd_scalable_fields;
7082 val = scl_val;
7083 if (*ptr == '-')
7086 ptr++;
7087 if (i == *field)
7089 if ('0' <= *ptr && *ptr <= '9')
7091 *val = *ptr++ - '0';
7092 while ('0' <= *ptr && *ptr <= '9' && *val < 10000)
7093 *val = *val * 10 + *ptr++ - '0';
7094 if (*ptr != '-')
7095 *val = -1;
7097 field++;
7098 val++;
7100 ptr = strchr (ptr, '-');
7101 i++;
7103 while (ptr && i < 14);
7105 if (i == 14 && ptr == NULL)
7107 if (scl_val[XLFD_SCL_PIXEL_SIZE] < 0)
7108 scl_val[XLFD_SCL_PIXEL_SIZE] =
7109 (scl_val[XLFD_SCL_POINT_SIZE] > 0 ? scl_val[XLFD_SCL_POINT_SIZE] / 10
7110 : (scl_val[XLFD_SCL_AVGWIDTH] > 0 ? scl_val[XLFD_SCL_AVGWIDTH] / 10
7111 : -1));
7112 if (scl_val[XLFD_SCL_POINT_SIZE] < 0)
7113 scl_val[XLFD_SCL_POINT_SIZE] =
7114 (scl_val[XLFD_SCL_PIXEL_SIZE] > 0 ? scl_val[XLFD_SCL_PIXEL_SIZE] * 10
7115 : (scl_val[XLFD_SCL_AVGWIDTH] > 0 ? scl_val[XLFD_SCL_AVGWIDTH]
7116 : -1));
7117 if (scl_val[XLFD_SCL_AVGWIDTH] < 0)
7118 scl_val[XLFD_SCL_AVGWIDTH] =
7119 (scl_val[XLFD_SCL_PIXEL_SIZE] > 0 ? scl_val[XLFD_SCL_PIXEL_SIZE] * 10
7120 : (scl_val[XLFD_SCL_POINT_SIZE] > 0 ? scl_val[XLFD_SCL_POINT_SIZE]
7121 : -1));
7123 else
7124 scl_val[XLFD_SCL_PIXEL_SIZE] = -1;
7126 pat = xlfdpat_create (pattern);
7127 if (pat == NULL)
7128 return Qnil;
7130 exact = xlfdpat_exact_p (pat);
7132 for (i = 0; i < font_name_count; i++)
7134 if (xlfdpat_match (pat, font_name_table[i]))
7136 font_list = Fcons (build_string (font_name_table[i]), font_list);
7137 if (exact || maxnames > 0 && ++n_fonts >= maxnames)
7138 break;
7140 else if (scl_val[XLFD_SCL_PIXEL_SIZE] > 0
7141 && (ptr = strstr (font_name_table[i], "-0-0-0-0-m-0-")))
7143 int former_len = ptr - font_name_table[i];
7145 scaled = xmalloc (strlen (font_name_table[i]) + 20 + 1);
7146 if (scaled == NULL)
7147 continue;
7148 memcpy (scaled, font_name_table[i], former_len);
7149 sprintf (scaled + former_len,
7150 "-%d-%d-72-72-m-%d-%s",
7151 scl_val[XLFD_SCL_PIXEL_SIZE],
7152 scl_val[XLFD_SCL_POINT_SIZE],
7153 scl_val[XLFD_SCL_AVGWIDTH],
7154 ptr + sizeof ("-0-0-0-0-m-0-") - 1);
7156 if (xlfdpat_match (pat, scaled))
7158 font_list = Fcons (build_string (scaled), font_list);
7159 xfree (scaled);
7160 if (exact || maxnames > 0 && ++n_fonts >= maxnames)
7161 break;
7163 else
7164 xfree (scaled);
7168 xlfdpat_destroy (pat);
7170 return font_list;
7173 /* Return a list of names of available fonts matching PATTERN on frame F.
7175 Frame F null means we have not yet created any frame on Mac, and
7176 consult the first display in x_display_list. MAXNAMES sets a limit
7177 on how many fonts to match. */
7179 Lisp_Object
7180 x_list_fonts (f, pattern, size, maxnames)
7181 struct frame *f;
7182 Lisp_Object pattern;
7183 int size, maxnames;
7185 Lisp_Object list = Qnil, patterns, tem, key;
7186 struct mac_display_info *dpyinfo
7187 = f ? FRAME_MAC_DISPLAY_INFO (f) : x_display_list;
7189 xassert (size <= 0);
7191 patterns = Fassoc (pattern, Valternate_fontname_alist);
7192 if (NILP (patterns))
7193 patterns = Fcons (pattern, Qnil);
7195 for (; CONSP (patterns); patterns = XCDR (patterns))
7197 pattern = XCAR (patterns);
7199 if (!STRINGP (pattern))
7200 continue;
7202 tem = XCAR (XCDR (dpyinfo->name_list_element));
7203 key = Fcons (pattern, make_number (maxnames));
7205 list = Fassoc (key, tem);
7206 if (!NILP (list))
7208 list = Fcdr_safe (list);
7209 /* We have a cashed list. Don't have to get the list again. */
7210 goto label_cached;
7213 BLOCK_INPUT;
7214 list = mac_do_list_fonts (SDATA (pattern), maxnames);
7215 UNBLOCK_INPUT;
7217 /* MAC_TODO: add code for matching outline fonts here */
7219 /* Now store the result in the cache. */
7220 XSETCAR (XCDR (dpyinfo->name_list_element),
7221 Fcons (Fcons (key, list),
7222 XCAR (XCDR (dpyinfo->name_list_element))));
7224 label_cached:
7225 if (NILP (list)) continue; /* Try the remaining alternatives. */
7228 return list;
7232 #if GLYPH_DEBUG
7234 /* Check that FONT is valid on frame F. It is if it can be found in F's
7235 font table. */
7237 static void
7238 x_check_font (f, font)
7239 struct frame *f;
7240 XFontStruct *font;
7242 int i;
7243 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
7245 xassert (font != NULL);
7247 for (i = 0; i < dpyinfo->n_fonts; i++)
7248 if (dpyinfo->font_table[i].name
7249 && font == dpyinfo->font_table[i].font)
7250 break;
7252 xassert (i < dpyinfo->n_fonts);
7255 #endif /* GLYPH_DEBUG != 0 */
7257 /* Set *W to the minimum width, *H to the minimum font height of FONT.
7258 Note: There are (broken) X fonts out there with invalid XFontStruct
7259 min_bounds contents. For example, handa@etl.go.jp reports that
7260 "-adobe-courier-medium-r-normal--*-180-*-*-m-*-iso8859-1" fonts
7261 have font->min_bounds.width == 0. */
7263 static INLINE void
7264 x_font_min_bounds (font, w, h)
7265 MacFontStruct *font;
7266 int *w, *h;
7268 *h = FONT_HEIGHT (font);
7269 *w = font->min_bounds.width;
7273 /* Compute the smallest character width and smallest font height over
7274 all fonts available on frame F. Set the members smallest_char_width
7275 and smallest_font_height in F's x_display_info structure to
7276 the values computed. Value is non-zero if smallest_font_height or
7277 smallest_char_width become smaller than they were before. */
7279 static int
7280 x_compute_min_glyph_bounds (f)
7281 struct frame *f;
7283 int i;
7284 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
7285 MacFontStruct *font;
7286 int old_width = dpyinfo->smallest_char_width;
7287 int old_height = dpyinfo->smallest_font_height;
7289 dpyinfo->smallest_font_height = 100000;
7290 dpyinfo->smallest_char_width = 100000;
7292 for (i = 0; i < dpyinfo->n_fonts; ++i)
7293 if (dpyinfo->font_table[i].name)
7295 struct font_info *fontp = dpyinfo->font_table + i;
7296 int w, h;
7298 font = (MacFontStruct *) fontp->font;
7299 xassert (font != (MacFontStruct *) ~0);
7300 x_font_min_bounds (font, &w, &h);
7302 dpyinfo->smallest_font_height = min (dpyinfo->smallest_font_height, h);
7303 dpyinfo->smallest_char_width = min (dpyinfo->smallest_char_width, w);
7306 xassert (dpyinfo->smallest_char_width > 0
7307 && dpyinfo->smallest_font_height > 0);
7309 return (dpyinfo->n_fonts == 1
7310 || dpyinfo->smallest_char_width < old_width
7311 || dpyinfo->smallest_font_height < old_height);
7315 /* Determine whether given string is a fully-specified XLFD: all 14
7316 fields are present, none is '*'. */
7318 static int
7319 is_fully_specified_xlfd (char *p)
7321 int i;
7322 char *q;
7324 if (*p != '-')
7325 return 0;
7327 for (i = 0; i < 13; i++)
7329 q = strchr (p + 1, '-');
7330 if (q == NULL)
7331 return 0;
7332 if (q - p == 2 && *(p + 1) == '*')
7333 return 0;
7334 p = q;
7337 if (strchr (p + 1, '-') != NULL)
7338 return 0;
7340 if (*(p + 1) == '*' && *(p + 2) == '\0')
7341 return 0;
7343 return 1;
7347 /* XLoadQueryFont creates and returns an internal representation for a
7348 font in a MacFontStruct struct. There is really no concept
7349 corresponding to "loading" a font on the Mac. But we check its
7350 existence and find the font number and all other information for it
7351 and store them in the returned MacFontStruct. */
7353 static MacFontStruct *
7354 XLoadQueryFont (Display *dpy, char *fontname)
7356 int i, size, char_width;
7357 char *name;
7358 Str255 family;
7359 Str31 charset;
7360 SInt16 fontnum;
7361 #if USE_ATSUI
7362 static ATSUFontID font_id;
7363 ATSUStyle mac_style = NULL;
7364 #endif
7365 Style fontface;
7366 #if TARGET_API_MAC_CARBON
7367 TextEncoding encoding;
7368 int scriptcode;
7369 #else
7370 short scriptcode;
7371 #endif
7372 MacFontStruct *font;
7374 if (is_fully_specified_xlfd (fontname))
7375 name = fontname;
7376 else
7378 Lisp_Object matched_fonts;
7380 matched_fonts = mac_do_list_fonts (fontname, 1);
7381 if (NILP (matched_fonts))
7382 return NULL;
7383 name = SDATA (XCAR (matched_fonts));
7386 if (parse_x_font_name (name, family, &size, &fontface, charset) == 0)
7387 return NULL;
7389 #if USE_ATSUI
7390 if (strcmp (charset, "iso10646-1") == 0) /* XXX */
7392 OSErr err;
7393 ATSUAttributeTag tags[] = {kATSUFontTag, kATSUSizeTag,
7394 kATSUQDBoldfaceTag, kATSUQDItalicTag};
7395 ByteCount sizes[] = {sizeof (ATSUFontID), sizeof (Fixed),
7396 sizeof (Boolean), sizeof (Boolean)};
7397 static Fixed size_fixed;
7398 static Boolean bold_p, italic_p;
7399 ATSUAttributeValuePtr values[] = {&font_id, &size_fixed,
7400 &bold_p, &italic_p};
7401 ATSUFontFeatureType types[] = {kAllTypographicFeaturesType};
7402 ATSUFontFeatureSelector selectors[] = {kAllTypeFeaturesOffSelector};
7403 Lisp_Object font_id_cons;
7405 font_id_cons = Fgethash (make_unibyte_string (family, strlen (family)),
7406 atsu_font_id_hash, Qnil);
7407 if (NILP (font_id_cons))
7408 return NULL;
7409 font_id = cons_to_long (font_id_cons);
7410 size_fixed = Long2Fix (size);
7411 bold_p = (fontface & bold) != 0;
7412 italic_p = (fontface & italic) != 0;
7413 err = ATSUCreateStyle (&mac_style);
7414 if (err != noErr)
7415 return NULL;
7416 err = ATSUSetFontFeatures (mac_style, sizeof (types) / sizeof (types[0]),
7417 types, selectors);
7418 if (err != noErr)
7419 return NULL;
7420 err = ATSUSetAttributes (mac_style, sizeof (tags) / sizeof (tags[0]),
7421 tags, sizes, values);
7422 fontnum = -1;
7423 scriptcode = kTextEncodingMacUnicode;
7425 else
7426 #endif
7428 Lisp_Object tmp = Fassoc (build_string (family), fm_font_family_alist);
7430 if (NILP (tmp))
7431 return NULL;
7432 fontnum = XINT (XCDR (tmp));
7433 #if TARGET_API_MAC_CARBON
7434 if (FMGetFontFamilyTextEncoding (fontnum, &encoding) != noErr)
7435 return NULL;
7436 scriptcode = GetTextEncodingBase (encoding);
7437 #else
7438 scriptcode = FontToScript (fontnum);
7439 #endif
7442 font = (MacFontStruct *) xmalloc (sizeof (struct MacFontStruct));
7444 font->mac_fontnum = fontnum;
7445 font->mac_fontsize = size;
7446 font->mac_fontface = fontface;
7447 font->mac_scriptcode = scriptcode;
7448 #if USE_ATSUI
7449 font->mac_style = mac_style;
7450 #if USE_CG_TEXT_DRAWING
7451 font->cg_font = NULL;
7452 font->cg_glyphs = NULL;
7453 #endif
7454 #endif
7456 /* Apple Japanese (SJIS) font is listed as both
7457 "*-jisx0208.1983-sjis" (Japanese script) and "*-jisx0201.1976-0"
7458 (Roman script) in init_font_name_table (). The latter should be
7459 treated as a one-byte font. */
7460 if (scriptcode == smJapanese && strcmp (charset, "jisx0201.1976-0") == 0)
7461 font->mac_scriptcode = smRoman;
7463 font->full_name = mac_to_x_fontname (family, size, fontface, charset);
7465 #if USE_ATSUI
7466 if (font->mac_style)
7468 OSErr err;
7469 ATSUTextLayout text_layout;
7470 UniChar c = 0x20;
7471 Rect char_bounds, min_bounds, max_bounds;
7472 int min_width, max_width;
7473 ATSTrapezoid glyph_bounds;
7475 font->per_char = xmalloc (sizeof (XCharStruct) * 0x10000);
7476 if (font->per_char == NULL)
7478 mac_unload_font (&one_mac_display_info, font);
7479 return NULL;
7481 bzero (font->per_char, sizeof (XCharStruct) * 0x10000);
7483 #if USE_CG_TEXT_DRAWING
7485 FMFontFamily font_family;
7486 FMFontStyle style;
7487 ATSFontRef ats_font;
7489 err = FMGetFontFamilyInstanceFromFont (font_id, &font_family, &style);
7490 if (err == noErr)
7491 err = FMGetFontFromFontFamilyInstance (font_family, fontface,
7492 &font_id, &style);
7493 /* Use CG text drawing if italic/bold is not synthesized. */
7494 if (err == noErr && style == fontface)
7496 ats_font = FMGetATSFontRefFromFont (font_id);
7497 font->cg_font = CGFontCreateWithPlatformFont (&ats_font);
7501 if (font->cg_font)
7502 font->cg_glyphs = xmalloc (sizeof (CGGlyph) * 0x100);
7503 if (font->cg_glyphs)
7504 bzero (font->cg_glyphs, sizeof (CGGlyph) * 0x100);
7505 #endif
7507 err = atsu_get_text_layout_with_text_ptr (&c, 1,
7508 font->mac_style,
7509 &text_layout);
7510 if (err != noErr)
7512 mac_unload_font (&one_mac_display_info, font);
7513 return NULL;
7516 for (c = 0x20; c <= 0xff; c++)
7518 if (c == 0xad)
7519 /* Soft hyphen is not supported in ATSUI. */
7520 continue;
7521 else if (c == 0x7f)
7523 STORE_XCHARSTRUCT (font->min_bounds, min_width, min_bounds);
7524 STORE_XCHARSTRUCT (font->max_bounds, max_width, max_bounds);
7525 c = 0x9f;
7526 continue;
7529 err = ATSUClearLayoutCache (text_layout, kATSUFromTextBeginning);
7530 if (err == noErr)
7531 err = ATSUMeasureTextImage (text_layout,
7532 kATSUFromTextBeginning, kATSUToTextEnd,
7533 0, 0, &char_bounds);
7534 if (err == noErr)
7535 err = ATSUGetGlyphBounds (text_layout, 0, 0,
7536 kATSUFromTextBeginning, kATSUToTextEnd,
7537 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
7538 kATSUseFractionalOrigins,
7539 #else
7540 kATSUseDeviceOrigins,
7541 #endif
7542 1, &glyph_bounds, NULL);
7543 if (err == noErr)
7545 xassert (glyph_bounds.lowerRight.x - glyph_bounds.lowerLeft.x
7546 == glyph_bounds.upperRight.x - glyph_bounds.upperLeft.x);
7548 char_width = Fix2Long (glyph_bounds.upperRight.x
7549 - glyph_bounds.upperLeft.x);
7550 STORE_XCHARSTRUCT (font->per_char[c],
7551 char_width, char_bounds);
7552 if (c == 0x20)
7554 min_width = max_width = char_width;
7555 min_bounds = max_bounds = char_bounds;
7556 font->ascent = -Fix2Long (glyph_bounds.upperLeft.y);
7557 font->descent = Fix2Long (glyph_bounds.lowerLeft.y);
7559 else
7561 if (char_width > 0)
7563 min_width = min (min_width, char_width);
7564 max_width = max (max_width, char_width);
7566 if (!EmptyRect (&char_bounds))
7568 SetRect (&min_bounds,
7569 max (min_bounds.left, char_bounds.left),
7570 max (min_bounds.top, char_bounds.top),
7571 min (min_bounds.right, char_bounds.right),
7572 min (min_bounds.bottom, char_bounds.bottom));
7573 UnionRect (&max_bounds, &char_bounds, &max_bounds);
7577 #if USE_CG_TEXT_DRAWING
7578 if (err == noErr && char_width > 0 && font->cg_font)
7580 ATSUGlyphInfoArray glyph_info_array;
7581 ByteCount count = sizeof (ATSUGlyphInfoArray);
7583 err = ATSUMatchFontsToText (text_layout, kATSUFromTextBeginning,
7584 kATSUToTextEnd, NULL, NULL, NULL);
7585 if (err == noErr)
7586 err = ATSUGetGlyphInfo (text_layout, kATSUFromTextBeginning,
7587 kATSUToTextEnd, &count,
7588 &glyph_info_array);
7589 if (err == noErr)
7590 font->cg_glyphs[c] = glyph_info_array.glyphs[0].glyphID;
7591 else
7593 /* Don't use CG text drawing if font substitution
7594 occurs in ASCII or Latin-1 characters. */
7595 CGFontRelease (font->cg_font);
7596 font->cg_font = NULL;
7597 xfree (font->cg_glyphs);
7598 font->cg_glyphs = NULL;
7601 #endif
7604 font->min_byte1 = 0;
7605 font->max_byte1 = 0xff;
7606 font->min_char_or_byte2 = 0;
7607 font->max_char_or_byte2 = 0xff;
7609 else
7610 #endif
7612 GrafPtr port;
7613 SInt16 old_fontnum, old_fontsize;
7614 Style old_fontface;
7615 FontInfo the_fontinfo;
7616 int is_two_byte_font;
7618 /* Save the current font number used. */
7619 GetPort (&port);
7620 #if TARGET_API_MAC_CARBON
7621 old_fontnum = GetPortTextFont (port);
7622 old_fontsize = GetPortTextSize (port);
7623 old_fontface = GetPortTextFace (port);
7624 #else
7625 old_fontnum = port->txFont;
7626 old_fontsize = port->txSize;
7627 old_fontface = port->txFace;
7628 #endif
7630 TextFont (fontnum);
7631 TextSize (size);
7632 TextFace (fontface);
7634 GetFontInfo (&the_fontinfo);
7636 font->ascent = the_fontinfo.ascent;
7637 font->descent = the_fontinfo.descent;
7639 is_two_byte_font = (font->mac_scriptcode == smJapanese
7640 || font->mac_scriptcode == smTradChinese
7641 || font->mac_scriptcode == smSimpChinese
7642 || font->mac_scriptcode == smKorean);
7644 if (is_two_byte_font)
7646 font->min_byte1 = 0xa1;
7647 font->max_byte1 = 0xfe;
7648 font->min_char_or_byte2 = 0xa1;
7649 font->max_char_or_byte2 = 0xfe;
7651 /* Use the width of an "ideographic space" of that font
7652 because the_fontinfo.widMax returns the wrong width for
7653 some fonts. */
7654 switch (font->mac_scriptcode)
7656 case smJapanese:
7657 font->min_byte1 = 0x81;
7658 font->max_byte1 = 0xfc;
7659 font->min_char_or_byte2 = 0x40;
7660 font->max_char_or_byte2 = 0xfc;
7661 char_width = StringWidth("\p\x81\x40");
7662 break;
7663 case smTradChinese:
7664 font->min_char_or_byte2 = 0x40;
7665 char_width = StringWidth("\p\xa1\x40");
7666 break;
7667 case smSimpChinese:
7668 char_width = StringWidth("\p\xa1\xa1");
7669 break;
7670 case smKorean:
7671 char_width = StringWidth("\p\xa1\xa1");
7672 break;
7675 else
7677 font->min_byte1 = font->max_byte1 = 0;
7678 font->min_char_or_byte2 = 0x20;
7679 font->max_char_or_byte2 = 0xff;
7681 /* Do this instead of use the_fontinfo.widMax, which
7682 incorrectly returns 15 for 12-point Monaco! */
7683 char_width = CharWidth ('m');
7686 if (is_two_byte_font)
7688 font->per_char = NULL;
7690 if (fontface & italic)
7691 font->max_bounds.rbearing = char_width + 1;
7692 else
7693 font->max_bounds.rbearing = char_width;
7694 font->max_bounds.lbearing = 0;
7695 font->max_bounds.width = char_width;
7696 font->max_bounds.ascent = the_fontinfo.ascent;
7697 font->max_bounds.descent = the_fontinfo.descent;
7699 font->min_bounds = font->max_bounds;
7701 else
7703 int c, min_width, max_width;
7704 Rect char_bounds, min_bounds, max_bounds;
7705 char ch;
7707 font->per_char = xmalloc (sizeof (XCharStruct) * (0xff - 0x20 + 1));
7708 bzero (font->per_char, sizeof (XCharStruct) * (0xff - 0x20 + 1));
7710 min_width = max_width = char_width;
7711 SetRect (&min_bounds, -32767, -32767, 32767, 32767);
7712 SetRect (&max_bounds, 0, 0, 0, 0);
7713 for (c = 0x20; c <= 0xff; c++)
7715 if (c == 0x7f)
7717 STORE_XCHARSTRUCT (font->min_bounds, min_width, min_bounds);
7718 STORE_XCHARSTRUCT (font->max_bounds, max_width, max_bounds);
7719 continue;
7722 ch = c;
7723 char_width = CharWidth (ch);
7724 QDTextBounds (1, &ch, &char_bounds);
7725 STORE_XCHARSTRUCT (font->per_char[c - 0x20],
7726 char_width, char_bounds);
7727 /* Some Japanese fonts (in SJIS encoding) return 0 as
7728 the character width of 0x7f. */
7729 if (char_width > 0)
7731 min_width = min (min_width, char_width);
7732 max_width = max (max_width, char_width);
7734 if (!EmptyRect (&char_bounds))
7736 SetRect (&min_bounds,
7737 max (min_bounds.left, char_bounds.left),
7738 max (min_bounds.top, char_bounds.top),
7739 min (min_bounds.right, char_bounds.right),
7740 min (min_bounds.bottom, char_bounds.bottom));
7741 UnionRect (&max_bounds, &char_bounds, &max_bounds);
7744 if (min_width == max_width
7745 && max_bounds.left >= 0 && max_bounds.right <= max_width)
7747 /* Fixed width and no overhangs. */
7748 xfree (font->per_char);
7749 font->per_char = NULL;
7753 /* Restore previous font number, size and face. */
7754 TextFont (old_fontnum);
7755 TextSize (old_fontsize);
7756 TextFace (old_fontface);
7759 #if !defined (MAC_OS8) || USE_ATSUI
7760 /* AppKit and WebKit do some adjustment to the heights of Courier,
7761 Helvetica, and Times. This only works on the environments where
7762 the XDrawImageString counterpart is never used. */
7763 if (strcmp (family, "courier") == 0 || strcmp (family, "helvetica") == 0
7764 || strcmp (family, "times") == 0)
7765 font->ascent += (font->ascent + font->descent) * .15 + 0.5;
7766 #endif
7768 return font;
7772 void
7773 mac_unload_font (dpyinfo, font)
7774 struct mac_display_info *dpyinfo;
7775 XFontStruct *font;
7777 xfree (font->full_name);
7778 if (font->per_char)
7779 xfree (font->per_char);
7780 #if USE_ATSUI
7781 if (font->mac_style)
7782 ATSUDisposeStyle (font->mac_style);
7783 #if USE_CG_TEXT_DRAWING
7784 if (font->cg_font)
7785 CGFontRelease (font->cg_font);
7786 if (font->cg_glyphs)
7787 xfree (font->cg_glyphs);
7788 #endif
7789 #endif
7790 xfree (font);
7794 /* Load font named FONTNAME of the size SIZE for frame F, and return a
7795 pointer to the structure font_info while allocating it dynamically.
7796 If SIZE is 0, load any size of font.
7797 If loading is failed, return NULL. */
7799 struct font_info *
7800 x_load_font (f, fontname, size)
7801 struct frame *f;
7802 register char *fontname;
7803 int size;
7805 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
7806 Lisp_Object font_names;
7808 /* Get a list of all the fonts that match this name. Once we
7809 have a list of matching fonts, we compare them against the fonts
7810 we already have by comparing names. */
7811 font_names = x_list_fonts (f, build_string (fontname), size, 1);
7813 if (!NILP (font_names))
7815 Lisp_Object tail;
7816 int i;
7818 for (i = 0; i < dpyinfo->n_fonts; i++)
7819 for (tail = font_names; CONSP (tail); tail = XCDR (tail))
7820 if (dpyinfo->font_table[i].name
7821 && (!strcmp (dpyinfo->font_table[i].name,
7822 SDATA (XCAR (tail)))
7823 || !strcmp (dpyinfo->font_table[i].full_name,
7824 SDATA (XCAR (tail)))))
7825 return (dpyinfo->font_table + i);
7827 else
7828 return NULL;
7830 /* Load the font and add it to the table. */
7832 char *full_name;
7833 struct MacFontStruct *font;
7834 struct font_info *fontp;
7835 unsigned long value;
7836 int i;
7838 fontname = (char *) SDATA (XCAR (font_names));
7840 BLOCK_INPUT;
7841 font = (MacFontStruct *) XLoadQueryFont (FRAME_MAC_DISPLAY (f), fontname);
7842 UNBLOCK_INPUT;
7843 if (!font)
7844 return NULL;
7846 /* Find a free slot in the font table. */
7847 for (i = 0; i < dpyinfo->n_fonts; ++i)
7848 if (dpyinfo->font_table[i].name == NULL)
7849 break;
7851 /* If no free slot found, maybe enlarge the font table. */
7852 if (i == dpyinfo->n_fonts
7853 && dpyinfo->n_fonts == dpyinfo->font_table_size)
7855 int sz;
7856 dpyinfo->font_table_size = max (16, 2 * dpyinfo->font_table_size);
7857 sz = dpyinfo->font_table_size * sizeof *dpyinfo->font_table;
7858 dpyinfo->font_table
7859 = (struct font_info *) xrealloc (dpyinfo->font_table, sz);
7862 fontp = dpyinfo->font_table + i;
7863 if (i == dpyinfo->n_fonts)
7864 ++dpyinfo->n_fonts;
7866 /* Now fill in the slots of *FONTP. */
7867 BLOCK_INPUT;
7868 bzero (fontp, sizeof (*fontp));
7869 fontp->font = font;
7870 fontp->font_idx = i;
7871 fontp->name = (char *) xmalloc (strlen (fontname) + 1);
7872 bcopy (fontname, fontp->name, strlen (fontname) + 1);
7874 if (font->min_bounds.width == font->max_bounds.width)
7876 /* Fixed width font. */
7877 fontp->average_width = fontp->space_width = font->min_bounds.width;
7879 else
7881 XChar2b char2b;
7882 XCharStruct *pcm;
7884 char2b.byte1 = 0x00, char2b.byte2 = 0x20;
7885 pcm = mac_per_char_metric (font, &char2b, 0);
7886 if (pcm)
7887 fontp->space_width = pcm->width;
7888 else
7889 fontp->space_width = FONT_WIDTH (font);
7891 if (pcm)
7893 int width = pcm->width;
7894 for (char2b.byte2 = 33; char2b.byte2 <= 126; char2b.byte2++)
7895 if ((pcm = mac_per_char_metric (font, &char2b, 0)) != NULL)
7896 width += pcm->width;
7897 fontp->average_width = width / 95;
7899 else
7900 fontp->average_width = FONT_WIDTH (font);
7903 fontp->full_name = (char *) xmalloc (strlen (font->full_name) + 1);
7904 bcopy (font->full_name, fontp->full_name, strlen (font->full_name) + 1);
7906 fontp->size = font->max_bounds.width;
7907 fontp->height = FONT_HEIGHT (font);
7909 /* For some font, ascent and descent in max_bounds field is
7910 larger than the above value. */
7911 int max_height = font->max_bounds.ascent + font->max_bounds.descent;
7912 if (max_height > fontp->height)
7913 fontp->height = max_height;
7916 /* The slot `encoding' specifies how to map a character
7917 code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
7918 the font code-points (0:0x20..0x7F, 1:0xA0..0xFF), or
7919 (0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF,
7920 2:0xA020..0xFF7F). For the moment, we don't know which charset
7921 uses this font. So, we set information in fontp->encoding[1]
7922 which is never used by any charset. If mapping can't be
7923 decided, set FONT_ENCODING_NOT_DECIDED. */
7924 if (font->mac_scriptcode == smJapanese)
7925 fontp->encoding[1] = 4;
7926 else
7928 fontp->encoding[1]
7929 = (font->max_byte1 == 0
7930 /* 1-byte font */
7931 ? (font->min_char_or_byte2 < 0x80
7932 ? (font->max_char_or_byte2 < 0x80
7933 ? 0 /* 0x20..0x7F */
7934 : FONT_ENCODING_NOT_DECIDED) /* 0x20..0xFF */
7935 : 1) /* 0xA0..0xFF */
7936 /* 2-byte font */
7937 : (font->min_byte1 < 0x80
7938 ? (font->max_byte1 < 0x80
7939 ? (font->min_char_or_byte2 < 0x80
7940 ? (font->max_char_or_byte2 < 0x80
7941 ? 0 /* 0x2020..0x7F7F */
7942 : FONT_ENCODING_NOT_DECIDED) /* 0x2020..0x7FFF */
7943 : 3) /* 0x20A0..0x7FFF */
7944 : FONT_ENCODING_NOT_DECIDED) /* 0x20??..0xA0?? */
7945 : (font->min_char_or_byte2 < 0x80
7946 ? (font->max_char_or_byte2 < 0x80
7947 ? 2 /* 0xA020..0xFF7F */
7948 : FONT_ENCODING_NOT_DECIDED) /* 0xA020..0xFFFF */
7949 : 1))); /* 0xA0A0..0xFFFF */
7952 #if 0 /* MAC_TODO: fill these out with more reasonably values */
7953 fontp->baseline_offset
7954 = (XGetFontProperty (font, dpyinfo->Xatom_MULE_BASELINE_OFFSET, &value)
7955 ? (long) value : 0);
7956 fontp->relative_compose
7957 = (XGetFontProperty (font, dpyinfo->Xatom_MULE_RELATIVE_COMPOSE, &value)
7958 ? (long) value : 0);
7959 fontp->default_ascent
7960 = (XGetFontProperty (font, dpyinfo->Xatom_MULE_DEFAULT_ASCENT, &value)
7961 ? (long) value : 0);
7962 #else
7963 fontp->baseline_offset = 0;
7964 fontp->relative_compose = 0;
7965 fontp->default_ascent = 0;
7966 #endif
7968 /* Set global flag fonts_changed_p to non-zero if the font loaded
7969 has a character with a smaller width than any other character
7970 before, or if the font loaded has a smaller height than any
7971 other font loaded before. If this happens, it will make a
7972 glyph matrix reallocation necessary. */
7973 fonts_changed_p |= x_compute_min_glyph_bounds (f);
7974 UNBLOCK_INPUT;
7975 return fontp;
7980 /* Return a pointer to struct font_info of a font named FONTNAME for
7981 frame F. If no such font is loaded, return NULL. */
7983 struct font_info *
7984 x_query_font (f, fontname)
7985 struct frame *f;
7986 register char *fontname;
7988 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
7989 int i;
7991 for (i = 0; i < dpyinfo->n_fonts; i++)
7992 if (dpyinfo->font_table[i].name
7993 && (!strcmp (dpyinfo->font_table[i].name, fontname)
7994 || !strcmp (dpyinfo->font_table[i].full_name, fontname)))
7995 return (dpyinfo->font_table + i);
7996 return NULL;
8000 /* Find a CCL program for a font specified by FONTP, and set the member
8001 `encoder' of the structure. */
8003 void
8004 x_find_ccl_program (fontp)
8005 struct font_info *fontp;
8007 Lisp_Object list, elt;
8009 for (list = Vfont_ccl_encoder_alist; CONSP (list); list = XCDR (list))
8011 elt = XCAR (list);
8012 if (CONSP (elt)
8013 && STRINGP (XCAR (elt))
8014 && (fast_c_string_match_ignore_case (XCAR (elt), fontp->name)
8015 >= 0))
8016 break;
8018 if (! NILP (list))
8020 struct ccl_program *ccl
8021 = (struct ccl_program *) xmalloc (sizeof (struct ccl_program));
8023 if (setup_ccl_program (ccl, XCDR (elt)) < 0)
8024 xfree (ccl);
8025 else
8026 fontp->font_encoder = ccl;
8032 /* The Mac Event loop code */
8034 #if !TARGET_API_MAC_CARBON
8035 #include <Events.h>
8036 #include <Quickdraw.h>
8037 #include <Balloons.h>
8038 #include <Devices.h>
8039 #include <Fonts.h>
8040 #include <Gestalt.h>
8041 #include <Menus.h>
8042 #include <Processes.h>
8043 #include <Sound.h>
8044 #include <ToolUtils.h>
8045 #include <TextUtils.h>
8046 #include <Dialogs.h>
8047 #include <Script.h>
8048 #include <Types.h>
8049 #include <Resources.h>
8051 #if __MWERKS__
8052 #include <unix.h>
8053 #endif
8054 #endif /* ! TARGET_API_MAC_CARBON */
8056 #define M_APPLE 128
8057 #define I_ABOUT 1
8059 #define WINDOW_RESOURCE 128
8060 #define TERM_WINDOW_RESOURCE 129
8062 #define DEFAULT_NUM_COLS 80
8064 #define MIN_DOC_SIZE 64
8065 #define MAX_DOC_SIZE 32767
8067 #define EXTRA_STACK_ALLOC (256 * 1024)
8069 #define ARGV_STRING_LIST_ID 129
8070 #define ABOUT_ALERT_ID 128
8071 #define RAM_TOO_LARGE_ALERT_ID 129
8073 /* Contains the string "reverse", which is a constant for mouse button emu.*/
8074 Lisp_Object Qreverse;
8077 /* Modifier associated with the control key, or nil to ignore. */
8078 Lisp_Object Vmac_control_modifier;
8080 /* Modifier associated with the option key, or nil to ignore. */
8081 Lisp_Object Vmac_option_modifier;
8083 /* Modifier associated with the command key, or nil to ignore. */
8084 Lisp_Object Vmac_command_modifier;
8086 /* Modifier associated with the function key, or nil to ignore. */
8087 Lisp_Object Vmac_function_modifier;
8089 /* True if the option and command modifiers should be used to emulate
8090 a three button mouse */
8091 Lisp_Object Vmac_emulate_three_button_mouse;
8093 #if USE_CARBON_EVENTS
8094 /* True if the mouse wheel button (i.e. button 4) should map to
8095 mouse-2, instead of mouse-3. */
8096 Lisp_Object Vmac_wheel_button_is_mouse_2;
8098 /* If Non-nil, the Mac "Command" key is passed on to the Mac Toolbox
8099 for processing before Emacs sees it. */
8100 Lisp_Object Vmac_pass_command_to_system;
8102 /* If Non-nil, the Mac "Control" key is passed on to the Mac Toolbox
8103 for processing before Emacs sees it. */
8104 Lisp_Object Vmac_pass_control_to_system;
8105 #endif
8107 /* Points to the variable `inev' in the function XTread_socket. It is
8108 used for passing an input event to the function back from
8109 Carbon/Apple event handlers. */
8110 static struct input_event *read_socket_inev = NULL;
8112 /* Set in term/mac-win.el to indicate that event loop can now generate
8113 drag and drop events. */
8114 Lisp_Object Qmac_ready_for_drag_n_drop;
8116 Point saved_menu_event_location;
8118 /* Apple Events */
8119 static void init_required_apple_events (void);
8120 static pascal OSErr
8121 do_ae_open_application (const AppleEvent *, AppleEvent *, long);
8122 static pascal OSErr
8123 do_ae_print_documents (const AppleEvent *, AppleEvent *, long);
8124 static pascal OSErr do_ae_open_documents (AppleEvent *, AppleEvent *, long);
8125 static pascal OSErr do_ae_quit_application (AppleEvent *, AppleEvent *, long);
8127 #if TARGET_API_MAC_CARBON
8128 /* Drag and Drop */
8129 static pascal OSErr mac_do_track_drag (DragTrackingMessage, WindowPtr, void*, DragReference);
8130 static pascal OSErr mac_do_receive_drag (WindowPtr, void*, DragReference);
8131 static DragTrackingHandlerUPP mac_do_track_dragUPP = NULL;
8132 static DragReceiveHandlerUPP mac_do_receive_dragUPP = NULL;
8133 #endif
8135 static Lisp_Object Qapplication, Qabout;
8136 #if USE_CARBON_EVENTS
8137 #ifdef MAC_OSX
8138 extern void init_service_handler ();
8139 static Lisp_Object Qpreferences, Qservices, Qpaste, Qperform;
8140 #endif
8141 /* Window Event Handler */
8142 static pascal OSStatus mac_handle_window_event (EventHandlerCallRef,
8143 EventRef, void *);
8144 #endif
8145 OSErr install_window_handler (WindowPtr);
8147 extern void init_emacs_passwd_dir ();
8148 extern int emacs_main (int, char **, char **);
8150 extern void initialize_applescript();
8151 extern void terminate_applescript();
8153 static unsigned int
8154 #if USE_CARBON_EVENTS
8155 mac_to_emacs_modifiers (UInt32 mods)
8156 #else
8157 mac_to_emacs_modifiers (EventModifiers mods)
8158 #endif
8160 unsigned int result = 0;
8161 if (mods & shiftKey)
8162 result |= shift_modifier;
8166 /* Deactivated to simplify configuration:
8167 if Vmac_option_modifier is non-NIL, we fully process the Option
8168 key. Otherwise, we only process it if an additional Ctrl or Command
8169 is pressed. That way the system may convert the character to a
8170 composed one.
8171 if ((mods & optionKey) &&
8172 (( !NILP(Vmac_option_modifier) ||
8173 ((mods & cmdKey) || (mods & controlKey))))) */
8175 if (!NILP (Vmac_option_modifier) && (mods & optionKey)) {
8176 Lisp_Object val = Fget(Vmac_option_modifier, Qmodifier_value);
8177 if (INTEGERP(val))
8178 result |= XUINT(val);
8180 if (!NILP (Vmac_command_modifier) && (mods & cmdKey)) {
8181 Lisp_Object val = Fget(Vmac_command_modifier, Qmodifier_value);
8182 if (INTEGERP(val))
8183 result |= XUINT(val);
8185 if (!NILP (Vmac_control_modifier) && (mods & controlKey)) {
8186 Lisp_Object val = Fget(Vmac_control_modifier, Qmodifier_value);
8187 if (INTEGERP(val))
8188 result |= XUINT(val);
8191 #ifdef MAC_OSX
8192 if (!NILP (Vmac_function_modifier) && (mods & kEventKeyModifierFnMask)) {
8193 Lisp_Object val = Fget(Vmac_function_modifier, Qmodifier_value);
8194 if (INTEGERP(val))
8195 result |= XUINT(val);
8197 #endif
8199 return result;
8202 static int
8203 mac_get_emulated_btn ( UInt32 modifiers )
8205 int result = 0;
8206 if (!NILP (Vmac_emulate_three_button_mouse)) {
8207 int cmdIs3 = !EQ (Vmac_emulate_three_button_mouse, Qreverse);
8208 if (modifiers & cmdKey)
8209 result = cmdIs3 ? 2 : 1;
8210 else if (modifiers & optionKey)
8211 result = cmdIs3 ? 1 : 2;
8213 return result;
8216 #if USE_CARBON_EVENTS
8217 /* Obtains the event modifiers from the event ref and then calls
8218 mac_to_emacs_modifiers. */
8219 static UInt32
8220 mac_event_to_emacs_modifiers (EventRef eventRef)
8222 UInt32 mods = 0;
8223 GetEventParameter (eventRef, kEventParamKeyModifiers, typeUInt32, NULL,
8224 sizeof (UInt32), NULL, &mods);
8225 if (!NILP (Vmac_emulate_three_button_mouse) &&
8226 GetEventClass(eventRef) == kEventClassMouse)
8228 mods &= ~(optionKey | cmdKey);
8230 return mac_to_emacs_modifiers (mods);
8233 /* Given an event ref, return the code to use for the mouse button
8234 code in the emacs input_event. */
8235 static int
8236 mac_get_mouse_btn (EventRef ref)
8238 EventMouseButton result = kEventMouseButtonPrimary;
8239 GetEventParameter (ref, kEventParamMouseButton, typeMouseButton, NULL,
8240 sizeof (EventMouseButton), NULL, &result);
8241 switch (result)
8243 case kEventMouseButtonPrimary:
8244 if (NILP (Vmac_emulate_three_button_mouse))
8245 return 0;
8246 else {
8247 UInt32 mods = 0;
8248 GetEventParameter (ref, kEventParamKeyModifiers, typeUInt32, NULL,
8249 sizeof (UInt32), NULL, &mods);
8250 return mac_get_emulated_btn(mods);
8252 case kEventMouseButtonSecondary:
8253 return NILP (Vmac_wheel_button_is_mouse_2) ? 1 : 2;
8254 case kEventMouseButtonTertiary:
8255 case 4: /* 4 is the number for the mouse wheel button */
8256 return NILP (Vmac_wheel_button_is_mouse_2) ? 2 : 1;
8257 default:
8258 return 0;
8262 /* Normally, ConvertEventRefToEventRecord will correctly handle all
8263 events. However the click of the mouse wheel is not converted to a
8264 mouseDown or mouseUp event. Likewise for dead key down events.
8265 This calls ConvertEventRef, but then checks to see if it is a mouse
8266 up/down, or a dead key down carbon event that has not been
8267 converted, and if so, converts it by hand (to be picked up in the
8268 XTread_socket loop). */
8269 static Boolean mac_convert_event_ref (EventRef eventRef, EventRecord *eventRec)
8271 Boolean result = ConvertEventRefToEventRecord (eventRef, eventRec);
8273 if (result)
8274 return result;
8276 switch (GetEventClass (eventRef))
8278 case kEventClassMouse:
8279 switch (GetEventKind (eventRef))
8281 case kEventMouseDown:
8282 eventRec->what = mouseDown;
8283 result = 1;
8284 break;
8286 case kEventMouseUp:
8287 eventRec->what = mouseUp;
8288 result = 1;
8289 break;
8291 default:
8292 break;
8294 break;
8296 case kEventClassKeyboard:
8297 switch (GetEventKind (eventRef))
8299 case kEventRawKeyDown:
8301 unsigned char char_codes;
8302 UInt32 key_code;
8304 eventRec->what = keyDown;
8305 GetEventParameter (eventRef, kEventParamKeyMacCharCodes, typeChar,
8306 NULL, sizeof (char), NULL, &char_codes);
8307 GetEventParameter (eventRef, kEventParamKeyCode, typeUInt32,
8308 NULL, sizeof (UInt32), NULL, &key_code);
8309 eventRec->message = char_codes | ((key_code & 0xff) << 8);
8310 result = 1;
8312 break;
8314 default:
8315 break;
8317 break;
8319 default:
8320 break;
8323 if (result)
8325 /* Need where and when. */
8326 UInt32 mods;
8328 GetEventParameter (eventRef, kEventParamMouseLocation, typeQDPoint,
8329 NULL, sizeof (Point), NULL, &eventRec->where);
8330 /* Use two step process because new event modifiers are 32-bit
8331 and old are 16-bit. Currently, only loss is NumLock & Fn. */
8332 GetEventParameter (eventRef, kEventParamKeyModifiers, typeUInt32,
8333 NULL, sizeof (UInt32), NULL, &mods);
8334 eventRec->modifiers = mods;
8336 eventRec->when = EventTimeToTicks (GetEventTime (eventRef));
8339 return result;
8342 #endif
8344 static void
8345 do_get_menus (void)
8347 Handle menubar_handle;
8348 MenuHandle menu_handle;
8350 menubar_handle = GetNewMBar (128);
8351 if(menubar_handle == NULL)
8352 abort ();
8353 SetMenuBar (menubar_handle);
8354 DrawMenuBar ();
8356 #if !TARGET_API_MAC_CARBON
8357 menu_handle = GetMenuHandle (M_APPLE);
8358 if(menu_handle != NULL)
8359 AppendResMenu (menu_handle,'DRVR');
8360 else
8361 abort ();
8362 #endif
8366 static void
8367 do_init_managers (void)
8369 #if !TARGET_API_MAC_CARBON
8370 InitGraf (&qd.thePort);
8371 InitFonts ();
8372 FlushEvents (everyEvent, 0);
8373 InitWindows ();
8374 InitMenus ();
8375 TEInit ();
8376 InitDialogs (NULL);
8377 #endif /* !TARGET_API_MAC_CARBON */
8378 InitCursor ();
8380 #if !TARGET_API_MAC_CARBON
8381 /* set up some extra stack space for use by emacs */
8382 SetApplLimit ((Ptr) ((long) GetApplLimit () - EXTRA_STACK_ALLOC));
8384 /* MaxApplZone must be called for AppleScript to execute more
8385 complicated scripts */
8386 MaxApplZone ();
8387 MoreMasters ();
8388 #endif /* !TARGET_API_MAC_CARBON */
8391 static void
8392 do_check_ram_size (void)
8394 SInt32 physical_ram_size, logical_ram_size;
8396 if (Gestalt (gestaltPhysicalRAMSize, &physical_ram_size) != noErr
8397 || Gestalt (gestaltLogicalRAMSize, &logical_ram_size) != noErr
8398 || physical_ram_size > (1 << VALBITS)
8399 || logical_ram_size > (1 << VALBITS))
8401 StopAlert (RAM_TOO_LARGE_ALERT_ID, NULL);
8402 exit (1);
8406 static void
8407 do_window_update (WindowPtr win)
8409 struct frame *f = mac_window_to_frame (win);
8411 BeginUpdate (win);
8413 /* The tooltip has been drawn already. Avoid the SET_FRAME_GARBAGED
8414 below. */
8415 if (win != tip_window)
8417 if (f->async_visible == 0)
8419 /* Update events may occur when a frame gets iconified. */
8420 #if 0
8421 f->async_visible = 1;
8422 f->async_iconified = 0;
8423 SET_FRAME_GARBAGED (f);
8424 #endif
8426 else
8428 Rect r;
8429 #if TARGET_API_MAC_CARBON
8430 RgnHandle region = NewRgn ();
8432 GetPortVisibleRegion (GetWindowPort (win), region);
8433 GetRegionBounds (region, &r);
8434 expose_frame (f, r.left, r.top, r.right - r.left, r.bottom - r.top);
8435 UpdateControls (win, region);
8436 DisposeRgn (region);
8437 #else
8438 r = (*win->visRgn)->rgnBBox;
8439 expose_frame (f, r.left, r.top, r.right - r.left, r.bottom - r.top);
8440 UpdateControls (win, win->visRgn);
8441 #endif
8445 EndUpdate (win);
8448 static int
8449 is_emacs_window (WindowPtr win)
8451 Lisp_Object tail, frame;
8453 if (!win)
8454 return 0;
8456 FOR_EACH_FRAME (tail, frame)
8457 if (FRAME_MAC_P (XFRAME (frame)))
8458 if (FRAME_MAC_WINDOW (XFRAME (frame)) == win)
8459 return 1;
8461 return 0;
8464 static void
8465 do_app_resume ()
8467 /* Window-activate events will do the job. */
8470 static void
8471 do_app_suspend ()
8473 /* Window-deactivate events will do the job. */
8477 static void
8478 do_apple_menu (SInt16 menu_item)
8480 #if !TARGET_API_MAC_CARBON
8481 Str255 item_name;
8482 SInt16 da_driver_refnum;
8484 if (menu_item == I_ABOUT)
8485 NoteAlert (ABOUT_ALERT_ID, NULL);
8486 else
8488 GetMenuItemText (GetMenuHandle (M_APPLE), menu_item, item_name);
8489 da_driver_refnum = OpenDeskAcc (item_name);
8491 #endif /* !TARGET_API_MAC_CARBON */
8494 void
8495 do_menu_choice (SInt32 menu_choice)
8497 SInt16 menu_id, menu_item;
8499 menu_id = HiWord (menu_choice);
8500 menu_item = LoWord (menu_choice);
8502 switch (menu_id)
8504 case 0:
8505 break;
8507 case M_APPLE:
8508 do_apple_menu (menu_item);
8509 break;
8511 default:
8513 struct frame *f = mac_focus_frame (&one_mac_display_info);
8514 MenuHandle menu = GetMenuHandle (menu_id);
8515 if (menu)
8517 UInt32 refcon;
8519 GetMenuItemRefCon (menu, menu_item, &refcon);
8520 menubar_selection_callback (f, refcon);
8525 HiliteMenu (0);
8529 /* Handle drags in size box. Based on code contributed by Ben
8530 Mesander and IM - Window Manager A. */
8532 static void
8533 do_grow_window (WindowPtr w, EventRecord *e)
8535 Rect limit_rect;
8536 int rows, columns, width, height;
8537 struct frame *f = mac_window_to_frame (w);
8538 XSizeHints *size_hints = FRAME_SIZE_HINTS (f);
8539 int min_width = MIN_DOC_SIZE, min_height = MIN_DOC_SIZE;
8540 #if TARGET_API_MAC_CARBON
8541 Rect new_rect;
8542 #else
8543 long grow_size;
8544 #endif
8546 if (size_hints->flags & PMinSize)
8548 min_width = size_hints->min_width;
8549 min_height = size_hints->min_height;
8551 SetRect (&limit_rect, min_width, min_height, MAX_DOC_SIZE, MAX_DOC_SIZE);
8553 #if TARGET_API_MAC_CARBON
8554 if (!ResizeWindow (w, e->where, &limit_rect, &new_rect))
8555 return;
8556 height = new_rect.bottom - new_rect.top;
8557 width = new_rect.right - new_rect.left;
8558 #else
8559 grow_size = GrowWindow (w, e->where, &limit_rect);
8560 /* see if it really changed size */
8561 if (grow_size == 0)
8562 return;
8563 height = HiWord (grow_size);
8564 width = LoWord (grow_size);
8565 #endif
8567 if (width != FRAME_PIXEL_WIDTH (f)
8568 || height != FRAME_PIXEL_HEIGHT (f))
8570 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, height);
8571 columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, width);
8573 x_set_window_size (f, 0, columns, rows);
8578 /* Handle clicks in zoom box. Calculation of "standard state" based
8579 on code in IM - Window Manager A and code contributed by Ben
8580 Mesander. The standard state of an Emacs window is 80-characters
8581 wide (DEFAULT_NUM_COLS) and as tall as will fit on the screen. */
8583 static void
8584 do_zoom_window (WindowPtr w, int zoom_in_or_out)
8586 GrafPtr save_port;
8587 Rect zoom_rect, port_rect;
8588 Point top_left;
8589 int w_title_height, columns, rows, width, height;
8590 struct frame *f = mac_window_to_frame (w);
8591 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
8593 #if TARGET_API_MAC_CARBON
8595 Point standard_size;
8597 standard_size.h = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, DEFAULT_NUM_COLS);
8598 standard_size.v = dpyinfo->height;
8600 if (IsWindowInStandardState (w, &standard_size, &zoom_rect))
8601 zoom_in_or_out = inZoomIn;
8602 else
8604 /* Adjust the standard size according to character boundaries. */
8606 columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, zoom_rect.right - zoom_rect.left);
8607 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, zoom_rect.bottom - zoom_rect.top);
8608 standard_size.h = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, columns);
8609 standard_size.v = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
8610 GetWindowBounds (w, kWindowContentRgn, &port_rect);
8611 if (IsWindowInStandardState (w, &standard_size, &zoom_rect)
8612 && port_rect.left == zoom_rect.left
8613 && port_rect.top == zoom_rect.top)
8614 zoom_in_or_out = inZoomIn;
8615 else
8616 zoom_in_or_out = inZoomOut;
8619 ZoomWindowIdeal (w, zoom_in_or_out, &standard_size);
8621 #else /* not TARGET_API_MAC_CARBON */
8622 GetPort (&save_port);
8624 SetPortWindowPort (w);
8626 /* Clear window to avoid flicker. */
8627 EraseRect (&(w->portRect));
8628 if (zoom_in_or_out == inZoomOut)
8630 SetPt (&top_left, w->portRect.left, w->portRect.top);
8631 LocalToGlobal (&top_left);
8633 /* calculate height of window's title bar */
8634 w_title_height = top_left.v - 1
8635 - (**((WindowPeek) w)->strucRgn).rgnBBox.top + GetMBarHeight ();
8637 /* get maximum height of window into zoom_rect.bottom - zoom_rect.top */
8638 zoom_rect = qd.screenBits.bounds;
8639 zoom_rect.top += w_title_height;
8640 InsetRect (&zoom_rect, 8, 4); /* not too tight */
8642 zoom_rect.right = zoom_rect.left
8643 + FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, DEFAULT_NUM_COLS);
8645 /* Adjust the standard size according to character boundaries. */
8646 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, zoom_rect.bottom - zoom_rect.top);
8647 zoom_rect.bottom =
8648 zoom_rect.top + FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
8650 (**((WStateDataHandle) ((WindowPeek) w)->dataHandle)).stdState
8651 = zoom_rect;
8654 ZoomWindow (w, zoom_in_or_out, f == mac_focus_frame (dpyinfo));
8656 SetPort (save_port);
8657 #endif /* not TARGET_API_MAC_CARBON */
8659 /* retrieve window size and update application values */
8660 #if TARGET_API_MAC_CARBON
8661 GetWindowPortBounds (w, &port_rect);
8662 #else
8663 port_rect = w->portRect;
8664 #endif
8665 height = port_rect.bottom - port_rect.top;
8666 width = port_rect.right - port_rect.left;
8668 if (width != FRAME_PIXEL_WIDTH (f)
8669 || height != FRAME_PIXEL_HEIGHT (f))
8671 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, height);
8672 columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, width);
8674 change_frame_size (f, rows, columns, 0, 1, 0);
8675 SET_FRAME_GARBAGED (f);
8676 cancel_mouse_face (f);
8678 FRAME_PIXEL_WIDTH (f) = width;
8679 FRAME_PIXEL_HEIGHT (f) = height;
8681 x_real_positions (f, &f->left_pos, &f->top_pos);
8684 /* Intialize AppleEvent dispatcher table for the required events. */
8685 void
8686 init_required_apple_events ()
8688 OSErr err;
8689 long result;
8691 /* Make sure we have apple events before starting. */
8692 err = Gestalt (gestaltAppleEventsAttr, &result);
8693 if (err != noErr)
8694 abort ();
8696 if (!(result & (1 << gestaltAppleEventsPresent)))
8697 abort ();
8699 #if TARGET_API_MAC_CARBON
8700 err = AEInstallEventHandler(kCoreEventClass, kAEOpenApplication,
8701 NewAEEventHandlerUPP
8702 ((AEEventHandlerProcPtr) do_ae_open_application),
8703 0L, false);
8704 #else
8705 err = AEInstallEventHandler(kCoreEventClass, kAEOpenApplication,
8706 NewAEEventHandlerProc
8707 ((AEEventHandlerProcPtr) do_ae_open_application),
8708 0L, false);
8709 #endif
8710 if (err != noErr)
8711 abort ();
8713 #if TARGET_API_MAC_CARBON
8714 err = AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments,
8715 NewAEEventHandlerUPP
8716 ((AEEventHandlerProcPtr) do_ae_open_documents),
8717 0L, false);
8718 #else
8719 err = AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments,
8720 NewAEEventHandlerProc
8721 ((AEEventHandlerProcPtr) do_ae_open_documents),
8722 0L, false);
8723 #endif
8724 if (err != noErr)
8725 abort ();
8727 #if TARGET_API_MAC_CARBON
8728 err = AEInstallEventHandler(kCoreEventClass, kAEPrintDocuments,
8729 NewAEEventHandlerUPP
8730 ((AEEventHandlerProcPtr) do_ae_print_documents),
8731 0L, false);
8732 #else
8733 err = AEInstallEventHandler(kCoreEventClass, kAEPrintDocuments,
8734 NewAEEventHandlerProc
8735 ((AEEventHandlerProcPtr) do_ae_print_documents),
8736 0L, false);
8737 #endif
8738 if (err != noErr)
8739 abort ();
8741 #if TARGET_API_MAC_CARBON
8742 err = AEInstallEventHandler(kCoreEventClass, kAEQuitApplication,
8743 NewAEEventHandlerUPP
8744 ((AEEventHandlerProcPtr) do_ae_quit_application),
8745 0L, false);
8746 #else
8747 err = AEInstallEventHandler(kCoreEventClass, kAEQuitApplication,
8748 NewAEEventHandlerProc
8749 ((AEEventHandlerProcPtr) do_ae_quit_application),
8750 0L, false);
8751 #endif
8752 if (err != noErr)
8753 abort ();
8756 void
8757 mac_store_application_menu_event (event)
8758 #if USE_CARBON_EVENTS
8759 EventRef event;
8760 #else
8761 UInt32 event;
8762 #endif
8764 struct input_event buf;
8765 Lisp_Object frame, entry;
8767 EVENT_INIT (buf);
8769 XSETFRAME (frame, mac_focus_frame (&one_mac_display_info));
8770 buf.kind = MENU_BAR_EVENT;
8771 buf.frame_or_window = frame;
8772 buf.arg = frame;
8773 kbd_buffer_store_event (&buf);
8775 buf.arg = Qapplication;
8776 kbd_buffer_store_event (&buf);
8778 #if USE_CARBON_EVENTS
8779 switch (GetEventClass (event))
8781 #ifdef MAC_OSX
8782 case kEventClassService:
8783 buf.arg = Qservices;
8784 kbd_buffer_store_event (&buf);
8785 switch (GetEventKind (event))
8787 case kEventServicePaste:
8788 entry = Qpaste;
8789 break;
8791 case kEventServicePerform:
8793 OSErr err;
8794 CFStringRef message;
8796 err = GetEventParameter (event, kEventParamServiceMessageName,
8797 typeCFStringRef, NULL,
8798 sizeof (CFStringRef), NULL, &message);
8799 buf.arg = Qperform;
8800 kbd_buffer_store_event (&buf);
8801 if (err == noErr && message)
8802 entry = intern (SDATA (cfstring_to_lisp (message)));
8803 else
8804 entry = Qnil;
8806 break;
8808 default:
8809 abort ();
8811 break;
8812 #endif /* MAC_OSX */
8813 case kEventClassCommand:
8815 HICommand command;
8817 GetEventParameter(event, kEventParamDirectObject, typeHICommand,
8818 NULL, sizeof (HICommand), NULL, &command);
8819 switch (command.commandID)
8821 case kHICommandAbout:
8822 entry = Qabout;
8823 break;
8824 #ifdef MAC_OSX
8825 case kHICommandPreferences:
8826 entry = Qpreferences;
8827 break;
8828 #endif /* MAC_OSX */
8829 case kHICommandQuit:
8830 entry = Qquit;
8831 break;
8832 default:
8833 abort ();
8836 break;
8838 default:
8839 abort ();
8841 #else /* USE_CARBON_EVENTS */
8842 switch (event)
8844 case kHICommandAbout:
8845 entry = Qabout;
8846 break;
8847 case kHICommandQuit:
8848 entry = Qquit;
8849 break;
8850 default:
8851 abort ();
8853 #endif
8855 buf.arg = entry;
8856 kbd_buffer_store_event (&buf);
8859 #if USE_CARBON_EVENTS
8860 static pascal OSStatus
8861 mac_handle_command_event (next_handler, event, data)
8862 EventHandlerCallRef next_handler;
8863 EventRef event;
8864 void *data;
8866 HICommand command;
8867 OSErr result;
8869 GetEventParameter(event, kEventParamDirectObject, typeHICommand, NULL,
8870 sizeof (HICommand), NULL, &command);
8872 switch (command.commandID)
8874 case kHICommandAbout:
8875 #ifdef MAC_OSX
8876 case kHICommandPreferences:
8877 #endif /* MAC_OSX */
8878 result = CallNextEventHandler (next_handler, event);
8879 if (result != eventNotHandledErr)
8880 return result;
8882 mac_store_application_menu_event (event);
8883 return noErr;
8885 default:
8886 break;
8889 return eventNotHandledErr;
8892 static OSErr
8893 init_command_handler ()
8895 OSErr err = noErr;
8896 EventTypeSpec specs[] = {{kEventClassCommand, kEventCommandProcess}};
8897 static EventHandlerUPP handle_command_eventUPP = NULL;
8899 if (handle_command_eventUPP == NULL)
8900 handle_command_eventUPP = NewEventHandlerUPP (mac_handle_command_event);
8901 return InstallApplicationEventHandler (handle_command_eventUPP,
8902 GetEventTypeCount (specs), specs,
8903 NULL, NULL);
8906 static pascal OSStatus
8907 mac_handle_window_event (next_handler, event, data)
8908 EventHandlerCallRef next_handler;
8909 EventRef event;
8910 void *data;
8912 WindowPtr wp;
8913 OSStatus result;
8914 UInt32 attributes;
8915 XSizeHints *size_hints;
8917 GetEventParameter (event, kEventParamDirectObject, typeWindowRef,
8918 NULL, sizeof (WindowPtr), NULL, &wp);
8920 switch (GetEventKind (event))
8922 case kEventWindowUpdate:
8923 result = CallNextEventHandler (next_handler, event);
8924 if (result != eventNotHandledErr)
8925 return result;
8927 do_window_update (wp);
8928 return noErr;
8930 case kEventWindowBoundsChanging:
8931 result = CallNextEventHandler (next_handler, event);
8932 if (result != eventNotHandledErr)
8933 return result;
8935 GetEventParameter (event, kEventParamAttributes, typeUInt32,
8936 NULL, sizeof (UInt32), NULL, &attributes);
8937 size_hints = FRAME_SIZE_HINTS (mac_window_to_frame (wp));
8938 if ((attributes & kWindowBoundsChangeUserResize)
8939 && ((size_hints->flags & (PResizeInc | PBaseSize | PMinSize))
8940 == (PResizeInc | PBaseSize | PMinSize)))
8942 Rect bounds;
8943 int width, height;
8945 GetEventParameter (event, kEventParamCurrentBounds,
8946 typeQDRectangle,
8947 NULL, sizeof (Rect), NULL, &bounds);
8948 width = bounds.right - bounds.left;
8949 height = bounds.bottom - bounds.top;
8951 if (width < size_hints->min_width)
8952 width = size_hints->min_width;
8953 else
8954 width = size_hints->base_width
8955 + (int) ((width - size_hints->base_width)
8956 / (float) size_hints->width_inc + .5)
8957 * size_hints->width_inc;
8959 if (height < size_hints->min_height)
8960 height = size_hints->min_height;
8961 else
8962 height = size_hints->base_height
8963 + (int) ((height - size_hints->base_height)
8964 / (float) size_hints->height_inc + .5)
8965 * size_hints->height_inc;
8967 bounds.right = bounds.left + width;
8968 bounds.bottom = bounds.top + height;
8969 SetEventParameter (event, kEventParamCurrentBounds,
8970 typeQDRectangle, sizeof (Rect), &bounds);
8971 return noErr;
8973 break;
8975 case kEventWindowShown:
8976 case kEventWindowHidden:
8977 case kEventWindowExpanded:
8978 case kEventWindowCollapsed:
8979 result = CallNextEventHandler (next_handler, event);
8981 mac_handle_visibility_change (mac_window_to_frame (wp));
8982 return noErr;
8984 break;
8987 return eventNotHandledErr;
8990 static pascal OSStatus
8991 mac_handle_mouse_event (next_handler, event, data)
8992 EventHandlerCallRef next_handler;
8993 EventRef event;
8994 void *data;
8996 OSStatus result;
8998 switch (GetEventKind (event))
9000 case kEventMouseWheelMoved:
9002 WindowPtr wp;
9003 struct frame *f;
9004 EventMouseWheelAxis axis;
9005 SInt32 delta;
9006 Point point;
9008 result = CallNextEventHandler (next_handler, event);
9009 if (result != eventNotHandledErr || read_socket_inev == NULL)
9010 return result;
9012 GetEventParameter (event, kEventParamWindowRef, typeWindowRef,
9013 NULL, sizeof (WindowRef), NULL, &wp);
9014 f = mac_window_to_frame (wp);
9015 if (f != mac_focus_frame (&one_mac_display_info))
9016 break;
9018 GetEventParameter (event, kEventParamMouseWheelAxis,
9019 typeMouseWheelAxis, NULL,
9020 sizeof (EventMouseWheelAxis), NULL, &axis);
9021 if (axis != kEventMouseWheelAxisY)
9022 break;
9024 GetEventParameter (event, kEventParamMouseWheelDelta, typeSInt32,
9025 NULL, sizeof (SInt32), NULL, &delta);
9026 GetEventParameter (event, kEventParamMouseLocation, typeQDPoint,
9027 NULL, sizeof (Point), NULL, &point);
9028 read_socket_inev->kind = WHEEL_EVENT;
9029 read_socket_inev->code = 0;
9030 read_socket_inev->modifiers =
9031 (mac_event_to_emacs_modifiers (event)
9032 | ((delta < 0) ? down_modifier : up_modifier));
9033 SetPortWindowPort (wp);
9034 GlobalToLocal (&point);
9035 XSETINT (read_socket_inev->x, point.h);
9036 XSETINT (read_socket_inev->y, point.v);
9037 XSETFRAME (read_socket_inev->frame_or_window, f);
9039 return noErr;
9041 break;
9043 default:
9044 break;
9047 return eventNotHandledErr;
9049 #endif /* USE_CARBON_EVENTS */
9052 OSErr
9053 install_window_handler (window)
9054 WindowPtr window;
9056 OSErr err = noErr;
9057 #if USE_CARBON_EVENTS
9058 EventTypeSpec specs_window[] =
9059 {{kEventClassWindow, kEventWindowUpdate},
9060 {kEventClassWindow, kEventWindowBoundsChanging},
9061 {kEventClassWindow, kEventWindowShown},
9062 {kEventClassWindow, kEventWindowHidden},
9063 {kEventClassWindow, kEventWindowExpanded},
9064 {kEventClassWindow, kEventWindowCollapsed}};
9065 EventTypeSpec specs_mouse[] = {{kEventClassMouse, kEventMouseWheelMoved}};
9066 static EventHandlerUPP handle_window_eventUPP = NULL;
9067 static EventHandlerUPP handle_mouse_eventUPP = NULL;
9069 if (handle_window_eventUPP == NULL)
9070 handle_window_eventUPP = NewEventHandlerUPP (mac_handle_window_event);
9071 if (handle_mouse_eventUPP == NULL)
9072 handle_mouse_eventUPP = NewEventHandlerUPP (mac_handle_mouse_event);
9073 err = InstallWindowEventHandler (window, handle_window_eventUPP,
9074 GetEventTypeCount (specs_window),
9075 specs_window, NULL, NULL);
9076 if (err == noErr)
9077 err = InstallWindowEventHandler (window, handle_mouse_eventUPP,
9078 GetEventTypeCount (specs_mouse),
9079 specs_mouse, NULL, NULL);
9080 #endif
9081 #if TARGET_API_MAC_CARBON
9082 if (mac_do_track_dragUPP == NULL)
9083 mac_do_track_dragUPP = NewDragTrackingHandlerUPP (mac_do_track_drag);
9084 if (mac_do_receive_dragUPP == NULL)
9085 mac_do_receive_dragUPP = NewDragReceiveHandlerUPP (mac_do_receive_drag);
9087 if (err == noErr)
9088 err = InstallTrackingHandler (mac_do_track_dragUPP, window, NULL);
9089 if (err == noErr)
9090 err = InstallReceiveHandler (mac_do_receive_dragUPP, window, NULL);
9091 #endif
9092 return err;
9095 void
9096 remove_window_handler (window)
9097 WindowPtr window;
9099 #if TARGET_API_MAC_CARBON
9100 if (mac_do_track_dragUPP)
9101 RemoveTrackingHandler (mac_do_track_dragUPP, window);
9102 if (mac_do_receive_dragUPP)
9103 RemoveReceiveHandler (mac_do_receive_dragUPP, window);
9104 #endif
9107 /* Open Application Apple Event */
9108 static pascal OSErr
9109 do_ae_open_application(const AppleEvent *pae, AppleEvent *preply, long prefcon)
9111 return noErr;
9115 /* Called when we receive an AppleEvent with an ID of
9116 "kAEOpenDocuments". This routine gets the direct parameter,
9117 extracts the FSSpecs in it, and puts their names on a list. */
9118 #pragma options align=mac68k
9119 typedef struct SelectionRange {
9120 short unused1; // 0 (not used)
9121 short lineNum; // line to select (<0 to specify range)
9122 long startRange; // start of selection range (if line < 0)
9123 long endRange; // end of selection range (if line < 0)
9124 long unused2; // 0 (not used)
9125 long theDate; // modification date/time
9126 } SelectionRange;
9127 #pragma options align=reset
9129 static pascal OSErr
9130 do_ae_open_documents(AppleEvent *message, AppleEvent *reply, long refcon)
9132 OSErr err, err2;
9133 AEDesc the_desc;
9134 AEKeyword keyword;
9135 DescType actual_type;
9136 Size actual_size;
9137 SelectionRange position;
9138 Lisp_Object file_list = Qnil;
9140 xassert (read_socket_inev);
9142 err = AEGetParamDesc (message, keyDirectObject, typeAEList, &the_desc);
9143 if (err != noErr)
9144 goto descriptor_error_exit;
9146 err = AEGetParamPtr (message, keyAEPosition, typeChar, &actual_type, &position, sizeof(SelectionRange), &actual_size);
9147 if (err == noErr)
9148 file_list = Fcons (list3 (make_number (position.lineNum + 1),
9149 make_number (position.startRange + 1),
9150 make_number (position.endRange + 1)),
9151 file_list);
9153 /* Check to see that we got all of the required parameters from the
9154 event descriptor. For an 'odoc' event this should just be the
9155 file list. */
9156 err = AEGetAttributePtr(message, keyMissedKeywordAttr, typeWildCard,
9157 &actual_type, (Ptr) &keyword,
9158 sizeof (keyword), &actual_size);
9159 /* No error means that we found some unused parameters.
9160 errAEDescNotFound means that there are no more parameters. If we
9161 get an error code other than that, flag it. */
9162 if ((err == noErr) || (err != errAEDescNotFound))
9164 err = errAEEventNotHandled;
9165 goto error_exit;
9167 err = noErr;
9169 /* Got all the parameters we need. Now, go through the direct
9170 object list and parse it up. */
9172 long num_files_to_open;
9174 err = AECountItems (&the_desc, &num_files_to_open);
9175 if (err == noErr)
9177 int i;
9179 /* AE file list is one based so just use that for indexing here. */
9180 for (i = 1; i <= num_files_to_open; i++)
9182 char unix_path_name[MAXPATHLEN];
9183 #ifdef MAC_OSX
9184 FSRef fref;
9186 err = AEGetNthPtr (&the_desc, i, typeFSRef, &keyword,
9187 &actual_type, &fref, sizeof (FSRef),
9188 &actual_size);
9189 if (err != noErr || actual_type != typeFSRef)
9190 continue;
9192 if (FSRefMakePath (&fref, unix_path_name, sizeof (unix_path_name))
9193 == noErr)
9194 #else
9195 FSSpec fs;
9197 err = AEGetNthPtr(&the_desc, i, typeFSS, &keyword, &actual_type,
9198 (Ptr) &fs, sizeof (fs), &actual_size);
9199 if (err != noErr) continue;
9201 if (fsspec_to_posix_pathname (&fs, unix_path_name,
9202 sizeof (unix_path_name) - 1) == noErr)
9203 #endif
9204 /* x-dnd functions expect undecoded filenames. */
9205 file_list = Fcons (make_unibyte_string (unix_path_name,
9206 strlen (unix_path_name)),
9207 file_list);
9211 /* Build a DRAG_N_DROP_EVENT type event as is done in
9212 constuct_drag_n_drop in w32term.c. */
9213 if (!NILP (file_list))
9215 struct frame *f = mac_focus_frame (&one_mac_display_info);
9216 WindowPtr wp;
9217 Lisp_Object frame;
9219 read_socket_inev->kind = DRAG_N_DROP_EVENT;
9220 read_socket_inev->code = 0;
9221 read_socket_inev->modifiers = 0;
9223 XSETINT (read_socket_inev->x, 0);
9224 XSETINT (read_socket_inev->y, 0);
9226 XSETFRAME (frame, f);
9227 read_socket_inev->frame_or_window = Fcons (frame, file_list);
9229 #if 0
9230 /* Regardless of whether Emacs was suspended or in the
9231 foreground, ask it to redraw its entire screen. Otherwise
9232 parts of the screen can be left in an inconsistent
9233 state. */
9234 wp = FRAME_MAC_WINDOW (f);
9235 if (wp)
9236 #if TARGET_API_MAC_CARBON
9238 Rect r;
9240 GetWindowPortBounds (wp, &r);
9241 InvalWindowRect (wp, &r);
9243 #else /* not TARGET_API_MAC_CARBON */
9244 InvalRect (&(wp->portRect));
9245 #endif /* not TARGET_API_MAC_CARBON */
9246 #endif
9250 error_exit:
9251 /* Nuke the coerced file list in any case */
9252 err2 = AEDisposeDesc(&the_desc);
9254 descriptor_error_exit:
9255 /* InvalRect(&(gFrontMacWindowP->mWP->portRect)); */
9256 return err;
9260 #if TARGET_API_MAC_CARBON
9261 static pascal OSErr
9262 mac_do_track_drag (DragTrackingMessage message, WindowPtr window,
9263 void *handlerRefCon, DragReference theDrag)
9265 static int can_accept;
9266 short items;
9267 short index;
9268 ItemReference theItem;
9269 FlavorFlags theFlags;
9270 OSErr result;
9272 if (GetFrontWindowOfClass (kMovableModalWindowClass, false))
9273 return dragNotAcceptedErr;
9275 switch (message)
9277 case kDragTrackingEnterHandler:
9278 CountDragItems (theDrag, &items);
9279 can_accept = 0;
9280 for (index = 1; index <= items; index++)
9282 GetDragItemReferenceNumber (theDrag, index, &theItem);
9283 result = GetFlavorFlags (theDrag, theItem, flavorTypeHFS, &theFlags);
9284 if (result == noErr)
9286 can_accept = 1;
9287 break;
9290 break;
9292 case kDragTrackingEnterWindow:
9293 if (can_accept)
9295 RgnHandle hilite_rgn = NewRgn ();
9296 Rect r;
9297 struct frame *f = mac_window_to_frame (window);
9299 GetWindowPortBounds (window, &r);
9300 OffsetRect (&r, -r.left, -r.top);
9301 RectRgn (hilite_rgn, &r);
9302 ShowDragHilite (theDrag, hilite_rgn, true);
9303 DisposeRgn (hilite_rgn);
9304 SetThemeCursor (kThemeCopyArrowCursor);
9306 break;
9308 case kDragTrackingInWindow:
9309 break;
9311 case kDragTrackingLeaveWindow:
9312 if (can_accept)
9314 struct frame *f = mac_window_to_frame (window);
9316 HideDragHilite (theDrag);
9317 SetThemeCursor (kThemeArrowCursor);
9319 break;
9321 case kDragTrackingLeaveHandler:
9322 break;
9325 return noErr;
9328 static pascal OSErr
9329 mac_do_receive_drag (WindowPtr window, void *handlerRefCon,
9330 DragReference theDrag)
9332 short items;
9333 short index;
9334 FlavorFlags theFlags;
9335 Point mouse;
9336 OSErr result;
9337 ItemReference theItem;
9338 HFSFlavor data;
9339 Size size = sizeof (HFSFlavor);
9340 Lisp_Object file_list;
9342 if (GetFrontWindowOfClass (kMovableModalWindowClass, false))
9343 return dragNotAcceptedErr;
9345 file_list = Qnil;
9346 GetDragMouse (theDrag, &mouse, 0L);
9347 CountDragItems (theDrag, &items);
9348 for (index = 1; index <= items; index++)
9350 /* Only handle file references. */
9351 GetDragItemReferenceNumber (theDrag, index, &theItem);
9352 result = GetFlavorFlags (theDrag, theItem, flavorTypeHFS, &theFlags);
9353 if (result == noErr)
9355 #ifdef MAC_OSX
9356 FSRef fref;
9357 #endif
9358 char unix_path_name[MAXPATHLEN];
9360 GetFlavorData (theDrag, theItem, flavorTypeHFS, &data, &size, 0L);
9361 #ifdef MAC_OSX
9362 /* Use Carbon routines, otherwise it converts the file name
9363 to /Macintosh HD/..., which is not correct. */
9364 FSpMakeFSRef (&data.fileSpec, &fref);
9365 if (! FSRefMakePath (&fref, unix_path_name, sizeof (unix_path_name)));
9366 #else
9367 if (fsspec_to_posix_pathname (&data.fileSpec, unix_path_name,
9368 sizeof (unix_path_name) - 1) == noErr)
9369 #endif
9370 /* x-dnd functions expect undecoded filenames. */
9371 file_list = Fcons (make_unibyte_string (unix_path_name,
9372 strlen (unix_path_name)),
9373 file_list);
9376 /* If there are items in the list, construct an event and post it to
9377 the queue like an interrupt using kbd_buffer_store_event. */
9378 if (!NILP (file_list))
9380 struct input_event event;
9381 Lisp_Object frame;
9382 struct frame *f = mac_window_to_frame (window);
9383 SInt16 modifiers;
9385 GlobalToLocal (&mouse);
9386 GetDragModifiers (theDrag, NULL, NULL, &modifiers);
9388 event.kind = DRAG_N_DROP_EVENT;
9389 event.code = 0;
9390 event.modifiers = mac_to_emacs_modifiers (modifiers);
9391 event.timestamp = TickCount () * (1000 / 60);
9392 XSETINT (event.x, mouse.h);
9393 XSETINT (event.y, mouse.v);
9394 XSETFRAME (frame, f);
9395 event.frame_or_window = Fcons (frame, file_list);
9396 event.arg = Qnil;
9397 /* Post to the interrupt queue */
9398 kbd_buffer_store_event (&event);
9399 /* MAC_TODO: Mimic behavior of windows by switching contexts to Emacs */
9401 ProcessSerialNumber psn;
9402 GetCurrentProcess (&psn);
9403 SetFrontProcess (&psn);
9406 return noErr;
9408 else
9409 return dragNotAcceptedErr;
9411 #endif
9414 /* Print Document Apple Event */
9415 static pascal OSErr
9416 do_ae_print_documents (const AppleEvent *pAE, AppleEvent *reply, long refcon)
9418 return errAEEventNotHandled;
9422 static pascal OSErr
9423 do_ae_quit_application (AppleEvent* message, AppleEvent *reply, long refcon)
9425 #if USE_CARBON_EVENTS
9426 OSErr err;
9427 EventRef event = NULL;
9428 static const HICommand quit_command = {kEventAttributeNone, kHICommandQuit};
9430 err = CreateEvent (NULL, kEventClassCommand, kEventCommandProcess, 0,
9431 kEventAttributeUserEvent, &event);
9432 if (err == noErr)
9433 err = SetEventParameter (event, kEventParamDirectObject, typeHICommand,
9434 sizeof (HICommand), &quit_command);
9435 if (err == noErr)
9436 mac_store_application_menu_event (event);
9437 if (event)
9438 ReleaseEvent (event);
9440 if (err == noErr)
9441 return noErr;
9442 else
9443 return errAEEventNotHandled;
9444 #else
9445 mac_store_application_menu_event (kHICommandQuit);
9447 return noErr;
9448 #endif
9452 #if __profile__
9453 void
9454 profiler_exit_proc ()
9456 ProfilerDump ("\pEmacs.prof");
9457 ProfilerTerm ();
9459 #endif
9461 /* These few functions implement Emacs as a normal Mac application
9462 (almost): set up the heap and the Toolbox, handle necessary system
9463 events plus a few simple menu events. They also set up Emacs's
9464 access to functions defined in the rest of this file. Emacs uses
9465 function hooks to perform all its terminal I/O. A complete list of
9466 these functions appear in termhooks.h. For what they do, read the
9467 comments there and see also w32term.c and xterm.c. What's
9468 noticeably missing here is the event loop, which is normally
9469 present in most Mac application. After performing the necessary
9470 Mac initializations, main passes off control to emacs_main
9471 (corresponding to main in emacs.c). Emacs_main calls XTread_socket
9472 (defined further below) to read input. This is where
9473 WaitNextEvent/ReceiveNextEvent is called to process Mac events. */
9475 #ifdef MAC_OS8
9476 #undef main
9478 main (void)
9480 #if __profile__ /* is the profiler on? */
9481 if (ProfilerInit(collectDetailed, bestTimeBase, 5000, 200))
9482 exit(1);
9483 #endif
9485 #if __MWERKS__
9486 /* set creator and type for files created by MSL */
9487 _fcreator = 'EMAx';
9488 _ftype = 'TEXT';
9489 #endif
9491 do_init_managers ();
9493 do_get_menus ();
9495 #ifndef USE_LSB_TAG
9496 do_check_ram_size ();
9497 #endif
9499 init_emacs_passwd_dir ();
9501 init_environ ();
9503 initialize_applescript ();
9505 init_required_apple_events ();
9508 char **argv;
9509 int argc = 0;
9511 /* set up argv array from STR# resource */
9512 get_string_list (&argv, ARGV_STRING_LIST_ID);
9513 while (argv[argc])
9514 argc++;
9516 /* free up AppleScript resources on exit */
9517 atexit (terminate_applescript);
9519 #if __profile__ /* is the profiler on? */
9520 atexit (profiler_exit_proc);
9521 #endif
9523 /* 3rd param "envp" never used in emacs_main */
9524 (void) emacs_main (argc, argv, 0);
9527 /* Never reached - real exit in Fkill_emacs */
9528 return 0;
9530 #endif
9532 /* Table for translating Mac keycode to X keysym values. Contributed
9533 by Sudhir Shenoy.
9534 Mapping for special keys is now identical to that in Apple X11
9535 except `clear' (-> <clear>) on the KeyPad, `enter' (-> <kp-enter>)
9536 on the right of the Cmd key on laptops, and fn + `enter' (->
9537 <linefeed>). */
9538 static unsigned char keycode_to_xkeysym_table[] = {
9539 /*0x00*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9540 /*0x10*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9541 /*0x20*/ 0, 0, 0, 0, 0x0d /*return*/, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9543 /*0x30*/ 0x09 /*tab*/, 0 /*0x0020 space*/, 0, 0x08 /*backspace*/,
9544 /*0x34*/ 0x8d /*enter on laptops*/, 0x1b /*escape*/, 0, 0,
9545 /*0x38*/ 0, 0, 0, 0,
9546 /*0x3C*/ 0, 0, 0, 0,
9548 /*0x40*/ 0, 0xae /*kp-.*/, 0, 0xaa /*kp-**/,
9549 /*0x44*/ 0, 0xab /*kp-+*/, 0, 0x0b /*clear*/,
9550 /*0x48*/ 0, 0, 0, 0xaf /*kp-/*/,
9551 /*0x4C*/ 0x8d /*kp-enter*/, 0, 0xad /*kp--*/, 0,
9553 /*0x50*/ 0, 0xbd /*kp-=*/, 0xb0 /*kp-0*/, 0xb1 /*kp-1*/,
9554 /*0x54*/ 0xb2 /*kp-2*/, 0xb3 /*kp-3*/, 0xb4 /*kp-4*/, 0xb5 /*kp-5*/,
9555 /*0x58*/ 0xb6 /*kp-6*/, 0xb7 /*kp-7*/, 0, 0xb8 /*kp-8*/,
9556 /*0x5C*/ 0xb9 /*kp-9*/, 0, 0, 0,
9558 /*0x60*/ 0xc2 /*f5*/, 0xc3 /*f6*/, 0xc4 /*f7*/, 0xc0 /*f3*/,
9559 /*0x64*/ 0xc5 /*f8*/, 0xc6 /*f9*/, 0, 0xc8 /*f11*/,
9560 /*0x68*/ 0, 0xca /*f13*/, 0, 0xcb /*f14*/,
9561 /*0x6C*/ 0, 0xc7 /*f10*/, 0x0a /*fn+enter on laptops*/, 0xc9 /*f12*/,
9563 /*0x70*/ 0, 0xcc /*f15*/, 0x6a /*help*/, 0x50 /*home*/,
9564 /*0x74*/ 0x55 /*pgup*/, 0xff /*delete*/, 0xc1 /*f4*/, 0x57 /*end*/,
9565 /*0x78*/ 0xbf /*f2*/, 0x56 /*pgdown*/, 0xbe /*f1*/, 0x51 /*left*/,
9566 /*0x7C*/ 0x53 /*right*/, 0x54 /*down*/, 0x52 /*up*/, 0
9570 static int
9571 keycode_to_xkeysym (int keyCode, int *xKeySym)
9573 *xKeySym = keycode_to_xkeysym_table [keyCode & 0x7f];
9574 return *xKeySym != 0;
9577 static unsigned char fn_keycode_to_xkeysym_table[] = {
9578 /*0x00*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9579 /*0x10*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9580 /*0x20*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9582 /*0x30*/ 0, 0, 0, 0,
9583 /*0x34*/ 0, 0, 0, 0,
9584 /*0x38*/ 0, 0, 0, 0,
9585 /*0x3C*/ 0, 0, 0, 0,
9587 /*0x40*/ 0, 0x2e /*kp-. = .*/, 0, 0x50 /*kp-* = 'p'*/,
9588 /*0x44*/ 0, '/' /*kp-+*/, 0, 0,
9589 /*0x48*/ 0, 0, 0, 0x30 /*kp-/ = '0'*/,
9590 /*0x4C*/ 0, 0, 0x3b /*kp-- = ';'*/, 0,
9592 /*0x50*/ 0, 0x2d /*kp-= = '-'*/, 0x6d /*kp-0 = 'm'*/, 0x6a /*kp-1 = 'j'*/,
9593 /*0x54*/ 0x6b /*kp-2 = 'k'*/, 0x6c /*kp-3 = 'l'*/, 'u' /*kp-4*/, 'i' /*kp-5*/,
9594 /*0x58*/ 'o' /*kp-6*/, '7' /*kp-7*/, 0, '8' /*kp-8*/,
9595 /*0x5C*/ '9' /*kp-9*/, 0, 0, 0,
9597 /*0x60*/ 0, 0, 0, 0,
9598 /*0x64*/ 0, 0, 0, 0,
9599 /*0x68*/ 0, 0, 0, 0,
9600 /*0x6C*/ 0, 0, 0, 0,
9602 /*0x70*/ 0, 0, 0, 0,
9603 /*0x74*/ 0, 0, 0, 0,
9604 /*0x78*/ 0, 0, 0, 0,
9605 /*0x7C*/ 0, 0, 0, 0
9607 static int
9608 convert_fn_keycode (EventRef eventRef, int keyCode, int *newCode)
9610 #ifdef MAC_OSX
9611 /* Use the special map to translate keys when function modifier is
9612 to be caught. KeyTranslate can't be used in that case.
9613 We can't detect the function key using the input_event.modifiers,
9614 because this uses the high word of an UInt32. Therefore,
9615 we'll just read it out of the original eventRef.
9619 /* TODO / known issues
9621 - Fn-Shift-j is regonized as Fn-j and not Fn-J.
9622 The above table always translates to lower characters. We need to use
9623 the KCHR keyboard resource (KeyTranslate() ) to map k->K and 8->*.
9625 - The table is meant for English language keyboards, and it will work
9626 for many others with the exception of key combinations like Fn-ö on
9627 a German keyboard, which is currently mapped to Fn-;.
9628 How to solve this without keeping separate tables for all keyboards
9629 around? KeyTranslate isn't of much help here, as it only takes a 16-bit
9630 value for keycode with the modifiers in he high byte, i.e. no room for the
9631 Fn modifier. That's why we need the table.
9635 UInt32 mods = 0;
9636 if (!NILP(Vmac_function_modifier))
9638 GetEventParameter (eventRef, kEventParamKeyModifiers, typeUInt32, NULL,
9639 sizeof (UInt32), NULL, &mods);
9640 if (mods & kEventKeyModifierFnMask)
9641 { *newCode = fn_keycode_to_xkeysym_table [keyCode & 0x7f];
9643 return (*newCode != 0);
9646 #endif
9647 return false;
9650 static int
9651 backtranslate_modified_keycode(int mods, int keycode, int def)
9653 if (mods &
9654 (controlKey |
9655 (NILP (Vmac_option_modifier) ? 0 : optionKey) |
9656 cmdKey))
9658 /* This code comes from Keyboard Resource,
9659 Appendix C of IM - Text. This is necessary
9660 since shift is ignored in KCHR table
9661 translation when option or command is pressed.
9662 It also does not translate correctly
9663 control-shift chars like C-% so mask off shift
9664 here also.
9666 Not done for combinations with the option key (alt)
9667 unless it is to be caught by Emacs: this is
9668 to preserve key combinations translated by the OS
9669 such as Alt-3.
9671 /* mask off option and command */
9672 int new_modifiers = mods & 0xe600;
9673 /* set high byte of keycode to modifier high byte*/
9674 int new_keycode = keycode | new_modifiers;
9675 Ptr kchr_ptr = (Ptr) GetScriptManagerVariable (smKCHRCache);
9676 unsigned long some_state = 0;
9677 return (int) KeyTranslate (kchr_ptr, new_keycode,
9678 &some_state) & 0xff;
9679 /* TO DO: Recognize two separate resulting characters, "for
9680 example, when the user presses Option-E followed by N, you
9681 can map this through the KeyTranslate function using the
9682 U.S. 'KCHR' resource to produce ´n, which KeyTranslate
9683 returns as two characters in the bytes labeled Character code
9684 1 and Character code 2." (from Carbon API doc) */
9687 else
9688 return def;
9692 #if !USE_CARBON_EVENTS
9693 static RgnHandle mouse_region = NULL;
9695 Boolean
9696 mac_wait_next_event (er, sleep_time, dequeue)
9697 EventRecord *er;
9698 UInt32 sleep_time;
9699 Boolean dequeue;
9701 static EventRecord er_buf = {nullEvent};
9702 UInt32 target_tick, current_tick;
9703 EventMask event_mask;
9705 if (mouse_region == NULL)
9706 mouse_region = NewRgn ();
9708 event_mask = everyEvent;
9709 if (NILP (Fboundp (Qmac_ready_for_drag_n_drop)))
9710 event_mask -= highLevelEventMask;
9712 current_tick = TickCount ();
9713 target_tick = current_tick + sleep_time;
9715 if (er_buf.what == nullEvent)
9716 while (!WaitNextEvent (event_mask, &er_buf,
9717 target_tick - current_tick, mouse_region))
9719 current_tick = TickCount ();
9720 if (target_tick <= current_tick)
9721 return false;
9724 *er = er_buf;
9725 if (dequeue)
9726 er_buf.what = nullEvent;
9727 return true;
9729 #endif /* not USE_CARBON_EVENTS */
9731 /* Emacs calls this whenever it wants to read an input event from the
9732 user. */
9734 XTread_socket (sd, expected, hold_quit)
9735 int sd, expected;
9736 struct input_event *hold_quit;
9738 struct input_event inev;
9739 int count = 0;
9740 #if USE_CARBON_EVENTS
9741 EventRef eventRef;
9742 EventTargetRef toolbox_dispatcher;
9743 #endif
9744 EventRecord er;
9745 struct mac_display_info *dpyinfo = &one_mac_display_info;
9747 if (interrupt_input_blocked)
9749 interrupt_input_pending = 1;
9750 return -1;
9753 interrupt_input_pending = 0;
9754 BLOCK_INPUT;
9756 /* So people can tell when we have read the available input. */
9757 input_signal_count++;
9759 #if USE_CARBON_EVENTS
9760 toolbox_dispatcher = GetEventDispatcherTarget ();
9762 while (!ReceiveNextEvent (0, NULL, kEventDurationNoWait,
9763 kEventRemoveFromQueue, &eventRef))
9764 #else /* !USE_CARBON_EVENTS */
9765 while (mac_wait_next_event (&er, 0, true))
9766 #endif /* !USE_CARBON_EVENTS */
9768 int do_help = 0;
9769 struct frame *f;
9770 unsigned long timestamp;
9772 /* It is necessary to set this (additional) argument slot of an
9773 event to nil because keyboard.c protects incompletely
9774 processed event from being garbage collected by placing them
9775 in the kbd_buffer_gcpro vector. */
9776 EVENT_INIT (inev);
9777 inev.kind = NO_EVENT;
9778 inev.arg = Qnil;
9780 #if USE_CARBON_EVENTS
9781 timestamp = GetEventTime (eventRef) / kEventDurationMillisecond;
9782 #else
9783 timestamp = er.when * (1000 / 60); /* ticks to milliseconds */
9784 #endif
9786 #if USE_CARBON_EVENTS
9787 /* Handle new events */
9788 if (!mac_convert_event_ref (eventRef, &er))
9790 /* There used to be a handler for the kEventMouseWheelMoved
9791 event here. But as of Mac OS X 10.4, this kind of event
9792 is not directly posted to the main event queue by
9793 two-finger scrolling on the trackpad. Instead, some
9794 private event is posted and it is converted to a wheel
9795 event by the default handler for the application target.
9796 The converted one can be received by a Carbon event
9797 handler installed on a window target. */
9798 read_socket_inev = &inev;
9799 SendEventToEventTarget (eventRef, toolbox_dispatcher);
9800 read_socket_inev = NULL;
9802 else
9803 #endif /* USE_CARBON_EVENTS */
9804 switch (er.what)
9806 case mouseDown:
9807 case mouseUp:
9809 WindowPtr window_ptr;
9810 ControlPartCode part_code;
9811 int tool_bar_p = 0;
9813 #if USE_CARBON_EVENTS
9814 /* This is needed to send mouse events like aqua window
9815 buttons to the correct handler. */
9816 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
9817 != eventNotHandledErr)
9818 break;
9819 #endif
9820 last_mouse_glyph_frame = 0;
9822 if (dpyinfo->grabbed && last_mouse_frame
9823 && FRAME_LIVE_P (last_mouse_frame))
9825 window_ptr = FRAME_MAC_WINDOW (last_mouse_frame);
9826 part_code = inContent;
9828 else
9830 part_code = FindWindow (er.where, &window_ptr);
9831 if (tip_window && window_ptr == tip_window)
9833 HideWindow (tip_window);
9834 part_code = FindWindow (er.where, &window_ptr);
9838 if (er.what != mouseDown &&
9839 (part_code != inContent || dpyinfo->grabbed == 0))
9840 break;
9842 switch (part_code)
9844 case inMenuBar:
9845 f = mac_focus_frame (dpyinfo);
9846 saved_menu_event_location = er.where;
9847 inev.kind = MENU_BAR_ACTIVATE_EVENT;
9848 XSETFRAME (inev.frame_or_window, f);
9849 break;
9851 case inContent:
9852 if (window_ptr != FRAME_MAC_WINDOW (mac_focus_frame (dpyinfo)))
9853 SelectWindow (window_ptr);
9854 else
9856 ControlPartCode control_part_code;
9857 ControlHandle ch;
9858 Point mouse_loc = er.where;
9859 #ifdef MAC_OSX
9860 ControlKind control_kind;
9861 #endif
9863 f = mac_window_to_frame (window_ptr);
9864 /* convert to local coordinates of new window */
9865 SetPortWindowPort (window_ptr);
9867 GlobalToLocal (&mouse_loc);
9868 #if TARGET_API_MAC_CARBON
9869 ch = FindControlUnderMouse (mouse_loc, window_ptr,
9870 &control_part_code);
9871 #ifdef MAC_OSX
9872 if (ch)
9873 GetControlKind (ch, &control_kind);
9874 #endif
9875 #else
9876 control_part_code = FindControl (mouse_loc, window_ptr,
9877 &ch);
9878 #endif
9880 #if USE_CARBON_EVENTS
9881 inev.code = mac_get_mouse_btn (eventRef);
9882 inev.modifiers = mac_event_to_emacs_modifiers (eventRef);
9883 #else
9884 inev.code = mac_get_emulated_btn (er.modifiers);
9885 inev.modifiers = mac_to_emacs_modifiers (er.modifiers);
9886 #endif
9887 XSETINT (inev.x, mouse_loc.h);
9888 XSETINT (inev.y, mouse_loc.v);
9890 if (dpyinfo->grabbed && tracked_scroll_bar
9891 || ch != 0
9892 #ifndef USE_TOOLKIT_SCROLL_BARS
9893 /* control_part_code becomes kControlNoPart if
9894 a progress indicator is clicked. */
9895 && control_part_code != kControlNoPart
9896 #else /* USE_TOOLKIT_SCROLL_BARS */
9897 #ifdef MAC_OSX
9898 && control_kind.kind == kControlKindScrollBar
9899 #endif /* MAC_OSX */
9900 #endif /* USE_TOOLKIT_SCROLL_BARS */
9903 struct scroll_bar *bar;
9905 if (dpyinfo->grabbed && tracked_scroll_bar)
9907 bar = tracked_scroll_bar;
9908 #ifndef USE_TOOLKIT_SCROLL_BARS
9909 control_part_code = kControlIndicatorPart;
9910 #endif
9912 else
9913 bar = (struct scroll_bar *) GetControlReference (ch);
9914 #ifdef USE_TOOLKIT_SCROLL_BARS
9915 /* Make the "Ctrl-Mouse-2 splits window" work
9916 for toolkit scroll bars. */
9917 if (er.modifiers & controlKey)
9918 x_scroll_bar_handle_click (bar, control_part_code,
9919 &er, &inev);
9920 else if (er.what == mouseDown)
9921 x_scroll_bar_handle_press (bar, control_part_code,
9922 &inev);
9923 else
9924 x_scroll_bar_handle_release (bar, &inev);
9925 #else /* not USE_TOOLKIT_SCROLL_BARS */
9926 x_scroll_bar_handle_click (bar, control_part_code,
9927 &er, &inev);
9928 if (er.what == mouseDown
9929 && control_part_code == kControlIndicatorPart)
9930 tracked_scroll_bar = bar;
9931 else
9932 tracked_scroll_bar = NULL;
9933 #endif /* not USE_TOOLKIT_SCROLL_BARS */
9935 else
9937 Lisp_Object window;
9938 int x = mouse_loc.h;
9939 int y = mouse_loc.v;
9941 window = window_from_coordinates (f, x, y, 0, 0, 0, 1);
9942 if (EQ (window, f->tool_bar_window))
9944 if (er.what == mouseDown)
9945 handle_tool_bar_click (f, x, y, 1, 0);
9946 else
9947 handle_tool_bar_click (f, x, y, 0,
9948 inev.modifiers);
9949 tool_bar_p = 1;
9951 else
9953 XSETFRAME (inev.frame_or_window, f);
9954 inev.kind = MOUSE_CLICK_EVENT;
9958 if (er.what == mouseDown)
9960 dpyinfo->grabbed |= (1 << inev.code);
9961 last_mouse_frame = f;
9963 if (!tool_bar_p)
9964 last_tool_bar_item = -1;
9966 else
9968 if ((dpyinfo->grabbed & (1 << inev.code)) == 0)
9969 /* If a button is released though it was not
9970 previously pressed, that would be because
9971 of multi-button emulation. */
9972 dpyinfo->grabbed = 0;
9973 else
9974 dpyinfo->grabbed &= ~(1 << inev.code);
9977 /* Ignore any mouse motion that happened before
9978 this event; any subsequent mouse-movement Emacs
9979 events should reflect only motion after the
9980 ButtonPress. */
9981 if (f != 0)
9982 f->mouse_moved = 0;
9984 #ifdef USE_TOOLKIT_SCROLL_BARS
9985 if (inev.kind == MOUSE_CLICK_EVENT)
9986 #endif
9987 switch (er.what)
9989 case mouseDown:
9990 inev.modifiers |= down_modifier;
9991 break;
9992 case mouseUp:
9993 inev.modifiers |= up_modifier;
9994 break;
9997 break;
9999 case inDrag:
10000 #if TARGET_API_MAC_CARBON
10001 DragWindow (window_ptr, er.where, NULL);
10002 #else /* not TARGET_API_MAC_CARBON */
10003 DragWindow (window_ptr, er.where, &qd.screenBits.bounds);
10004 #endif /* not TARGET_API_MAC_CARBON */
10005 /* Update the frame parameters. */
10007 struct frame *f = mac_window_to_frame (window_ptr);
10009 if (f && !f->async_iconified)
10010 x_real_positions (f, &f->left_pos, &f->top_pos);
10012 break;
10014 case inGoAway:
10015 if (TrackGoAway (window_ptr, er.where))
10017 inev.kind = DELETE_WINDOW_EVENT;
10018 XSETFRAME (inev.frame_or_window,
10019 mac_window_to_frame (window_ptr));
10021 break;
10023 /* window resize handling added --ben */
10024 case inGrow:
10025 do_grow_window (window_ptr, &er);
10026 break;
10028 /* window zoom handling added --ben */
10029 case inZoomIn:
10030 case inZoomOut:
10031 if (TrackBox (window_ptr, er.where, part_code))
10032 do_zoom_window (window_ptr, part_code);
10033 break;
10035 default:
10036 break;
10039 break;
10041 case updateEvt:
10042 #if USE_CARBON_EVENTS
10043 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
10044 != eventNotHandledErr)
10045 break;
10046 #else
10047 do_window_update ((WindowPtr) er.message);
10048 #endif
10049 break;
10051 case osEvt:
10052 #if USE_CARBON_EVENTS
10053 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
10054 != eventNotHandledErr)
10055 break;
10056 #endif
10057 switch ((er.message >> 24) & 0x000000FF)
10059 case suspendResumeMessage:
10060 if ((er.message & resumeFlag) == 1)
10061 do_app_resume ();
10062 else
10063 do_app_suspend ();
10064 break;
10066 case mouseMovedMessage:
10067 #if !USE_CARBON_EVENTS
10068 SetRectRgn (mouse_region, er.where.h, er.where.v,
10069 er.where.h + 1, er.where.v + 1);
10070 #endif
10071 previous_help_echo_string = help_echo_string;
10072 help_echo_string = Qnil;
10074 if (dpyinfo->grabbed && last_mouse_frame
10075 && FRAME_LIVE_P (last_mouse_frame))
10076 f = last_mouse_frame;
10077 else
10078 f = dpyinfo->x_focus_frame;
10080 if (dpyinfo->mouse_face_hidden)
10082 dpyinfo->mouse_face_hidden = 0;
10083 clear_mouse_face (dpyinfo);
10086 if (f)
10088 WindowPtr wp = FRAME_MAC_WINDOW (f);
10089 Point mouse_pos = er.where;
10091 SetPortWindowPort (wp);
10093 GlobalToLocal (&mouse_pos);
10095 if (dpyinfo->grabbed && tracked_scroll_bar)
10096 #ifdef USE_TOOLKIT_SCROLL_BARS
10097 x_scroll_bar_handle_drag (wp, tracked_scroll_bar,
10098 mouse_pos, &inev);
10099 #else /* not USE_TOOLKIT_SCROLL_BARS */
10100 x_scroll_bar_note_movement (tracked_scroll_bar,
10101 mouse_pos.v
10102 - XINT (tracked_scroll_bar->top),
10103 er.when * (1000 / 60));
10104 #endif /* not USE_TOOLKIT_SCROLL_BARS */
10105 else
10107 /* Generate SELECT_WINDOW_EVENTs when needed. */
10108 if (mouse_autoselect_window)
10110 Lisp_Object window;
10112 window = window_from_coordinates (f,
10113 mouse_pos.h,
10114 mouse_pos.v,
10115 0, 0, 0, 0);
10117 /* Window will be selected only when it is
10118 not selected now and last mouse movement
10119 event was not in it. Minibuffer window
10120 will be selected iff it is active. */
10121 if (WINDOWP (window)
10122 && !EQ (window, last_window)
10123 && !EQ (window, selected_window))
10125 inev.kind = SELECT_WINDOW_EVENT;
10126 inev.frame_or_window = window;
10129 last_window=window;
10131 if (!note_mouse_movement (f, &mouse_pos))
10132 help_echo_string = previous_help_echo_string;
10136 /* If the contents of the global variable
10137 help_echo_string has changed, generate a
10138 HELP_EVENT. */
10139 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
10140 do_help = 1;
10141 break;
10143 break;
10145 case activateEvt:
10147 WindowPtr window_ptr = (WindowPtr) er.message;
10149 #if USE_CARBON_EVENTS
10150 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
10151 != eventNotHandledErr)
10152 break;
10153 #endif
10154 if (window_ptr == tip_window)
10156 HideWindow (tip_window);
10157 break;
10160 if (!is_emacs_window (window_ptr))
10161 break;
10163 if ((er.modifiers & activeFlag) != 0)
10165 /* A window has been activated */
10166 Point mouse_loc = er.where;
10168 x_detect_focus_change (dpyinfo, &er, &inev);
10170 SetPortWindowPort (window_ptr);
10171 GlobalToLocal (&mouse_loc);
10172 /* Window-activated event counts as mouse movement,
10173 so update things that depend on mouse position. */
10174 note_mouse_movement (mac_window_to_frame (window_ptr),
10175 &mouse_loc);
10177 else
10179 /* A window has been deactivated */
10180 #if USE_TOOLKIT_SCROLL_BARS
10181 if (dpyinfo->grabbed && tracked_scroll_bar)
10183 struct input_event event;
10185 EVENT_INIT (event);
10186 event.kind = NO_EVENT;
10187 x_scroll_bar_handle_release (tracked_scroll_bar, &event);
10188 if (event.kind != NO_EVENT)
10190 event.timestamp = timestamp;
10191 kbd_buffer_store_event_hold (&event, hold_quit);
10192 count++;
10195 #endif
10196 dpyinfo->grabbed = 0;
10198 x_detect_focus_change (dpyinfo, &er, &inev);
10200 f = mac_window_to_frame (window_ptr);
10201 if (f == dpyinfo->mouse_face_mouse_frame)
10203 /* If we move outside the frame, then we're
10204 certainly no longer on any text in the
10205 frame. */
10206 clear_mouse_face (dpyinfo);
10207 dpyinfo->mouse_face_mouse_frame = 0;
10210 /* Generate a nil HELP_EVENT to cancel a help-echo.
10211 Do it only if there's something to cancel.
10212 Otherwise, the startup message is cleared when the
10213 mouse leaves the frame. */
10214 if (any_help_event_p)
10215 do_help = -1;
10218 break;
10220 case keyDown:
10221 case autoKey:
10223 int keycode = (er.message & keyCodeMask) >> 8;
10224 int xkeysym;
10226 #if USE_CARBON_EVENTS && defined (MAC_OSX)
10227 /* When using Carbon Events, we need to pass raw keyboard
10228 events to the TSM ourselves. If TSM handles it, it
10229 will pass back noErr, otherwise it will pass back
10230 "eventNotHandledErr" and we can process it
10231 normally. */
10232 if ((!NILP (Vmac_pass_command_to_system)
10233 || !(er.modifiers & cmdKey))
10234 && (!NILP (Vmac_pass_control_to_system)
10235 || !(er.modifiers & controlKey))
10236 && (NILP (Vmac_option_modifier)
10237 || !(er.modifiers & optionKey)))
10238 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
10239 != eventNotHandledErr)
10240 break;
10241 #endif
10243 #if 0
10244 if (dpyinfo->x_focus_frame == NULL)
10246 /* Beep if keyboard input occurs when all the frames
10247 are invisible. */
10248 SysBeep (1);
10249 break;
10251 #endif
10254 static SInt16 last_key_script = -1;
10255 SInt16 current_key_script = GetScriptManagerVariable (smKeyScript);
10257 if (last_key_script != current_key_script)
10259 struct input_event event;
10261 EVENT_INIT (event);
10262 event.kind = LANGUAGE_CHANGE_EVENT;
10263 event.arg = Qnil;
10264 event.code = current_key_script;
10265 event.timestamp = timestamp;
10266 kbd_buffer_store_event (&event);
10267 count++;
10269 last_key_script = current_key_script;
10272 ObscureCursor ();
10274 if (!dpyinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
10276 clear_mouse_face (dpyinfo);
10277 dpyinfo->mouse_face_hidden = 1;
10280 /* translate the keycode back to determine the original key */
10281 /* Convert key code if function key is pressed.
10282 Otherwise, if non-ASCII-event, take care of that
10283 without re-translating the key code. */
10284 #if USE_CARBON_EVENTS
10285 if (convert_fn_keycode (eventRef, keycode, &xkeysym))
10287 inev.code = xkeysym;
10288 /* this doesn't work - tried to add shift modifiers */
10289 inev.code =
10290 backtranslate_modified_keycode(er.modifiers & (~0x2200),
10291 xkeysym | 0x80, xkeysym);
10292 inev.kind = ASCII_KEYSTROKE_EVENT;
10294 else
10295 #endif
10296 if (keycode_to_xkeysym (keycode, &xkeysym))
10298 inev.code = 0xff00 | xkeysym;
10299 inev.kind = NON_ASCII_KEYSTROKE_EVENT;
10301 else
10304 inev.code =
10305 backtranslate_modified_keycode(er.modifiers, keycode,
10306 er.message & charCodeMask);
10307 inev.kind = ASCII_KEYSTROKE_EVENT;
10312 #if USE_CARBON_EVENTS
10313 inev.modifiers = mac_event_to_emacs_modifiers (eventRef);
10314 #else
10315 inev.modifiers = mac_to_emacs_modifiers (er.modifiers);
10316 #endif
10317 inev.modifiers |= (extra_keyboard_modifiers
10318 & (meta_modifier | alt_modifier
10319 | hyper_modifier | super_modifier));
10320 XSETFRAME (inev.frame_or_window, mac_focus_frame (dpyinfo));
10321 break;
10323 case kHighLevelEvent:
10324 read_socket_inev = &inev;
10325 AEProcessAppleEvent (&er);
10326 read_socket_inev = NULL;
10327 break;
10329 default:
10330 break;
10332 #if USE_CARBON_EVENTS
10333 ReleaseEvent (eventRef);
10334 #endif
10336 if (inev.kind != NO_EVENT)
10338 inev.timestamp = timestamp;
10339 kbd_buffer_store_event_hold (&inev, hold_quit);
10340 count++;
10343 if (do_help
10344 && !(hold_quit && hold_quit->kind != NO_EVENT))
10346 Lisp_Object frame;
10348 if (f)
10349 XSETFRAME (frame, f);
10350 else
10351 frame = Qnil;
10353 if (do_help > 0)
10355 any_help_event_p = 1;
10356 gen_help_event (help_echo_string, frame, help_echo_window,
10357 help_echo_object, help_echo_pos);
10359 else
10361 help_echo_string = Qnil;
10362 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
10364 count++;
10369 /* If the focus was just given to an autoraising frame,
10370 raise it now. */
10371 /* ??? This ought to be able to handle more than one such frame. */
10372 if (pending_autoraise_frame)
10374 x_raise_frame (pending_autoraise_frame);
10375 pending_autoraise_frame = 0;
10378 #if !USE_CARBON_EVENTS
10379 /* Check which frames are still visible. We do this here because
10380 there doesn't seem to be any direct notification from the Window
10381 Manager that the visibility of a window has changed (at least,
10382 not in all cases). */
10384 Lisp_Object tail, frame;
10386 FOR_EACH_FRAME (tail, frame)
10388 struct frame *f = XFRAME (frame);
10390 /* The tooltip has been drawn already. Avoid the
10391 SET_FRAME_GARBAGED in mac_handle_visibility_change. */
10392 if (EQ (frame, tip_frame))
10393 continue;
10395 if (FRAME_MAC_P (f))
10396 mac_handle_visibility_change (f);
10399 #endif
10401 UNBLOCK_INPUT;
10402 return count;
10406 /* Need to override CodeWarrior's input function so no conversion is
10407 done on newlines Otherwise compiled functions in .elc files will be
10408 read incorrectly. Defined in ...:MSL C:MSL
10409 Common:Source:buffer_io.c. */
10410 #ifdef __MWERKS__
10411 void
10412 __convert_to_newlines (unsigned char * p, size_t * n)
10414 #pragma unused(p,n)
10417 void
10418 __convert_from_newlines (unsigned char * p, size_t * n)
10420 #pragma unused(p,n)
10422 #endif
10424 #ifdef MAC_OS8
10425 void
10426 make_mac_terminal_frame (struct frame *f)
10428 Lisp_Object frame;
10429 Rect r;
10431 XSETFRAME (frame, f);
10433 f->output_method = output_mac;
10434 f->output_data.mac = (struct mac_output *)
10435 xmalloc (sizeof (struct mac_output));
10436 bzero (f->output_data.mac, sizeof (struct mac_output));
10438 XSETFRAME (FRAME_KBOARD (f)->Vdefault_minibuffer_frame, f);
10440 FRAME_COLS (f) = 96;
10441 FRAME_LINES (f) = 4;
10443 FRAME_CAN_HAVE_SCROLL_BARS (f) = 1;
10444 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = vertical_scroll_bar_right;
10446 FRAME_DESIRED_CURSOR (f) = FILLED_BOX_CURSOR;
10448 f->output_data.mac->cursor_pixel = 0;
10449 f->output_data.mac->border_pixel = 0x00ff00;
10450 f->output_data.mac->mouse_pixel = 0xff00ff;
10451 f->output_data.mac->cursor_foreground_pixel = 0x0000ff;
10453 f->output_data.mac->text_cursor = kThemeIBeamCursor;
10454 f->output_data.mac->nontext_cursor = kThemeArrowCursor;
10455 f->output_data.mac->modeline_cursor = kThemeArrowCursor;
10456 f->output_data.mac->hand_cursor = kThemePointingHandCursor;
10457 f->output_data.mac->hourglass_cursor = kThemeWatchCursor;
10458 f->output_data.mac->horizontal_drag_cursor = kThemeResizeLeftRightCursor;
10460 FRAME_FONTSET (f) = -1;
10461 f->output_data.mac->explicit_parent = 0;
10462 f->left_pos = 8;
10463 f->top_pos = 32;
10464 f->border_width = 0;
10466 f->internal_border_width = 0;
10468 f->auto_raise = 1;
10469 f->auto_lower = 1;
10471 f->new_text_cols = 0;
10472 f->new_text_lines = 0;
10474 SetRect (&r, f->left_pos, f->top_pos,
10475 f->left_pos + FRAME_PIXEL_WIDTH (f),
10476 f->top_pos + FRAME_PIXEL_HEIGHT (f));
10478 BLOCK_INPUT;
10480 if (!(FRAME_MAC_WINDOW (f) =
10481 NewCWindow (NULL, &r, "\p", true, dBoxProc,
10482 (WindowPtr) -1, 1, (long) f->output_data.mac)))
10483 abort ();
10484 /* so that update events can find this mac_output struct */
10485 f->output_data.mac->mFP = f; /* point back to emacs frame */
10487 UNBLOCK_INPUT;
10489 x_make_gc (f);
10491 /* Need to be initialized for unshow_buffer in window.c. */
10492 selected_window = f->selected_window;
10494 Fmodify_frame_parameters (frame,
10495 Fcons (Fcons (Qfont,
10496 build_string ("-*-monaco-medium-r-*--*-90-*-*-*-*-mac-roman")), Qnil));
10497 Fmodify_frame_parameters (frame,
10498 Fcons (Fcons (Qforeground_color,
10499 build_string ("black")), Qnil));
10500 Fmodify_frame_parameters (frame,
10501 Fcons (Fcons (Qbackground_color,
10502 build_string ("white")), Qnil));
10504 #endif
10507 /***********************************************************************
10508 Initialization
10509 ***********************************************************************/
10511 int mac_initialized = 0;
10513 void
10514 mac_initialize_display_info ()
10516 struct mac_display_info *dpyinfo = &one_mac_display_info;
10517 GDHandle main_device_handle;
10519 bzero (dpyinfo, sizeof (*dpyinfo));
10521 #ifdef MAC_OSX
10522 dpyinfo->mac_id_name
10523 = (char *) xmalloc (SCHARS (Vinvocation_name)
10524 + SCHARS (Vsystem_name)
10525 + 2);
10526 sprintf (dpyinfo->mac_id_name, "%s@%s",
10527 SDATA (Vinvocation_name), SDATA (Vsystem_name));
10528 #else
10529 dpyinfo->mac_id_name = (char *) xmalloc (strlen ("Mac Display") + 1);
10530 strcpy (dpyinfo->mac_id_name, "Mac Display");
10531 #endif
10533 main_device_handle = LMGetMainDevice();
10535 dpyinfo->reference_count = 0;
10536 dpyinfo->resx = 72.0;
10537 dpyinfo->resy = 72.0;
10538 dpyinfo->color_p = TestDeviceAttribute (main_device_handle, gdDevType);
10539 #ifdef MAC_OSX
10540 /* HasDepth returns true if it is possible to have a 32 bit display,
10541 but this may not be what is actually used. Mac OSX can do better.
10542 CGMainDisplayID is only available on OSX 10.2 and higher, but the
10543 header for CGGetActiveDisplayList says that the first display returned
10544 is the active one, so we use that. */
10546 CGDirectDisplayID disp_id[1];
10547 CGDisplayCount disp_count;
10548 CGDisplayErr error_code;
10550 error_code = CGGetActiveDisplayList (1, disp_id, &disp_count);
10551 if (error_code != 0)
10552 error ("No display found, CGGetActiveDisplayList error %d", error_code);
10554 dpyinfo->n_planes = CGDisplayBitsPerPixel (disp_id[0]);
10556 #else
10557 for (dpyinfo->n_planes = 32; dpyinfo->n_planes > 0; dpyinfo->n_planes >>= 1)
10558 if (HasDepth (main_device_handle, dpyinfo->n_planes,
10559 gdDevType, dpyinfo->color_p))
10560 break;
10561 #endif
10562 dpyinfo->height = (**main_device_handle).gdRect.bottom;
10563 dpyinfo->width = (**main_device_handle).gdRect.right;
10564 dpyinfo->grabbed = 0;
10565 dpyinfo->root_window = NULL;
10566 dpyinfo->image_cache = make_image_cache ();
10568 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
10569 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
10570 dpyinfo->mouse_face_face_id = DEFAULT_FACE_ID;
10571 dpyinfo->mouse_face_window = Qnil;
10572 dpyinfo->mouse_face_overlay = Qnil;
10573 dpyinfo->mouse_face_hidden = 0;
10577 static XrmDatabase
10578 mac_make_rdb (xrm_option)
10579 char *xrm_option;
10581 XrmDatabase database;
10583 database = xrm_get_preference_database (NULL);
10584 if (xrm_option)
10585 xrm_merge_string_database (database, xrm_option);
10587 return database;
10590 struct mac_display_info *
10591 mac_term_init (display_name, xrm_option, resource_name)
10592 Lisp_Object display_name;
10593 char *xrm_option;
10594 char *resource_name;
10596 struct mac_display_info *dpyinfo;
10598 BLOCK_INPUT;
10600 if (!mac_initialized)
10602 mac_initialize ();
10603 mac_initialized = 1;
10606 if (x_display_list)
10607 error ("Sorry, this version can only handle one display");
10609 mac_initialize_display_info ();
10611 dpyinfo = &one_mac_display_info;
10613 dpyinfo->xrdb = mac_make_rdb (xrm_option);
10615 /* Put this display on the chain. */
10616 dpyinfo->next = x_display_list;
10617 x_display_list = dpyinfo;
10619 /* Put it on x_display_name_list. */
10620 x_display_name_list = Fcons (Fcons (display_name,
10621 Fcons (Qnil, dpyinfo->xrdb)),
10622 x_display_name_list);
10623 dpyinfo->name_list_element = XCAR (x_display_name_list);
10625 UNBLOCK_INPUT;
10627 return dpyinfo;
10629 /* Get rid of display DPYINFO, assuming all frames are already gone. */
10631 void
10632 x_delete_display (dpyinfo)
10633 struct mac_display_info *dpyinfo;
10635 int i;
10637 /* Discard this display from x_display_name_list and x_display_list.
10638 We can't use Fdelq because that can quit. */
10639 if (! NILP (x_display_name_list)
10640 && EQ (XCAR (x_display_name_list), dpyinfo->name_list_element))
10641 x_display_name_list = XCDR (x_display_name_list);
10642 else
10644 Lisp_Object tail;
10646 tail = x_display_name_list;
10647 while (CONSP (tail) && CONSP (XCDR (tail)))
10649 if (EQ (XCAR (XCDR (tail)), dpyinfo->name_list_element))
10651 XSETCDR (tail, XCDR (XCDR (tail)));
10652 break;
10654 tail = XCDR (tail);
10658 if (x_display_list == dpyinfo)
10659 x_display_list = dpyinfo->next;
10660 else
10662 struct x_display_info *tail;
10664 for (tail = x_display_list; tail; tail = tail->next)
10665 if (tail->next == dpyinfo)
10666 tail->next = tail->next->next;
10669 /* Free the font names in the font table. */
10670 for (i = 0; i < dpyinfo->n_fonts; i++)
10671 if (dpyinfo->font_table[i].name)
10673 if (dpyinfo->font_table[i].name != dpyinfo->font_table[i].full_name)
10674 xfree (dpyinfo->font_table[i].full_name);
10675 xfree (dpyinfo->font_table[i].name);
10678 if (dpyinfo->font_table->font_encoder)
10679 xfree (dpyinfo->font_table->font_encoder);
10681 xfree (dpyinfo->font_table);
10682 xfree (dpyinfo->mac_id_name);
10684 if (x_display_list == 0)
10686 mac_clear_font_name_table ();
10687 bzero (dpyinfo, sizeof (*dpyinfo));
10692 #ifdef MAC_OSX
10693 void
10694 mac_check_bundle()
10696 extern int inhibit_window_system;
10697 extern int noninteractive;
10698 CFBundleRef appsBundle;
10699 pid_t child;
10701 /* No need to test if already -nw*/
10702 if (inhibit_window_system || noninteractive)
10703 return;
10705 appsBundle = CFBundleGetMainBundle();
10706 if (appsBundle != NULL)
10708 CFStringRef cfBI = CFSTR("CFBundleIdentifier");
10709 CFTypeRef res = CFBundleGetValueForInfoDictionaryKey(appsBundle, cfBI);
10710 /* We found the bundle identifier, now we know we are valid. */
10711 if (res != NULL)
10713 CFRelease(res);
10714 return;
10717 /* MAC_TODO: Have this start the bundled executable */
10719 /* For now, prevent the fatal error by bringing it up in the terminal */
10720 inhibit_window_system = 1;
10723 void
10724 MakeMeTheFrontProcess ()
10726 ProcessSerialNumber psn;
10727 OSErr err;
10729 err = GetCurrentProcess (&psn);
10730 if (err == noErr)
10731 (void) SetFrontProcess (&psn);
10734 /***** Code to handle C-g testing *****/
10736 /* Contains the Mac modifier formed from quit_char */
10737 int mac_quit_char_modifiers = 0;
10738 int mac_quit_char_keycode;
10739 extern int quit_char;
10741 static void
10742 mac_determine_quit_char_modifiers()
10744 /* Todo: Determine modifiers from quit_char. */
10745 UInt32 qc_modifiers = ctrl_modifier;
10747 /* Map modifiers */
10748 mac_quit_char_modifiers = 0;
10749 if (qc_modifiers & ctrl_modifier) mac_quit_char_modifiers |= controlKey;
10750 if (qc_modifiers & shift_modifier) mac_quit_char_modifiers |= shiftKey;
10751 if (qc_modifiers & alt_modifier) mac_quit_char_modifiers |= optionKey;
10754 static void
10755 init_quit_char_handler ()
10757 /* TODO: Let this support keys other the 'g' */
10758 mac_quit_char_keycode = 5;
10759 /* Look at <architecture/adb_kb_map.h> for details */
10760 /* http://gemma.apple.com/techpubs/mac/Toolbox/Toolbox-40.html#MARKER-9-184*/
10762 mac_determine_quit_char_modifiers();
10764 #endif /* MAC_OSX */
10766 static void
10767 init_menu_bar ()
10769 #ifdef MAC_OSX
10770 OSErr err;
10771 MenuRef menu;
10772 MenuItemIndex menu_index;
10774 err = GetIndMenuItemWithCommandID (NULL, kHICommandQuit, 1,
10775 &menu, &menu_index);
10776 if (err == noErr)
10777 SetMenuItemCommandKey (menu, menu_index, false, 0);
10778 #if USE_CARBON_EVENTS
10779 EnableMenuCommand (NULL, kHICommandPreferences);
10780 err = GetIndMenuItemWithCommandID (NULL, kHICommandPreferences, 1,
10781 &menu, &menu_index);
10782 if (err == noErr)
10784 SetMenuItemCommandKey (menu, menu_index, false, 0);
10785 InsertMenuItemTextWithCFString (menu, NULL,
10786 0, kMenuItemAttrSeparator, 0);
10787 InsertMenuItemTextWithCFString (menu, CFSTR ("About Emacs"),
10788 0, 0, kHICommandAbout);
10790 #endif /* USE_CARBON_EVENTS */
10791 #else /* !MAC_OSX */
10792 #if USE_CARBON_EVENTS
10793 SetMenuItemCommandID (GetMenuHandle (M_APPLE), I_ABOUT, kHICommandAbout);
10794 #endif
10795 #endif
10799 /* Set up use of X before we make the first connection. */
10801 extern frame_parm_handler mac_frame_parm_handlers[];
10803 static struct redisplay_interface x_redisplay_interface =
10805 mac_frame_parm_handlers,
10806 x_produce_glyphs,
10807 x_write_glyphs,
10808 x_insert_glyphs,
10809 x_clear_end_of_line,
10810 x_scroll_run,
10811 x_after_update_window_line,
10812 x_update_window_begin,
10813 x_update_window_end,
10814 x_cursor_to,
10815 x_flush,
10816 0, /* flush_display_optional */
10817 x_clear_window_mouse_face,
10818 x_get_glyph_overhangs,
10819 x_fix_overlapping_area,
10820 x_draw_fringe_bitmap,
10821 0, /* define_fringe_bitmap */
10822 0, /* destroy_fringe_bitmap */
10823 mac_per_char_metric,
10824 mac_encode_char,
10825 mac_compute_glyph_string_overhangs,
10826 x_draw_glyph_string,
10827 mac_define_frame_cursor,
10828 mac_clear_frame_area,
10829 mac_draw_window_cursor,
10830 mac_draw_vertical_window_border,
10831 mac_shift_glyphs_for_insert
10834 void
10835 mac_initialize ()
10837 rif = &x_redisplay_interface;
10839 clear_frame_hook = x_clear_frame;
10840 ins_del_lines_hook = x_ins_del_lines;
10841 delete_glyphs_hook = x_delete_glyphs;
10842 ring_bell_hook = XTring_bell;
10843 reset_terminal_modes_hook = XTreset_terminal_modes;
10844 set_terminal_modes_hook = XTset_terminal_modes;
10845 update_begin_hook = x_update_begin;
10846 update_end_hook = x_update_end;
10847 set_terminal_window_hook = XTset_terminal_window;
10848 read_socket_hook = XTread_socket;
10849 frame_up_to_date_hook = XTframe_up_to_date;
10850 mouse_position_hook = XTmouse_position;
10851 frame_rehighlight_hook = XTframe_rehighlight;
10852 frame_raise_lower_hook = XTframe_raise_lower;
10854 set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
10855 condemn_scroll_bars_hook = XTcondemn_scroll_bars;
10856 redeem_scroll_bar_hook = XTredeem_scroll_bar;
10857 judge_scroll_bars_hook = XTjudge_scroll_bars;
10859 scroll_region_ok = 1; /* we'll scroll partial frames */
10860 char_ins_del_ok = 1;
10861 line_ins_del_ok = 1; /* we'll just blt 'em */
10862 fast_clear_end_of_line = 1; /* X does this well */
10863 memory_below_frame = 0; /* we don't remember what scrolls
10864 off the bottom */
10865 baud_rate = 19200;
10867 last_tool_bar_item = -1;
10868 any_help_event_p = 0;
10870 /* Try to use interrupt input; if we can't, then start polling. */
10871 Fset_input_mode (Qt, Qnil, Qt, Qnil);
10873 BLOCK_INPUT;
10875 #if TARGET_API_MAC_CARBON
10876 init_required_apple_events ();
10878 #if USE_CARBON_EVENTS
10879 #ifdef MAC_OSX
10880 init_service_handler ();
10882 init_quit_char_handler ();
10883 #endif /* MAC_OSX */
10885 init_command_handler ();
10887 init_menu_bar ();
10888 #endif /* USE_CARBON_EVENTS */
10890 #ifdef MAC_OSX
10891 if (!inhibit_window_system)
10892 MakeMeTheFrontProcess ();
10893 #endif
10894 #endif
10895 UNBLOCK_INPUT;
10899 void
10900 syms_of_macterm ()
10902 #if 0
10903 staticpro (&x_error_message_string);
10904 x_error_message_string = Qnil;
10905 #endif
10907 Qmodifier_value = intern ("modifier-value");
10908 Qctrl = intern ("ctrl");
10909 Fput (Qctrl, Qmodifier_value, make_number (ctrl_modifier));
10910 Qmeta = intern ("meta");
10911 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
10912 Qalt = intern ("alt");
10913 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
10914 Qhyper = intern ("hyper");
10915 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
10916 Qsuper = intern ("super");
10917 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
10919 Qapplication = intern ("application"); staticpro (&Qapplication);
10920 Qabout = intern ("about"); staticpro (&Qabout);
10922 #if USE_CARBON_EVENTS && defined (MAC_OSX)
10923 Qpreferences = intern ("preferences"); staticpro (&Qpreferences);
10924 Qservices = intern ("services"); staticpro (&Qservices);
10925 Qpaste = intern ("paste"); staticpro (&Qpaste);
10926 Qperform = intern ("perform"); staticpro (&Qperform);
10927 #endif
10929 #ifdef MAC_OSX
10930 Fprovide (intern ("mac-carbon"), Qnil);
10931 #endif
10933 staticpro (&Qreverse);
10934 Qreverse = intern ("reverse");
10936 staticpro (&Qmac_ready_for_drag_n_drop);
10937 Qmac_ready_for_drag_n_drop = intern ("mac-ready-for-drag-n-drop");
10939 staticpro (&x_display_name_list);
10940 x_display_name_list = Qnil;
10942 staticpro (&last_mouse_scroll_bar);
10943 last_mouse_scroll_bar = Qnil;
10945 staticpro (&fm_font_family_alist);
10946 fm_font_family_alist = Qnil;
10948 #if USE_ATSUI
10949 staticpro (&atsu_font_id_hash);
10950 atsu_font_id_hash = Qnil;
10951 #endif
10953 DEFVAR_LISP ("x-toolkit-scroll-bars", &Vx_toolkit_scroll_bars,
10954 doc: /* If not nil, Emacs uses toolkit scroll bars. */);
10955 #ifdef USE_TOOLKIT_SCROLL_BARS
10956 Vx_toolkit_scroll_bars = Qt;
10957 #else
10958 Vx_toolkit_scroll_bars = Qnil;
10959 #endif
10961 staticpro (&last_mouse_motion_frame);
10962 last_mouse_motion_frame = Qnil;
10966 /* Variables to configure modifier key assignment. */
10968 DEFVAR_LISP ("mac-control-modifier", &Vmac_control_modifier,
10969 doc: /* Modifier key assumed when the Mac control key is pressed.
10970 The value can be `alt', `ctrl', `hyper', or `super' for the respective
10971 modifier. The default is `ctrl'. */);
10972 Vmac_control_modifier = Qctrl;
10974 DEFVAR_LISP ("mac-option-modifier", &Vmac_option_modifier,
10975 doc: /* Modifier key assumed when the Mac alt/option key is pressed.
10976 The value can be `alt', `ctrl', `hyper', or `super' for the respective
10977 modifier. If the value is nil then the key will act as the normal
10978 Mac control modifier, and the option key can be used to compose
10979 characters depending on the chosen Mac keyboard setting. */);
10980 Vmac_option_modifier = Qnil;
10982 DEFVAR_LISP ("mac-command-modifier", &Vmac_command_modifier,
10983 doc: /* Modifier key assumed when the Mac command key is pressed.
10984 The value can be `alt', `ctrl', `hyper', or `super' for the respective
10985 modifier. The default is `meta'. */);
10986 Vmac_command_modifier = Qmeta;
10988 DEFVAR_LISP ("mac-function-modifier", &Vmac_function_modifier,
10989 doc: /* Modifier key assumed when the Mac function key is pressed.
10990 The value can be `alt', `ctrl', `hyper', or `super' for the respective
10991 modifier. Note that remapping the function key may lead to unexpected
10992 results for some keys on non-US/GB keyboards. */);
10993 Vmac_function_modifier = Qnil;
10995 DEFVAR_LISP ("mac-emulate-three-button-mouse",
10996 &Vmac_emulate_three_button_mouse,
10997 doc: /* t means that when the option-key is held down while pressing the
10998 mouse button, the click will register as mouse-2 and while the
10999 command-key is held down, the click will register as mouse-3.
11000 'reverse means that the option-key will register for mouse-3
11001 and the command-key will register for mouse-2. nil means that
11002 no emulation should be done and the modifiers should be placed
11003 on the mouse-1 event. */);
11004 Vmac_emulate_three_button_mouse = Qnil;
11006 #if USE_CARBON_EVENTS
11007 DEFVAR_LISP ("mac-wheel-button-is-mouse-2", &Vmac_wheel_button_is_mouse_2,
11008 doc: /* Non-nil means that the wheel button will be treated as mouse-2 and
11009 the right click will be mouse-3.
11010 Otherwise, the right click will be mouse-2 and the wheel button mouse-3.*/);
11011 Vmac_wheel_button_is_mouse_2 = Qt;
11013 DEFVAR_LISP ("mac-pass-command-to-system", &Vmac_pass_command_to_system,
11014 doc: /* If non-nil, the Mac \"Command\" key is passed on to the Mac
11015 Toolbox for processing before Emacs sees it. */);
11016 Vmac_pass_command_to_system = Qt;
11018 DEFVAR_LISP ("mac-pass-control-to-system", &Vmac_pass_control_to_system,
11019 doc: /* If non-nil, the Mac \"Control\" key is passed on to the Mac
11020 Toolbox for processing before Emacs sees it. */);
11021 Vmac_pass_control_to_system = Qt;
11023 #endif
11025 DEFVAR_LISP ("mac-allow-anti-aliasing", &Vmac_use_core_graphics,
11026 doc: /* If non-nil, allow anti-aliasing.
11027 The text will be rendered using Core Graphics text rendering which
11028 may anti-alias the text. */);
11029 Vmac_use_core_graphics = Qnil;
11031 /* Register an entry for `mac-roman' so that it can be used when
11032 creating the terminal frame on Mac OS 9 before loading
11033 term/mac-win.elc. */
11034 DEFVAR_LISP ("mac-charset-info-alist", &Vmac_charset_info_alist,
11035 doc: /* Alist linking Emacs character sets to Mac text encoding and Emacs coding system.
11036 Each entry should be of the form:
11038 (CHARSET-NAME TEXT-ENCODING CODING-SYSTEM)
11040 where CHARSET-NAME is a string used in font names to identify the
11041 charset, TEXT-ENCODING is a TextEncodingBase value, and CODING_SYSTEM
11042 is a coding system corresponding to TEXT-ENCODING. */);
11043 Vmac_charset_info_alist =
11044 Fcons (list3 (build_string ("mac-roman"),
11045 make_number (smRoman), Qnil), Qnil);
11048 /* arch-tag: f2259165-4454-4c04-a029-a133c8af7b5b
11049 (do not change this comment) */