Reworked.
[emacs/old-mirror.git] / src / macterm.c
blob69181958cf059614664177bb8f05932fce9ae58e
1 /* Implementation of GUI terminal on the Mac OS.
2 Copyright (C) 2000, 2001, 2002, 2003, 2004,
3 2005, 2006 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>
72 #include "charset.h"
73 #include "coding.h"
74 #include "frame.h"
75 #include "dispextern.h"
76 #include "fontset.h"
77 #include "termhooks.h"
78 #include "termopts.h"
79 #include "termchar.h"
80 #include "gnu.h"
81 #include "disptab.h"
82 #include "buffer.h"
83 #include "window.h"
84 #include "keyboard.h"
85 #include "intervals.h"
86 #include "atimer.h"
87 #include "keymap.h"
91 /* Non-nil means Emacs uses toolkit scroll bars. */
93 Lisp_Object Vx_toolkit_scroll_bars;
95 /* If non-zero, the text will be rendered using Core Graphics text
96 rendering which may anti-alias the text. */
97 int mac_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 /* Non-zero means make use of UNDERLINE_POSITION font properties.
109 (Not yet supported.) */
110 int x_use_underline_position_properties;
112 /* This is a chain of structures for all the X displays currently in
113 use. */
115 struct x_display_info *x_display_list;
117 /* This is a list of cons cells, each of the form (NAME
118 FONT-LIST-CACHE . RESOURCE-DATABASE), one for each element of
119 x_display_list and in the same order. NAME is the name of the
120 frame. FONT-LIST-CACHE records previous values returned by
121 x-list-fonts. RESOURCE-DATABASE preserves the X Resource Database
122 equivalent, which is implemented with a Lisp object, for the
123 display. */
125 Lisp_Object x_display_name_list;
127 /* This is display since Mac does not support multiple ones. */
128 struct mac_display_info one_mac_display_info;
130 /* Frame being updated by update_frame. This is declared in term.c.
131 This is set by update_begin and looked at by all the XT functions.
132 It is zero while not inside an update. In that case, the XT
133 functions assume that `selected_frame' is the frame to apply to. */
135 extern struct frame *updating_frame;
137 /* This is a frame waiting to be auto-raised, within XTread_socket. */
139 struct frame *pending_autoraise_frame;
141 /* Mouse movement.
143 Formerly, we used PointerMotionHintMask (in standard_event_mask)
144 so that we would have to call XQueryPointer after each MotionNotify
145 event to ask for another such event. However, this made mouse tracking
146 slow, and there was a bug that made it eventually stop.
148 Simply asking for MotionNotify all the time seems to work better.
150 In order to avoid asking for motion events and then throwing most
151 of them away or busy-polling the server for mouse positions, we ask
152 the server for pointer motion hints. This means that we get only
153 one event per group of mouse movements. "Groups" are delimited by
154 other kinds of events (focus changes and button clicks, for
155 example), or by XQueryPointer calls; when one of these happens, we
156 get another MotionNotify event the next time the mouse moves. This
157 is at least as efficient as getting motion events when mouse
158 tracking is on, and I suspect only negligibly worse when tracking
159 is off. */
161 /* Where the mouse was last time we reported a mouse event. */
163 static Rect last_mouse_glyph;
164 static FRAME_PTR last_mouse_glyph_frame;
166 /* The scroll bar in which the last X motion event occurred.
168 If the last X motion event occurred in a scroll bar, we set this so
169 XTmouse_position can know whether to report a scroll bar motion or
170 an ordinary motion.
172 If the last X motion event didn't occur in a scroll bar, we set
173 this to Qnil, to tell XTmouse_position to return an ordinary motion
174 event. */
176 static Lisp_Object last_mouse_scroll_bar;
178 /* This is a hack. We would really prefer that XTmouse_position would
179 return the time associated with the position it returns, but there
180 doesn't seem to be any way to wrest the time-stamp from the server
181 along with the position query. So, we just keep track of the time
182 of the last movement we received, and return that in hopes that
183 it's somewhat accurate. */
185 static Time last_mouse_movement_time;
187 struct scroll_bar *tracked_scroll_bar = NULL;
189 /* Incremented by XTread_socket whenever it really tries to read
190 events. */
192 #ifdef __STDC__
193 static int volatile input_signal_count;
194 #else
195 static int input_signal_count;
196 #endif
198 extern Lisp_Object Vsystem_name;
200 /* A mask of extra modifier bits to put into every keyboard char. */
202 extern EMACS_INT extra_keyboard_modifiers;
204 /* The keysyms to use for the various modifiers. */
206 static Lisp_Object Qalt, Qhyper, Qsuper, Qcontrol, Qmeta, Qmodifier_value;
208 extern int inhibit_window_system;
210 #if __MRC__ && !TARGET_API_MAC_CARBON
211 QDGlobals qd; /* QuickDraw global information structure. */
212 #endif
214 #define mac_window_to_frame(wp) (((mac_output *) GetWRefCon (wp))->mFP)
216 struct mac_display_info *mac_display_info_for_display (Display *);
217 static void x_update_window_end P_ ((struct window *, int, int));
218 static int x_io_error_quitter P_ ((Display *));
219 int x_catch_errors P_ ((Display *));
220 void x_uncatch_errors P_ ((Display *, int));
221 void x_lower_frame P_ ((struct frame *));
222 void x_scroll_bar_clear P_ ((struct frame *));
223 int x_had_errors_p P_ ((Display *));
224 void x_wm_set_size_hint P_ ((struct frame *, long, int));
225 void x_raise_frame P_ ((struct frame *));
226 void x_set_window_size P_ ((struct frame *, int, int, int));
227 void x_wm_set_window_state P_ ((struct frame *, int));
228 void x_wm_set_icon_pixmap P_ ((struct frame *, int));
229 void mac_initialize P_ ((void));
230 static void x_font_min_bounds P_ ((XFontStruct *, int *, int *));
231 static int x_compute_min_glyph_bounds P_ ((struct frame *));
232 static void x_update_end P_ ((struct frame *));
233 static void XTframe_up_to_date P_ ((struct frame *));
234 static void XTset_terminal_modes P_ ((void));
235 static void XTreset_terminal_modes P_ ((void));
236 static void x_clear_frame P_ ((void));
237 static void frame_highlight P_ ((struct frame *));
238 static void frame_unhighlight P_ ((struct frame *));
239 static void x_new_focus_frame P_ ((struct x_display_info *, struct frame *));
240 static void mac_focus_changed P_ ((int, struct mac_display_info *,
241 struct frame *, struct input_event *));
242 static void x_detect_focus_change P_ ((struct mac_display_info *,
243 EventRecord *, struct input_event *));
244 static void XTframe_rehighlight P_ ((struct frame *));
245 static void x_frame_rehighlight P_ ((struct x_display_info *));
246 static void x_draw_hollow_cursor P_ ((struct window *, struct glyph_row *));
247 static void x_draw_bar_cursor P_ ((struct window *, struct glyph_row *, int,
248 enum text_cursor_kinds));
250 static void x_clip_to_row P_ ((struct window *, struct glyph_row *, int, GC));
251 static void x_flush P_ ((struct frame *f));
252 static void x_update_begin P_ ((struct frame *));
253 static void x_update_window_begin P_ ((struct window *));
254 static void x_after_update_window_line P_ ((struct glyph_row *));
255 static void x_scroll_bar_report_motion P_ ((struct frame **, Lisp_Object *,
256 enum scroll_bar_part *,
257 Lisp_Object *, Lisp_Object *,
258 unsigned long *));
260 static int is_emacs_window P_ ((WindowPtr));
261 static XCharStruct *mac_per_char_metric P_ ((XFontStruct *, XChar2b *, int));
262 static void XSetFont P_ ((Display *, GC, XFontStruct *));
264 /* Defined in macmenu.h. */
265 extern void menubar_selection_callback (FRAME_PTR, int);
267 #define GC_FORE_COLOR(gc) (&(gc)->fore_color)
268 #define GC_BACK_COLOR(gc) (&(gc)->back_color)
269 #define GC_FONT(gc) ((gc)->xgcv.font)
270 #define GC_CLIP_REGION(gc) ((gc)->clip_region)
271 #define FRAME_NORMAL_GC(f) ((f)->output_data.mac->normal_gc)
273 static RgnHandle saved_port_clip_region = NULL;
275 static void
276 mac_begin_clip (region)
277 RgnHandle region;
279 static RgnHandle new_region = NULL;
281 if (saved_port_clip_region == NULL)
282 saved_port_clip_region = NewRgn ();
283 if (new_region == NULL)
284 new_region = NewRgn ();
286 if (region)
288 GetClip (saved_port_clip_region);
289 SectRgn (saved_port_clip_region, region, new_region);
290 SetClip (new_region);
294 static void
295 mac_end_clip (region)
296 RgnHandle region;
298 if (region)
299 SetClip (saved_port_clip_region);
303 /* X display function emulation */
305 void
306 XFreePixmap (display, pixmap)
307 Display *display; /* not used */
308 Pixmap pixmap;
310 DisposeGWorld (pixmap);
314 /* Mac version of XDrawLine. */
316 static void
317 mac_draw_line (f, gc, x1, y1, x2, y2)
318 struct frame *f;
319 GC gc;
320 int x1, y1, x2, y2;
322 SetPortWindowPort (FRAME_MAC_WINDOW (f));
324 RGBForeColor (GC_FORE_COLOR (gc));
326 mac_begin_clip (GC_CLIP_REGION (gc));
327 MoveTo (x1, y1);
328 LineTo (x2, y2);
329 mac_end_clip (GC_CLIP_REGION (gc));
332 void
333 mac_draw_line_to_pixmap (display, p, gc, x1, y1, x2, y2)
334 Display *display;
335 Pixmap p;
336 GC gc;
337 int x1, y1, x2, y2;
339 CGrafPtr old_port;
340 GDHandle old_gdh;
342 GetGWorld (&old_port, &old_gdh);
343 SetGWorld (p, NULL);
345 RGBForeColor (GC_FORE_COLOR (gc));
347 LockPixels (GetGWorldPixMap (p));
348 MoveTo (x1, y1);
349 LineTo (x2, y2);
350 UnlockPixels (GetGWorldPixMap (p));
352 SetGWorld (old_port, old_gdh);
356 static void
357 mac_erase_rectangle (f, gc, x, y, width, height)
358 struct frame *f;
359 GC gc;
360 int x, y;
361 unsigned int width, height;
363 Rect r;
365 SetPortWindowPort (FRAME_MAC_WINDOW (f));
367 RGBBackColor (GC_BACK_COLOR (gc));
368 SetRect (&r, x, y, x + width, y + height);
370 mac_begin_clip (GC_CLIP_REGION (gc));
371 EraseRect (&r);
372 mac_end_clip (GC_CLIP_REGION (gc));
374 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
378 /* Mac version of XClearArea. */
380 void
381 mac_clear_area (f, x, y, width, height)
382 struct frame *f;
383 int x, y;
384 unsigned int width, height;
386 mac_erase_rectangle (f, FRAME_NORMAL_GC (f), x, y, width, height);
389 /* Mac version of XClearWindow. */
391 static void
392 mac_clear_window (f)
393 struct frame *f;
395 SetPortWindowPort (FRAME_MAC_WINDOW (f));
397 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
399 #if TARGET_API_MAC_CARBON
401 Rect r;
403 GetWindowPortBounds (FRAME_MAC_WINDOW (f), &r);
404 EraseRect (&r);
406 #else /* not TARGET_API_MAC_CARBON */
407 EraseRect (&(FRAME_MAC_WINDOW (f)->portRect));
408 #endif /* not TARGET_API_MAC_CARBON */
412 /* Mac replacement for XCopyArea. */
414 static void
415 mac_draw_bitmap (f, gc, x, y, width, height, bits, overlay_p)
416 struct frame *f;
417 GC gc;
418 int x, y, width, height;
419 unsigned short *bits;
420 int overlay_p;
422 BitMap bitmap;
423 Rect r;
425 bitmap.rowBytes = sizeof(unsigned short);
426 bitmap.baseAddr = (char *)bits;
427 SetRect (&(bitmap.bounds), 0, 0, width, height);
429 SetPortWindowPort (FRAME_MAC_WINDOW (f));
431 RGBForeColor (GC_FORE_COLOR (gc));
432 RGBBackColor (GC_BACK_COLOR (gc));
433 SetRect (&r, x, y, x + width, y + height);
435 mac_begin_clip (GC_CLIP_REGION (gc));
436 #if TARGET_API_MAC_CARBON
438 CGrafPtr port;
440 GetPort (&port);
441 LockPortBits (port);
442 CopyBits (&bitmap, GetPortBitMapForCopyBits (port),
443 &(bitmap.bounds), &r, overlay_p ? srcOr : srcCopy, 0);
444 UnlockPortBits (port);
446 #else /* not TARGET_API_MAC_CARBON */
447 CopyBits (&bitmap, &(FRAME_MAC_WINDOW (f)->portBits), &(bitmap.bounds), &r,
448 overlay_p ? srcOr : srcCopy, 0);
449 #endif /* not TARGET_API_MAC_CARBON */
450 mac_end_clip (GC_CLIP_REGION (gc));
452 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
456 /* Mac replacement for XCreateBitmapFromBitmapData. */
458 static void
459 mac_create_bitmap_from_bitmap_data (bitmap, bits, w, h)
460 BitMap *bitmap;
461 char *bits;
462 int w, h;
464 static unsigned char swap_nibble[16]
465 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
466 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
467 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
468 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
469 int i, j, w1;
470 char *p;
472 w1 = (w + 7) / 8; /* nb of 8bits elt in X bitmap */
473 bitmap->rowBytes = ((w + 15) / 16) * 2; /* nb of 16bits elt in Mac bitmap */
474 bitmap->baseAddr = xmalloc (bitmap->rowBytes * h);
475 bzero (bitmap->baseAddr, bitmap->rowBytes * h);
476 for (i = 0; i < h; i++)
478 p = bitmap->baseAddr + i * bitmap->rowBytes;
479 for (j = 0; j < w1; j++)
481 /* Bitswap XBM bytes to match how Mac does things. */
482 unsigned char c = *bits++;
483 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
484 | (swap_nibble[(c>>4) & 0xf]));;
488 SetRect (&(bitmap->bounds), 0, 0, w, h);
492 static void
493 mac_free_bitmap (bitmap)
494 BitMap *bitmap;
496 xfree (bitmap->baseAddr);
500 Pixmap
501 XCreatePixmap (display, w, width, height, depth)
502 Display *display; /* not used */
503 WindowPtr w;
504 unsigned int width, height;
505 unsigned int depth;
507 Pixmap pixmap;
508 Rect r;
509 QDErr err;
511 SetPortWindowPort (w);
513 SetRect (&r, 0, 0, width, height);
514 err = NewGWorld (&pixmap, depth, &r, NULL, NULL, 0);
515 if (err != noErr)
516 return NULL;
517 return pixmap;
521 Pixmap
522 XCreatePixmapFromBitmapData (display, w, data, width, height, fg, bg, depth)
523 Display *display; /* not used */
524 WindowPtr w;
525 char *data;
526 unsigned int width, height;
527 unsigned long fg, bg;
528 unsigned int depth;
530 Pixmap pixmap;
531 BitMap bitmap;
532 CGrafPtr old_port;
533 GDHandle old_gdh;
534 static GC gc = NULL; /* not reentrant */
536 if (gc == NULL)
537 gc = XCreateGC (display, w, 0, NULL);
539 pixmap = XCreatePixmap (display, w, width, height, depth);
540 if (pixmap == NULL)
541 return NULL;
543 GetGWorld (&old_port, &old_gdh);
544 SetGWorld (pixmap, NULL);
545 mac_create_bitmap_from_bitmap_data (&bitmap, data, width, height);
546 XSetForeground (display, gc, fg);
547 XSetBackground (display, gc, bg);
548 RGBForeColor (GC_FORE_COLOR (gc));
549 RGBBackColor (GC_BACK_COLOR (gc));
550 LockPixels (GetGWorldPixMap (pixmap));
551 #if TARGET_API_MAC_CARBON
552 CopyBits (&bitmap, GetPortBitMapForCopyBits (pixmap),
553 &bitmap.bounds, &bitmap.bounds, srcCopy, 0);
554 #else /* not TARGET_API_MAC_CARBON */
555 CopyBits (&bitmap, &(((GrafPtr)pixmap)->portBits),
556 &bitmap.bounds, &bitmap.bounds, srcCopy, 0);
557 #endif /* not TARGET_API_MAC_CARBON */
558 UnlockPixels (GetGWorldPixMap (pixmap));
559 SetGWorld (old_port, old_gdh);
560 mac_free_bitmap (&bitmap);
562 return pixmap;
566 /* Mac replacement for XFillRectangle. */
568 static void
569 mac_fill_rectangle (f, gc, x, y, width, height)
570 struct frame *f;
571 GC gc;
572 int x, y;
573 unsigned int width, height;
575 Rect r;
577 SetPortWindowPort (FRAME_MAC_WINDOW (f));
579 RGBForeColor (GC_FORE_COLOR (gc));
580 SetRect (&r, x, y, x + width, y + height);
582 mac_begin_clip (GC_CLIP_REGION (gc));
583 PaintRect (&r); /* using foreground color of gc */
584 mac_end_clip (GC_CLIP_REGION (gc));
588 /* Mac replacement for XDrawRectangle: dest is a window. */
590 static void
591 mac_draw_rectangle (f, gc, x, y, width, height)
592 struct frame *f;
593 GC gc;
594 int x, y;
595 unsigned int width, height;
597 Rect r;
599 SetPortWindowPort (FRAME_MAC_WINDOW (f));
601 RGBForeColor (GC_FORE_COLOR (gc));
602 SetRect (&r, x, y, x + width + 1, y + height + 1);
604 mac_begin_clip (GC_CLIP_REGION (gc));
605 FrameRect (&r); /* using foreground color of gc */
606 mac_end_clip (GC_CLIP_REGION (gc));
610 #if USE_ATSUI
611 static OSStatus
612 atsu_get_text_layout_with_text_ptr (text, text_length, style, text_layout)
613 ConstUniCharArrayPtr text;
614 UniCharCount text_length;
615 ATSUStyle style;
616 ATSUTextLayout *text_layout;
618 OSStatus err;
619 static ATSUTextLayout saved_text_layout = NULL; /* not reentrant */
621 if (saved_text_layout == NULL)
623 UniCharCount lengths[] = {kATSUToTextEnd};
624 ATSUAttributeTag tags[] = {kATSULineLayoutOptionsTag};
625 ByteCount sizes[] = {sizeof (ATSLineLayoutOptions)};
626 static ATSLineLayoutOptions line_layout =
627 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
628 kATSLineDisableAllLayoutOperations | kATSLineUseDeviceMetrics
629 | kATSLineUseQDRendering
630 #else
631 kATSLineIsDisplayOnly | kATSLineFractDisable
632 #endif
634 ATSUAttributeValuePtr values[] = {&line_layout};
636 err = ATSUCreateTextLayoutWithTextPtr (text,
637 kATSUFromTextBeginning,
638 kATSUToTextEnd,
639 text_length,
640 1, lengths, &style,
641 &saved_text_layout);
642 if (err == noErr)
643 err = ATSUSetLayoutControls (saved_text_layout,
644 sizeof (tags) / sizeof (tags[0]),
645 tags, sizes, values);
646 /* XXX: Should we do this? */
647 if (err == noErr)
648 err = ATSUSetTransientFontMatching (saved_text_layout, true);
650 else
652 err = ATSUSetRunStyle (saved_text_layout, style,
653 kATSUFromTextBeginning, kATSUToTextEnd);
654 if (err == noErr)
655 err = ATSUSetTextPointerLocation (saved_text_layout, text,
656 kATSUFromTextBeginning,
657 kATSUToTextEnd,
658 text_length);
661 if (err == noErr)
662 *text_layout = saved_text_layout;
663 return err;
665 #endif
668 static void
669 mac_invert_rectangle (f, x, y, width, height)
670 struct frame *f;
671 int x, y;
672 unsigned int width, height;
674 Rect r;
676 SetPortWindowPort (FRAME_MAC_WINDOW (f));
678 SetRect (&r, x, y, x + width, y + height);
680 InvertRect (&r);
684 static void
685 mac_draw_string_common (f, gc, x, y, buf, nchars, mode, bytes_per_char)
686 struct frame *f;
687 GC gc;
688 int x, y;
689 char *buf;
690 int nchars, mode, bytes_per_char;
692 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
693 UInt32 textFlags, savedFlags;
694 if (mac_use_core_graphics) {
695 textFlags = kQDUseCGTextRendering;
696 savedFlags = SwapQDTextFlags(textFlags);
698 #endif
700 SetPortWindowPort (FRAME_MAC_WINDOW (f));
702 RGBForeColor (GC_FORE_COLOR (gc));
703 if (mode != srcOr)
704 RGBBackColor (GC_BACK_COLOR (gc));
706 #if USE_ATSUI
707 if (GC_FONT (gc)->mac_style)
709 OSErr err;
710 ATSUTextLayout text_layout;
712 xassert (bytes_per_char == 2);
714 #ifndef WORDS_BIG_ENDIAN
716 int i;
717 UniChar *text = (UniChar *)buf;
719 for (i = 0; i < nchars; i++)
720 text[i] = EndianU16_BtoN (text[i]);
722 #endif
723 err = atsu_get_text_layout_with_text_ptr ((ConstUniCharArrayPtr)buf,
724 nchars,
725 GC_FONT (gc)->mac_style,
726 &text_layout);
727 if (err == noErr)
729 #ifdef MAC_OSX
730 if (!mac_use_core_graphics)
732 #endif
733 mac_begin_clip (GC_CLIP_REGION (gc));
734 MoveTo (x, y);
735 ATSUDrawText (text_layout,
736 kATSUFromTextBeginning, kATSUToTextEnd,
737 kATSUUseGrafPortPenLoc, kATSUUseGrafPortPenLoc);
738 mac_end_clip (GC_CLIP_REGION (gc));
739 #ifdef MAC_OSX
741 else
743 CGrafPtr port;
744 CGContextRef context;
745 float port_height = FRAME_PIXEL_HEIGHT (f);
746 ATSUAttributeTag tags[] = {kATSUCGContextTag};
747 ByteCount sizes[] = {sizeof (CGContextRef)};
748 ATSUAttributeValuePtr values[] = {&context};
750 GetPort (&port);
751 QDBeginCGContext (port, &context);
752 if (gc->n_clip_rects)
754 CGContextTranslateCTM (context, 0, port_height);
755 CGContextScaleCTM (context, 1, -1);
756 CGContextClipToRects (context, gc->clip_rects,
757 gc->n_clip_rects);
758 CGContextScaleCTM (context, 1, -1);
759 CGContextTranslateCTM (context, 0, -port_height);
761 CGContextSetRGBFillColor
762 (context,
763 RED_FROM_ULONG (gc->xgcv.foreground) / 255.0,
764 GREEN_FROM_ULONG (gc->xgcv.foreground) / 255.0,
765 BLUE_FROM_ULONG (gc->xgcv.foreground) / 255.0,
766 1.0);
767 err = ATSUSetLayoutControls (text_layout,
768 sizeof (tags) / sizeof (tags[0]),
769 tags, sizes, values);
770 if (err == noErr)
771 ATSUDrawText (text_layout,
772 kATSUFromTextBeginning, kATSUToTextEnd,
773 Long2Fix (x), Long2Fix (port_height - y));
774 CGContextSynchronize (context);
775 QDEndCGContext (port, &context);
776 #if 0
777 /* This doesn't work on Mac OS X 10.1. */
778 ATSUClearLayoutControls (text_layout,
779 sizeof (tags) / sizeof (tags[0]),
780 tags);
781 #else
782 ATSUSetLayoutControls (text_layout,
783 sizeof (tags) / sizeof (tags[0]),
784 tags, sizes, values);
785 #endif
787 #endif
790 else
792 #endif
793 TextFont (GC_FONT (gc)->mac_fontnum);
794 TextSize (GC_FONT (gc)->mac_fontsize);
795 TextFace (GC_FONT (gc)->mac_fontface);
796 TextMode (mode);
798 mac_begin_clip (GC_CLIP_REGION (gc));
799 MoveTo (x, y);
800 DrawText (buf, 0, nchars * bytes_per_char);
801 mac_end_clip (GC_CLIP_REGION (gc));
802 #if USE_ATSUI
804 #endif
806 if (mode != srcOr)
807 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
808 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
809 if (mac_use_core_graphics)
810 SwapQDTextFlags(savedFlags);
811 #endif
815 /* Mac replacement for XDrawString. */
817 static void
818 mac_draw_string (f, gc, x, y, buf, nchars)
819 struct frame *f;
820 GC gc;
821 int x, y;
822 char *buf;
823 int nchars;
825 mac_draw_string_common (f, gc, x, y, buf, nchars, srcOr, 1);
829 /* Mac replacement for XDrawString16. */
831 static void
832 mac_draw_string_16 (f, gc, x, y, buf, nchars)
833 struct frame *f;
834 GC gc;
835 int x, y;
836 XChar2b *buf;
837 int nchars;
839 mac_draw_string_common (f, gc, x, y, (char *) buf, nchars, srcOr, 2);
843 /* Mac replacement for XDrawImageString. */
845 static void
846 mac_draw_image_string (f, gc, x, y, buf, nchars)
847 struct frame *f;
848 GC gc;
849 int x, y;
850 char *buf;
851 int nchars;
853 mac_draw_string_common (f, gc, x, y, buf, nchars, srcCopy, 1);
857 /* Mac replacement for XDrawString16. */
859 static void
860 mac_draw_image_string_16 (f, gc, x, y, buf, nchars)
861 struct frame *f;
862 GC gc;
863 int x, y;
864 XChar2b *buf;
865 int nchars;
867 mac_draw_string_common (f, gc, x, y, (char *) buf, nchars, srcCopy, 2);
871 /* Mac replacement for XQueryTextExtents, but takes a character. If
872 STYLE is NULL, measurement is done by QuickDraw Text routines for
873 the font of the current graphics port. If CG_GLYPH is not NULL,
874 *CG_GLYPH is set to the glyph ID or 0 if it cannot be obtained. */
876 static OSErr
877 mac_query_char_extents (style, c,
878 font_ascent_return, font_descent_return,
879 overall_return, cg_glyph)
880 #if USE_ATSUI
881 ATSUStyle style;
882 #else
883 void *style;
884 #endif
885 int c;
886 int *font_ascent_return, *font_descent_return;
887 XCharStruct *overall_return;
888 #if USE_CG_TEXT_DRAWING
889 CGGlyph *cg_glyph;
890 #else
891 void *cg_glyph;
892 #endif
894 OSErr err = noErr;
895 int width;
896 Rect char_bounds;
898 #if USE_ATSUI
899 if (style)
901 ATSUTextLayout text_layout;
902 UniChar ch = c;
904 err = atsu_get_text_layout_with_text_ptr (&ch, 1, style, &text_layout);
905 if (err == noErr)
907 ATSTrapezoid glyph_bounds;
909 err = ATSUGetGlyphBounds (text_layout, 0, 0,
910 kATSUFromTextBeginning, kATSUToTextEnd,
911 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
912 kATSUseFractionalOrigins,
913 #else
914 kATSUseDeviceOrigins,
915 #endif
916 1, &glyph_bounds, NULL);
917 if (err == noErr)
919 xassert (glyph_bounds.lowerRight.x - glyph_bounds.lowerLeft.x
920 == glyph_bounds.upperRight.x - glyph_bounds.upperLeft.x);
922 width = Fix2Long (glyph_bounds.upperRight.x
923 - glyph_bounds.upperLeft.x);
924 if (font_ascent_return)
925 *font_ascent_return = -Fix2Long (glyph_bounds.upperLeft.y);
926 if (font_descent_return)
927 *font_descent_return = Fix2Long (glyph_bounds.lowerLeft.y);
930 if (err == noErr && overall_return)
932 err = ATSUMeasureTextImage (text_layout,
933 kATSUFromTextBeginning, kATSUToTextEnd,
934 0, 0, &char_bounds);
935 if (err == noErr)
936 STORE_XCHARSTRUCT (*overall_return, width, char_bounds);
937 #if USE_CG_TEXT_DRAWING
938 if (err == noErr && cg_glyph)
940 OSErr err1;
941 ATSUGlyphInfoArray glyph_info_array;
942 ByteCount count = sizeof (ATSUGlyphInfoArray);
944 err1 = ATSUMatchFontsToText (text_layout, kATSUFromTextBeginning,
945 kATSUToTextEnd, NULL, NULL, NULL);
946 if (err1 == noErr)
947 err1 = ATSUGetGlyphInfo (text_layout, kATSUFromTextBeginning,
948 kATSUToTextEnd, &count,
949 &glyph_info_array);
950 if (err1 == noErr)
952 xassert (glyph_info_array.glyphs[0].glyphID);
953 *cg_glyph = glyph_info_array.glyphs[0].glyphID;
955 else
956 *cg_glyph = 0;
958 #endif
961 else
962 #endif
964 if (font_ascent_return || font_descent_return)
966 FontInfo font_info;
968 GetFontInfo (&font_info);
969 if (font_ascent_return)
970 *font_ascent_return = font_info.ascent;
971 if (font_descent_return)
972 *font_descent_return = font_info.descent;
974 if (overall_return)
976 char ch = c;
978 width = CharWidth (ch);
979 QDTextBounds (1, &ch, &char_bounds);
980 STORE_XCHARSTRUCT (*overall_return, width, char_bounds);
984 return err;
988 /* Mac replacement for XTextExtents16. Only sets horizontal metrics. */
990 static int
991 mac_text_extents_16 (font_struct, string, nchars, overall_return)
992 XFontStruct *font_struct;
993 XChar2b *string;
994 int nchars;
995 XCharStruct *overall_return;
997 int i;
998 short width = 0, lbearing = 0, rbearing = 0;
999 XCharStruct *pcm;
1001 for (i = 0; i < nchars; i++)
1003 pcm = mac_per_char_metric (font_struct, string, 0);
1004 if (pcm == NULL)
1005 width += FONT_WIDTH (font_struct);
1006 else
1008 lbearing = min (lbearing, width + pcm->lbearing);
1009 rbearing = max (rbearing, width + pcm->rbearing);
1010 width += pcm->width;
1012 string++;
1015 overall_return->lbearing = lbearing;
1016 overall_return->rbearing = rbearing;
1017 overall_return->width = width;
1019 /* What's the meaning of the return value of XTextExtents16? */
1023 #if USE_CG_TEXT_DRAWING
1024 static int cg_text_anti_aliasing_threshold = 8;
1026 static void
1027 init_cg_text_anti_aliasing_threshold ()
1029 int threshold;
1030 Boolean valid_p;
1032 threshold =
1033 CFPreferencesGetAppIntegerValue (CFSTR ("AppleAntiAliasingThreshold"),
1034 kCFPreferencesCurrentApplication,
1035 &valid_p);
1036 if (valid_p)
1037 cg_text_anti_aliasing_threshold = threshold;
1040 static int
1041 mac_draw_string_cg (f, gc, x, y, buf, nchars)
1042 struct frame *f;
1043 GC gc;
1044 int x, y;
1045 XChar2b *buf;
1046 int nchars;
1048 CGrafPtr port;
1049 float port_height, gx, gy;
1050 int i;
1051 CGContextRef context;
1052 CGGlyph *glyphs;
1053 CGSize *advances;
1055 if (!mac_use_core_graphics || GC_FONT (gc)->cg_font == NULL)
1056 return 0;
1058 port = GetWindowPort (FRAME_MAC_WINDOW (f));
1059 port_height = FRAME_PIXEL_HEIGHT (f);
1060 gx = x;
1061 gy = port_height - y;
1062 glyphs = (CGGlyph *)buf;
1063 advances = xmalloc (sizeof (CGSize) * nchars);
1064 for (i = 0; i < nchars; i++)
1066 XCharStruct *pcm = mac_per_char_metric (GC_FONT (gc), buf, 0);
1068 advances[i].width = pcm->width;
1069 advances[i].height = 0;
1070 glyphs[i] = GC_FONT (gc)->cg_glyphs[buf->byte2];
1071 buf++;
1074 QDBeginCGContext (port, &context);
1075 if (gc->n_clip_rects)
1077 CGContextTranslateCTM (context, 0, port_height);
1078 CGContextScaleCTM (context, 1, -1);
1079 CGContextClipToRects (context, gc->clip_rects, gc->n_clip_rects);
1080 CGContextScaleCTM (context, 1, -1);
1081 CGContextTranslateCTM (context, 0, -port_height);
1083 CGContextSetRGBFillColor (context,
1084 RED_FROM_ULONG (gc->xgcv.foreground) / 255.0,
1085 GREEN_FROM_ULONG (gc->xgcv.foreground) / 255.0,
1086 BLUE_FROM_ULONG (gc->xgcv.foreground) / 255.0,
1087 1.0);
1088 CGContextSetFont (context, GC_FONT (gc)->cg_font);
1089 CGContextSetFontSize (context, GC_FONT (gc)->mac_fontsize);
1090 if (GC_FONT (gc)->mac_fontsize <= cg_text_anti_aliasing_threshold)
1091 CGContextSetShouldAntialias (context, false);
1092 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1030
1093 CGContextSetTextPosition (context, gx, gy);
1094 CGContextShowGlyphsWithAdvances (context, glyphs, advances, nchars);
1095 #else
1096 for (i = 0; i < nchars; i++)
1098 CGContextShowGlyphsAtPoint (context, gx, gy, glyphs + i, 1);
1099 gx += advances[i].width;
1101 #endif
1102 CGContextSynchronize (context);
1103 QDEndCGContext (port, &context);
1105 xfree (advances);
1107 return 1;
1109 #endif
1112 /* Mac replacement for XCopyArea: dest must be window. */
1114 static void
1115 mac_copy_area (src, f, gc, src_x, src_y, width, height, dest_x, dest_y)
1116 Pixmap src;
1117 struct frame *f;
1118 GC gc;
1119 int src_x, src_y;
1120 unsigned int width, height;
1121 int dest_x, dest_y;
1123 Rect src_r, dest_r;
1125 SetPortWindowPort (FRAME_MAC_WINDOW (f));
1127 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
1128 SetRect (&dest_r, dest_x, dest_y, dest_x + width, dest_y + height);
1130 ForeColor (blackColor);
1131 BackColor (whiteColor);
1133 mac_begin_clip (GC_CLIP_REGION (gc));
1134 LockPixels (GetGWorldPixMap (src));
1135 #if TARGET_API_MAC_CARBON
1137 CGrafPtr port;
1139 GetPort (&port);
1140 LockPortBits (port);
1141 CopyBits (GetPortBitMapForCopyBits (src),
1142 GetPortBitMapForCopyBits (port),
1143 &src_r, &dest_r, srcCopy, 0);
1144 UnlockPortBits (port);
1146 #else /* not TARGET_API_MAC_CARBON */
1147 CopyBits (&(((GrafPtr)src)->portBits), &(FRAME_MAC_WINDOW (f)->portBits),
1148 &src_r, &dest_r, srcCopy, 0);
1149 #endif /* not TARGET_API_MAC_CARBON */
1150 UnlockPixels (GetGWorldPixMap (src));
1151 mac_end_clip (GC_CLIP_REGION (gc));
1153 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
1157 static void
1158 mac_copy_area_with_mask (src, mask, f, gc, src_x, src_y,
1159 width, height, dest_x, dest_y)
1160 Pixmap src, mask;
1161 struct frame *f;
1162 GC gc;
1163 int src_x, src_y;
1164 unsigned int width, height;
1165 int dest_x, dest_y;
1167 Rect src_r, dest_r;
1169 SetPortWindowPort (FRAME_MAC_WINDOW (f));
1171 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
1172 SetRect (&dest_r, dest_x, dest_y, dest_x + width, dest_y + height);
1174 ForeColor (blackColor);
1175 BackColor (whiteColor);
1177 mac_begin_clip (GC_CLIP_REGION (gc));
1178 LockPixels (GetGWorldPixMap (src));
1179 LockPixels (GetGWorldPixMap (mask));
1180 #if TARGET_API_MAC_CARBON
1182 CGrafPtr port;
1184 GetPort (&port);
1185 LockPortBits (port);
1186 CopyMask (GetPortBitMapForCopyBits (src), GetPortBitMapForCopyBits (mask),
1187 GetPortBitMapForCopyBits (port),
1188 &src_r, &src_r, &dest_r);
1189 UnlockPortBits (port);
1191 #else /* not TARGET_API_MAC_CARBON */
1192 CopyMask (&(((GrafPtr)src)->portBits), &(((GrafPtr)mask)->portBits),
1193 &(FRAME_MAC_WINDOW (f)->portBits), &src_r, &src_r, &dest_r);
1194 #endif /* not TARGET_API_MAC_CARBON */
1195 UnlockPixels (GetGWorldPixMap (mask));
1196 UnlockPixels (GetGWorldPixMap (src));
1197 mac_end_clip (GC_CLIP_REGION (gc));
1199 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
1203 /* Mac replacement for XCopyArea: used only for scrolling. */
1205 static void
1206 mac_scroll_area (f, gc, src_x, src_y, width, height, dest_x, dest_y)
1207 struct frame *f;
1208 GC gc;
1209 int src_x, src_y;
1210 unsigned int width, height;
1211 int dest_x, dest_y;
1213 #if TARGET_API_MAC_CARBON
1214 Rect src_r;
1215 RgnHandle dummy = NewRgn (); /* For avoiding update events. */
1217 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
1218 ScrollWindowRect (FRAME_MAC_WINDOW (f),
1219 &src_r, dest_x - src_x, dest_y - src_y,
1220 kScrollWindowNoOptions, dummy);
1221 DisposeRgn (dummy);
1222 #else /* not TARGET_API_MAC_CARBON */
1223 Rect src_r, dest_r;
1224 WindowPtr w = FRAME_MAC_WINDOW (f);
1226 SetPort (w);
1228 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
1229 SetRect (&dest_r, dest_x, dest_y, dest_x + width, dest_y + height);
1231 /* In Color QuickDraw, set ForeColor and BackColor as follows to avoid
1232 color mapping in CopyBits. Otherwise, it will be slow. */
1233 ForeColor (blackColor);
1234 BackColor (whiteColor);
1235 mac_begin_clip (GC_CLIP_REGION (gc));
1236 CopyBits (&(w->portBits), &(w->portBits), &src_r, &dest_r, srcCopy, 0);
1237 mac_end_clip (GC_CLIP_REGION (gc));
1239 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
1240 #endif /* not TARGET_API_MAC_CARBON */
1244 /* Mac replacement for XChangeGC. */
1246 static void
1247 XChangeGC (display, gc, mask, xgcv)
1248 Display *display;
1249 GC gc;
1250 unsigned long mask;
1251 XGCValues *xgcv;
1253 if (mask & GCForeground)
1254 XSetForeground (display, gc, xgcv->foreground);
1255 if (mask & GCBackground)
1256 XSetBackground (display, gc, xgcv->background);
1257 if (mask & GCFont)
1258 XSetFont (display, gc, xgcv->font);
1262 /* Mac replacement for XCreateGC. */
1265 XCreateGC (display, window, mask, xgcv)
1266 Display *display;
1267 Window window;
1268 unsigned long mask;
1269 XGCValues *xgcv;
1271 GC gc = xmalloc (sizeof (*gc));
1273 if (gc)
1275 bzero (gc, sizeof (*gc));
1276 XChangeGC (display, gc, mask, xgcv);
1279 return gc;
1283 /* Used in xfaces.c. */
1285 void
1286 XFreeGC (display, gc)
1287 Display *display;
1288 GC gc;
1290 if (gc->clip_region)
1291 DisposeRgn (gc->clip_region);
1292 xfree (gc);
1296 /* Mac replacement for XGetGCValues. */
1298 static void
1299 XGetGCValues (display, gc, mask, xgcv)
1300 Display *display;
1301 GC gc;
1302 unsigned long mask;
1303 XGCValues *xgcv;
1305 if (mask & GCForeground)
1306 xgcv->foreground = gc->xgcv.foreground;
1307 if (mask & GCBackground)
1308 xgcv->background = gc->xgcv.background;
1309 if (mask & GCFont)
1310 xgcv->font = gc->xgcv.font;
1314 /* Mac replacement for XSetForeground. */
1316 void
1317 XSetForeground (display, gc, color)
1318 Display *display;
1319 GC gc;
1320 unsigned long color;
1322 if (gc->xgcv.foreground != color)
1324 gc->xgcv.foreground = color;
1325 gc->fore_color.red = RED16_FROM_ULONG (color);
1326 gc->fore_color.green = GREEN16_FROM_ULONG (color);
1327 gc->fore_color.blue = BLUE16_FROM_ULONG (color);
1332 /* Mac replacement for XSetBackground. */
1334 void
1335 XSetBackground (display, gc, color)
1336 Display *display;
1337 GC gc;
1338 unsigned long color;
1340 if (gc->xgcv.background != color)
1342 gc->xgcv.background = color;
1343 gc->back_color.red = RED16_FROM_ULONG (color);
1344 gc->back_color.green = GREEN16_FROM_ULONG (color);
1345 gc->back_color.blue = BLUE16_FROM_ULONG (color);
1350 /* Mac replacement for XSetFont. */
1352 static void
1353 XSetFont (display, gc, font)
1354 Display *display;
1355 GC gc;
1356 XFontStruct *font;
1358 gc->xgcv.font = font;
1362 /* Mac replacement for XSetClipRectangles. */
1364 static void
1365 mac_set_clip_rectangles (display, gc, rectangles, n)
1366 Display *display;
1367 GC gc;
1368 Rect *rectangles;
1369 int n;
1371 int i;
1373 if (n < 0 || n > MAX_CLIP_RECTS)
1374 abort ();
1375 if (n == 0)
1377 if (gc->clip_region)
1379 DisposeRgn (gc->clip_region);
1380 gc->clip_region = NULL;
1383 else
1385 if (gc->clip_region == NULL)
1386 gc->clip_region = NewRgn ();
1387 RectRgn (gc->clip_region, rectangles);
1388 if (n > 1)
1390 RgnHandle region = NewRgn ();
1392 for (i = 1; i < n; i++)
1394 RectRgn (region, rectangles + i);
1395 UnionRgn (gc->clip_region, region, gc->clip_region);
1397 DisposeRgn (region);
1400 #if defined (MAC_OSX) && USE_ATSUI
1401 gc->n_clip_rects = n;
1403 for (i = 0; i < n; i++)
1405 Rect *rect = rectangles + i;
1407 gc->clip_rects[i] = CGRectMake (rect->left, rect->top,
1408 rect->right - rect->left,
1409 rect->bottom - rect->top);
1411 #endif
1415 /* Mac replacement for XSetClipMask. */
1417 static INLINE void
1418 mac_reset_clip_rectangles (display, gc)
1419 Display *display;
1420 GC gc;
1422 mac_set_clip_rectangles (display, gc, NULL, 0);
1426 /* Mac replacement for XSetWindowBackground. */
1428 void
1429 XSetWindowBackground (display, w, color)
1430 Display *display;
1431 WindowPtr w;
1432 unsigned long color;
1434 #if !TARGET_API_MAC_CARBON
1435 AuxWinHandle aw_handle;
1436 CTabHandle ctab_handle;
1437 ColorSpecPtr ct_table;
1438 short ct_size;
1439 #endif
1440 RGBColor bg_color;
1442 bg_color.red = RED16_FROM_ULONG (color);
1443 bg_color.green = GREEN16_FROM_ULONG (color);
1444 bg_color.blue = BLUE16_FROM_ULONG (color);
1446 #if TARGET_API_MAC_CARBON
1447 SetWindowContentColor (w, &bg_color);
1448 #else
1449 if (GetAuxWin (w, &aw_handle))
1451 ctab_handle = (*aw_handle)->awCTable;
1452 HandToHand ((Handle *) &ctab_handle);
1453 ct_table = (*ctab_handle)->ctTable;
1454 ct_size = (*ctab_handle)->ctSize;
1455 while (ct_size > -1)
1457 if (ct_table->value == 0)
1459 ct_table->rgb = bg_color;
1460 CTabChanged (ctab_handle);
1461 SetWinColor (w, (WCTabHandle) ctab_handle);
1463 ct_size--;
1466 #endif
1469 /* x_sync is a no-op on Mac. */
1470 void
1471 x_sync (f)
1472 void *f;
1477 /* Flush display of frame F, or of all frames if F is null. */
1479 static void
1480 x_flush (f)
1481 struct frame *f;
1483 #if TARGET_API_MAC_CARBON
1484 BLOCK_INPUT;
1485 if (f)
1486 QDFlushPortBuffer (GetWindowPort (FRAME_MAC_WINDOW (f)), NULL);
1487 else
1488 QDFlushPortBuffer (GetQDGlobalsThePort (), NULL);
1489 UNBLOCK_INPUT;
1490 #endif
1494 /* Remove calls to XFlush by defining XFlush to an empty replacement.
1495 Calls to XFlush should be unnecessary because the X output buffer
1496 is flushed automatically as needed by calls to XPending,
1497 XNextEvent, or XWindowEvent according to the XFlush man page.
1498 XTread_socket calls XPending. Removing XFlush improves
1499 performance. */
1501 #define XFlush(DISPLAY) (void) 0
1504 /* Return the struct mac_display_info corresponding to DPY. There's
1505 only one. */
1507 struct mac_display_info *
1508 mac_display_info_for_display (dpy)
1509 Display *dpy;
1511 return &one_mac_display_info;
1516 /***********************************************************************
1517 Starting and ending an update
1518 ***********************************************************************/
1520 /* Start an update of frame F. This function is installed as a hook
1521 for update_begin, i.e. it is called when update_begin is called.
1522 This function is called prior to calls to x_update_window_begin for
1523 each window being updated. */
1525 static void
1526 x_update_begin (f)
1527 struct frame *f;
1529 #if TARGET_API_MAC_CARBON
1530 /* During update of a frame, availability of input events is
1531 periodically checked with ReceiveNextEvent if
1532 redisplay-dont-pause is nil. That normally flushes window buffer
1533 changes for every check, and thus screen update looks waving even
1534 if no input is available. So we disable screen updates during
1535 update of a frame. */
1536 BLOCK_INPUT;
1537 DisableScreenUpdates ();
1538 UNBLOCK_INPUT;
1539 #endif
1543 /* Start update of window W. Set the global variable updated_window
1544 to the window being updated and set output_cursor to the cursor
1545 position of W. */
1547 static void
1548 x_update_window_begin (w)
1549 struct window *w;
1551 struct frame *f = XFRAME (WINDOW_FRAME (w));
1552 struct mac_display_info *display_info = FRAME_MAC_DISPLAY_INFO (f);
1554 updated_window = w;
1555 set_output_cursor (&w->cursor);
1557 BLOCK_INPUT;
1559 if (f == display_info->mouse_face_mouse_frame)
1561 /* Don't do highlighting for mouse motion during the update. */
1562 display_info->mouse_face_defer = 1;
1564 /* If F needs to be redrawn, simply forget about any prior mouse
1565 highlighting. */
1566 if (FRAME_GARBAGED_P (f))
1567 display_info->mouse_face_window = Qnil;
1569 #if 0 /* Rows in a current matrix containing glyphs in mouse-face have
1570 their mouse_face_p flag set, which means that they are always
1571 unequal to rows in a desired matrix which never have that
1572 flag set. So, rows containing mouse-face glyphs are never
1573 scrolled, and we don't have to switch the mouse highlight off
1574 here to prevent it from being scrolled. */
1576 /* Can we tell that this update does not affect the window
1577 where the mouse highlight is? If so, no need to turn off.
1578 Likewise, don't do anything if the frame is garbaged;
1579 in that case, the frame's current matrix that we would use
1580 is all wrong, and we will redisplay that line anyway. */
1581 if (!NILP (display_info->mouse_face_window)
1582 && w == XWINDOW (display_info->mouse_face_window))
1584 int i;
1586 for (i = 0; i < w->desired_matrix->nrows; ++i)
1587 if (MATRIX_ROW_ENABLED_P (w->desired_matrix, i))
1588 break;
1590 if (i < w->desired_matrix->nrows)
1591 clear_mouse_face (display_info);
1593 #endif /* 0 */
1596 UNBLOCK_INPUT;
1600 /* Draw a vertical window border from (x,y0) to (x,y1) */
1602 static void
1603 mac_draw_vertical_window_border (w, x, y0, y1)
1604 struct window *w;
1605 int x, y0, y1;
1607 struct frame *f = XFRAME (WINDOW_FRAME (w));
1608 struct face *face;
1610 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
1611 if (face)
1612 XSetForeground (FRAME_MAC_DISPLAY (f), f->output_data.mac->normal_gc,
1613 face->foreground);
1615 mac_draw_line (f, f->output_data.mac->normal_gc, x, y0, x, y1);
1618 /* End update of window W (which is equal to updated_window).
1620 Draw vertical borders between horizontally adjacent windows, and
1621 display W's cursor if CURSOR_ON_P is non-zero.
1623 MOUSE_FACE_OVERWRITTEN_P non-zero means that some row containing
1624 glyphs in mouse-face were overwritten. In that case we have to
1625 make sure that the mouse-highlight is properly redrawn.
1627 W may be a menu bar pseudo-window in case we don't have X toolkit
1628 support. Such windows don't have a cursor, so don't display it
1629 here. */
1631 static void
1632 x_update_window_end (w, cursor_on_p, mouse_face_overwritten_p)
1633 struct window *w;
1634 int cursor_on_p, mouse_face_overwritten_p;
1636 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (XFRAME (w->frame));
1638 if (!w->pseudo_window_p)
1640 BLOCK_INPUT;
1642 if (cursor_on_p)
1643 display_and_set_cursor (w, 1, output_cursor.hpos,
1644 output_cursor.vpos,
1645 output_cursor.x, output_cursor.y);
1647 if (draw_window_fringes (w, 1))
1648 x_draw_vertical_border (w);
1650 UNBLOCK_INPUT;
1653 /* If a row with mouse-face was overwritten, arrange for
1654 XTframe_up_to_date to redisplay the mouse highlight. */
1655 if (mouse_face_overwritten_p)
1657 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
1658 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
1659 dpyinfo->mouse_face_window = Qnil;
1662 updated_window = NULL;
1666 /* End update of frame F. This function is installed as a hook in
1667 update_end. */
1669 static void
1670 x_update_end (f)
1671 struct frame *f;
1673 /* Mouse highlight may be displayed again. */
1674 FRAME_MAC_DISPLAY_INFO (f)->mouse_face_defer = 0;
1676 BLOCK_INPUT;
1677 #if TARGET_API_MAC_CARBON
1678 EnableScreenUpdates ();
1679 #endif
1680 XFlush (FRAME_MAC_DISPLAY (f));
1681 UNBLOCK_INPUT;
1685 /* This function is called from various places in xdisp.c whenever a
1686 complete update has been performed. The global variable
1687 updated_window is not available here. */
1689 static void
1690 XTframe_up_to_date (f)
1691 struct frame *f;
1693 if (FRAME_MAC_P (f))
1695 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
1697 if (dpyinfo->mouse_face_deferred_gc
1698 || f == dpyinfo->mouse_face_mouse_frame)
1700 BLOCK_INPUT;
1701 if (dpyinfo->mouse_face_mouse_frame)
1702 note_mouse_highlight (dpyinfo->mouse_face_mouse_frame,
1703 dpyinfo->mouse_face_mouse_x,
1704 dpyinfo->mouse_face_mouse_y);
1705 dpyinfo->mouse_face_deferred_gc = 0;
1706 UNBLOCK_INPUT;
1712 /* Draw truncation mark bitmaps, continuation mark bitmaps, overlay
1713 arrow bitmaps, or clear the fringes if no bitmaps are required
1714 before DESIRED_ROW is made current. The window being updated is
1715 found in updated_window. This function is called from
1716 update_window_line only if it is known that there are differences
1717 between bitmaps to be drawn between current row and DESIRED_ROW. */
1719 static void
1720 x_after_update_window_line (desired_row)
1721 struct glyph_row *desired_row;
1723 struct window *w = updated_window;
1724 struct frame *f;
1725 int width, height;
1727 xassert (w);
1729 if (!desired_row->mode_line_p && !w->pseudo_window_p)
1730 desired_row->redraw_fringe_bitmaps_p = 1;
1732 /* When a window has disappeared, make sure that no rest of
1733 full-width rows stays visible in the internal border. Could
1734 check here if updated_window is the leftmost/rightmost window,
1735 but I guess it's not worth doing since vertically split windows
1736 are almost never used, internal border is rarely set, and the
1737 overhead is very small. */
1738 if (windows_or_buffers_changed
1739 && desired_row->full_width_p
1740 && (f = XFRAME (w->frame),
1741 width = FRAME_INTERNAL_BORDER_WIDTH (f),
1742 width != 0)
1743 && (height = desired_row->visible_height,
1744 height > 0))
1746 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
1748 /* Internal border is drawn below the tool bar. */
1749 if (WINDOWP (f->tool_bar_window)
1750 && w == XWINDOW (f->tool_bar_window))
1751 y -= width;
1753 BLOCK_INPUT;
1754 mac_clear_area (f, 0, y, width, height);
1755 mac_clear_area (f, FRAME_PIXEL_WIDTH (f) - width, y, width, height);
1756 UNBLOCK_INPUT;
1761 /* Draw the bitmap WHICH in one of the left or right fringes of
1762 window W. ROW is the glyph row for which to display the bitmap; it
1763 determines the vertical position at which the bitmap has to be
1764 drawn. */
1766 static void
1767 x_draw_fringe_bitmap (w, row, p)
1768 struct window *w;
1769 struct glyph_row *row;
1770 struct draw_fringe_bitmap_params *p;
1772 struct frame *f = XFRAME (WINDOW_FRAME (w));
1773 Display *display = FRAME_MAC_DISPLAY (f);
1774 struct face *face = p->face;
1775 int rowY;
1777 /* Must clip because of partially visible lines. */
1778 rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
1779 if (p->y < rowY)
1781 /* Adjust position of "bottom aligned" bitmap on partially
1782 visible last row. */
1783 int oldY = row->y;
1784 int oldVH = row->visible_height;
1785 row->visible_height = p->h;
1786 row->y -= rowY - p->y;
1787 x_clip_to_row (w, row, -1, face->gc);
1788 row->y = oldY;
1789 row->visible_height = oldVH;
1791 else
1792 x_clip_to_row (w, row, -1, face->gc);
1794 if (p->bx >= 0 && !p->overlay_p)
1796 #if 0 /* MAC_TODO: stipple */
1797 /* In case the same realized face is used for fringes and
1798 for something displayed in the text (e.g. face `region' on
1799 mono-displays, the fill style may have been changed to
1800 FillSolid in x_draw_glyph_string_background. */
1801 if (face->stipple)
1802 XSetFillStyle (FRAME_X_DISPLAY (f), face->gc, FillOpaqueStippled);
1803 else
1804 XSetForeground (FRAME_X_DISPLAY (f), face->gc, face->background);
1805 #endif
1807 mac_erase_rectangle (f, face->gc, p->bx, p->by, p->nx, p->ny);
1809 #if 0 /* MAC_TODO: stipple */
1810 if (!face->stipple)
1811 XSetForeground (FRAME_X_DISPLAY (f), face->gc, face->foreground);
1812 #endif
1815 if (p->which)
1817 unsigned short *bits = p->bits + p->dh;
1818 XGCValues gcv;
1820 XGetGCValues (display, face->gc, GCForeground, &gcv);
1821 XSetForeground (display, face->gc,
1822 (p->cursor_p
1823 ? (p->overlay_p ? face->background
1824 : f->output_data.mac->cursor_pixel)
1825 : face->foreground));
1826 mac_draw_bitmap (f, face->gc, p->x, p->y,
1827 p->wd, p->h, bits, p->overlay_p);
1828 XSetForeground (display, face->gc, gcv.foreground);
1831 mac_reset_clip_rectangles (display, face->gc);
1836 /* This is called when starting Emacs and when restarting after
1837 suspend. When starting Emacs, no window is mapped. And nothing
1838 must be done to Emacs's own window if it is suspended (though that
1839 rarely happens). */
1841 static void
1842 XTset_terminal_modes ()
1846 /* This is called when exiting or suspending Emacs. Exiting will make
1847 the windows go away, and suspending requires no action. */
1849 static void
1850 XTreset_terminal_modes ()
1856 /***********************************************************************
1857 Display Iterator
1858 ***********************************************************************/
1860 /* Function prototypes of this page. */
1862 static XCharStruct *x_per_char_metric P_ ((XFontStruct *, XChar2b *));
1863 static int mac_encode_char P_ ((int, XChar2b *, struct font_info *, int *));
1866 /* Get metrics of character CHAR2B in FONT. Value is null if CHAR2B
1867 is not contained in the font. */
1869 static INLINE XCharStruct *
1870 x_per_char_metric (font, char2b)
1871 XFontStruct *font;
1872 XChar2b *char2b;
1874 /* The result metric information. */
1875 XCharStruct *pcm = NULL;
1877 xassert (font && char2b);
1879 #if USE_ATSUI
1880 if (font->mac_style)
1882 XCharStructRow **row = font->bounds.rows + char2b->byte1;
1884 if (*row == NULL)
1886 *row = xmalloc (sizeof (XCharStructRow));
1887 if (*row)
1888 bzero (*row, sizeof (XCharStructRow));
1890 if (*row)
1892 pcm = (*row)->per_char + char2b->byte2;
1893 if (!XCHARSTRUCTROW_CHAR_VALID_P (*row, char2b->byte2))
1895 BLOCK_INPUT;
1896 mac_query_char_extents (font->mac_style,
1897 (char2b->byte1 << 8) + char2b->byte2,
1898 NULL, NULL, pcm, NULL);
1899 UNBLOCK_INPUT;
1900 XCHARSTRUCTROW_SET_CHAR_VALID (*row, char2b->byte2);
1904 else
1906 #endif
1907 if (font->bounds.per_char != NULL)
1909 if (font->min_byte1 == 0 && font->max_byte1 == 0)
1911 /* min_char_or_byte2 specifies the linear character index
1912 corresponding to the first element of the per_char array,
1913 max_char_or_byte2 is the index of the last character. A
1914 character with non-zero CHAR2B->byte1 is not in the font.
1915 A character with byte2 less than min_char_or_byte2 or
1916 greater max_char_or_byte2 is not in the font. */
1917 if (char2b->byte1 == 0
1918 && char2b->byte2 >= font->min_char_or_byte2
1919 && char2b->byte2 <= font->max_char_or_byte2)
1920 pcm = font->bounds.per_char
1921 + (char2b->byte2 - font->min_char_or_byte2);
1923 else
1925 /* If either min_byte1 or max_byte1 are nonzero, both
1926 min_char_or_byte2 and max_char_or_byte2 are less than
1927 256, and the 2-byte character index values corresponding
1928 to the per_char array element N (counting from 0) are:
1930 byte1 = N/D + min_byte1
1931 byte2 = N\D + min_char_or_byte2
1933 where:
1935 D = max_char_or_byte2 - min_char_or_byte2 + 1
1936 / = integer division
1937 \ = integer modulus */
1938 if (char2b->byte1 >= font->min_byte1
1939 && char2b->byte1 <= font->max_byte1
1940 && char2b->byte2 >= font->min_char_or_byte2
1941 && char2b->byte2 <= font->max_char_or_byte2)
1943 pcm = (font->bounds.per_char
1944 + ((font->max_char_or_byte2 - font->min_char_or_byte2 + 1)
1945 * (char2b->byte1 - font->min_byte1))
1946 + (char2b->byte2 - font->min_char_or_byte2));
1950 else
1952 /* If the per_char pointer is null, all glyphs between the first
1953 and last character indexes inclusive have the same
1954 information, as given by both min_bounds and max_bounds. */
1955 if (char2b->byte2 >= font->min_char_or_byte2
1956 && char2b->byte2 <= font->max_char_or_byte2)
1957 pcm = &font->max_bounds;
1959 #if USE_ATSUI
1961 #endif
1963 return ((pcm == NULL
1964 || (pcm->width == 0 && (pcm->rbearing - pcm->lbearing) == 0))
1965 ? NULL : pcm);
1968 /* RIF:
1971 static XCharStruct *
1972 mac_per_char_metric (font, char2b, font_type)
1973 XFontStruct *font;
1974 XChar2b *char2b;
1975 int font_type;
1977 return x_per_char_metric (font, char2b);
1980 /* RIF:
1981 Encode CHAR2B using encoding information from FONT_INFO. CHAR2B is
1982 the two-byte form of C. Encoding is returned in *CHAR2B. */
1984 static int
1985 mac_encode_char (c, char2b, font_info, two_byte_p)
1986 int c;
1987 XChar2b *char2b;
1988 struct font_info *font_info;
1989 int *two_byte_p;
1991 int charset = CHAR_CHARSET (c);
1992 XFontStruct *font = font_info->font;
1994 /* FONT_INFO may define a scheme by which to encode byte1 and byte2.
1995 This may be either a program in a special encoder language or a
1996 fixed encoding. */
1997 if (font_info->font_encoder)
1999 /* It's a program. */
2000 struct ccl_program *ccl = font_info->font_encoder;
2002 check_ccl_update (ccl);
2003 if (CHARSET_DIMENSION (charset) == 1)
2005 ccl->reg[0] = charset;
2006 ccl->reg[1] = char2b->byte2;
2007 ccl->reg[2] = -1;
2009 else
2011 ccl->reg[0] = charset;
2012 ccl->reg[1] = char2b->byte1;
2013 ccl->reg[2] = char2b->byte2;
2016 ccl_driver (ccl, NULL, NULL, 0, 0, NULL);
2018 /* We assume that MSBs are appropriately set/reset by CCL
2019 program. */
2020 if (font->max_byte1 == 0) /* 1-byte font */
2021 char2b->byte1 = 0, char2b->byte2 = ccl->reg[1];
2022 else
2023 char2b->byte1 = ccl->reg[1], char2b->byte2 = ccl->reg[2];
2025 else if (font_info->encoding[charset])
2027 /* Fixed encoding scheme. See fontset.h for the meaning of the
2028 encoding numbers. */
2029 int enc = font_info->encoding[charset];
2031 if ((enc == 1 || enc == 2)
2032 && CHARSET_DIMENSION (charset) == 2)
2033 char2b->byte1 |= 0x80;
2035 if (enc == 1 || enc == 3)
2036 char2b->byte2 |= 0x80;
2038 if (enc == 4)
2040 int sjis1, sjis2;
2042 ENCODE_SJIS (char2b->byte1, char2b->byte2, sjis1, sjis2);
2043 char2b->byte1 = sjis1;
2044 char2b->byte2 = sjis2;
2048 if (two_byte_p)
2049 *two_byte_p = ((XFontStruct *) (font_info->font))->max_byte1 > 0;
2051 return FONT_TYPE_UNKNOWN;
2056 /***********************************************************************
2057 Glyph display
2058 ***********************************************************************/
2062 static void x_set_glyph_string_clipping P_ ((struct glyph_string *));
2063 static void x_set_glyph_string_gc P_ ((struct glyph_string *));
2064 static void x_draw_glyph_string_background P_ ((struct glyph_string *,
2065 int));
2066 static void x_draw_glyph_string_foreground P_ ((struct glyph_string *));
2067 static void x_draw_composite_glyph_string_foreground P_ ((struct glyph_string *));
2068 static void x_draw_glyph_string_box P_ ((struct glyph_string *));
2069 static void x_draw_glyph_string P_ ((struct glyph_string *));
2070 static void mac_compute_glyph_string_overhangs P_ ((struct glyph_string *));
2071 static void x_set_cursor_gc P_ ((struct glyph_string *));
2072 static void x_set_mode_line_face_gc P_ ((struct glyph_string *));
2073 static void x_set_mouse_face_gc P_ ((struct glyph_string *));
2074 /*static int x_alloc_lighter_color P_ ((struct frame *, Display *, Colormap,
2075 unsigned long *, double, int));*/
2076 static void x_setup_relief_color P_ ((struct frame *, struct relief *,
2077 double, int, unsigned long));
2078 static void x_setup_relief_colors P_ ((struct glyph_string *));
2079 static void x_draw_image_glyph_string P_ ((struct glyph_string *));
2080 static void x_draw_image_relief P_ ((struct glyph_string *));
2081 static void x_draw_image_foreground P_ ((struct glyph_string *));
2082 static void x_draw_image_foreground_1 P_ ((struct glyph_string *, Pixmap));
2083 static void x_clear_glyph_string_rect P_ ((struct glyph_string *, int,
2084 int, int, int));
2085 static void x_draw_relief_rect P_ ((struct frame *, int, int, int, int,
2086 int, int, int, int, int, int,
2087 Rect *));
2088 static void x_draw_box_rect P_ ((struct glyph_string *, int, int, int, int,
2089 int, int, int, Rect *));
2091 #if GLYPH_DEBUG
2092 static void x_check_font P_ ((struct frame *, XFontStruct *));
2093 #endif
2096 /* Set S->gc to a suitable GC for drawing glyph string S in cursor
2097 face. */
2099 static void
2100 x_set_cursor_gc (s)
2101 struct glyph_string *s;
2103 if (s->font == FRAME_FONT (s->f)
2104 && s->face->background == FRAME_BACKGROUND_PIXEL (s->f)
2105 && s->face->foreground == FRAME_FOREGROUND_PIXEL (s->f)
2106 && !s->cmp)
2107 s->gc = s->f->output_data.mac->cursor_gc;
2108 else
2110 /* Cursor on non-default face: must merge. */
2111 XGCValues xgcv;
2112 unsigned long mask;
2114 xgcv.background = s->f->output_data.mac->cursor_pixel;
2115 xgcv.foreground = s->face->background;
2117 /* If the glyph would be invisible, try a different foreground. */
2118 if (xgcv.foreground == xgcv.background)
2119 xgcv.foreground = s->face->foreground;
2120 if (xgcv.foreground == xgcv.background)
2121 xgcv.foreground = s->f->output_data.mac->cursor_foreground_pixel;
2122 if (xgcv.foreground == xgcv.background)
2123 xgcv.foreground = s->face->foreground;
2125 /* Make sure the cursor is distinct from text in this face. */
2126 if (xgcv.background == s->face->background
2127 && xgcv.foreground == s->face->foreground)
2129 xgcv.background = s->face->foreground;
2130 xgcv.foreground = s->face->background;
2133 IF_DEBUG (x_check_font (s->f, s->font));
2134 xgcv.font = s->font;
2135 mask = GCForeground | GCBackground | GCFont;
2137 if (FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc)
2138 XChangeGC (s->display, FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc,
2139 mask, &xgcv);
2140 else
2141 FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc
2142 = XCreateGC (s->display, s->window, mask, &xgcv);
2144 s->gc = FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc;
2149 /* Set up S->gc of glyph string S for drawing text in mouse face. */
2151 static void
2152 x_set_mouse_face_gc (s)
2153 struct glyph_string *s;
2155 int face_id;
2156 struct face *face;
2158 /* What face has to be used last for the mouse face? */
2159 face_id = FRAME_X_DISPLAY_INFO (s->f)->mouse_face_face_id;
2160 face = FACE_FROM_ID (s->f, face_id);
2161 if (face == NULL)
2162 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2164 if (s->first_glyph->type == CHAR_GLYPH)
2165 face_id = FACE_FOR_CHAR (s->f, face, s->first_glyph->u.ch);
2166 else
2167 face_id = FACE_FOR_CHAR (s->f, face, 0);
2168 s->face = FACE_FROM_ID (s->f, face_id);
2169 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
2171 /* If font in this face is same as S->font, use it. */
2172 if (s->font == s->face->font)
2173 s->gc = s->face->gc;
2174 else
2176 /* Otherwise construct scratch_cursor_gc with values from FACE
2177 but font FONT. */
2178 XGCValues xgcv;
2179 unsigned long mask;
2181 xgcv.background = s->face->background;
2182 xgcv.foreground = s->face->foreground;
2183 IF_DEBUG (x_check_font (s->f, s->font));
2184 xgcv.font = s->font;
2185 mask = GCForeground | GCBackground | GCFont;
2187 if (FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc)
2188 XChangeGC (s->display, FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc,
2189 mask, &xgcv);
2190 else
2191 FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc
2192 = XCreateGC (s->display, s->window, mask, &xgcv);
2194 s->gc = FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc;
2197 xassert (s->gc != 0);
2201 /* Set S->gc of glyph string S to a GC suitable for drawing a mode line.
2202 Faces to use in the mode line have already been computed when the
2203 matrix was built, so there isn't much to do, here. */
2205 static INLINE void
2206 x_set_mode_line_face_gc (s)
2207 struct glyph_string *s;
2209 s->gc = s->face->gc;
2213 /* Set S->gc of glyph string S for drawing that glyph string. Set
2214 S->stippled_p to a non-zero value if the face of S has a stipple
2215 pattern. */
2217 static INLINE void
2218 x_set_glyph_string_gc (s)
2219 struct glyph_string *s;
2221 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
2223 if (s->hl == DRAW_NORMAL_TEXT)
2225 s->gc = s->face->gc;
2226 s->stippled_p = s->face->stipple != 0;
2228 else if (s->hl == DRAW_INVERSE_VIDEO)
2230 x_set_mode_line_face_gc (s);
2231 s->stippled_p = s->face->stipple != 0;
2233 else if (s->hl == DRAW_CURSOR)
2235 x_set_cursor_gc (s);
2236 s->stippled_p = 0;
2238 else if (s->hl == DRAW_MOUSE_FACE)
2240 x_set_mouse_face_gc (s);
2241 s->stippled_p = s->face->stipple != 0;
2243 else if (s->hl == DRAW_IMAGE_RAISED
2244 || s->hl == DRAW_IMAGE_SUNKEN)
2246 s->gc = s->face->gc;
2247 s->stippled_p = s->face->stipple != 0;
2249 else
2251 s->gc = s->face->gc;
2252 s->stippled_p = s->face->stipple != 0;
2255 /* GC must have been set. */
2256 xassert (s->gc != 0);
2260 /* Set clipping for output of glyph string S. S may be part of a mode
2261 line or menu if we don't have X toolkit support. */
2263 static INLINE void
2264 x_set_glyph_string_clipping (s)
2265 struct glyph_string *s;
2267 Rect rects[MAX_CLIP_RECTS];
2268 int n;
2270 n = get_glyph_string_clip_rects (s, rects, MAX_CLIP_RECTS);
2271 mac_set_clip_rectangles (s->display, s->gc, rects, n);
2275 /* RIF:
2276 Compute left and right overhang of glyph string S. If S is a glyph
2277 string for a composition, assume overhangs don't exist. */
2279 static void
2280 mac_compute_glyph_string_overhangs (s)
2281 struct glyph_string *s;
2283 if (s->cmp == NULL
2284 && s->first_glyph->type == CHAR_GLYPH)
2285 if (!s->two_byte_p
2286 #if USE_ATSUI
2287 || s->font->mac_style
2288 #endif
2291 XCharStruct cs;
2293 mac_text_extents_16 (s->font, s->char2b, s->nchars, &cs);
2294 s->right_overhang = cs.rbearing > cs.width ? cs.rbearing - cs.width : 0;
2295 s->left_overhang = cs.lbearing < 0 ? -cs.lbearing : 0;
2297 else
2299 Rect r;
2300 MacFontStruct *font = s->font;
2302 TextFont (font->mac_fontnum);
2303 TextSize (font->mac_fontsize);
2304 TextFace (font->mac_fontface);
2306 QDTextBounds (s->nchars * 2, (char *)s->char2b, &r);
2308 s->right_overhang = r.right > s->width ? r.right - s->width : 0;
2309 s->left_overhang = r.left < 0 ? -r.left : 0;
2314 /* Fill rectangle X, Y, W, H with background color of glyph string S. */
2316 static INLINE void
2317 x_clear_glyph_string_rect (s, x, y, w, h)
2318 struct glyph_string *s;
2319 int x, y, w, h;
2321 mac_erase_rectangle (s->f, s->gc, x, y, w, h);
2325 /* We prefer not to use XDrawImageString (srcCopy text transfer mode)
2326 on Mac OS X because:
2327 - Screen is double-buffered. (In srcCopy mode, a text is drawn
2328 into an offscreen graphics world first. So performance gain
2329 cannot be expected.)
2330 - It lowers rendering quality.
2331 - Some fonts leave garbage on cursor movement. */
2333 /* Draw the background of glyph_string S. If S->background_filled_p
2334 is non-zero don't draw it. FORCE_P non-zero means draw the
2335 background even if it wouldn't be drawn normally. This is used
2336 when a string preceding S draws into the background of S, or S
2337 contains the first component of a composition. */
2339 static void
2340 x_draw_glyph_string_background (s, force_p)
2341 struct glyph_string *s;
2342 int force_p;
2344 /* Nothing to do if background has already been drawn or if it
2345 shouldn't be drawn in the first place. */
2346 if (!s->background_filled_p)
2348 int box_line_width = max (s->face->box_line_width, 0);
2350 #if 0 /* MAC_TODO: stipple */
2351 if (s->stippled_p)
2353 /* Fill background with a stipple pattern. */
2354 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2355 XFillRectangle (s->display, s->window, s->gc, s->x,
2356 s->y + box_line_width,
2357 s->background_width,
2358 s->height - 2 * box_line_width);
2359 XSetFillStyle (s->display, s->gc, FillSolid);
2360 s->background_filled_p = 1;
2362 else
2363 #endif
2364 #if defined (MAC_OS8) && !USE_ATSUI
2365 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2366 || s->font_not_found_p
2367 || s->extends_to_end_of_line_p
2368 || force_p)
2369 #endif
2371 x_clear_glyph_string_rect (s, s->x, s->y + box_line_width,
2372 s->background_width,
2373 s->height - 2 * box_line_width);
2374 s->background_filled_p = 1;
2380 /* Draw the foreground of glyph string S. */
2382 static void
2383 x_draw_glyph_string_foreground (s)
2384 struct glyph_string *s;
2386 int i, x;
2388 /* If first glyph of S has a left box line, start drawing the text
2389 of S to the right of that box line. */
2390 if (s->face->box != FACE_NO_BOX
2391 && s->first_glyph->left_box_line_p)
2392 x = s->x + abs (s->face->box_line_width);
2393 else
2394 x = s->x;
2396 /* Draw characters of S as rectangles if S's font could not be
2397 loaded. */
2398 if (s->font_not_found_p)
2400 for (i = 0; i < s->nchars; ++i)
2402 struct glyph *g = s->first_glyph + i;
2403 mac_draw_rectangle (s->f, s->gc, x, s->y,
2404 g->pixel_width - 1, s->height - 1);
2405 x += g->pixel_width;
2408 else
2410 char *char1b = (char *) s->char2b;
2411 int boff = s->font_info->baseline_offset;
2413 if (s->font_info->vertical_centering)
2414 boff = VCENTER_BASELINE_OFFSET (s->font, s->f) - boff;
2416 /* If we can use 8-bit functions, condense S->char2b. */
2417 if (!s->two_byte_p
2418 #if USE_ATSUI
2419 && GC_FONT (s->gc)->mac_style == NULL
2420 #endif
2422 for (i = 0; i < s->nchars; ++i)
2423 char1b[i] = s->char2b[i].byte2;
2425 #if defined (MAC_OS8) && !USE_ATSUI
2426 /* Draw text with XDrawString if background has already been
2427 filled. Otherwise, use XDrawImageString. (Note that
2428 XDrawImageString is usually faster than XDrawString.) Always
2429 use XDrawImageString when drawing the cursor so that there is
2430 no chance that characters under a box cursor are invisible. */
2431 if (s->for_overlaps
2432 || (s->background_filled_p && s->hl != DRAW_CURSOR))
2433 #endif
2435 /* Draw characters with 16-bit or 8-bit functions. */
2436 if (s->two_byte_p
2437 #if USE_ATSUI
2438 || GC_FONT (s->gc)->mac_style
2439 #endif
2441 #if USE_CG_TEXT_DRAWING
2442 if (!s->two_byte_p
2443 && mac_draw_string_cg (s->f, s->gc, x, s->ybase - boff,
2444 s->char2b, s->nchars))
2446 else
2447 #endif
2448 mac_draw_string_16 (s->f, s->gc, x, s->ybase - boff,
2449 s->char2b, s->nchars);
2450 else
2451 mac_draw_string (s->f, s->gc, x, s->ybase - boff,
2452 char1b, s->nchars);
2454 #if defined (MAC_OS8) && !USE_ATSUI
2455 else
2457 if (s->two_byte_p)
2458 mac_draw_image_string_16 (s->f, s->gc, x, s->ybase - boff,
2459 s->char2b, s->nchars);
2460 else
2461 mac_draw_image_string (s->f, s->gc, x, s->ybase - boff,
2462 char1b, s->nchars);
2464 #endif
2468 /* Draw the foreground of composite glyph string S. */
2470 static void
2471 x_draw_composite_glyph_string_foreground (s)
2472 struct glyph_string *s;
2474 int i, x;
2476 /* If first glyph of S has a left box line, start drawing the text
2477 of S to the right of that box line. */
2478 if (s->face->box != FACE_NO_BOX
2479 && s->first_glyph->left_box_line_p)
2480 x = s->x + abs (s->face->box_line_width);
2481 else
2482 x = s->x;
2484 /* S is a glyph string for a composition. S->gidx is the index of
2485 the first character drawn for glyphs of this composition.
2486 S->gidx == 0 means we are drawing the very first character of
2487 this composition. */
2489 /* Draw a rectangle for the composition if the font for the very
2490 first character of the composition could not be loaded. */
2491 if (s->font_not_found_p)
2493 if (s->gidx == 0)
2494 mac_draw_rectangle (s->f, s->gc, x, s->y,
2495 s->width - 1, s->height - 1);
2497 else
2499 for (i = 0; i < s->nchars; i++, ++s->gidx)
2500 mac_draw_string_16 (s->f, s->gc,
2501 x + s->cmp->offsets[s->gidx * 2],
2502 s->ybase - s->cmp->offsets[s->gidx * 2 + 1],
2503 s->char2b + i, 1);
2508 #ifdef USE_X_TOOLKIT
2510 static struct frame *x_frame_of_widget P_ ((Widget));
2513 /* Return the frame on which widget WIDGET is used.. Abort if frame
2514 cannot be determined. */
2516 static struct frame *
2517 x_frame_of_widget (widget)
2518 Widget widget;
2520 struct x_display_info *dpyinfo;
2521 Lisp_Object tail;
2522 struct frame *f;
2524 dpyinfo = x_display_info_for_display (XtDisplay (widget));
2526 /* Find the top-level shell of the widget. Note that this function
2527 can be called when the widget is not yet realized, so XtWindow
2528 (widget) == 0. That's the reason we can't simply use
2529 x_any_window_to_frame. */
2530 while (!XtIsTopLevelShell (widget))
2531 widget = XtParent (widget);
2533 /* Look for a frame with that top-level widget. Allocate the color
2534 on that frame to get the right gamma correction value. */
2535 for (tail = Vframe_list; GC_CONSP (tail); tail = XCDR (tail))
2536 if (GC_FRAMEP (XCAR (tail))
2537 && (f = XFRAME (XCAR (tail)),
2538 (f->output_data.nothing != 1
2539 && FRAME_X_DISPLAY_INFO (f) == dpyinfo))
2540 && f->output_data.x->widget == widget)
2541 return f;
2543 abort ();
2547 /* Allocate the color COLOR->pixel on the screen and display of
2548 widget WIDGET in colormap CMAP. If an exact match cannot be
2549 allocated, try the nearest color available. Value is non-zero
2550 if successful. This is called from lwlib. */
2553 x_alloc_nearest_color_for_widget (widget, cmap, color)
2554 Widget widget;
2555 Colormap cmap;
2556 XColor *color;
2558 struct frame *f = x_frame_of_widget (widget);
2559 return x_alloc_nearest_color (f, cmap, color);
2563 #endif /* USE_X_TOOLKIT */
2565 #if 0 /* MAC_TODO */
2567 /* Allocate the color COLOR->pixel on SCREEN of DISPLAY, colormap
2568 CMAP. If an exact match can't be allocated, try the nearest color
2569 available. Value is non-zero if successful. Set *COLOR to the
2570 color allocated. */
2573 x_alloc_nearest_color (f, cmap, color)
2574 struct frame *f;
2575 Colormap cmap;
2576 XColor *color;
2578 Display *display = FRAME_X_DISPLAY (f);
2579 Screen *screen = FRAME_X_SCREEN (f);
2580 int rc;
2582 gamma_correct (f, color);
2583 rc = XAllocColor (display, cmap, color);
2584 if (rc == 0)
2586 /* If we got to this point, the colormap is full, so we're going
2587 to try to get the next closest color. The algorithm used is
2588 a least-squares matching, which is what X uses for closest
2589 color matching with StaticColor visuals. */
2590 int nearest, i;
2591 unsigned long nearest_delta = ~0;
2592 int ncells = XDisplayCells (display, XScreenNumberOfScreen (screen));
2593 XColor *cells = (XColor *) alloca (ncells * sizeof *cells);
2595 for (i = 0; i < ncells; ++i)
2596 cells[i].pixel = i;
2597 XQueryColors (display, cmap, cells, ncells);
2599 for (nearest = i = 0; i < ncells; ++i)
2601 long dred = (color->red >> 8) - (cells[i].red >> 8);
2602 long dgreen = (color->green >> 8) - (cells[i].green >> 8);
2603 long dblue = (color->blue >> 8) - (cells[i].blue >> 8);
2604 unsigned long delta = dred * dred + dgreen * dgreen + dblue * dblue;
2606 if (delta < nearest_delta)
2608 nearest = i;
2609 nearest_delta = delta;
2613 color->red = cells[nearest].red;
2614 color->green = cells[nearest].green;
2615 color->blue = cells[nearest].blue;
2616 rc = XAllocColor (display, cmap, color);
2619 #ifdef DEBUG_X_COLORS
2620 if (rc)
2621 register_color (color->pixel);
2622 #endif /* DEBUG_X_COLORS */
2624 return rc;
2628 /* Allocate color PIXEL on frame F. PIXEL must already be allocated.
2629 It's necessary to do this instead of just using PIXEL directly to
2630 get color reference counts right. */
2632 unsigned long
2633 x_copy_color (f, pixel)
2634 struct frame *f;
2635 unsigned long pixel;
2637 XColor color;
2639 color.pixel = pixel;
2640 BLOCK_INPUT;
2641 XQueryColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
2642 XAllocColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
2643 UNBLOCK_INPUT;
2644 #ifdef DEBUG_X_COLORS
2645 register_color (pixel);
2646 #endif
2647 return color.pixel;
2651 /* Allocate color PIXEL on display DPY. PIXEL must already be allocated.
2652 It's necessary to do this instead of just using PIXEL directly to
2653 get color reference counts right. */
2655 unsigned long
2656 x_copy_dpy_color (dpy, cmap, pixel)
2657 Display *dpy;
2658 Colormap cmap;
2659 unsigned long pixel;
2661 XColor color;
2663 color.pixel = pixel;
2664 BLOCK_INPUT;
2665 XQueryColor (dpy, cmap, &color);
2666 XAllocColor (dpy, cmap, &color);
2667 UNBLOCK_INPUT;
2668 #ifdef DEBUG_X_COLORS
2669 register_color (pixel);
2670 #endif
2671 return color.pixel;
2674 #endif /* MAC_TODO */
2677 /* Brightness beyond which a color won't have its highlight brightness
2678 boosted.
2680 Nominally, highlight colors for `3d' faces are calculated by
2681 brightening an object's color by a constant scale factor, but this
2682 doesn't yield good results for dark colors, so for colors who's
2683 brightness is less than this value (on a scale of 0-255) have to
2684 use an additional additive factor.
2686 The value here is set so that the default menu-bar/mode-line color
2687 (grey75) will not have its highlights changed at all. */
2688 #define HIGHLIGHT_COLOR_DARK_BOOST_LIMIT 187
2691 /* Allocate a color which is lighter or darker than *COLOR by FACTOR
2692 or DELTA. Try a color with RGB values multiplied by FACTOR first.
2693 If this produces the same color as COLOR, try a color where all RGB
2694 values have DELTA added. Return the allocated color in *COLOR.
2695 DISPLAY is the X display, CMAP is the colormap to operate on.
2696 Value is non-zero if successful. */
2698 static int
2699 mac_alloc_lighter_color (f, color, factor, delta)
2700 struct frame *f;
2701 unsigned long *color;
2702 double factor;
2703 int delta;
2705 unsigned long new;
2706 long bright;
2708 /* On Mac, RGB values are 0-255, not 0-65535, so scale delta. */
2709 delta /= 256;
2711 /* Change RGB values by specified FACTOR. Avoid overflow! */
2712 xassert (factor >= 0);
2713 new = RGB_TO_ULONG (min (0xff, (int) (factor * RED_FROM_ULONG (*color))),
2714 min (0xff, (int) (factor * GREEN_FROM_ULONG (*color))),
2715 min (0xff, (int) (factor * BLUE_FROM_ULONG (*color))));
2717 /* Calculate brightness of COLOR. */
2718 bright = (2 * RED_FROM_ULONG (*color) + 3 * GREEN_FROM_ULONG (*color)
2719 + BLUE_FROM_ULONG (*color)) / 6;
2721 /* We only boost colors that are darker than
2722 HIGHLIGHT_COLOR_DARK_BOOST_LIMIT. */
2723 if (bright < HIGHLIGHT_COLOR_DARK_BOOST_LIMIT)
2724 /* Make an additive adjustment to NEW, because it's dark enough so
2725 that scaling by FACTOR alone isn't enough. */
2727 /* How far below the limit this color is (0 - 1, 1 being darker). */
2728 double dimness = 1 - (double)bright / HIGHLIGHT_COLOR_DARK_BOOST_LIMIT;
2729 /* The additive adjustment. */
2730 int min_delta = delta * dimness * factor / 2;
2732 if (factor < 1)
2733 new = RGB_TO_ULONG (max (0, min (0xff, (int) (RED_FROM_ULONG (*color)) - min_delta)),
2734 max (0, min (0xff, (int) (GREEN_FROM_ULONG (*color)) - min_delta)),
2735 max (0, min (0xff, (int) (BLUE_FROM_ULONG (*color)) - min_delta)));
2736 else
2737 new = RGB_TO_ULONG (max (0, min (0xff, (int) (min_delta + RED_FROM_ULONG (*color)))),
2738 max (0, min (0xff, (int) (min_delta + GREEN_FROM_ULONG (*color)))),
2739 max (0, min (0xff, (int) (min_delta + BLUE_FROM_ULONG (*color)))));
2742 if (new == *color)
2743 new = RGB_TO_ULONG (max (0, min (0xff, (int) (delta + RED_FROM_ULONG (*color)))),
2744 max (0, min (0xff, (int) (delta + GREEN_FROM_ULONG (*color)))),
2745 max (0, min (0xff, (int) (delta + BLUE_FROM_ULONG (*color)))));
2747 /* MAC_TODO: Map to palette and retry with delta if same? */
2748 /* MAC_TODO: Free colors (if using palette)? */
2750 if (new == *color)
2751 return 0;
2753 *color = new;
2755 return 1;
2759 /* Set up the foreground color for drawing relief lines of glyph
2760 string S. RELIEF is a pointer to a struct relief containing the GC
2761 with which lines will be drawn. Use a color that is FACTOR or
2762 DELTA lighter or darker than the relief's background which is found
2763 in S->f->output_data.x->relief_background. If such a color cannot
2764 be allocated, use DEFAULT_PIXEL, instead. */
2766 static void
2767 x_setup_relief_color (f, relief, factor, delta, default_pixel)
2768 struct frame *f;
2769 struct relief *relief;
2770 double factor;
2771 int delta;
2772 unsigned long default_pixel;
2774 XGCValues xgcv;
2775 struct mac_output *di = f->output_data.mac;
2776 unsigned long mask = GCForeground;
2777 unsigned long pixel;
2778 unsigned long background = di->relief_background;
2779 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
2781 /* MAC_TODO: Free colors (if using palette)? */
2783 /* Allocate new color. */
2784 xgcv.foreground = default_pixel;
2785 pixel = background;
2786 if (dpyinfo->n_planes != 1
2787 && mac_alloc_lighter_color (f, &pixel, factor, delta))
2789 relief->allocated_p = 1;
2790 xgcv.foreground = relief->pixel = pixel;
2793 if (relief->gc == 0)
2795 #if 0 /* MAC_TODO: stipple */
2796 xgcv.stipple = dpyinfo->gray;
2797 mask |= GCStipple;
2798 #endif
2799 relief->gc = XCreateGC (NULL, FRAME_MAC_WINDOW (f), mask, &xgcv);
2801 else
2802 XChangeGC (NULL, relief->gc, mask, &xgcv);
2806 /* Set up colors for the relief lines around glyph string S. */
2808 static void
2809 x_setup_relief_colors (s)
2810 struct glyph_string *s;
2812 struct mac_output *di = s->f->output_data.mac;
2813 unsigned long color;
2815 if (s->face->use_box_color_for_shadows_p)
2816 color = s->face->box_color;
2817 else if (s->first_glyph->type == IMAGE_GLYPH
2818 && s->img->pixmap
2819 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2820 color = IMAGE_BACKGROUND (s->img, s->f, 0);
2821 else
2823 XGCValues xgcv;
2825 /* Get the background color of the face. */
2826 XGetGCValues (s->display, s->gc, GCBackground, &xgcv);
2827 color = xgcv.background;
2830 if (di->white_relief.gc == 0
2831 || color != di->relief_background)
2833 di->relief_background = color;
2834 x_setup_relief_color (s->f, &di->white_relief, 1.2, 0x8000,
2835 WHITE_PIX_DEFAULT (s->f));
2836 x_setup_relief_color (s->f, &di->black_relief, 0.6, 0x4000,
2837 BLACK_PIX_DEFAULT (s->f));
2842 /* Draw a relief on frame F inside the rectangle given by LEFT_X,
2843 TOP_Y, RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the relief
2844 to draw, it must be >= 0. RAISED_P non-zero means draw a raised
2845 relief. LEFT_P non-zero means draw a relief on the left side of
2846 the rectangle. RIGHT_P non-zero means draw a relief on the right
2847 side of the rectangle. CLIP_RECT is the clipping rectangle to use
2848 when drawing. */
2850 static void
2851 x_draw_relief_rect (f, left_x, top_y, right_x, bottom_y, width,
2852 raised_p, top_p, bot_p, left_p, right_p, clip_rect)
2853 struct frame *f;
2854 int left_x, top_y, right_x, bottom_y, width;
2855 int top_p, bot_p, left_p, right_p, raised_p;
2856 Rect *clip_rect;
2858 Display *dpy = FRAME_MAC_DISPLAY (f);
2859 int i;
2860 GC gc;
2862 if (raised_p)
2863 gc = f->output_data.mac->white_relief.gc;
2864 else
2865 gc = f->output_data.mac->black_relief.gc;
2866 mac_set_clip_rectangles (dpy, gc, clip_rect, 1);
2868 /* Top. */
2869 if (top_p)
2870 for (i = 0; i < width; ++i)
2871 mac_draw_line (f, gc,
2872 left_x + i * left_p, top_y + i,
2873 right_x - i * right_p, top_y + i);
2875 /* Left. */
2876 if (left_p)
2877 for (i = 0; i < width; ++i)
2878 mac_draw_line (f, gc,
2879 left_x + i, top_y + i, left_x + i, bottom_y - i);
2881 mac_reset_clip_rectangles (dpy, gc);
2882 if (raised_p)
2883 gc = f->output_data.mac->black_relief.gc;
2884 else
2885 gc = f->output_data.mac->white_relief.gc;
2886 mac_set_clip_rectangles (dpy, gc, clip_rect, 1);
2888 /* Bottom. */
2889 if (bot_p)
2890 for (i = 0; i < width; ++i)
2891 mac_draw_line (f, gc,
2892 left_x + i * left_p, bottom_y - i,
2893 right_x - i * right_p, bottom_y - i);
2895 /* Right. */
2896 if (right_p)
2897 for (i = 0; i < width; ++i)
2898 mac_draw_line (f, gc,
2899 right_x - i, top_y + i + 1, right_x - i, bottom_y - i - 1);
2901 mac_reset_clip_rectangles (dpy, gc);
2905 /* Draw a box on frame F inside the rectangle given by LEFT_X, TOP_Y,
2906 RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the lines to
2907 draw, it must be >= 0. LEFT_P non-zero means draw a line on the
2908 left side of the rectangle. RIGHT_P non-zero means draw a line
2909 on the right side of the rectangle. CLIP_RECT is the clipping
2910 rectangle to use when drawing. */
2912 static void
2913 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
2914 left_p, right_p, clip_rect)
2915 struct glyph_string *s;
2916 int left_x, top_y, right_x, bottom_y, width, left_p, right_p;
2917 Rect *clip_rect;
2919 XGCValues xgcv;
2921 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2922 XSetForeground (s->display, s->gc, s->face->box_color);
2923 mac_set_clip_rectangles (s->display, s->gc, clip_rect, 1);
2925 /* Top. */
2926 mac_fill_rectangle (s->f, s->gc, left_x, top_y,
2927 right_x - left_x + 1, width);
2929 /* Left. */
2930 if (left_p)
2931 mac_fill_rectangle (s->f, s->gc, left_x, top_y,
2932 width, bottom_y - top_y + 1);
2934 /* Bottom. */
2935 mac_fill_rectangle (s->f, s->gc, left_x, bottom_y - width + 1,
2936 right_x - left_x + 1, width);
2938 /* Right. */
2939 if (right_p)
2940 mac_fill_rectangle (s->f, s->gc, right_x - width + 1,
2941 top_y, width, bottom_y - top_y + 1);
2943 XSetForeground (s->display, s->gc, xgcv.foreground);
2944 mac_reset_clip_rectangles (s->display, s->gc);
2948 /* Draw a box around glyph string S. */
2950 static void
2951 x_draw_glyph_string_box (s)
2952 struct glyph_string *s;
2954 int width, left_x, right_x, top_y, bottom_y, last_x, raised_p;
2955 int left_p, right_p;
2956 struct glyph *last_glyph;
2957 Rect clip_rect;
2959 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2960 ? WINDOW_RIGHT_EDGE_X (s->w)
2961 : window_box_right (s->w, s->area));
2963 /* The glyph that may have a right box line. */
2964 last_glyph = (s->cmp || s->img
2965 ? s->first_glyph
2966 : s->first_glyph + s->nchars - 1);
2968 width = abs (s->face->box_line_width);
2969 raised_p = s->face->box == FACE_RAISED_BOX;
2970 left_x = s->x;
2971 right_x = (s->row->full_width_p && s->extends_to_end_of_line_p
2972 ? last_x - 1
2973 : min (last_x, s->x + s->background_width) - 1);
2974 top_y = s->y;
2975 bottom_y = top_y + s->height - 1;
2977 left_p = (s->first_glyph->left_box_line_p
2978 || (s->hl == DRAW_MOUSE_FACE
2979 && (s->prev == NULL
2980 || s->prev->hl != s->hl)));
2981 right_p = (last_glyph->right_box_line_p
2982 || (s->hl == DRAW_MOUSE_FACE
2983 && (s->next == NULL
2984 || s->next->hl != s->hl)));
2986 get_glyph_string_clip_rect (s, &clip_rect);
2988 if (s->face->box == FACE_SIMPLE_BOX)
2989 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
2990 left_p, right_p, &clip_rect);
2991 else
2993 x_setup_relief_colors (s);
2994 x_draw_relief_rect (s->f, left_x, top_y, right_x, bottom_y,
2995 width, raised_p, 1, 1, left_p, right_p, &clip_rect);
3000 /* Draw foreground of image glyph string S. */
3002 static void
3003 x_draw_image_foreground (s)
3004 struct glyph_string *s;
3006 int x = s->x;
3007 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3009 /* If first glyph of S has a left box line, start drawing it to the
3010 right of that line. */
3011 if (s->face->box != FACE_NO_BOX
3012 && s->first_glyph->left_box_line_p
3013 && s->slice.x == 0)
3014 x += abs (s->face->box_line_width);
3016 /* If there is a margin around the image, adjust x- and y-position
3017 by that margin. */
3018 if (s->slice.x == 0)
3019 x += s->img->hmargin;
3020 if (s->slice.y == 0)
3021 y += s->img->vmargin;
3023 if (s->img->pixmap)
3025 x_set_glyph_string_clipping (s);
3027 if (s->img->mask)
3028 mac_copy_area_with_mask (s->img->pixmap, s->img->mask,
3029 s->f, s->gc, s->slice.x, s->slice.y,
3030 s->slice.width, s->slice.height, x, y);
3031 else
3033 mac_copy_area (s->img->pixmap,
3034 s->f, s->gc, s->slice.x, s->slice.y,
3035 s->slice.width, s->slice.height, x, y);
3037 /* When the image has a mask, we can expect that at
3038 least part of a mouse highlight or a block cursor will
3039 be visible. If the image doesn't have a mask, make
3040 a block cursor visible by drawing a rectangle around
3041 the image. I believe it's looking better if we do
3042 nothing here for mouse-face. */
3043 if (s->hl == DRAW_CURSOR)
3045 int r = s->img->relief;
3046 if (r < 0) r = -r;
3047 mac_draw_rectangle (s->f, s->gc, x - r, y - r,
3048 s->slice.width + r*2 - 1,
3049 s->slice.height + r*2 - 1);
3053 else
3054 /* Draw a rectangle if image could not be loaded. */
3055 mac_draw_rectangle (s->f, s->gc, x, y,
3056 s->slice.width - 1, s->slice.height - 1);
3060 /* Draw a relief around the image glyph string S. */
3062 static void
3063 x_draw_image_relief (s)
3064 struct glyph_string *s;
3066 int x0, y0, x1, y1, thick, raised_p;
3067 Rect r;
3068 int x = s->x;
3069 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3071 /* If first glyph of S has a left box line, start drawing it to the
3072 right of that line. */
3073 if (s->face->box != FACE_NO_BOX
3074 && s->first_glyph->left_box_line_p
3075 && s->slice.x == 0)
3076 x += abs (s->face->box_line_width);
3078 /* If there is a margin around the image, adjust x- and y-position
3079 by that margin. */
3080 if (s->slice.x == 0)
3081 x += s->img->hmargin;
3082 if (s->slice.y == 0)
3083 y += s->img->vmargin;
3085 if (s->hl == DRAW_IMAGE_SUNKEN
3086 || s->hl == DRAW_IMAGE_RAISED)
3088 thick = tool_bar_button_relief >= 0 ? tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3089 raised_p = s->hl == DRAW_IMAGE_RAISED;
3091 else
3093 thick = abs (s->img->relief);
3094 raised_p = s->img->relief > 0;
3097 x0 = x - thick;
3098 y0 = y - thick;
3099 x1 = x + s->slice.width + thick - 1;
3100 y1 = y + s->slice.height + thick - 1;
3102 x_setup_relief_colors (s);
3103 get_glyph_string_clip_rect (s, &r);
3104 x_draw_relief_rect (s->f, x0, y0, x1, y1, thick, raised_p,
3105 s->slice.y == 0,
3106 s->slice.y + s->slice.height == s->img->height,
3107 s->slice.x == 0,
3108 s->slice.x + s->slice.width == s->img->width,
3109 &r);
3113 /* Draw part of the background of glyph string S. X, Y, W, and H
3114 give the rectangle to draw. */
3116 static void
3117 x_draw_glyph_string_bg_rect (s, x, y, w, h)
3118 struct glyph_string *s;
3119 int x, y, w, h;
3121 #if 0 /* MAC_TODO: stipple */
3122 if (s->stippled_p)
3124 /* Fill background with a stipple pattern. */
3125 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
3126 XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
3127 XSetFillStyle (s->display, s->gc, FillSolid);
3129 else
3130 #endif /* MAC_TODO */
3131 x_clear_glyph_string_rect (s, x, y, w, h);
3135 /* Draw image glyph string S.
3137 s->y
3138 s->x +-------------------------
3139 | s->face->box
3141 | +-------------------------
3142 | | s->img->margin
3144 | | +-------------------
3145 | | | the image
3149 static void
3150 x_draw_image_glyph_string (s)
3151 struct glyph_string *s;
3153 int x, y;
3154 int box_line_hwidth = abs (s->face->box_line_width);
3155 int box_line_vwidth = max (s->face->box_line_width, 0);
3156 int height;
3157 Pixmap pixmap = 0;
3159 height = s->height - 2 * box_line_vwidth;
3162 /* Fill background with face under the image. Do it only if row is
3163 taller than image or if image has a clip mask to reduce
3164 flickering. */
3165 s->stippled_p = s->face->stipple != 0;
3166 if (height > s->slice.height
3167 || s->img->hmargin
3168 || s->img->vmargin
3169 || s->img->mask
3170 || s->img->pixmap == 0
3171 || s->width != s->background_width)
3173 x = s->x;
3174 if (s->first_glyph->left_box_line_p
3175 && s->slice.x == 0)
3176 x += box_line_hwidth;
3178 y = s->y;
3179 if (s->slice.y == 0)
3180 y += box_line_vwidth;
3182 x_draw_glyph_string_bg_rect (s, x, y, s->background_width, height);
3184 s->background_filled_p = 1;
3187 /* Draw the foreground. */
3188 x_draw_image_foreground (s);
3190 /* If we must draw a relief around the image, do it. */
3191 if (s->img->relief
3192 || s->hl == DRAW_IMAGE_RAISED
3193 || s->hl == DRAW_IMAGE_SUNKEN)
3194 x_draw_image_relief (s);
3198 /* Draw stretch glyph string S. */
3200 static void
3201 x_draw_stretch_glyph_string (s)
3202 struct glyph_string *s;
3204 xassert (s->first_glyph->type == STRETCH_GLYPH);
3205 s->stippled_p = s->face->stipple != 0;
3207 if (s->hl == DRAW_CURSOR
3208 && !x_stretch_cursor_p)
3210 /* If `x-stretch-block-cursor' is nil, don't draw a block cursor
3211 as wide as the stretch glyph. */
3212 int width = min (FRAME_COLUMN_WIDTH (s->f), s->background_width);
3214 /* Draw cursor. */
3215 x_draw_glyph_string_bg_rect (s, s->x, s->y, width, s->height);
3217 /* Clear rest using the GC of the original non-cursor face. */
3218 if (width < s->background_width)
3220 int x = s->x + width, y = s->y;
3221 int w = s->background_width - width, h = s->height;
3222 Rect r;
3223 GC gc;
3225 if (s->row->mouse_face_p
3226 && cursor_in_mouse_face_p (s->w))
3228 x_set_mouse_face_gc (s);
3229 gc = s->gc;
3231 else
3232 gc = s->face->gc;
3234 get_glyph_string_clip_rect (s, &r);
3235 mac_set_clip_rectangles (s->display, gc, &r, 1);
3237 #if 0 /* MAC_TODO: stipple */
3238 if (s->face->stipple)
3240 /* Fill background with a stipple pattern. */
3241 XSetFillStyle (s->display, gc, FillOpaqueStippled);
3242 XFillRectangle (s->display, s->window, gc, x, y, w, h);
3243 XSetFillStyle (s->display, gc, FillSolid);
3245 else
3246 #endif /* MAC_TODO */
3247 mac_erase_rectangle (s->f, gc, x, y, w, h);
3250 else if (!s->background_filled_p)
3251 x_draw_glyph_string_bg_rect (s, s->x, s->y, s->background_width,
3252 s->height);
3254 s->background_filled_p = 1;
3258 /* Draw glyph string S. */
3260 static void
3261 x_draw_glyph_string (s)
3262 struct glyph_string *s;
3264 int relief_drawn_p = 0;
3266 /* If S draws into the background of its successor that does not
3267 draw a cursor, draw the background of the successor first so that
3268 S can draw into it. This makes S->next use XDrawString instead
3269 of XDrawImageString. */
3270 if (s->next && s->right_overhang && !s->for_overlaps
3271 && s->next->hl != DRAW_CURSOR)
3273 xassert (s->next->img == NULL);
3274 x_set_glyph_string_gc (s->next);
3275 x_set_glyph_string_clipping (s->next);
3276 x_draw_glyph_string_background (s->next, 1);
3279 /* Set up S->gc, set clipping and draw S. */
3280 x_set_glyph_string_gc (s);
3282 /* Draw relief (if any) in advance for char/composition so that the
3283 glyph string can be drawn over it. */
3284 if (!s->for_overlaps
3285 && s->face->box != FACE_NO_BOX
3286 && (s->first_glyph->type == CHAR_GLYPH
3287 || s->first_glyph->type == COMPOSITE_GLYPH))
3290 x_set_glyph_string_clipping (s);
3291 x_draw_glyph_string_background (s, 1);
3292 x_draw_glyph_string_box (s);
3293 x_set_glyph_string_clipping (s);
3294 relief_drawn_p = 1;
3296 else
3297 x_set_glyph_string_clipping (s);
3299 switch (s->first_glyph->type)
3301 case IMAGE_GLYPH:
3302 x_draw_image_glyph_string (s);
3303 break;
3305 case STRETCH_GLYPH:
3306 x_draw_stretch_glyph_string (s);
3307 break;
3309 case CHAR_GLYPH:
3310 if (s->for_overlaps)
3311 s->background_filled_p = 1;
3312 else
3313 x_draw_glyph_string_background (s, 0);
3314 x_draw_glyph_string_foreground (s);
3315 break;
3317 case COMPOSITE_GLYPH:
3318 if (s->for_overlaps || s->gidx > 0)
3319 s->background_filled_p = 1;
3320 else
3321 x_draw_glyph_string_background (s, 1);
3322 x_draw_composite_glyph_string_foreground (s);
3323 break;
3325 default:
3326 abort ();
3329 if (!s->for_overlaps)
3331 /* Draw underline. */
3332 if (s->face->underline_p)
3334 unsigned long h = 1;
3335 unsigned long dy = s->height - h;
3337 if (s->face->underline_defaulted_p)
3338 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3339 s->width, h);
3340 else
3342 XGCValues xgcv;
3343 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3344 XSetForeground (s->display, s->gc, s->face->underline_color);
3345 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3346 s->width, h);
3347 XSetForeground (s->display, s->gc, xgcv.foreground);
3351 /* Draw overline. */
3352 if (s->face->overline_p)
3354 unsigned long dy = 0, h = 1;
3356 if (s->face->overline_color_defaulted_p)
3357 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3358 s->width, h);
3359 else
3361 XGCValues xgcv;
3362 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3363 XSetForeground (s->display, s->gc, s->face->overline_color);
3364 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3365 s->width, h);
3366 XSetForeground (s->display, s->gc, xgcv.foreground);
3370 /* Draw strike-through. */
3371 if (s->face->strike_through_p)
3373 unsigned long h = 1;
3374 unsigned long dy = (s->height - h) / 2;
3376 if (s->face->strike_through_color_defaulted_p)
3377 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3378 s->width, h);
3379 else
3381 XGCValues xgcv;
3382 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3383 XSetForeground (s->display, s->gc, s->face->strike_through_color);
3384 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3385 s->width, h);
3386 XSetForeground (s->display, s->gc, xgcv.foreground);
3390 /* Draw relief if not yet drawn. */
3391 if (!relief_drawn_p && s->face->box != FACE_NO_BOX)
3392 x_draw_glyph_string_box (s);
3395 /* Reset clipping. */
3396 mac_reset_clip_rectangles (s->display, s->gc);
3399 /* Shift display to make room for inserted glyphs. */
3401 void
3402 mac_shift_glyphs_for_insert (f, x, y, width, height, shift_by)
3403 struct frame *f;
3404 int x, y, width, height, shift_by;
3406 mac_scroll_area (f, f->output_data.mac->normal_gc,
3407 x, y, width, height,
3408 x + shift_by, y);
3411 /* Delete N glyphs at the nominal cursor position. Not implemented
3412 for X frames. */
3414 static void
3415 x_delete_glyphs (n)
3416 register int n;
3418 abort ();
3422 /* Clear entire frame. If updating_frame is non-null, clear that
3423 frame. Otherwise clear the selected frame. */
3425 static void
3426 x_clear_frame ()
3428 struct frame *f;
3430 if (updating_frame)
3431 f = updating_frame;
3432 else
3433 f = SELECTED_FRAME ();
3435 /* Clearing the frame will erase any cursor, so mark them all as no
3436 longer visible. */
3437 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
3438 output_cursor.hpos = output_cursor.vpos = 0;
3439 output_cursor.x = -1;
3441 /* We don't set the output cursor here because there will always
3442 follow an explicit cursor_to. */
3443 BLOCK_INPUT;
3444 mac_clear_window (f);
3446 /* We have to clear the scroll bars, too. If we have changed
3447 colors or something like that, then they should be notified. */
3448 x_scroll_bar_clear (f);
3450 XFlush (FRAME_MAC_DISPLAY (f));
3451 UNBLOCK_INPUT;
3456 /* Invert the middle quarter of the frame for .15 sec. */
3458 /* We use the select system call to do the waiting, so we have to make
3459 sure it's available. If it isn't, we just won't do visual bells. */
3461 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
3464 /* Subtract the `struct timeval' values X and Y, storing the result in
3465 *RESULT. Return 1 if the difference is negative, otherwise 0. */
3467 static int
3468 timeval_subtract (result, x, y)
3469 struct timeval *result, x, y;
3471 /* Perform the carry for the later subtraction by updating y. This
3472 is safer because on some systems the tv_sec member is unsigned. */
3473 if (x.tv_usec < y.tv_usec)
3475 int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
3476 y.tv_usec -= 1000000 * nsec;
3477 y.tv_sec += nsec;
3480 if (x.tv_usec - y.tv_usec > 1000000)
3482 int nsec = (y.tv_usec - x.tv_usec) / 1000000;
3483 y.tv_usec += 1000000 * nsec;
3484 y.tv_sec -= nsec;
3487 /* Compute the time remaining to wait. tv_usec is certainly
3488 positive. */
3489 result->tv_sec = x.tv_sec - y.tv_sec;
3490 result->tv_usec = x.tv_usec - y.tv_usec;
3492 /* Return indication of whether the result should be considered
3493 negative. */
3494 return x.tv_sec < y.tv_sec;
3497 void
3498 XTflash (f)
3499 struct frame *f;
3501 /* Get the height not including a menu bar widget. */
3502 int height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, FRAME_LINES (f));
3503 /* Height of each line to flash. */
3504 int flash_height = FRAME_LINE_HEIGHT (f);
3505 /* These will be the left and right margins of the rectangles. */
3506 int flash_left = FRAME_INTERNAL_BORDER_WIDTH (f);
3507 int flash_right = FRAME_PIXEL_WIDTH (f) - FRAME_INTERNAL_BORDER_WIDTH (f);
3509 int width;
3511 /* Don't flash the area between a scroll bar and the frame
3512 edge it is next to. */
3513 switch (FRAME_VERTICAL_SCROLL_BAR_TYPE (f))
3515 case vertical_scroll_bar_left:
3516 flash_left += VERTICAL_SCROLL_BAR_WIDTH_TRIM;
3517 break;
3519 case vertical_scroll_bar_right:
3520 flash_right -= VERTICAL_SCROLL_BAR_WIDTH_TRIM;
3521 break;
3523 default:
3524 break;
3527 width = flash_right - flash_left;
3529 BLOCK_INPUT;
3531 /* If window is tall, flash top and bottom line. */
3532 if (height > 3 * FRAME_LINE_HEIGHT (f))
3534 mac_invert_rectangle (f, flash_left,
3535 (FRAME_INTERNAL_BORDER_WIDTH (f)
3536 + FRAME_TOOL_BAR_LINES (f) * FRAME_LINE_HEIGHT (f)),
3537 width, flash_height);
3538 mac_invert_rectangle (f, flash_left,
3539 (height - flash_height
3540 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3541 width, flash_height);
3543 else
3544 /* If it is short, flash it all. */
3545 mac_invert_rectangle (f, flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3546 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3548 x_flush (f);
3551 struct timeval wakeup;
3553 EMACS_GET_TIME (wakeup);
3555 /* Compute time to wait until, propagating carry from usecs. */
3556 wakeup.tv_usec += 150000;
3557 wakeup.tv_sec += (wakeup.tv_usec / 1000000);
3558 wakeup.tv_usec %= 1000000;
3560 /* Keep waiting until past the time wakeup or any input gets
3561 available. */
3562 while (! detect_input_pending ())
3564 struct timeval current;
3565 struct timeval timeout;
3567 EMACS_GET_TIME (current);
3569 /* Break if result would be negative. */
3570 if (timeval_subtract (&current, wakeup, current))
3571 break;
3573 /* How long `select' should wait. */
3574 timeout.tv_sec = 0;
3575 timeout.tv_usec = 10000;
3577 /* Try to wait that long--but we might wake up sooner. */
3578 select (0, NULL, NULL, NULL, &timeout);
3582 /* If window is tall, flash top and bottom line. */
3583 if (height > 3 * FRAME_LINE_HEIGHT (f))
3585 mac_invert_rectangle (f, flash_left,
3586 (FRAME_INTERNAL_BORDER_WIDTH (f)
3587 + FRAME_TOOL_BAR_LINES (f) * FRAME_LINE_HEIGHT (f)),
3588 width, flash_height);
3589 mac_invert_rectangle (f, flash_left,
3590 (height - flash_height
3591 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3592 width, flash_height);
3594 else
3595 /* If it is short, flash it all. */
3596 mac_invert_rectangle (f, flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3597 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3599 x_flush (f);
3601 UNBLOCK_INPUT;
3604 #endif /* defined (HAVE_TIMEVAL) && defined (HAVE_SELECT) */
3607 /* Make audible bell. */
3609 void
3610 XTring_bell ()
3612 struct frame *f = SELECTED_FRAME ();
3614 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
3615 if (visible_bell)
3616 XTflash (f);
3617 else
3618 #endif
3620 BLOCK_INPUT;
3621 SysBeep (1);
3622 XFlush (FRAME_MAC_DISPLAY (f));
3623 UNBLOCK_INPUT;
3628 /* Specify how many text lines, from the top of the window,
3629 should be affected by insert-lines and delete-lines operations.
3630 This, and those operations, are used only within an update
3631 that is bounded by calls to x_update_begin and x_update_end. */
3633 static void
3634 XTset_terminal_window (n)
3635 register int n;
3637 /* This function intentionally left blank. */
3642 /***********************************************************************
3643 Line Dance
3644 ***********************************************************************/
3646 /* Perform an insert-lines or delete-lines operation, inserting N
3647 lines or deleting -N lines at vertical position VPOS. */
3649 static void
3650 x_ins_del_lines (vpos, n)
3651 int vpos, n;
3653 abort ();
3657 /* Scroll part of the display as described by RUN. */
3659 static void
3660 x_scroll_run (w, run)
3661 struct window *w;
3662 struct run *run;
3664 struct frame *f = XFRAME (w->frame);
3665 int x, y, width, height, from_y, to_y, bottom_y;
3667 /* Get frame-relative bounding box of the text display area of W,
3668 without mode lines. Include in this box the left and right
3669 fringe of W. */
3670 window_box (w, -1, &x, &y, &width, &height);
3672 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
3673 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
3674 bottom_y = y + height;
3676 if (to_y < from_y)
3678 /* Scrolling up. Make sure we don't copy part of the mode
3679 line at the bottom. */
3680 if (from_y + run->height > bottom_y)
3681 height = bottom_y - from_y;
3682 else
3683 height = run->height;
3685 else
3687 /* Scolling down. Make sure we don't copy over the mode line.
3688 at the bottom. */
3689 if (to_y + run->height > bottom_y)
3690 height = bottom_y - to_y;
3691 else
3692 height = run->height;
3695 BLOCK_INPUT;
3697 /* Cursor off. Will be switched on again in x_update_window_end. */
3698 updated_window = w;
3699 x_clear_cursor (w);
3701 mac_scroll_area (f, f->output_data.mac->normal_gc,
3702 x, from_y,
3703 width, height,
3704 x, to_y);
3706 UNBLOCK_INPUT;
3711 /***********************************************************************
3712 Exposure Events
3713 ***********************************************************************/
3716 static void
3717 frame_highlight (f)
3718 struct frame *f;
3720 OSErr err;
3721 ControlRef root_control;
3723 BLOCK_INPUT;
3724 err = GetRootControl (FRAME_MAC_WINDOW (f), &root_control);
3725 if (err == noErr)
3726 ActivateControl (root_control);
3727 UNBLOCK_INPUT;
3728 x_update_cursor (f, 1);
3731 static void
3732 frame_unhighlight (f)
3733 struct frame *f;
3735 OSErr err;
3736 ControlRef root_control;
3738 BLOCK_INPUT;
3739 err = GetRootControl (FRAME_MAC_WINDOW (f), &root_control);
3740 if (err == noErr)
3741 DeactivateControl (root_control);
3742 UNBLOCK_INPUT;
3743 x_update_cursor (f, 1);
3746 /* The focus has changed. Update the frames as necessary to reflect
3747 the new situation. Note that we can't change the selected frame
3748 here, because the Lisp code we are interrupting might become confused.
3749 Each event gets marked with the frame in which it occurred, so the
3750 Lisp code can tell when the switch took place by examining the events. */
3752 static void
3753 x_new_focus_frame (dpyinfo, frame)
3754 struct x_display_info *dpyinfo;
3755 struct frame *frame;
3757 struct frame *old_focus = dpyinfo->x_focus_frame;
3759 if (frame != dpyinfo->x_focus_frame)
3761 /* Set this before calling other routines, so that they see
3762 the correct value of x_focus_frame. */
3763 dpyinfo->x_focus_frame = frame;
3765 if (old_focus && old_focus->auto_lower)
3766 x_lower_frame (old_focus);
3768 #if 0
3769 selected_frame = frame;
3770 XSETFRAME (XWINDOW (selected_frame->selected_window)->frame,
3771 selected_frame);
3772 Fselect_window (selected_frame->selected_window, Qnil);
3773 choose_minibuf_frame ();
3774 #endif /* ! 0 */
3776 if (dpyinfo->x_focus_frame && dpyinfo->x_focus_frame->auto_raise)
3777 pending_autoraise_frame = dpyinfo->x_focus_frame;
3778 else
3779 pending_autoraise_frame = 0;
3782 x_frame_rehighlight (dpyinfo);
3785 /* Handle FocusIn and FocusOut state changes for FRAME.
3786 If FRAME has focus and there exists more than one frame, puts
3787 a FOCUS_IN_EVENT into *BUFP. */
3789 static void
3790 mac_focus_changed (type, dpyinfo, frame, bufp)
3791 int type;
3792 struct mac_display_info *dpyinfo;
3793 struct frame *frame;
3794 struct input_event *bufp;
3796 if (type == activeFlag)
3798 if (dpyinfo->x_focus_event_frame != frame)
3800 x_new_focus_frame (dpyinfo, frame);
3801 dpyinfo->x_focus_event_frame = frame;
3803 /* Don't stop displaying the initial startup message
3804 for a switch-frame event we don't need. */
3805 if (GC_NILP (Vterminal_frame)
3806 && GC_CONSP (Vframe_list)
3807 && !GC_NILP (XCDR (Vframe_list)))
3809 bufp->kind = FOCUS_IN_EVENT;
3810 XSETFRAME (bufp->frame_or_window, frame);
3814 else
3816 if (dpyinfo->x_focus_event_frame == frame)
3818 dpyinfo->x_focus_event_frame = 0;
3819 x_new_focus_frame (dpyinfo, 0);
3824 /* The focus may have changed. Figure out if it is a real focus change,
3825 by checking both FocusIn/Out and Enter/LeaveNotify events.
3827 Returns FOCUS_IN_EVENT event in *BUFP. */
3829 static void
3830 x_detect_focus_change (dpyinfo, event, bufp)
3831 struct mac_display_info *dpyinfo;
3832 EventRecord *event;
3833 struct input_event *bufp;
3835 struct frame *frame;
3837 frame = mac_window_to_frame ((WindowPtr) event->message);
3838 if (! frame)
3839 return;
3841 /* On Mac, this is only called from focus events, so no switch needed. */
3842 mac_focus_changed ((event->modifiers & activeFlag),
3843 dpyinfo, frame, bufp);
3847 /* Handle an event saying the mouse has moved out of an Emacs frame. */
3849 void
3850 x_mouse_leave (dpyinfo)
3851 struct x_display_info *dpyinfo;
3853 x_new_focus_frame (dpyinfo, dpyinfo->x_focus_event_frame);
3856 /* The focus has changed, or we have redirected a frame's focus to
3857 another frame (this happens when a frame uses a surrogate
3858 mini-buffer frame). Shift the highlight as appropriate.
3860 The FRAME argument doesn't necessarily have anything to do with which
3861 frame is being highlighted or un-highlighted; we only use it to find
3862 the appropriate X display info. */
3864 static void
3865 XTframe_rehighlight (frame)
3866 struct frame *frame;
3868 x_frame_rehighlight (FRAME_X_DISPLAY_INFO (frame));
3871 static void
3872 x_frame_rehighlight (dpyinfo)
3873 struct x_display_info *dpyinfo;
3875 struct frame *old_highlight = dpyinfo->x_highlight_frame;
3877 if (dpyinfo->x_focus_frame)
3879 dpyinfo->x_highlight_frame
3880 = ((GC_FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame)))
3881 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
3882 : dpyinfo->x_focus_frame);
3883 if (! FRAME_LIVE_P (dpyinfo->x_highlight_frame))
3885 FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
3886 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
3889 else
3890 dpyinfo->x_highlight_frame = 0;
3892 if (dpyinfo->x_highlight_frame != old_highlight)
3894 if (old_highlight)
3895 frame_unhighlight (old_highlight);
3896 if (dpyinfo->x_highlight_frame)
3897 frame_highlight (dpyinfo->x_highlight_frame);
3903 /* Keyboard processing - modifier keys, vendor-specific keysyms, etc. */
3905 #if 0 /* MAC_TODO */
3906 /* Initialize mode_switch_bit and modifier_meaning. */
3907 static void
3908 x_find_modifier_meanings (dpyinfo)
3909 struct x_display_info *dpyinfo;
3911 int min_code, max_code;
3912 KeySym *syms;
3913 int syms_per_code;
3914 XModifierKeymap *mods;
3916 dpyinfo->meta_mod_mask = 0;
3917 dpyinfo->shift_lock_mask = 0;
3918 dpyinfo->alt_mod_mask = 0;
3919 dpyinfo->super_mod_mask = 0;
3920 dpyinfo->hyper_mod_mask = 0;
3922 #ifdef HAVE_X11R4
3923 XDisplayKeycodes (dpyinfo->display, &min_code, &max_code);
3924 #else
3925 min_code = dpyinfo->display->min_keycode;
3926 max_code = dpyinfo->display->max_keycode;
3927 #endif
3929 syms = XGetKeyboardMapping (dpyinfo->display,
3930 min_code, max_code - min_code + 1,
3931 &syms_per_code);
3932 mods = XGetModifierMapping (dpyinfo->display);
3934 /* Scan the modifier table to see which modifier bits the Meta and
3935 Alt keysyms are on. */
3937 int row, col; /* The row and column in the modifier table. */
3939 for (row = 3; row < 8; row++)
3940 for (col = 0; col < mods->max_keypermod; col++)
3942 KeyCode code
3943 = mods->modifiermap[(row * mods->max_keypermod) + col];
3945 /* Zeroes are used for filler. Skip them. */
3946 if (code == 0)
3947 continue;
3949 /* Are any of this keycode's keysyms a meta key? */
3951 int code_col;
3953 for (code_col = 0; code_col < syms_per_code; code_col++)
3955 int sym = syms[((code - min_code) * syms_per_code) + code_col];
3957 switch (sym)
3959 case XK_Meta_L:
3960 case XK_Meta_R:
3961 dpyinfo->meta_mod_mask |= (1 << row);
3962 break;
3964 case XK_Alt_L:
3965 case XK_Alt_R:
3966 dpyinfo->alt_mod_mask |= (1 << row);
3967 break;
3969 case XK_Hyper_L:
3970 case XK_Hyper_R:
3971 dpyinfo->hyper_mod_mask |= (1 << row);
3972 break;
3974 case XK_Super_L:
3975 case XK_Super_R:
3976 dpyinfo->super_mod_mask |= (1 << row);
3977 break;
3979 case XK_Shift_Lock:
3980 /* Ignore this if it's not on the lock modifier. */
3981 if ((1 << row) == LockMask)
3982 dpyinfo->shift_lock_mask = LockMask;
3983 break;
3990 /* If we couldn't find any meta keys, accept any alt keys as meta keys. */
3991 if (! dpyinfo->meta_mod_mask)
3993 dpyinfo->meta_mod_mask = dpyinfo->alt_mod_mask;
3994 dpyinfo->alt_mod_mask = 0;
3997 /* If some keys are both alt and meta,
3998 make them just meta, not alt. */
3999 if (dpyinfo->alt_mod_mask & dpyinfo->meta_mod_mask)
4001 dpyinfo->alt_mod_mask &= ~dpyinfo->meta_mod_mask;
4004 XFree ((char *) syms);
4005 XFreeModifiermap (mods);
4008 #endif /* MAC_TODO */
4010 /* Convert between the modifier bits X uses and the modifier bits
4011 Emacs uses. */
4013 static unsigned int
4014 x_mac_to_emacs_modifiers (dpyinfo, state)
4015 struct x_display_info *dpyinfo;
4016 unsigned short state;
4018 return (((state & shiftKey) ? shift_modifier : 0)
4019 | ((state & controlKey) ? ctrl_modifier : 0)
4020 | ((state & cmdKey) ? meta_modifier : 0)
4021 | ((state & optionKey) ? alt_modifier : 0));
4024 #if 0 /* MAC_TODO */
4025 static unsigned short
4026 x_emacs_to_x_modifiers (dpyinfo, state)
4027 struct x_display_info *dpyinfo;
4028 unsigned int state;
4030 return ( ((state & alt_modifier) ? dpyinfo->alt_mod_mask : 0)
4031 | ((state & super_modifier) ? dpyinfo->super_mod_mask : 0)
4032 | ((state & hyper_modifier) ? dpyinfo->hyper_mod_mask : 0)
4033 | ((state & shift_modifier) ? ShiftMask : 0)
4034 | ((state & ctrl_modifier) ? ControlMask : 0)
4035 | ((state & meta_modifier) ? dpyinfo->meta_mod_mask : 0));
4037 #endif /* MAC_TODO */
4039 /* Convert a keysym to its name. */
4041 char *
4042 x_get_keysym_name (keysym)
4043 int keysym;
4045 char *value;
4047 BLOCK_INPUT;
4048 #if 0
4049 value = XKeysymToString (keysym);
4050 #else
4051 value = 0;
4052 #endif
4053 UNBLOCK_INPUT;
4055 return value;
4060 /* Function to report a mouse movement to the mainstream Emacs code.
4061 The input handler calls this.
4063 We have received a mouse movement event, which is given in *event.
4064 If the mouse is over a different glyph than it was last time, tell
4065 the mainstream emacs code by setting mouse_moved. If not, ask for
4066 another motion event, so we can check again the next time it moves. */
4068 static Point last_mouse_motion_position;
4069 static Lisp_Object last_mouse_motion_frame;
4071 static int
4072 note_mouse_movement (frame, pos)
4073 FRAME_PTR frame;
4074 Point *pos;
4076 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (frame);
4077 #if TARGET_API_MAC_CARBON
4078 Rect r;
4079 #endif
4081 last_mouse_movement_time = TickCount () * (1000 / 60); /* to milliseconds */
4082 last_mouse_motion_position = *pos;
4083 XSETFRAME (last_mouse_motion_frame, frame);
4085 #if TARGET_API_MAC_CARBON
4086 if (!PtInRect (*pos, GetWindowPortBounds (FRAME_MAC_WINDOW (frame), &r)))
4087 #else
4088 if (!PtInRect (*pos, &FRAME_MAC_WINDOW (frame)->portRect))
4089 #endif
4091 if (frame == dpyinfo->mouse_face_mouse_frame)
4092 /* This case corresponds to LeaveNotify in X11. */
4094 /* If we move outside the frame, then we're certainly no
4095 longer on any text in the frame. */
4096 clear_mouse_face (dpyinfo);
4097 dpyinfo->mouse_face_mouse_frame = 0;
4098 if (!dpyinfo->grabbed)
4099 rif->define_frame_cursor (frame,
4100 frame->output_data.mac->nontext_cursor);
4102 return 1;
4104 /* Has the mouse moved off the glyph it was on at the last sighting? */
4105 if (frame != last_mouse_glyph_frame
4106 || !PtInRect (*pos, &last_mouse_glyph))
4108 frame->mouse_moved = 1;
4109 last_mouse_scroll_bar = Qnil;
4110 note_mouse_highlight (frame, pos->h, pos->v);
4111 /* Remember which glyph we're now on. */
4112 remember_mouse_glyph (frame, pos->h, pos->v, &last_mouse_glyph);
4113 last_mouse_glyph_frame = frame;
4114 return 1;
4117 return 0;
4121 /************************************************************************
4122 Mouse Face
4123 ************************************************************************/
4125 /* MAC TODO: This should be called from somewhere (or removed) ++KFS */
4127 static void
4128 redo_mouse_highlight ()
4130 if (!NILP (last_mouse_motion_frame)
4131 && FRAME_LIVE_P (XFRAME (last_mouse_motion_frame)))
4132 note_mouse_highlight (XFRAME (last_mouse_motion_frame),
4133 last_mouse_motion_position.h,
4134 last_mouse_motion_position.v);
4138 static struct frame *
4139 mac_focus_frame (dpyinfo)
4140 struct mac_display_info *dpyinfo;
4142 if (dpyinfo->x_focus_frame)
4143 return dpyinfo->x_focus_frame;
4144 else
4145 /* Mac version may get events, such as a menu bar click, even when
4146 all the frames are invisible. In this case, we regard the
4147 event came to the selected frame. */
4148 return SELECTED_FRAME ();
4152 /* Return the current position of the mouse.
4153 *FP should be a frame which indicates which display to ask about.
4155 If the mouse movement started in a scroll bar, set *FP, *BAR_WINDOW,
4156 and *PART to the frame, window, and scroll bar part that the mouse
4157 is over. Set *X and *Y to the portion and whole of the mouse's
4158 position on the scroll bar.
4160 If the mouse movement started elsewhere, set *FP to the frame the
4161 mouse is on, *BAR_WINDOW to nil, and *X and *Y to the character cell
4162 the mouse is over.
4164 Set *TIME to the server time-stamp for the time at which the mouse
4165 was at this position.
4167 Don't store anything if we don't have a valid set of values to report.
4169 This clears the mouse_moved flag, so we can wait for the next mouse
4170 movement. */
4172 static void
4173 XTmouse_position (fp, insist, bar_window, part, x, y, time)
4174 FRAME_PTR *fp;
4175 int insist;
4176 Lisp_Object *bar_window;
4177 enum scroll_bar_part *part;
4178 Lisp_Object *x, *y;
4179 unsigned long *time;
4181 FRAME_PTR f1;
4183 BLOCK_INPUT;
4185 if (! NILP (last_mouse_scroll_bar) && insist == 0)
4186 x_scroll_bar_report_motion (fp, bar_window, part, x, y, time);
4187 else
4189 Lisp_Object frame, tail;
4191 /* Clear the mouse-moved flag for every frame on this display. */
4192 FOR_EACH_FRAME (tail, frame)
4193 XFRAME (frame)->mouse_moved = 0;
4195 last_mouse_scroll_bar = Qnil;
4197 if (FRAME_MAC_DISPLAY_INFO (*fp)->grabbed && last_mouse_frame
4198 && FRAME_LIVE_P (last_mouse_frame))
4199 f1 = last_mouse_frame;
4200 else
4201 f1 = mac_focus_frame (FRAME_MAC_DISPLAY_INFO (*fp));
4203 if (f1)
4205 /* Ok, we found a frame. Store all the values.
4206 last_mouse_glyph is a rectangle used to reduce the
4207 generation of mouse events. To not miss any motion
4208 events, we must divide the frame into rectangles of the
4209 size of the smallest character that could be displayed
4210 on it, i.e. into the same rectangles that matrices on
4211 the frame are divided into. */
4212 Point mouse_pos;
4214 SetPortWindowPort (FRAME_MAC_WINDOW (f1));
4215 GetMouse (&mouse_pos);
4216 remember_mouse_glyph (f1, mouse_pos.h, mouse_pos.v,
4217 &last_mouse_glyph);
4218 last_mouse_glyph_frame = f1;
4220 *bar_window = Qnil;
4221 *part = 0;
4222 *fp = f1;
4223 XSETINT (*x, mouse_pos.h);
4224 XSETINT (*y, mouse_pos.v);
4225 *time = last_mouse_movement_time;
4229 UNBLOCK_INPUT;
4233 /************************************************************************
4234 Toolkit scroll bars
4235 ************************************************************************/
4237 #ifdef USE_TOOLKIT_SCROLL_BARS
4239 static pascal void scroll_bar_timer_callback P_ ((EventLoopTimerRef, void *));
4240 static OSStatus install_scroll_bar_timer P_ ((void));
4241 static OSStatus set_scroll_bar_timer P_ ((EventTimerInterval));
4242 static int control_part_code_to_scroll_bar_part P_ ((ControlPartCode));
4243 static void construct_scroll_bar_click P_ ((struct scroll_bar *, int,
4244 struct input_event *));
4245 static OSErr get_control_part_bounds P_ ((ControlHandle, ControlPartCode,
4246 Rect *));
4247 static void x_scroll_bar_handle_press P_ ((struct scroll_bar *,
4248 ControlPartCode,
4249 struct input_event *));
4250 static void x_scroll_bar_handle_release P_ ((struct scroll_bar *,
4251 struct input_event *));
4252 static void x_scroll_bar_handle_drag P_ ((WindowPtr, struct scroll_bar *,
4253 Point, struct input_event *));
4254 static void x_set_toolkit_scroll_bar_thumb P_ ((struct scroll_bar *,
4255 int, int, int));
4257 /* Last scroll bar part sent in x_scroll_bar_handle_*. */
4259 static int last_scroll_bar_part;
4261 static EventLoopTimerRef scroll_bar_timer;
4263 static int scroll_bar_timer_event_posted_p;
4265 #define SCROLL_BAR_FIRST_DELAY 0.5
4266 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
4268 static pascal void
4269 scroll_bar_timer_callback (timer, data)
4270 EventLoopTimerRef timer;
4271 void *data;
4273 EventRef event = NULL;
4274 OSErr err;
4276 err = CreateEvent (NULL, kEventClassMouse, kEventMouseMoved, 0,
4277 kEventAttributeNone, &event);
4278 if (err == noErr)
4280 Point mouse_pos;
4282 GetMouse (&mouse_pos);
4283 LocalToGlobal (&mouse_pos);
4284 err = SetEventParameter (event, kEventParamMouseLocation, typeQDPoint,
4285 sizeof (Point), &mouse_pos);
4287 if (err == noErr)
4289 UInt32 modifiers = GetCurrentKeyModifiers ();
4291 err = SetEventParameter (event, kEventParamKeyModifiers, typeUInt32,
4292 sizeof (UInt32), &modifiers);
4294 if (err == noErr)
4295 err = PostEventToQueue (GetCurrentEventQueue (), event,
4296 kEventPriorityStandard);
4297 if (err == noErr)
4298 scroll_bar_timer_event_posted_p = 1;
4300 if (event)
4301 ReleaseEvent (event);
4304 static OSStatus
4305 install_scroll_bar_timer ()
4307 static EventLoopTimerUPP scroll_bar_timer_callbackUPP = NULL;
4309 if (scroll_bar_timer_callbackUPP == NULL)
4310 scroll_bar_timer_callbackUPP =
4311 NewEventLoopTimerUPP (scroll_bar_timer_callback);
4313 if (scroll_bar_timer == NULL)
4314 /* Mac OS X and CarbonLib 1.5 and later allow us to specify
4315 kEventDurationForever as delays. */
4316 return
4317 InstallEventLoopTimer (GetCurrentEventLoop (),
4318 kEventDurationForever, kEventDurationForever,
4319 scroll_bar_timer_callbackUPP, NULL,
4320 &scroll_bar_timer);
4323 static OSStatus
4324 set_scroll_bar_timer (delay)
4325 EventTimerInterval delay;
4327 if (scroll_bar_timer == NULL)
4328 install_scroll_bar_timer ();
4330 scroll_bar_timer_event_posted_p = 0;
4332 return SetEventLoopTimerNextFireTime (scroll_bar_timer, delay);
4335 static int
4336 control_part_code_to_scroll_bar_part (part_code)
4337 ControlPartCode part_code;
4339 switch (part_code)
4341 case kControlUpButtonPart: return scroll_bar_up_arrow;
4342 case kControlDownButtonPart: return scroll_bar_down_arrow;
4343 case kControlPageUpPart: return scroll_bar_above_handle;
4344 case kControlPageDownPart: return scroll_bar_below_handle;
4345 case kControlIndicatorPart: return scroll_bar_handle;
4348 return -1;
4351 static void
4352 construct_scroll_bar_click (bar, part, bufp)
4353 struct scroll_bar *bar;
4354 int part;
4355 struct input_event *bufp;
4357 bufp->kind = SCROLL_BAR_CLICK_EVENT;
4358 bufp->frame_or_window = bar->window;
4359 bufp->arg = Qnil;
4360 bufp->part = part;
4361 bufp->code = 0;
4362 XSETINT (bufp->x, 0);
4363 XSETINT (bufp->y, 0);
4364 bufp->modifiers = 0;
4367 static OSErr
4368 get_control_part_bounds (ch, part_code, rect)
4369 ControlHandle ch;
4370 ControlPartCode part_code;
4371 Rect *rect;
4373 RgnHandle region = NewRgn ();
4374 OSStatus err;
4376 err = GetControlRegion (ch, part_code, region);
4377 if (err == noErr)
4378 GetRegionBounds (region, rect);
4379 DisposeRgn (region);
4381 return err;
4384 static void
4385 x_scroll_bar_handle_press (bar, part_code, bufp)
4386 struct scroll_bar *bar;
4387 ControlPartCode part_code;
4388 struct input_event *bufp;
4390 int part = control_part_code_to_scroll_bar_part (part_code);
4392 if (part < 0)
4393 return;
4395 if (part != scroll_bar_handle)
4397 construct_scroll_bar_click (bar, part, bufp);
4398 HiliteControl (SCROLL_BAR_CONTROL_HANDLE (bar), part_code);
4399 set_scroll_bar_timer (SCROLL_BAR_FIRST_DELAY);
4402 last_scroll_bar_part = part;
4403 bar->dragging = Qnil;
4404 tracked_scroll_bar = bar;
4407 static void
4408 x_scroll_bar_handle_release (bar, bufp)
4409 struct scroll_bar *bar;
4410 struct input_event *bufp;
4412 if (last_scroll_bar_part != scroll_bar_handle
4413 || !GC_NILP (bar->dragging))
4414 construct_scroll_bar_click (bar, scroll_bar_end_scroll, bufp);
4416 HiliteControl (SCROLL_BAR_CONTROL_HANDLE (bar), 0);
4417 set_scroll_bar_timer (kEventDurationForever);
4419 last_scroll_bar_part = -1;
4420 bar->dragging = Qnil;
4421 tracked_scroll_bar = NULL;
4424 static void
4425 x_scroll_bar_handle_drag (win, bar, mouse_pos, bufp)
4426 WindowPtr win;
4427 struct scroll_bar *bar;
4428 Point mouse_pos;
4429 struct input_event *bufp;
4431 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4433 if (last_scroll_bar_part == scroll_bar_handle)
4435 int top, top_range;
4436 Rect r;
4438 get_control_part_bounds (SCROLL_BAR_CONTROL_HANDLE (bar),
4439 kControlIndicatorPart, &r);
4441 if (GC_NILP (bar->dragging))
4442 XSETINT (bar->dragging, mouse_pos.v - r.top);
4444 top = mouse_pos.v - XINT (bar->dragging) - XINT (bar->track_top);
4445 top_range = (XINT (bar->track_height) - (r.bottom - r.top)) *
4446 (1.0 + (float) GetControlViewSize (ch) / GetControl32BitMaximum (ch))
4447 + .5;
4449 if (top < 0)
4450 top = 0;
4451 if (top > top_range)
4452 top = top_range;
4454 construct_scroll_bar_click (bar, scroll_bar_handle, bufp);
4455 XSETINT (bufp->x, top);
4456 XSETINT (bufp->y, top_range);
4458 else
4460 ControlPartCode part_code;
4461 int unhilite_p = 0, part;
4463 if (ch != FindControlUnderMouse (mouse_pos, win, &part_code))
4464 unhilite_p = 1;
4465 else
4467 part = control_part_code_to_scroll_bar_part (part_code);
4469 switch (last_scroll_bar_part)
4471 case scroll_bar_above_handle:
4472 case scroll_bar_below_handle:
4473 if (part != scroll_bar_above_handle
4474 && part != scroll_bar_below_handle)
4475 unhilite_p = 1;
4476 break;
4478 case scroll_bar_up_arrow:
4479 case scroll_bar_down_arrow:
4480 if (part != scroll_bar_up_arrow
4481 && part != scroll_bar_down_arrow)
4482 unhilite_p = 1;
4483 break;
4487 if (unhilite_p)
4488 HiliteControl (SCROLL_BAR_CONTROL_HANDLE (bar), 0);
4489 else if (part != last_scroll_bar_part
4490 || scroll_bar_timer_event_posted_p)
4492 construct_scroll_bar_click (bar, part, bufp);
4493 last_scroll_bar_part = part;
4494 HiliteControl (SCROLL_BAR_CONTROL_HANDLE (bar), part_code);
4495 set_scroll_bar_timer (SCROLL_BAR_CONTINUOUS_DELAY);
4500 /* Set the thumb size and position of scroll bar BAR. We are currently
4501 displaying PORTION out of a whole WHOLE, and our position POSITION. */
4503 static void
4504 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole)
4505 struct scroll_bar *bar;
4506 int portion, position, whole;
4508 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4510 int value, viewsize, maximum;
4512 if (whole == 0 || XINT (bar->track_height) == 0)
4513 value = 0, viewsize = 1, maximum = 0;
4514 else
4516 value = position;
4517 viewsize = portion;
4518 maximum = max (0, whole - portion);
4521 BLOCK_INPUT;
4523 SetControl32BitMinimum (ch, 0);
4524 SetControl32BitMaximum (ch, maximum);
4525 SetControl32BitValue (ch, value);
4526 SetControlViewSize (ch, viewsize);
4528 UNBLOCK_INPUT;
4531 #endif /* USE_TOOLKIT_SCROLL_BARS */
4535 /************************************************************************
4536 Scroll bars, general
4537 ************************************************************************/
4539 /* Create a scroll bar and return the scroll bar vector for it. W is
4540 the Emacs window on which to create the scroll bar. TOP, LEFT,
4541 WIDTH and HEIGHT are the pixel coordinates and dimensions of the
4542 scroll bar. */
4544 static struct scroll_bar *
4545 x_scroll_bar_create (w, top, left, width, height, disp_top, disp_height)
4546 struct window *w;
4547 int top, left, width, height, disp_top, disp_height;
4549 struct frame *f = XFRAME (w->frame);
4550 struct scroll_bar *bar
4551 = XSCROLL_BAR (Fmake_vector (make_number (SCROLL_BAR_VEC_SIZE), Qnil));
4552 Rect r;
4553 ControlHandle ch;
4555 BLOCK_INPUT;
4557 r.left = left;
4558 r.top = disp_top;
4559 r.right = left + width;
4560 r.bottom = disp_top + disp_height;
4562 #if TARGET_API_MAC_CARBON
4563 ch = NewControl (FRAME_MAC_WINDOW (f), &r, "\p", width < disp_height,
4564 0, 0, 0, kControlScrollBarProc, (long) bar);
4565 #else
4566 ch = NewControl (FRAME_MAC_WINDOW (f), &r, "\p", width < disp_height,
4567 0, 0, 0, scrollBarProc, (long) bar);
4568 #endif
4569 SET_SCROLL_BAR_CONTROL_HANDLE (bar, ch);
4571 XSETWINDOW (bar->window, w);
4572 XSETINT (bar->top, top);
4573 XSETINT (bar->left, left);
4574 XSETINT (bar->width, width);
4575 XSETINT (bar->height, height);
4576 XSETINT (bar->start, 0);
4577 XSETINT (bar->end, 0);
4578 bar->dragging = Qnil;
4579 #ifdef USE_TOOLKIT_SCROLL_BARS
4580 bar->track_top = Qnil;
4581 bar->track_height = Qnil;
4582 #endif
4584 /* Add bar to its frame's list of scroll bars. */
4585 bar->next = FRAME_SCROLL_BARS (f);
4586 bar->prev = Qnil;
4587 XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
4588 if (!NILP (bar->next))
4589 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
4591 UNBLOCK_INPUT;
4592 return bar;
4596 /* Draw BAR's handle in the proper position.
4598 If the handle is already drawn from START to END, don't bother
4599 redrawing it, unless REBUILD is non-zero; in that case, always
4600 redraw it. (REBUILD is handy for drawing the handle after expose
4601 events.)
4603 Normally, we want to constrain the start and end of the handle to
4604 fit inside its rectangle, but if the user is dragging the scroll
4605 bar handle, we want to let them drag it down all the way, so that
4606 the bar's top is as far down as it goes; otherwise, there's no way
4607 to move to the very end of the buffer. */
4609 #ifndef USE_TOOLKIT_SCROLL_BARS
4611 static void
4612 x_scroll_bar_set_handle (bar, start, end, rebuild)
4613 struct scroll_bar *bar;
4614 int start, end;
4615 int rebuild;
4617 int dragging = ! NILP (bar->dragging);
4618 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4619 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4620 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, XINT (bar->height));
4621 int length = end - start;
4623 /* If the display is already accurate, do nothing. */
4624 if (! rebuild
4625 && start == XINT (bar->start)
4626 && end == XINT (bar->end))
4627 return;
4629 BLOCK_INPUT;
4631 /* Make sure the values are reasonable, and try to preserve the
4632 distance between start and end. */
4633 if (start < 0)
4634 start = 0;
4635 else if (start > top_range)
4636 start = top_range;
4637 end = start + length;
4639 if (end < start)
4640 end = start;
4641 else if (end > top_range && ! dragging)
4642 end = top_range;
4644 /* Store the adjusted setting in the scroll bar. */
4645 XSETINT (bar->start, start);
4646 XSETINT (bar->end, end);
4648 /* Clip the end position, just for display. */
4649 if (end > top_range)
4650 end = top_range;
4652 /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels below
4653 top positions, to make sure the handle is always at least that
4654 many pixels tall. */
4655 end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
4657 SetControlMinimum (ch, 0);
4658 /* Don't inadvertently activate deactivated scroll bars */
4659 if (GetControlMaximum (ch) != -1)
4660 SetControlMaximum (ch, top_range + VERTICAL_SCROLL_BAR_MIN_HANDLE
4661 - (end - start));
4662 SetControlValue (ch, start);
4663 #if TARGET_API_MAC_CARBON
4664 SetControlViewSize (ch, end - start);
4665 #endif
4667 UNBLOCK_INPUT;
4670 #endif /* !USE_TOOLKIT_SCROLL_BARS */
4672 /* Destroy scroll bar BAR, and set its Emacs window's scroll bar to
4673 nil. */
4675 static void
4676 x_scroll_bar_remove (bar)
4677 struct scroll_bar *bar;
4679 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4681 BLOCK_INPUT;
4683 /* Destroy the Mac scroll bar control */
4684 DisposeControl (SCROLL_BAR_CONTROL_HANDLE (bar));
4686 /* Disassociate this scroll bar from its window. */
4687 XWINDOW (bar->window)->vertical_scroll_bar = Qnil;
4689 UNBLOCK_INPUT;
4693 /* Set the handle of the vertical scroll bar for WINDOW to indicate
4694 that we are displaying PORTION characters out of a total of WHOLE
4695 characters, starting at POSITION. If WINDOW has no scroll bar,
4696 create one. */
4698 static void
4699 XTset_vertical_scroll_bar (w, portion, whole, position)
4700 struct window *w;
4701 int portion, whole, position;
4703 struct frame *f = XFRAME (w->frame);
4704 struct scroll_bar *bar;
4705 int top, height, left, sb_left, width, sb_width, disp_top, disp_height;
4706 int window_y, window_height;
4708 /* Get window dimensions. */
4709 window_box (w, -1, 0, &window_y, 0, &window_height);
4710 top = window_y;
4711 width = WINDOW_CONFIG_SCROLL_BAR_COLS (w) * FRAME_COLUMN_WIDTH (f);
4712 height = window_height;
4714 /* Compute the left edge of the scroll bar area. */
4715 left = WINDOW_SCROLL_BAR_AREA_X (w);
4717 /* Compute the width of the scroll bar which might be less than
4718 the width of the area reserved for the scroll bar. */
4719 if (WINDOW_CONFIG_SCROLL_BAR_WIDTH (w) > 0)
4720 sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
4721 else
4722 sb_width = width;
4724 /* Compute the left edge of the scroll bar. */
4725 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
4726 sb_left = left;
4727 else
4728 sb_left = left + width - sb_width;
4730 /* Adjustments according to Inside Macintosh to make it look nice */
4731 disp_top = top;
4732 disp_height = height;
4733 if (disp_top == 0)
4735 disp_top = -1;
4736 disp_height++;
4738 else if (disp_top == FRAME_PIXEL_HEIGHT (f) - 16)
4740 disp_top++;
4741 disp_height--;
4744 if (sb_left + sb_width == FRAME_PIXEL_WIDTH (f))
4745 sb_left++;
4747 /* Does the scroll bar exist yet? */
4748 if (NILP (w->vertical_scroll_bar))
4750 BLOCK_INPUT;
4751 mac_clear_area (f, left, top, width, height);
4752 UNBLOCK_INPUT;
4753 bar = x_scroll_bar_create (w, top, sb_left, sb_width, height, disp_top,
4754 disp_height);
4755 XSETVECTOR (w->vertical_scroll_bar, bar);
4757 else
4759 /* It may just need to be moved and resized. */
4760 ControlHandle ch;
4762 bar = XSCROLL_BAR (w->vertical_scroll_bar);
4763 ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4765 BLOCK_INPUT;
4767 /* If already correctly positioned, do nothing. */
4768 if (!(XINT (bar->left) == sb_left
4769 && XINT (bar->top) == top
4770 && XINT (bar->width) == sb_width
4771 && XINT (bar->height) == height))
4773 /* Since toolkit scroll bars are smaller than the space reserved
4774 for them on the frame, we have to clear "under" them. */
4775 mac_clear_area (f, left, top, width, height);
4777 HideControl (ch);
4778 MoveControl (ch, sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM, disp_top);
4779 SizeControl (ch, sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
4780 disp_height);
4781 if (sb_width < disp_height)
4782 ShowControl (ch);
4784 /* Remember new settings. */
4785 XSETINT (bar->left, sb_left);
4786 XSETINT (bar->top, top);
4787 XSETINT (bar->width, sb_width);
4788 XSETINT (bar->height, height);
4789 #ifdef USE_TOOLKIT_SCROLL_BARS
4790 bar->track_top = Qnil;
4791 bar->track_height = Qnil;
4792 #endif
4795 UNBLOCK_INPUT;
4798 #ifdef USE_TOOLKIT_SCROLL_BARS
4799 if (NILP (bar->track_top))
4801 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4802 Rect r0, r1;
4804 BLOCK_INPUT;
4806 SetControl32BitMinimum (ch, 0);
4807 SetControl32BitMaximum (ch, 1);
4808 SetControlViewSize (ch, 1);
4810 /* Move the scroll bar thumb to the top. */
4811 SetControl32BitValue (ch, 0);
4812 get_control_part_bounds (ch, kControlIndicatorPart, &r0);
4814 /* Move the scroll bar thumb to the bottom. */
4815 SetControl32BitValue (ch, 1);
4816 get_control_part_bounds (ch, kControlIndicatorPart, &r1);
4818 UnionRect (&r0, &r1, &r0);
4819 XSETINT (bar->track_top, r0.top);
4820 XSETINT (bar->track_height, r0.bottom - r0.top);
4822 UNBLOCK_INPUT;
4825 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
4826 #else /* not USE_TOOLKIT_SCROLL_BARS */
4827 /* Set the scroll bar's current state, unless we're currently being
4828 dragged. */
4829 if (NILP (bar->dragging))
4831 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, height);
4833 if (whole == 0)
4834 x_scroll_bar_set_handle (bar, 0, top_range, 0);
4835 else
4837 int start = ((double) position * top_range) / whole;
4838 int end = ((double) (position + portion) * top_range) / whole;
4839 x_scroll_bar_set_handle (bar, start, end, 0);
4842 #endif /* not USE_TOOLKIT_SCROLL_BARS */
4846 /* The following three hooks are used when we're doing a thorough
4847 redisplay of the frame. We don't explicitly know which scroll bars
4848 are going to be deleted, because keeping track of when windows go
4849 away is a real pain - "Can you say set-window-configuration, boys
4850 and girls?" Instead, we just assert at the beginning of redisplay
4851 that *all* scroll bars are to be removed, and then save a scroll bar
4852 from the fiery pit when we actually redisplay its window. */
4854 /* Arrange for all scroll bars on FRAME to be removed at the next call
4855 to `*judge_scroll_bars_hook'. A scroll bar may be spared if
4856 `*redeem_scroll_bar_hook' is applied to its window before the judgment. */
4858 static void
4859 XTcondemn_scroll_bars (frame)
4860 FRAME_PTR frame;
4862 /* Transfer all the scroll bars to FRAME_CONDEMNED_SCROLL_BARS. */
4863 while (! NILP (FRAME_SCROLL_BARS (frame)))
4865 Lisp_Object bar;
4866 bar = FRAME_SCROLL_BARS (frame);
4867 FRAME_SCROLL_BARS (frame) = XSCROLL_BAR (bar)->next;
4868 XSCROLL_BAR (bar)->next = FRAME_CONDEMNED_SCROLL_BARS (frame);
4869 XSCROLL_BAR (bar)->prev = Qnil;
4870 if (! NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
4871 XSCROLL_BAR (FRAME_CONDEMNED_SCROLL_BARS (frame))->prev = bar;
4872 FRAME_CONDEMNED_SCROLL_BARS (frame) = bar;
4877 /* Un-mark WINDOW's scroll bar for deletion in this judgment cycle.
4878 Note that WINDOW isn't necessarily condemned at all. */
4880 static void
4881 XTredeem_scroll_bar (window)
4882 struct window *window;
4884 struct scroll_bar *bar;
4885 struct frame *f;
4887 /* We can't redeem this window's scroll bar if it doesn't have one. */
4888 if (NILP (window->vertical_scroll_bar))
4889 abort ();
4891 bar = XSCROLL_BAR (window->vertical_scroll_bar);
4893 /* Unlink it from the condemned list. */
4894 f = XFRAME (WINDOW_FRAME (window));
4895 if (NILP (bar->prev))
4897 /* If the prev pointer is nil, it must be the first in one of
4898 the lists. */
4899 if (EQ (FRAME_SCROLL_BARS (f), window->vertical_scroll_bar))
4900 /* It's not condemned. Everything's fine. */
4901 return;
4902 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
4903 window->vertical_scroll_bar))
4904 FRAME_CONDEMNED_SCROLL_BARS (f) = bar->next;
4905 else
4906 /* If its prev pointer is nil, it must be at the front of
4907 one or the other! */
4908 abort ();
4910 else
4911 XSCROLL_BAR (bar->prev)->next = bar->next;
4913 if (! NILP (bar->next))
4914 XSCROLL_BAR (bar->next)->prev = bar->prev;
4916 bar->next = FRAME_SCROLL_BARS (f);
4917 bar->prev = Qnil;
4918 XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
4919 if (! NILP (bar->next))
4920 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
4923 /* Remove all scroll bars on FRAME that haven't been saved since the
4924 last call to `*condemn_scroll_bars_hook'. */
4926 static void
4927 XTjudge_scroll_bars (f)
4928 FRAME_PTR f;
4930 Lisp_Object bar, next;
4932 bar = FRAME_CONDEMNED_SCROLL_BARS (f);
4934 /* Clear out the condemned list now so we won't try to process any
4935 more events on the hapless scroll bars. */
4936 FRAME_CONDEMNED_SCROLL_BARS (f) = Qnil;
4938 for (; ! NILP (bar); bar = next)
4940 struct scroll_bar *b = XSCROLL_BAR (bar);
4942 x_scroll_bar_remove (b);
4944 next = b->next;
4945 b->next = b->prev = Qnil;
4948 /* Now there should be no references to the condemned scroll bars,
4949 and they should get garbage-collected. */
4953 /* Handle a mouse click on the scroll bar BAR. If *EMACS_EVENT's kind
4954 is set to something other than NO_EVENT, it is enqueued.
4956 This may be called from a signal handler, so we have to ignore GC
4957 mark bits. */
4959 static void
4960 x_scroll_bar_handle_click (bar, part_code, er, bufp)
4961 struct scroll_bar *bar;
4962 ControlPartCode part_code;
4963 EventRecord *er;
4964 struct input_event *bufp;
4966 int win_y, top_range;
4968 if (! GC_WINDOWP (bar->window))
4969 abort ();
4971 bufp->kind = SCROLL_BAR_CLICK_EVENT;
4972 bufp->frame_or_window = bar->window;
4973 bufp->arg = Qnil;
4975 bar->dragging = Qnil;
4977 switch (part_code)
4979 case kControlUpButtonPart:
4980 bufp->part = scroll_bar_up_arrow;
4981 break;
4982 case kControlDownButtonPart:
4983 bufp->part = scroll_bar_down_arrow;
4984 break;
4985 case kControlPageUpPart:
4986 bufp->part = scroll_bar_above_handle;
4987 break;
4988 case kControlPageDownPart:
4989 bufp->part = scroll_bar_below_handle;
4990 break;
4991 #if TARGET_API_MAC_CARBON
4992 default:
4993 #else
4994 case kControlIndicatorPart:
4995 #endif
4996 if (er->what == mouseDown)
4997 bar->dragging = make_number (0);
4998 XSETVECTOR (last_mouse_scroll_bar, bar);
4999 bufp->part = scroll_bar_handle;
5000 break;
5003 win_y = XINT (bufp->y) - XINT (bar->top);
5004 top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (0/*dummy*/, XINT (bar->height));
5006 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
5008 win_y -= 24;
5010 if (! NILP (bar->dragging))
5011 win_y -= XINT (bar->dragging);
5013 if (win_y < 0)
5014 win_y = 0;
5015 if (win_y > top_range)
5016 win_y = top_range;
5018 XSETINT (bufp->x, win_y);
5019 XSETINT (bufp->y, top_range);
5022 #ifndef USE_TOOLKIT_SCROLL_BARS
5024 /* Handle some mouse motion while someone is dragging the scroll bar.
5026 This may be called from a signal handler, so we have to ignore GC
5027 mark bits. */
5029 static void
5030 x_scroll_bar_note_movement (bar, y_pos, t)
5031 struct scroll_bar *bar;
5032 int y_pos;
5033 Time t;
5035 FRAME_PTR f = XFRAME (XWINDOW (bar->window)->frame);
5037 last_mouse_movement_time = t;
5039 f->mouse_moved = 1;
5040 XSETVECTOR (last_mouse_scroll_bar, bar);
5042 /* If we're dragging the bar, display it. */
5043 if (! GC_NILP (bar->dragging))
5045 /* Where should the handle be now? */
5046 int new_start = y_pos - 24;
5048 if (new_start != XINT (bar->start))
5050 int new_end = new_start + (XINT (bar->end) - XINT (bar->start));
5052 x_scroll_bar_set_handle (bar, new_start, new_end, 0);
5057 #endif /* !USE_TOOLKIT_SCROLL_BARS */
5059 /* Return information to the user about the current position of the mouse
5060 on the scroll bar. */
5062 static void
5063 x_scroll_bar_report_motion (fp, bar_window, part, x, y, time)
5064 FRAME_PTR *fp;
5065 Lisp_Object *bar_window;
5066 enum scroll_bar_part *part;
5067 Lisp_Object *x, *y;
5068 unsigned long *time;
5070 struct scroll_bar *bar = XSCROLL_BAR (last_mouse_scroll_bar);
5071 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
5072 #if TARGET_API_MAC_CARBON
5073 WindowPtr wp = GetControlOwner (ch);
5074 #else
5075 WindowPtr wp = (*ch)->contrlOwner;
5076 #endif
5077 Point mouse_pos;
5078 struct frame *f = mac_window_to_frame (wp);
5079 int win_y, top_range;
5081 SetPortWindowPort (wp);
5083 GetMouse (&mouse_pos);
5085 win_y = mouse_pos.v - XINT (bar->top);
5086 top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, XINT (bar->height));
5088 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
5090 win_y -= 24;
5092 if (! NILP (bar->dragging))
5093 win_y -= XINT (bar->dragging);
5095 if (win_y < 0)
5096 win_y = 0;
5097 if (win_y > top_range)
5098 win_y = top_range;
5100 *fp = f;
5101 *bar_window = bar->window;
5103 if (! NILP (bar->dragging))
5104 *part = scroll_bar_handle;
5105 else if (win_y < XINT (bar->start))
5106 *part = scroll_bar_above_handle;
5107 else if (win_y < XINT (bar->end) + VERTICAL_SCROLL_BAR_MIN_HANDLE)
5108 *part = scroll_bar_handle;
5109 else
5110 *part = scroll_bar_below_handle;
5112 XSETINT (*x, win_y);
5113 XSETINT (*y, top_range);
5115 f->mouse_moved = 0;
5116 last_mouse_scroll_bar = Qnil;
5118 *time = last_mouse_movement_time;
5122 /* The screen has been cleared so we may have changed foreground or
5123 background colors, and the scroll bars may need to be redrawn.
5124 Clear out the scroll bars, and ask for expose events, so we can
5125 redraw them. */
5127 void
5128 x_scroll_bar_clear (f)
5129 FRAME_PTR f;
5131 XTcondemn_scroll_bars (f);
5132 XTjudge_scroll_bars (f);
5136 /***********************************************************************
5137 Text Cursor
5138 ***********************************************************************/
5140 /* Set clipping for output in glyph row ROW. W is the window in which
5141 we operate. GC is the graphics context to set clipping in.
5143 ROW may be a text row or, e.g., a mode line. Text rows must be
5144 clipped to the interior of the window dedicated to text display,
5145 mode lines must be clipped to the whole window. */
5147 static void
5148 x_clip_to_row (w, row, area, gc)
5149 struct window *w;
5150 struct glyph_row *row;
5151 int area;
5152 GC gc;
5154 struct frame *f = XFRAME (WINDOW_FRAME (w));
5155 Rect clip_rect;
5156 int window_x, window_y, window_width;
5158 window_box (w, area, &window_x, &window_y, &window_width, 0);
5160 clip_rect.left = window_x;
5161 clip_rect.top = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
5162 clip_rect.top = max (clip_rect.top, window_y);
5163 clip_rect.right = clip_rect.left + window_width;
5164 clip_rect.bottom = clip_rect.top + row->visible_height;
5166 mac_set_clip_rectangles (FRAME_MAC_DISPLAY (f), gc, &clip_rect, 1);
5170 /* Draw a hollow box cursor on window W in glyph row ROW. */
5172 static void
5173 x_draw_hollow_cursor (w, row)
5174 struct window *w;
5175 struct glyph_row *row;
5177 struct frame *f = XFRAME (WINDOW_FRAME (w));
5178 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
5179 Display *dpy = FRAME_MAC_DISPLAY (f);
5180 int x, y, wd, h;
5181 XGCValues xgcv;
5182 struct glyph *cursor_glyph;
5183 GC gc;
5185 /* Get the glyph the cursor is on. If we can't tell because
5186 the current matrix is invalid or such, give up. */
5187 cursor_glyph = get_phys_cursor_glyph (w);
5188 if (cursor_glyph == NULL)
5189 return;
5191 /* Compute frame-relative coordinates for phys cursor. */
5192 x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
5193 y = get_phys_cursor_geometry (w, row, cursor_glyph, &h);
5194 wd = w->phys_cursor_width;
5196 /* The foreground of cursor_gc is typically the same as the normal
5197 background color, which can cause the cursor box to be invisible. */
5198 xgcv.foreground = f->output_data.mac->cursor_pixel;
5199 if (dpyinfo->scratch_cursor_gc)
5200 XChangeGC (dpy, dpyinfo->scratch_cursor_gc, GCForeground, &xgcv);
5201 else
5202 dpyinfo->scratch_cursor_gc = XCreateGC (dpy, FRAME_MAC_WINDOW (f),
5203 GCForeground, &xgcv);
5204 gc = dpyinfo->scratch_cursor_gc;
5206 /* Set clipping, draw the rectangle, and reset clipping again. */
5207 x_clip_to_row (w, row, TEXT_AREA, gc);
5208 mac_draw_rectangle (f, gc, x, y, wd, h);
5209 mac_reset_clip_rectangles (dpy, gc);
5213 /* Draw a bar cursor on window W in glyph row ROW.
5215 Implementation note: One would like to draw a bar cursor with an
5216 angle equal to the one given by the font property XA_ITALIC_ANGLE.
5217 Unfortunately, I didn't find a font yet that has this property set.
5218 --gerd. */
5220 static void
5221 x_draw_bar_cursor (w, row, width, kind)
5222 struct window *w;
5223 struct glyph_row *row;
5224 int width;
5225 enum text_cursor_kinds kind;
5227 struct frame *f = XFRAME (w->frame);
5228 struct glyph *cursor_glyph;
5230 /* If cursor is out of bounds, don't draw garbage. This can happen
5231 in mini-buffer windows when switching between echo area glyphs
5232 and mini-buffer. */
5233 cursor_glyph = get_phys_cursor_glyph (w);
5234 if (cursor_glyph == NULL)
5235 return;
5237 /* If on an image, draw like a normal cursor. That's usually better
5238 visible than drawing a bar, esp. if the image is large so that
5239 the bar might not be in the window. */
5240 if (cursor_glyph->type == IMAGE_GLYPH)
5242 struct glyph_row *row;
5243 row = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos);
5244 draw_phys_cursor_glyph (w, row, DRAW_CURSOR);
5246 else
5248 Display *dpy = FRAME_MAC_DISPLAY (f);
5249 Window window = FRAME_MAC_WINDOW (f);
5250 GC gc = FRAME_MAC_DISPLAY_INFO (f)->scratch_cursor_gc;
5251 unsigned long mask = GCForeground | GCBackground;
5252 struct face *face = FACE_FROM_ID (f, cursor_glyph->face_id);
5253 XGCValues xgcv;
5255 /* If the glyph's background equals the color we normally draw
5256 the bar cursor in, the bar cursor in its normal color is
5257 invisible. Use the glyph's foreground color instead in this
5258 case, on the assumption that the glyph's colors are chosen so
5259 that the glyph is legible. */
5260 if (face->background == f->output_data.mac->cursor_pixel)
5261 xgcv.background = xgcv.foreground = face->foreground;
5262 else
5263 xgcv.background = xgcv.foreground = f->output_data.mac->cursor_pixel;
5265 if (gc)
5266 XChangeGC (dpy, gc, mask, &xgcv);
5267 else
5269 gc = XCreateGC (dpy, window, mask, &xgcv);
5270 FRAME_MAC_DISPLAY_INFO (f)->scratch_cursor_gc = gc;
5273 if (width < 0)
5274 width = FRAME_CURSOR_WIDTH (f);
5275 width = min (cursor_glyph->pixel_width, width);
5277 w->phys_cursor_width = width;
5278 x_clip_to_row (w, row, TEXT_AREA, gc);
5280 if (kind == BAR_CURSOR)
5281 mac_fill_rectangle (f, gc,
5282 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x),
5283 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
5284 width, row->height);
5285 else
5286 mac_fill_rectangle (f, gc,
5287 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x),
5288 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y +
5289 row->height - width),
5290 cursor_glyph->pixel_width,
5291 width);
5293 mac_reset_clip_rectangles (dpy, gc);
5298 /* RIF: Define cursor CURSOR on frame F. */
5300 static void
5301 mac_define_frame_cursor (f, cursor)
5302 struct frame *f;
5303 Cursor cursor;
5305 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
5307 if (dpyinfo->x_focus_frame == f)
5308 SetThemeCursor (cursor);
5312 /* RIF: Clear area on frame F. */
5314 static void
5315 mac_clear_frame_area (f, x, y, width, height)
5316 struct frame *f;
5317 int x, y, width, height;
5319 mac_clear_area (f, x, y, width, height);
5323 /* RIF: Draw cursor on window W. */
5325 static void
5326 mac_draw_window_cursor (w, glyph_row, x, y, cursor_type, cursor_width, on_p, active_p)
5327 struct window *w;
5328 struct glyph_row *glyph_row;
5329 int x, y;
5330 int cursor_type, cursor_width;
5331 int on_p, active_p;
5333 if (on_p)
5335 w->phys_cursor_type = cursor_type;
5336 w->phys_cursor_on_p = 1;
5338 if (glyph_row->exact_window_width_line_p
5339 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
5341 glyph_row->cursor_in_fringe_p = 1;
5342 draw_fringe_bitmap (w, glyph_row, 0);
5344 else
5345 switch (cursor_type)
5347 case HOLLOW_BOX_CURSOR:
5348 x_draw_hollow_cursor (w, glyph_row);
5349 break;
5351 case FILLED_BOX_CURSOR:
5352 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
5353 break;
5355 case BAR_CURSOR:
5356 x_draw_bar_cursor (w, glyph_row, cursor_width, BAR_CURSOR);
5357 break;
5359 case HBAR_CURSOR:
5360 x_draw_bar_cursor (w, glyph_row, cursor_width, HBAR_CURSOR);
5361 break;
5363 case NO_CURSOR:
5364 w->phys_cursor_width = 0;
5365 break;
5367 default:
5368 abort ();
5374 /* Icons. */
5376 #if 0 /* MAC_TODO: no icon support yet. */
5378 x_bitmap_icon (f, icon)
5379 struct frame *f;
5380 Lisp_Object icon;
5382 HANDLE hicon;
5384 if (FRAME_W32_WINDOW (f) == 0)
5385 return 1;
5387 if (NILP (icon))
5388 hicon = LoadIcon (hinst, EMACS_CLASS);
5389 else if (STRINGP (icon))
5390 hicon = LoadImage (NULL, (LPCTSTR) SDATA (icon), IMAGE_ICON, 0, 0,
5391 LR_DEFAULTSIZE | LR_LOADFROMFILE);
5392 else if (SYMBOLP (icon))
5394 LPCTSTR name;
5396 if (EQ (icon, intern ("application")))
5397 name = (LPCTSTR) IDI_APPLICATION;
5398 else if (EQ (icon, intern ("hand")))
5399 name = (LPCTSTR) IDI_HAND;
5400 else if (EQ (icon, intern ("question")))
5401 name = (LPCTSTR) IDI_QUESTION;
5402 else if (EQ (icon, intern ("exclamation")))
5403 name = (LPCTSTR) IDI_EXCLAMATION;
5404 else if (EQ (icon, intern ("asterisk")))
5405 name = (LPCTSTR) IDI_ASTERISK;
5406 else if (EQ (icon, intern ("winlogo")))
5407 name = (LPCTSTR) IDI_WINLOGO;
5408 else
5409 return 1;
5411 hicon = LoadIcon (NULL, name);
5413 else
5414 return 1;
5416 if (hicon == NULL)
5417 return 1;
5419 PostMessage (FRAME_W32_WINDOW (f), WM_SETICON, (WPARAM) ICON_BIG,
5420 (LPARAM) hicon);
5422 return 0;
5424 #endif /* MAC_TODO */
5426 /************************************************************************
5427 Handling X errors
5428 ************************************************************************/
5430 /* Display Error Handling functions not used on W32. Listing them here
5431 helps diff stay in step when comparing w32term.c with xterm.c.
5433 x_error_catcher (display, error)
5434 x_catch_errors (dpy)
5435 x_catch_errors_unwind (old_val)
5436 x_check_errors (dpy, format)
5437 x_had_errors_p (dpy)
5438 x_clear_errors (dpy)
5439 x_uncatch_errors (dpy, count)
5440 x_trace_wire ()
5441 x_connection_signal (signalnum)
5442 x_connection_closed (dpy, error_message)
5443 x_error_quitter (display, error)
5444 x_error_handler (display, error)
5445 x_io_error_quitter (display)
5450 /* Changing the font of the frame. */
5452 /* Give frame F the font named FONTNAME as its default font, and
5453 return the full name of that font. FONTNAME may be a wildcard
5454 pattern; in that case, we choose some font that fits the pattern.
5455 The return value shows which font we chose. */
5457 Lisp_Object
5458 x_new_font (f, fontname)
5459 struct frame *f;
5460 register char *fontname;
5462 struct font_info *fontp
5463 = FS_LOAD_FONT (f, 0, fontname, -1);
5465 if (!fontp)
5466 return Qnil;
5468 FRAME_FONT (f) = (XFontStruct *) (fontp->font);
5469 FRAME_BASELINE_OFFSET (f) = fontp->baseline_offset;
5470 FRAME_FONTSET (f) = -1;
5472 FRAME_COLUMN_WIDTH (f) = fontp->average_width;
5473 FRAME_SPACE_WIDTH (f) = fontp->space_width;
5474 FRAME_LINE_HEIGHT (f) = FONT_HEIGHT (FRAME_FONT (f));
5476 compute_fringe_widths (f, 1);
5478 /* Compute the scroll bar width in character columns. */
5479 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
5481 int wid = FRAME_COLUMN_WIDTH (f);
5482 FRAME_CONFIG_SCROLL_BAR_COLS (f)
5483 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid-1) / wid;
5485 else
5487 int wid = FRAME_COLUMN_WIDTH (f);
5488 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
5491 /* Now make the frame display the given font. */
5492 if (FRAME_MAC_WINDOW (f) != 0)
5494 XSetFont (FRAME_MAC_DISPLAY (f), f->output_data.mac->normal_gc,
5495 FRAME_FONT (f));
5496 XSetFont (FRAME_MAC_DISPLAY (f), f->output_data.mac->reverse_gc,
5497 FRAME_FONT (f));
5498 XSetFont (FRAME_MAC_DISPLAY (f), f->output_data.mac->cursor_gc,
5499 FRAME_FONT (f));
5501 /* Don't change the size of a tip frame; there's no point in
5502 doing it because it's done in Fx_show_tip, and it leads to
5503 problems because the tip frame has no widget. */
5504 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
5505 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
5508 return build_string (fontp->full_name);
5511 /* Give frame F the fontset named FONTSETNAME as its default font, and
5512 return the full name of that fontset. FONTSETNAME may be a wildcard
5513 pattern; in that case, we choose some fontset that fits the pattern.
5514 The return value shows which fontset we chose. */
5516 Lisp_Object
5517 x_new_fontset (f, fontsetname)
5518 struct frame *f;
5519 char *fontsetname;
5521 int fontset = fs_query_fontset (build_string (fontsetname), 0);
5522 Lisp_Object result;
5524 if (fontset < 0)
5525 return Qnil;
5527 if (FRAME_FONTSET (f) == fontset)
5528 /* This fontset is already set in frame F. There's nothing more
5529 to do. */
5530 return fontset_name (fontset);
5532 result = x_new_font (f, (SDATA (fontset_ascii (fontset))));
5534 if (!STRINGP (result))
5535 /* Can't load ASCII font. */
5536 return Qnil;
5538 /* Since x_new_font doesn't update any fontset information, do it now. */
5539 FRAME_FONTSET (f) = fontset;
5541 return build_string (fontsetname);
5545 /***********************************************************************
5546 TODO: W32 Input Methods
5547 ***********************************************************************/
5548 /* Listing missing functions from xterm.c helps diff stay in step.
5550 xim_destroy_callback (xim, client_data, call_data)
5551 xim_open_dpy (dpyinfo, resource_name)
5552 struct xim_inst_t
5553 xim_instantiate_callback (display, client_data, call_data)
5554 xim_initialize (dpyinfo, resource_name)
5555 xim_close_dpy (dpyinfo)
5560 void
5561 mac_get_window_bounds (f, inner, outer)
5562 struct frame *f;
5563 Rect *inner, *outer;
5565 #if TARGET_API_MAC_CARBON
5566 GetWindowBounds (FRAME_MAC_WINDOW (f), kWindowContentRgn, inner);
5567 GetWindowBounds (FRAME_MAC_WINDOW (f), kWindowStructureRgn, outer);
5568 #else /* not TARGET_API_MAC_CARBON */
5569 RgnHandle region = NewRgn ();
5571 GetWindowRegion (FRAME_MAC_WINDOW (f), kWindowContentRgn, region);
5572 *inner = (*region)->rgnBBox;
5573 GetWindowRegion (FRAME_MAC_WINDOW (f), kWindowStructureRgn, region);
5574 *outer = (*region)->rgnBBox;
5575 DisposeRgn (region);
5576 #endif /* not TARGET_API_MAC_CARBON */
5581 /* Calculate the absolute position in frame F
5582 from its current recorded position values and gravity. */
5584 void
5585 x_calc_absolute_position (f)
5586 struct frame *f;
5588 int width_diff = 0, height_diff = 0;
5589 int flags = f->size_hint_flags;
5590 Rect inner, outer;
5592 /* We have nothing to do if the current position
5593 is already for the top-left corner. */
5594 if (! ((flags & XNegative) || (flags & YNegative)))
5595 return;
5597 /* Find the offsets of the outside upper-left corner of
5598 the inner window, with respect to the outer window. */
5599 mac_get_window_bounds (f, &inner, &outer);
5601 width_diff = (outer.right - outer.left) - (inner.right - inner.left);
5602 height_diff = (outer.bottom - outer.top) - (inner.bottom - inner.top);
5604 /* Treat negative positions as relative to the leftmost bottommost
5605 position that fits on the screen. */
5606 if (flags & XNegative)
5607 f->left_pos = (FRAME_MAC_DISPLAY_INFO (f)->width
5608 - width_diff
5609 - FRAME_PIXEL_WIDTH (f)
5610 + f->left_pos);
5612 if (flags & YNegative)
5613 f->top_pos = (FRAME_MAC_DISPLAY_INFO (f)->height
5614 - height_diff
5615 - FRAME_PIXEL_HEIGHT (f)
5616 + f->top_pos);
5618 /* The left_pos and top_pos
5619 are now relative to the top and left screen edges,
5620 so the flags should correspond. */
5621 f->size_hint_flags &= ~ (XNegative | YNegative);
5624 /* CHANGE_GRAVITY is 1 when calling from Fset_frame_position,
5625 to really change the position, and 0 when calling from
5626 x_make_frame_visible (in that case, XOFF and YOFF are the current
5627 position values). It is -1 when calling from x_set_frame_parameters,
5628 which means, do adjust for borders but don't change the gravity. */
5630 void
5631 x_set_offset (f, xoff, yoff, change_gravity)
5632 struct frame *f;
5633 register int xoff, yoff;
5634 int change_gravity;
5636 if (change_gravity > 0)
5638 f->top_pos = yoff;
5639 f->left_pos = xoff;
5640 f->size_hint_flags &= ~ (XNegative | YNegative);
5641 if (xoff < 0)
5642 f->size_hint_flags |= XNegative;
5643 if (yoff < 0)
5644 f->size_hint_flags |= YNegative;
5645 f->win_gravity = NorthWestGravity;
5647 x_calc_absolute_position (f);
5649 BLOCK_INPUT;
5650 x_wm_set_size_hint (f, (long) 0, 0);
5652 #if TARGET_API_MAC_CARBON
5653 MoveWindowStructure (FRAME_MAC_WINDOW (f), f->left_pos, f->top_pos);
5654 /* If the title bar is completely outside the screen, adjust the
5655 position. */
5656 ConstrainWindowToScreen (FRAME_MAC_WINDOW (f), kWindowTitleBarRgn,
5657 kWindowConstrainMoveRegardlessOfFit
5658 | kWindowConstrainAllowPartial, NULL, NULL);
5659 x_real_positions (f, &f->left_pos, &f->top_pos);
5660 #else
5662 Rect inner, outer, screen_rect, dummy;
5663 RgnHandle region = NewRgn ();
5665 mac_get_window_bounds (f, &inner, &outer);
5666 f->x_pixels_diff = inner.left - outer.left;
5667 f->y_pixels_diff = inner.top - outer.top;
5668 MoveWindow (FRAME_MAC_WINDOW (f), f->left_pos + f->x_pixels_diff,
5669 f->top_pos + f->y_pixels_diff, false);
5671 /* If the title bar is completely outside the screen, adjust the
5672 position. The variable `outer' holds the title bar rectangle.
5673 The variable `inner' holds slightly smaller one than `outer',
5674 so that the calculation of overlapping may not become too
5675 strict. */
5676 GetWindowRegion (FRAME_MAC_WINDOW (f), kWindowTitleBarRgn, region);
5677 outer = (*region)->rgnBBox;
5678 DisposeRgn (region);
5679 inner = outer;
5680 InsetRect (&inner, 8, 8);
5681 screen_rect = qd.screenBits.bounds;
5682 screen_rect.top += GetMBarHeight ();
5684 if (!SectRect (&inner, &screen_rect, &dummy))
5686 if (inner.right <= screen_rect.left)
5687 f->left_pos = screen_rect.left;
5688 else if (inner.left >= screen_rect.right)
5689 f->left_pos = screen_rect.right - (outer.right - outer.left);
5691 if (inner.bottom <= screen_rect.top)
5692 f->top_pos = screen_rect.top;
5693 else if (inner.top >= screen_rect.bottom)
5694 f->top_pos = screen_rect.bottom - (outer.bottom - outer.top);
5696 MoveWindow (FRAME_MAC_WINDOW (f), f->left_pos + f->x_pixels_diff,
5697 f->top_pos + f->y_pixels_diff, false);
5700 #endif
5702 UNBLOCK_INPUT;
5705 /* Call this to change the size of frame F's x-window.
5706 If CHANGE_GRAVITY is 1, we change to top-left-corner window gravity
5707 for this size change and subsequent size changes.
5708 Otherwise we leave the window gravity unchanged. */
5710 void
5711 x_set_window_size (f, change_gravity, cols, rows)
5712 struct frame *f;
5713 int change_gravity;
5714 int cols, rows;
5716 int pixelwidth, pixelheight;
5718 BLOCK_INPUT;
5720 check_frame_size (f, &rows, &cols);
5721 f->scroll_bar_actual_width
5722 = FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f);
5724 compute_fringe_widths (f, 0);
5726 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols);
5727 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
5729 f->win_gravity = NorthWestGravity;
5730 x_wm_set_size_hint (f, (long) 0, 0);
5732 SizeWindow (FRAME_MAC_WINDOW (f), pixelwidth, pixelheight, 0);
5733 #if TARGET_API_MAC_CARBON
5734 if (f->output_data.mac->hourglass_control)
5735 MoveControl (f->output_data.mac->hourglass_control,
5736 pixelwidth - HOURGLASS_WIDTH, 0);
5737 #endif
5739 /* Now, strictly speaking, we can't be sure that this is accurate,
5740 but the window manager will get around to dealing with the size
5741 change request eventually, and we'll hear how it went when the
5742 ConfigureNotify event gets here.
5744 We could just not bother storing any of this information here,
5745 and let the ConfigureNotify event set everything up, but that
5746 might be kind of confusing to the Lisp code, since size changes
5747 wouldn't be reported in the frame parameters until some random
5748 point in the future when the ConfigureNotify event arrives.
5750 We pass 1 for DELAY since we can't run Lisp code inside of
5751 a BLOCK_INPUT. */
5752 change_frame_size (f, rows, cols, 0, 1, 0);
5753 FRAME_PIXEL_WIDTH (f) = pixelwidth;
5754 FRAME_PIXEL_HEIGHT (f) = pixelheight;
5756 /* We've set {FRAME,PIXEL}_{WIDTH,HEIGHT} to the values we hope to
5757 receive in the ConfigureNotify event; if we get what we asked
5758 for, then the event won't cause the screen to become garbaged, so
5759 we have to make sure to do it here. */
5760 SET_FRAME_GARBAGED (f);
5762 XFlush (FRAME_X_DISPLAY (f));
5764 /* If cursor was outside the new size, mark it as off. */
5765 mark_window_cursors_off (XWINDOW (f->root_window));
5767 /* Clear out any recollection of where the mouse highlighting was,
5768 since it might be in a place that's outside the new frame size.
5769 Actually checking whether it is outside is a pain in the neck,
5770 so don't try--just let the highlighting be done afresh with new size. */
5771 cancel_mouse_face (f);
5773 UNBLOCK_INPUT;
5776 /* Mouse warping. */
5778 void x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y);
5780 void
5781 x_set_mouse_position (f, x, y)
5782 struct frame *f;
5783 int x, y;
5785 int pix_x, pix_y;
5787 pix_x = FRAME_COL_TO_PIXEL_X (f, x) + FRAME_COLUMN_WIDTH (f) / 2;
5788 pix_y = FRAME_LINE_TO_PIXEL_Y (f, y) + FRAME_LINE_HEIGHT (f) / 2;
5790 if (pix_x < 0) pix_x = 0;
5791 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
5793 if (pix_y < 0) pix_y = 0;
5794 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
5796 x_set_mouse_pixel_position (f, pix_x, pix_y);
5799 void
5800 x_set_mouse_pixel_position (f, pix_x, pix_y)
5801 struct frame *f;
5802 int pix_x, pix_y;
5804 #if 0 /* MAC_TODO: CursorDeviceMoveTo is non-Carbon */
5805 BLOCK_INPUT;
5807 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
5808 0, 0, 0, 0, pix_x, pix_y);
5809 UNBLOCK_INPUT;
5810 #endif
5813 /* focus shifting, raising and lowering. */
5815 void
5816 x_focus_on_frame (f)
5817 struct frame *f;
5819 #if 0 /* This proves to be unpleasant. */
5820 x_raise_frame (f);
5821 #endif
5822 #if 0
5823 /* I don't think that the ICCCM allows programs to do things like this
5824 without the interaction of the window manager. Whatever you end up
5825 doing with this code, do it to x_unfocus_frame too. */
5826 XSetInputFocus (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5827 RevertToPointerRoot, CurrentTime);
5828 #endif /* ! 0 */
5831 void
5832 x_unfocus_frame (f)
5833 struct frame *f;
5837 /* Raise frame F. */
5839 void
5840 x_raise_frame (f)
5841 struct frame *f;
5843 if (f->async_visible)
5845 BLOCK_INPUT;
5846 BringToFront (FRAME_MAC_WINDOW (f));
5847 UNBLOCK_INPUT;
5851 /* Lower frame F. */
5853 void
5854 x_lower_frame (f)
5855 struct frame *f;
5857 if (f->async_visible)
5859 BLOCK_INPUT;
5860 SendBehind (FRAME_MAC_WINDOW (f), NULL);
5861 UNBLOCK_INPUT;
5865 static void
5866 XTframe_raise_lower (f, raise_flag)
5867 FRAME_PTR f;
5868 int raise_flag;
5870 if (raise_flag)
5871 x_raise_frame (f);
5872 else
5873 x_lower_frame (f);
5876 /* Change of visibility. */
5878 static void
5879 mac_handle_visibility_change (f)
5880 struct frame *f;
5882 WindowPtr wp = FRAME_MAC_WINDOW (f);
5883 int visible = 0, iconified = 0;
5884 struct input_event buf;
5886 if (IsWindowVisible (wp))
5887 if (IsWindowCollapsed (wp))
5888 iconified = 1;
5889 else
5890 visible = 1;
5892 if (!f->async_visible && visible)
5894 if (f->iconified)
5896 /* wait_reading_process_output will notice this and update
5897 the frame's display structures. If we were made
5898 invisible, we should not set garbaged, because that stops
5899 redrawing on Update events. */
5900 SET_FRAME_GARBAGED (f);
5902 EVENT_INIT (buf);
5903 buf.kind = DEICONIFY_EVENT;
5904 XSETFRAME (buf.frame_or_window, f);
5905 kbd_buffer_store_event (&buf);
5907 else if (! NILP (Vframe_list) && ! NILP (XCDR (Vframe_list)))
5908 /* Force a redisplay sooner or later to update the
5909 frame titles in case this is the second frame. */
5910 record_asynch_buffer_change ();
5912 else if (f->async_visible && !visible)
5913 if (iconified)
5915 EVENT_INIT (buf);
5916 buf.kind = ICONIFY_EVENT;
5917 XSETFRAME (buf.frame_or_window, f);
5918 kbd_buffer_store_event (&buf);
5921 f->async_visible = visible;
5922 f->async_iconified = iconified;
5925 /* This tries to wait until the frame is really visible.
5926 However, if the window manager asks the user where to position
5927 the frame, this will return before the user finishes doing that.
5928 The frame will not actually be visible at that time,
5929 but it will become visible later when the window manager
5930 finishes with it. */
5932 void
5933 x_make_frame_visible (f)
5934 struct frame *f;
5936 Lisp_Object type;
5937 int original_top, original_left;
5939 BLOCK_INPUT;
5941 if (! FRAME_VISIBLE_P (f))
5943 /* We test FRAME_GARBAGED_P here to make sure we don't
5944 call x_set_offset a second time
5945 if we get to x_make_frame_visible a second time
5946 before the window gets really visible. */
5947 if (! FRAME_ICONIFIED_P (f)
5948 && ! f->output_data.mac->asked_for_visible)
5949 #if TARGET_API_MAC_CARBON
5950 if (!(FRAME_SIZE_HINTS (f)->flags & (USPosition | PPosition)))
5952 struct frame *sf = SELECTED_FRAME ();
5953 if (!FRAME_MAC_P (sf))
5954 RepositionWindow (FRAME_MAC_WINDOW (f), NULL,
5955 kWindowCenterOnMainScreen);
5956 else
5957 RepositionWindow (FRAME_MAC_WINDOW (f),
5958 FRAME_MAC_WINDOW (sf),
5959 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
5960 kWindowCascadeStartAtParentWindowScreen
5961 #else
5962 kWindowCascadeOnParentWindowScreen
5963 #endif
5965 x_real_positions (f, &f->left_pos, &f->top_pos);
5967 else
5968 #endif
5969 x_set_offset (f, f->left_pos, f->top_pos, 0);
5971 f->output_data.mac->asked_for_visible = 1;
5973 CollapseWindow (FRAME_MAC_WINDOW (f), false);
5974 ShowWindow (FRAME_MAC_WINDOW (f));
5977 XFlush (FRAME_MAC_DISPLAY (f));
5979 /* Synchronize to ensure Emacs knows the frame is visible
5980 before we do anything else. We do this loop with input not blocked
5981 so that incoming events are handled. */
5983 Lisp_Object frame;
5984 int count;
5986 /* This must come after we set COUNT. */
5987 UNBLOCK_INPUT;
5989 XSETFRAME (frame, f);
5991 /* Wait until the frame is visible. Process X events until a
5992 MapNotify event has been seen, or until we think we won't get a
5993 MapNotify at all.. */
5994 for (count = input_signal_count + 10;
5995 input_signal_count < count && !FRAME_VISIBLE_P (f);)
5997 /* Force processing of queued events. */
5998 x_sync (f);
6000 /* Machines that do polling rather than SIGIO have been
6001 observed to go into a busy-wait here. So we'll fake an
6002 alarm signal to let the handler know that there's something
6003 to be read. We used to raise a real alarm, but it seems
6004 that the handler isn't always enabled here. This is
6005 probably a bug. */
6006 if (input_polling_used ())
6008 /* It could be confusing if a real alarm arrives while
6009 processing the fake one. Turn it off and let the
6010 handler reset it. */
6011 extern void poll_for_input_1 P_ ((void));
6012 int old_poll_suppress_count = poll_suppress_count;
6013 poll_suppress_count = 1;
6014 poll_for_input_1 ();
6015 poll_suppress_count = old_poll_suppress_count;
6018 /* See if a MapNotify event has been processed. */
6019 FRAME_SAMPLE_VISIBILITY (f);
6024 /* Change from mapped state to withdrawn state. */
6026 /* Make the frame visible (mapped and not iconified). */
6028 void
6029 x_make_frame_invisible (f)
6030 struct frame *f;
6032 /* A deactivate event does not occur when the last visible frame is
6033 made invisible. So if we clear the highlight here, it will not
6034 be rehighlighted when it is made visible. */
6035 #if 0
6036 /* Don't keep the highlight on an invisible frame. */
6037 if (FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame == f)
6038 FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame = 0;
6039 #endif
6041 BLOCK_INPUT;
6043 /* Before unmapping the window, update the WM_SIZE_HINTS property to claim
6044 that the current position of the window is user-specified, rather than
6045 program-specified, so that when the window is mapped again, it will be
6046 placed at the same location, without forcing the user to position it
6047 by hand again (they have already done that once for this window.) */
6048 x_wm_set_size_hint (f, (long) 0, 1);
6050 HideWindow (FRAME_MAC_WINDOW (f));
6052 UNBLOCK_INPUT;
6054 #if !USE_CARBON_EVENTS
6055 mac_handle_visibility_change (f);
6056 #endif
6059 /* Change window state from mapped to iconified. */
6061 void
6062 x_iconify_frame (f)
6063 struct frame *f;
6065 OSErr err;
6067 /* A deactivate event does not occur when the last visible frame is
6068 iconified. So if we clear the highlight here, it will not be
6069 rehighlighted when it is deiconified. */
6070 #if 0
6071 /* Don't keep the highlight on an invisible frame. */
6072 if (FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame == f)
6073 FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame = 0;
6074 #endif
6076 if (f->async_iconified)
6077 return;
6079 BLOCK_INPUT;
6081 FRAME_SAMPLE_VISIBILITY (f);
6083 if (! FRAME_VISIBLE_P (f))
6084 ShowWindow (FRAME_MAC_WINDOW (f));
6086 err = CollapseWindow (FRAME_MAC_WINDOW (f), true);
6088 UNBLOCK_INPUT;
6090 if (err != noErr)
6091 error ("Can't notify window manager of iconification");
6093 #if !USE_CARBON_EVENTS
6094 mac_handle_visibility_change (f);
6095 #endif
6099 /* Free X resources of frame F. */
6101 void
6102 x_free_frame_resources (f)
6103 struct frame *f;
6105 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
6106 WindowPtr wp = FRAME_MAC_WINDOW (f);
6108 BLOCK_INPUT;
6110 if (wp != tip_window)
6111 remove_window_handler (wp);
6113 DisposeWindow (wp);
6114 if (wp == tip_window)
6115 /* Neither WaitNextEvent nor ReceiveNextEvent receives `window
6116 closed' event. So we reset tip_window here. */
6117 tip_window = NULL;
6119 free_frame_menubar (f);
6121 if (FRAME_FACE_CACHE (f))
6122 free_frame_faces (f);
6124 x_free_gcs (f);
6126 if (FRAME_SIZE_HINTS (f))
6127 xfree (FRAME_SIZE_HINTS (f));
6129 xfree (f->output_data.mac);
6130 f->output_data.mac = NULL;
6132 if (f == dpyinfo->x_focus_frame)
6133 dpyinfo->x_focus_frame = 0;
6134 if (f == dpyinfo->x_focus_event_frame)
6135 dpyinfo->x_focus_event_frame = 0;
6136 if (f == dpyinfo->x_highlight_frame)
6137 dpyinfo->x_highlight_frame = 0;
6139 if (f == dpyinfo->mouse_face_mouse_frame)
6141 dpyinfo->mouse_face_beg_row
6142 = dpyinfo->mouse_face_beg_col = -1;
6143 dpyinfo->mouse_face_end_row
6144 = dpyinfo->mouse_face_end_col = -1;
6145 dpyinfo->mouse_face_window = Qnil;
6146 dpyinfo->mouse_face_deferred_gc = 0;
6147 dpyinfo->mouse_face_mouse_frame = 0;
6150 UNBLOCK_INPUT;
6154 /* Destroy the X window of frame F. */
6156 void
6157 x_destroy_window (f)
6158 struct frame *f;
6160 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
6162 x_free_frame_resources (f);
6164 dpyinfo->reference_count--;
6168 /* Setting window manager hints. */
6170 /* Set the normal size hints for the window manager, for frame F.
6171 FLAGS is the flags word to use--or 0 meaning preserve the flags
6172 that the window now has.
6173 If USER_POSITION is nonzero, we set the USPosition
6174 flag (this is useful when FLAGS is 0). */
6175 void
6176 x_wm_set_size_hint (f, flags, user_position)
6177 struct frame *f;
6178 long flags;
6179 int user_position;
6181 int base_width, base_height, width_inc, height_inc;
6182 int min_rows = 0, min_cols = 0;
6183 XSizeHints *size_hints;
6185 base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
6186 base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
6187 width_inc = FRAME_COLUMN_WIDTH (f);
6188 height_inc = FRAME_LINE_HEIGHT (f);
6190 check_frame_size (f, &min_rows, &min_cols);
6192 size_hints = FRAME_SIZE_HINTS (f);
6193 if (size_hints == NULL)
6195 size_hints = FRAME_SIZE_HINTS (f) = xmalloc (sizeof (XSizeHints));
6196 bzero (size_hints, sizeof (XSizeHints));
6199 size_hints->flags |= PResizeInc | PMinSize | PBaseSize ;
6200 size_hints->width_inc = width_inc;
6201 size_hints->height_inc = height_inc;
6202 size_hints->min_width = base_width + min_cols * width_inc;
6203 size_hints->min_height = base_height + min_rows * height_inc;
6204 size_hints->base_width = base_width;
6205 size_hints->base_height = base_height;
6207 if (flags)
6208 size_hints->flags = flags;
6209 else if (user_position)
6211 size_hints->flags &= ~ PPosition;
6212 size_hints->flags |= USPosition;
6216 #if 0 /* MAC_TODO: hide application instead of iconify? */
6217 /* Used for IconicState or NormalState */
6219 void
6220 x_wm_set_window_state (f, state)
6221 struct frame *f;
6222 int state;
6224 #ifdef USE_X_TOOLKIT
6225 Arg al[1];
6227 XtSetArg (al[0], XtNinitialState, state);
6228 XtSetValues (f->output_data.x->widget, al, 1);
6229 #else /* not USE_X_TOOLKIT */
6230 Window window = FRAME_X_WINDOW (f);
6232 f->output_data.x->wm_hints.flags |= StateHint;
6233 f->output_data.x->wm_hints.initial_state = state;
6235 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
6236 #endif /* not USE_X_TOOLKIT */
6239 void
6240 x_wm_set_icon_pixmap (f, pixmap_id)
6241 struct frame *f;
6242 int pixmap_id;
6244 Pixmap icon_pixmap;
6246 #ifndef USE_X_TOOLKIT
6247 Window window = FRAME_X_WINDOW (f);
6248 #endif
6250 if (pixmap_id > 0)
6252 icon_pixmap = x_bitmap_pixmap (f, pixmap_id);
6253 f->output_data.x->wm_hints.icon_pixmap = icon_pixmap;
6255 else
6257 /* It seems there is no way to turn off use of an icon pixmap.
6258 The following line does it, only if no icon has yet been created,
6259 for some window managers. But with mwm it crashes.
6260 Some people say it should clear the IconPixmapHint bit in this case,
6261 but that doesn't work, and the X consortium said it isn't the
6262 right thing at all. Since there is no way to win,
6263 best to explicitly give up. */
6264 #if 0
6265 f->output_data.x->wm_hints.icon_pixmap = None;
6266 #else
6267 return;
6268 #endif
6271 #ifdef USE_X_TOOLKIT /* same as in x_wm_set_window_state. */
6274 Arg al[1];
6275 XtSetArg (al[0], XtNiconPixmap, icon_pixmap);
6276 XtSetValues (f->output_data.x->widget, al, 1);
6279 #else /* not USE_X_TOOLKIT */
6281 f->output_data.x->wm_hints.flags |= IconPixmapHint;
6282 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
6284 #endif /* not USE_X_TOOLKIT */
6287 #endif /* MAC_TODO */
6289 void
6290 x_wm_set_icon_position (f, icon_x, icon_y)
6291 struct frame *f;
6292 int icon_x, icon_y;
6294 #if 0 /* MAC_TODO: no icons on Mac */
6295 #ifdef USE_X_TOOLKIT
6296 Window window = XtWindow (f->output_data.x->widget);
6297 #else
6298 Window window = FRAME_X_WINDOW (f);
6299 #endif
6301 f->output_data.x->wm_hints.flags |= IconPositionHint;
6302 f->output_data.x->wm_hints.icon_x = icon_x;
6303 f->output_data.x->wm_hints.icon_y = icon_y;
6305 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
6306 #endif /* MAC_TODO */
6310 /***********************************************************************
6311 XLFD Pattern Match
6312 ***********************************************************************/
6314 /* An XLFD pattern is divided into blocks delimited by '*'. This
6315 structure holds information for each block. */
6316 struct xlfdpat_block
6318 /* Length of the pattern string in this block. Non-zero except for
6319 the first and the last blocks. */
6320 int len;
6322 /* Pattern string except the last character in this block. The last
6323 character is replaced with NUL in order to use it as a
6324 sentinel. */
6325 unsigned char *pattern;
6327 /* Last character of the pattern string. Must not be '?'. */
6328 unsigned char last_char;
6330 /* One of the tables for the Boyer-Moore string search. It
6331 specifies the number of positions to proceed for each character
6332 with which the match fails. */
6333 int skip[256];
6335 /* The skip value for the last character in the above `skip' is
6336 assigned to `infinity' in order to simplify a loop condition.
6337 The original value is saved here. */
6338 int last_char_skip;
6341 struct xlfdpat
6343 /* Normalized pattern string. "Normalized" means that capital
6344 letters are lowered, blocks are not empty except the first and
6345 the last ones, and trailing '?'s in a block that is not the last
6346 one are moved to the next one. The last character in each block
6347 is replaced with NUL. */
6348 unsigned char *buf;
6350 /* Number of characters except '*'s and trailing '?'s in the
6351 normalized pattern string. */
6352 int nchars;
6354 /* Number of trailing '?'s in the normalized pattern string. */
6355 int trailing_anychars;
6357 /* Number of blocks and information for each block. The latter is
6358 NULL if the pattern is exact (no '*' or '?' in it). */
6359 int nblocks;
6360 struct xlfdpat_block *blocks;
6363 static void
6364 xlfdpat_destroy (pat)
6365 struct xlfdpat *pat;
6367 if (pat)
6369 if (pat->buf)
6371 if (pat->blocks)
6372 xfree (pat->blocks);
6373 xfree (pat->buf);
6375 xfree (pat);
6379 static struct xlfdpat *
6380 xlfdpat_create (pattern)
6381 char *pattern;
6383 struct xlfdpat *pat;
6384 int nblocks, i, skip;
6385 unsigned char last_char, *p, *q, *anychar_head;
6386 struct xlfdpat_block *blk;
6388 pat = xmalloc (sizeof (struct xlfdpat));
6389 if (pat == NULL)
6390 goto error;
6392 pat->buf = xmalloc (strlen (pattern) + 1);
6393 if (pat->buf == NULL)
6394 goto error;
6396 /* Normalize the pattern string and store it to `pat->buf'. */
6397 nblocks = 0;
6398 anychar_head = NULL;
6399 q = pat->buf;
6400 last_char = '\0';
6401 for (p = pattern; *p; p++)
6403 unsigned char c = *p;
6405 if (c == '*')
6406 if (last_char == '*')
6407 /* ...a** -> ...a* */
6408 continue;
6409 else
6411 if (last_char == '?')
6412 if (anychar_head > pat->buf && *(anychar_head - 1) == '*')
6413 /* ...*??* -> ...*?? */
6414 continue;
6415 else
6416 /* ...a??* -> ...a*?? */
6418 *anychar_head++ = '*';
6419 c = '?';
6421 nblocks++;
6423 else if (c == '?')
6425 if (last_char != '?')
6426 anychar_head = q;
6428 else
6429 /* On Mac OS X 10.3, tolower also converts non-ASCII
6430 characters for some locales. */
6431 if (isascii (c))
6432 c = tolower (c);
6434 *q++ = last_char = c;
6436 *q = '\0';
6437 nblocks++;
6438 pat->nblocks = nblocks;
6439 if (last_char != '?')
6440 pat->trailing_anychars = 0;
6441 else
6443 pat->trailing_anychars = q - anychar_head;
6444 q = anychar_head;
6446 pat->nchars = q - pat->buf - (nblocks - 1);
6448 if (anychar_head == NULL && nblocks == 1)
6450 /* The pattern is exact. */
6451 pat->blocks = NULL;
6452 return pat;
6455 pat->blocks = xmalloc (sizeof (struct xlfdpat_block) * nblocks);
6456 if (pat->blocks == NULL)
6457 goto error;
6459 /* Divide the normalized pattern into blocks. */
6460 p = pat->buf;
6461 for (blk = pat->blocks; blk < pat->blocks + nblocks - 1; blk++)
6463 blk->pattern = p;
6464 while (*p != '*')
6465 p++;
6466 blk->len = p - blk->pattern;
6467 p++;
6469 blk->pattern = p;
6470 blk->len = q - blk->pattern;
6472 /* Setup a table for the Boyer-Moore string search. */
6473 for (blk = pat->blocks; blk < pat->blocks + nblocks; blk++)
6474 if (blk->len != 0)
6476 blk->last_char = blk->pattern[blk->len - 1];
6477 blk->pattern[blk->len - 1] = '\0';
6479 for (skip = 1; skip < blk->len; skip++)
6480 if (blk->pattern[blk->len - skip - 1] == '?')
6481 break;
6483 for (i = 0; i < 256; i++)
6484 blk->skip[i] = skip;
6486 p = blk->pattern + (blk->len - skip);
6487 while (--skip > 0)
6488 blk->skip[*p++] = skip;
6490 blk->last_char_skip = blk->skip[blk->last_char];
6493 return pat;
6495 error:
6496 xlfdpat_destroy (pat);
6497 return NULL;
6500 static INLINE int
6501 xlfdpat_exact_p (pat)
6502 struct xlfdpat *pat;
6504 return pat->blocks == NULL;
6507 /* Return the first string in STRING + 0, ..., STRING + START_MAX such
6508 that the pattern in *BLK matches with its prefix. Return NULL
6509 there is no such strings. STRING must be lowered in advance. */
6511 static char *
6512 xlfdpat_block_match_1 (blk, string, start_max)
6513 struct xlfdpat_block *blk;
6514 unsigned char *string;
6515 int start_max;
6517 int start, infinity;
6518 unsigned char *p, *s;
6520 xassert (blk->len > 0);
6521 xassert (start_max + blk->len <= strlen (string));
6522 xassert (blk->last_char != '?');
6524 /* See the comments in the function `boyer_moore' (search.c) for the
6525 use of `infinity'. */
6526 infinity = start_max + blk->len + 1;
6527 blk->skip[blk->last_char] = infinity;
6529 start = 0;
6532 /* Check the last character of the pattern. */
6533 s = string + blk->len - 1;
6536 start += blk->skip[*(s + start)];
6538 while (start <= start_max);
6540 if (start < infinity)
6541 /* Couldn't find the last character. */
6542 return NULL;
6544 /* No less than `infinity' means we could find the last
6545 character at `s[start - infinity]'. */
6546 start -= infinity;
6548 /* Check the remaining characters. We prefer making no-'?'
6549 cases faster because the use of '?' is really rare. */
6550 p = blk->pattern;
6551 s = string + start;
6554 while (*p++ == *s++)
6557 while (*(p - 1) == '?');
6559 if (*(p - 1) == '\0')
6560 /* Matched. */
6561 return string + start;
6563 /* Didn't match. */
6564 start += blk->last_char_skip;
6566 while (start <= start_max);
6568 return NULL;
6571 #define xlfdpat_block_match(b, s, m) \
6572 ((b)->len == 1 ? memchr ((s), (b)->last_char, (m) + 1) \
6573 : xlfdpat_block_match_1 (b, s, m))
6575 /* Check if XLFD pattern PAT, which is generated by `xfldpat_create',
6576 matches with STRING. STRING must be lowered in advance. */
6578 static int
6579 xlfdpat_match (pat, string)
6580 struct xlfdpat *pat;
6581 unsigned char *string;
6583 int str_len, nblocks, i, start_max;
6584 struct xlfdpat_block *blk;
6585 unsigned char *s;
6587 xassert (pat->nblocks > 0);
6589 if (xlfdpat_exact_p (pat))
6590 return strcmp (pat->buf, string) == 0;
6592 /* The number of the characters in the string must not be smaller
6593 than that in the pattern. */
6594 str_len = strlen (string);
6595 if (str_len < pat->nchars + pat->trailing_anychars)
6596 return 0;
6598 /* Chop off the trailing '?'s. */
6599 str_len -= pat->trailing_anychars;
6601 /* The last block. When it is non-empty, it must match at the end
6602 of the string. */
6603 nblocks = pat->nblocks;
6604 blk = pat->blocks + (nblocks - 1);
6605 if (nblocks == 1)
6606 /* The last block is also the first one. */
6607 return (str_len == blk->len
6608 && (blk->len == 0 || xlfdpat_block_match (blk, string, 0)));
6609 else if (blk->len != 0)
6610 if (!xlfdpat_block_match (blk, string + (str_len - blk->len), 0))
6611 return 0;
6613 /* The first block. When it is non-empty, it must match at the
6614 beginning of the string. */
6615 blk = pat->blocks;
6616 if (blk->len != 0)
6618 s = xlfdpat_block_match (blk, string, 0);
6619 if (s == NULL)
6620 return 0;
6621 string = s + blk->len;
6624 /* The rest of the blocks. */
6625 start_max = str_len - pat->nchars;
6626 for (i = 1, blk++; i < nblocks - 1; i++, blk++)
6628 s = xlfdpat_block_match (blk, string, start_max);
6629 if (s == NULL)
6630 return 0;
6631 start_max -= s - string;
6632 string = s + blk->len;
6635 return 1;
6639 /***********************************************************************
6640 Fonts
6641 ***********************************************************************/
6643 /* Return a pointer to struct font_info of font FONT_IDX of frame F. */
6645 struct font_info *
6646 x_get_font_info (f, font_idx)
6647 FRAME_PTR f;
6648 int font_idx;
6650 return (FRAME_MAC_FONT_TABLE (f) + font_idx);
6653 /* the global font name table */
6654 static char **font_name_table = NULL;
6655 static int font_name_table_size = 0;
6656 static int font_name_count = 0;
6658 /* Alist linking font family names to Font Manager font family
6659 references (which can also be used as QuickDraw font IDs). We use
6660 an alist because hash tables are not ready when the terminal frame
6661 for Mac OS Classic is created. */
6662 static Lisp_Object fm_font_family_alist;
6663 #if USE_ATSUI
6664 /* Hash table linking font family names to ATSU font IDs. */
6665 static Lisp_Object atsu_font_id_hash;
6666 #endif
6668 /* Alist linking character set strings to Mac text encoding and Emacs
6669 coding system. */
6670 static Lisp_Object Vmac_charset_info_alist;
6672 static Lisp_Object
6673 create_text_encoding_info_alist ()
6675 Lisp_Object result = Qnil, rest;
6677 for (rest = Vmac_charset_info_alist; CONSP (rest); rest = XCDR (rest))
6679 Lisp_Object charset_info = XCAR (rest);
6680 Lisp_Object charset, coding_system, text_encoding;
6681 Lisp_Object existing_info;
6683 if (!(CONSP (charset_info)
6684 && STRINGP (charset = XCAR (charset_info))
6685 && CONSP (XCDR (charset_info))
6686 && INTEGERP (text_encoding = XCAR (XCDR (charset_info)))
6687 && CONSP (XCDR (XCDR (charset_info)))
6688 && SYMBOLP (coding_system = XCAR (XCDR (XCDR (charset_info))))))
6689 continue;
6691 existing_info = assq_no_quit (text_encoding, result);
6692 if (NILP (existing_info))
6693 result = Fcons (list3 (text_encoding, coding_system, charset),
6694 result);
6695 else
6696 if (NILP (Fmember (charset, XCDR (XCDR (existing_info)))))
6697 XSETCDR (XCDR (existing_info),
6698 Fcons (charset, XCDR (XCDR (existing_info))));
6701 return result;
6705 static void
6706 decode_mac_font_name (name, size, coding_system)
6707 char *name;
6708 int size;
6709 Lisp_Object coding_system;
6711 struct coding_system coding;
6712 char *buf, *p;
6714 if (!NILP (coding_system) && !NILP (Fcoding_system_p (coding_system)))
6716 for (p = name; *p; p++)
6717 if (!isascii (*p) || iscntrl (*p))
6718 break;
6720 if (*p)
6722 setup_coding_system (coding_system, &coding);
6723 coding.src_multibyte = 0;
6724 coding.dst_multibyte = 1;
6725 coding.mode |= CODING_MODE_LAST_BLOCK;
6726 coding.composing = COMPOSITION_DISABLED;
6727 buf = (char *) alloca (size);
6729 decode_coding (&coding, name, buf, strlen (name), size - 1);
6730 bcopy (buf, name, coding.produced);
6731 name[coding.produced] = '\0';
6735 /* If there's just one occurrence of '-' in the family name, it is
6736 replaced with '_'. (More than one occurrence of '-' means a
6737 "FOUNDRY-FAMILY-CHARSET"-style name.) */
6738 p = strchr (name, '-');
6739 if (p && strchr (p + 1, '-') == NULL)
6740 *p = '_';
6742 for (p = name; *p; p++)
6743 /* On Mac OS X 10.3, tolower also converts non-ASCII characters
6744 for some locales. */
6745 if (isascii (*p))
6746 *p = tolower (*p);
6750 static char *
6751 mac_to_x_fontname (name, size, style, charset)
6752 char *name;
6753 int size;
6754 Style style;
6755 char *charset;
6757 Str31 foundry, cs;
6758 Str255 family;
6759 char xf[256], *result;
6760 unsigned char *p;
6762 if (sscanf (name, "%31[^-]-%255[^-]-%31s", foundry, family, cs) == 3)
6763 charset = cs;
6764 else
6766 strcpy(foundry, "Apple");
6767 strcpy(family, name);
6770 sprintf (xf, "%s-%c-normal--%d-%d-%d-%d-m-%d-%s",
6771 style & bold ? "bold" : "medium", style & italic ? 'i' : 'r',
6772 size, size * 10, size ? 72 : 0, size ? 72 : 0, size * 10, charset);
6774 result = xmalloc (strlen (foundry) + strlen (family) + strlen (xf) + 3 + 1);
6775 sprintf (result, "-%s-%s-%s", foundry, family, xf);
6776 for (p = result; *p; p++)
6777 /* On Mac OS X 10.3, tolower also converts non-ASCII characters
6778 for some locales. */
6779 if (isascii (*p))
6780 *p = tolower (*p);
6781 return result;
6785 /* Parse fully-specified and instantiated X11 font spec XF, and store
6786 the results to FAMILY, *SIZE, *STYLE, and CHARSET. Return 1 if the
6787 parsing succeeded, and 0 otherwise. For FAMILY and CHARSET, the
6788 caller must allocate at least 256 and 32 bytes respectively. For
6789 ordinary Mac fonts, the value stored to FAMILY should just be their
6790 names, like "monaco", "Taipei", etc. Fonts converted from the GNU
6791 intlfonts collection contain their charset designation in their
6792 names, like "ETL-Fixed-iso8859-1", "ETL-Fixed-koi8-r", etc. Both
6793 types of font names are handled accordingly. */
6795 const int kDefaultFontSize = 12;
6797 static int
6798 parse_x_font_name (xf, family, size, style, charset)
6799 char *xf, *family;
6800 int *size;
6801 Style *style;
6802 char *charset;
6804 Str31 foundry, weight;
6805 int point_size, avgwidth;
6806 char slant[2], *p;
6808 if (sscanf (xf, "-%31[^-]-%255[^-]-%31[^-]-%1[^-]-%*[^-]-%*[^-]-%d-%d-%*[^-]-%*[^-]-%*c-%d-%31s",
6809 foundry, family, weight, slant, size,
6810 &point_size, &avgwidth, charset) != 8
6811 && sscanf (xf, "-%31[^-]-%255[^-]-%31[^-]-%1[^-]-%*[^-]--%d-%d-%*[^-]-%*[^-]-%*c-%d-%31s",
6812 foundry, family, weight, slant, size,
6813 &point_size, &avgwidth, charset) != 8)
6814 return 0;
6816 if (*size == 0)
6818 if (point_size > 0)
6819 *size = point_size / 10;
6820 else if (avgwidth > 0)
6821 *size = avgwidth / 10;
6823 if (*size == 0)
6824 *size = kDefaultFontSize;
6826 *style = normal;
6827 if (strcmp (weight, "bold") == 0)
6828 *style |= bold;
6829 if (*slant == 'i')
6830 *style |= italic;
6832 if (NILP (Fassoc (build_string (charset), Vmac_charset_info_alist)))
6834 int foundry_len = strlen (foundry), family_len = strlen (family);
6836 if (foundry_len + family_len + strlen (charset) + 2 < sizeof (Str255))
6838 /* Like sprintf (family, "%s-%s-%s", foundry, family, charset),
6839 but take overlap into account. */
6840 memmove (family + foundry_len + 1, family, family_len);
6841 memcpy (family, foundry, foundry_len);
6842 family[foundry_len] = '-';
6843 family[foundry_len + 1 + family_len] = '-';
6844 strcpy (family + foundry_len + 1 + family_len + 1, charset);
6846 else
6847 return 0;
6850 for (p = family; *p; p++)
6851 /* On Mac OS X 10.3, tolower also converts non-ASCII characters
6852 for some locales. */
6853 if (isascii (*p))
6854 *p = tolower (*p);
6856 return 1;
6860 static void
6861 add_font_name_table_entry (char *font_name)
6863 if (font_name_table_size == 0)
6865 font_name_table_size = 256;
6866 font_name_table = (char **)
6867 xmalloc (font_name_table_size * sizeof (char *));
6869 else if (font_name_count + 1 >= font_name_table_size)
6871 font_name_table_size *= 2;
6872 font_name_table = (char **)
6873 xrealloc (font_name_table,
6874 font_name_table_size * sizeof (char *));
6877 font_name_table[font_name_count++] = font_name;
6880 /* Sets up the table font_name_table to contain the list of all fonts
6881 in the system the first time the table is used so that the Resource
6882 Manager need not be accessed every time this information is
6883 needed. */
6885 static void
6886 init_font_name_table ()
6888 #if TARGET_API_MAC_CARBON
6889 FMFontFamilyIterator ffi;
6890 FMFontFamilyInstanceIterator ffii;
6891 FMFontFamily ff;
6892 Lisp_Object text_encoding_info_alist;
6893 struct gcpro gcpro1;
6895 text_encoding_info_alist = create_text_encoding_info_alist ();
6897 #if USE_ATSUI
6898 #if USE_CG_TEXT_DRAWING
6899 init_cg_text_anti_aliasing_threshold ();
6900 #endif
6901 if (!NILP (assq_no_quit (make_number (kTextEncodingMacUnicode),
6902 text_encoding_info_alist)))
6904 OSErr err;
6905 ItemCount nfonts, i;
6906 ATSUFontID *font_ids = NULL;
6907 Ptr name, prev_name = NULL;
6908 ByteCount name_len;
6910 atsu_font_id_hash =
6911 make_hash_table (Qequal, make_number (DEFAULT_HASH_SIZE),
6912 make_float (DEFAULT_REHASH_SIZE),
6913 make_float (DEFAULT_REHASH_THRESHOLD),
6914 Qnil, Qnil, Qnil);;
6915 err = ATSUFontCount (&nfonts);
6916 if (err == noErr)
6917 font_ids = xmalloc (sizeof (ATSUFontID) * nfonts);
6918 if (font_ids)
6919 err = ATSUGetFontIDs (font_ids, nfonts, NULL);
6920 if (err == noErr)
6921 for (i = 0; i < nfonts; i++)
6923 err = ATSUFindFontName (font_ids[i], kFontFamilyName,
6924 kFontMacintoshPlatform, kFontNoScript,
6925 kFontNoLanguage, 0, NULL, &name_len, NULL);
6926 if (err != noErr)
6927 continue;
6928 name = xmalloc (name_len + 1);
6929 if (name == NULL)
6930 continue;
6931 name[name_len] = '\0';
6932 err = ATSUFindFontName (font_ids[i], kFontFamilyName,
6933 kFontMacintoshPlatform, kFontNoScript,
6934 kFontNoLanguage, name_len, name,
6935 NULL, NULL);
6936 if (err == noErr)
6937 decode_mac_font_name (name, name_len + 1, Qnil);
6938 if (err == noErr
6939 && *name != '.'
6940 && (prev_name == NULL
6941 || strcmp (name, prev_name) != 0))
6943 static char *cs = "iso10646-1";
6945 add_font_name_table_entry (mac_to_x_fontname (name, 0,
6946 normal, cs));
6947 add_font_name_table_entry (mac_to_x_fontname (name, 0,
6948 italic, cs));
6949 add_font_name_table_entry (mac_to_x_fontname (name, 0,
6950 bold, cs));
6951 add_font_name_table_entry (mac_to_x_fontname (name, 0,
6952 italic | bold, cs));
6953 Fputhash (make_unibyte_string (name, name_len),
6954 long_to_cons (font_ids[i]), atsu_font_id_hash);
6955 xfree (prev_name);
6956 prev_name = name;
6958 else
6959 xfree (name);
6961 if (prev_name)
6962 xfree (prev_name);
6963 if (font_ids)
6964 xfree (font_ids);
6966 #endif
6968 /* Create a dummy instance iterator here to avoid creating and
6969 destroying it in the loop. */
6970 if (FMCreateFontFamilyInstanceIterator (0, &ffii) != noErr)
6971 return;
6972 /* Create an iterator to enumerate the font families. */
6973 if (FMCreateFontFamilyIterator (NULL, NULL, kFMDefaultOptions, &ffi)
6974 != noErr)
6976 FMDisposeFontFamilyInstanceIterator (&ffii);
6977 return;
6980 GCPRO1 (text_encoding_info_alist);
6982 while (FMGetNextFontFamily (&ffi, &ff) == noErr)
6984 Str255 name;
6985 FMFont font;
6986 FMFontStyle style;
6987 FMFontSize size;
6988 TextEncoding encoding;
6989 TextEncodingBase sc;
6990 Lisp_Object text_encoding_info;
6992 if (FMGetFontFamilyName (ff, name) != noErr)
6993 break;
6994 p2cstr (name);
6995 if (*name == '.')
6996 continue;
6998 if (FMGetFontFamilyTextEncoding (ff, &encoding) != noErr)
6999 break;
7000 sc = GetTextEncodingBase (encoding);
7001 text_encoding_info = assq_no_quit (make_number (sc),
7002 text_encoding_info_alist);
7003 if (NILP (text_encoding_info))
7004 text_encoding_info = assq_no_quit (make_number (kTextEncodingMacRoman),
7005 text_encoding_info_alist);
7006 decode_mac_font_name (name, sizeof (name),
7007 XCAR (XCDR (text_encoding_info)));
7008 fm_font_family_alist = Fcons (Fcons (build_string (name),
7009 make_number (ff)),
7010 fm_font_family_alist);
7012 /* Point the instance iterator at the current font family. */
7013 if (FMResetFontFamilyInstanceIterator (ff, &ffii) != noErr)
7014 break;
7016 while (FMGetNextFontFamilyInstance (&ffii, &font, &style, &size)
7017 == noErr)
7019 Lisp_Object rest = XCDR (XCDR (text_encoding_info));
7021 if (size > 0 || style == normal)
7022 for (; !NILP (rest); rest = XCDR (rest))
7024 char *cs = SDATA (XCAR (rest));
7026 if (size == 0)
7028 add_font_name_table_entry (mac_to_x_fontname (name, size,
7029 style, cs));
7030 add_font_name_table_entry (mac_to_x_fontname (name, size,
7031 italic, cs));
7032 add_font_name_table_entry (mac_to_x_fontname (name, size,
7033 bold, cs));
7034 add_font_name_table_entry (mac_to_x_fontname (name, size,
7035 italic | bold,
7036 cs));
7038 else
7040 add_font_name_table_entry (mac_to_x_fontname (name, size,
7041 style, cs));
7047 UNGCPRO;
7049 /* Dispose of the iterators. */
7050 FMDisposeFontFamilyIterator (&ffi);
7051 FMDisposeFontFamilyInstanceIterator (&ffii);
7052 #else /* !TARGET_API_MAC_CARBON */
7053 GrafPtr port;
7054 SInt16 fontnum, old_fontnum;
7055 int num_mac_fonts = CountResources('FOND');
7056 int i, j;
7057 Handle font_handle, font_handle_2;
7058 short id, scriptcode;
7059 ResType type;
7060 Str255 name;
7061 struct FontAssoc *fat;
7062 struct AsscEntry *assc_entry;
7063 Lisp_Object text_encoding_info_alist, text_encoding_info;
7064 struct gcpro gcpro1;
7066 GetPort (&port); /* save the current font number used */
7067 old_fontnum = port->txFont;
7069 text_encoding_info_alist = create_text_encoding_info_alist ();
7071 GCPRO1 (text_encoding_info_alist);
7073 for (i = 1; i <= num_mac_fonts; i++) /* get all available fonts */
7075 font_handle = GetIndResource ('FOND', i);
7076 if (!font_handle)
7077 continue;
7079 GetResInfo (font_handle, &id, &type, name);
7080 GetFNum (name, &fontnum);
7081 p2cstr (name);
7082 if (fontnum == 0)
7083 continue;
7085 TextFont (fontnum);
7086 scriptcode = FontToScript (fontnum);
7087 text_encoding_info = assq_no_quit (make_number (scriptcode),
7088 text_encoding_info_alist);
7089 if (NILP (text_encoding_info))
7090 text_encoding_info = assq_no_quit (make_number (smRoman),
7091 text_encoding_info_alist);
7092 decode_mac_font_name (name, sizeof (name),
7093 XCAR (XCDR (text_encoding_info)));
7094 fm_font_family_alist = Fcons (Fcons (build_string (name),
7095 make_number (fontnum)),
7096 fm_font_family_alist);
7099 HLock (font_handle);
7101 if (GetResourceSizeOnDisk (font_handle)
7102 >= sizeof (struct FamRec))
7104 fat = (struct FontAssoc *) (*font_handle
7105 + sizeof (struct FamRec));
7106 assc_entry
7107 = (struct AsscEntry *) (*font_handle
7108 + sizeof (struct FamRec)
7109 + sizeof (struct FontAssoc));
7111 for (j = 0; j <= fat->numAssoc; j++, assc_entry++)
7113 Lisp_Object rest = XCDR (XCDR (text_encoding_info));
7115 for (; !NILP (rest); rest = XCDR (rest))
7117 char *cs = SDATA (XCAR (rest));
7119 add_font_name_table_entry (mac_to_x_fontname (name,
7120 assc_entry->fontSize,
7121 assc_entry->fontStyle,
7122 cs));
7127 HUnlock (font_handle);
7128 font_handle_2 = GetNextFOND (font_handle);
7129 ReleaseResource (font_handle);
7130 font_handle = font_handle_2;
7132 while (ResError () == noErr && font_handle);
7135 UNGCPRO;
7137 TextFont (old_fontnum);
7138 #endif /* !TARGET_API_MAC_CARBON */
7142 void
7143 mac_clear_font_name_table ()
7145 int i;
7147 for (i = 0; i < font_name_count; i++)
7148 xfree (font_name_table[i]);
7149 xfree (font_name_table);
7150 font_name_table = NULL;
7151 font_name_table_size = font_name_count = 0;
7152 fm_font_family_alist = Qnil;
7156 enum xlfd_scalable_field_index
7158 XLFD_SCL_PIXEL_SIZE,
7159 XLFD_SCL_POINT_SIZE,
7160 XLFD_SCL_AVGWIDTH,
7161 XLFD_SCL_LAST
7164 static int xlfd_scalable_fields[] =
7166 6, /* PIXEL_SIZE */
7167 7, /* POINT_SIZE */
7168 11, /* AVGWIDTH */
7172 static Lisp_Object
7173 mac_do_list_fonts (pattern, maxnames)
7174 char *pattern;
7175 int maxnames;
7177 int i, n_fonts = 0;
7178 Lisp_Object font_list = Qnil;
7179 struct xlfdpat *pat;
7180 char *scaled, *ptr;
7181 int scl_val[XLFD_SCL_LAST], *field, *val;
7182 int exact;
7184 if (font_name_table == NULL) /* Initialize when first used. */
7185 init_font_name_table ();
7187 for (i = 0; i < XLFD_SCL_LAST; i++)
7188 scl_val[i] = -1;
7190 /* If the pattern contains 14 dashes and one of PIXEL_SIZE,
7191 POINT_SIZE, and AVGWIDTH fields is explicitly specified, scalable
7192 fonts are scaled according to the specified size. */
7193 ptr = pattern;
7194 i = 0;
7195 field = xlfd_scalable_fields;
7196 val = scl_val;
7197 if (*ptr == '-')
7200 ptr++;
7201 if (i == *field)
7203 if ('0' <= *ptr && *ptr <= '9')
7205 *val = *ptr++ - '0';
7206 while ('0' <= *ptr && *ptr <= '9' && *val < 10000)
7207 *val = *val * 10 + *ptr++ - '0';
7208 if (*ptr != '-')
7209 *val = -1;
7211 field++;
7212 val++;
7214 ptr = strchr (ptr, '-');
7215 i++;
7217 while (ptr && i < 14);
7219 if (i == 14 && ptr == NULL)
7221 if (scl_val[XLFD_SCL_PIXEL_SIZE] < 0)
7222 scl_val[XLFD_SCL_PIXEL_SIZE] =
7223 (scl_val[XLFD_SCL_POINT_SIZE] > 0 ? scl_val[XLFD_SCL_POINT_SIZE] / 10
7224 : (scl_val[XLFD_SCL_AVGWIDTH] > 0 ? scl_val[XLFD_SCL_AVGWIDTH] / 10
7225 : -1));
7226 if (scl_val[XLFD_SCL_POINT_SIZE] < 0)
7227 scl_val[XLFD_SCL_POINT_SIZE] =
7228 (scl_val[XLFD_SCL_PIXEL_SIZE] > 0 ? scl_val[XLFD_SCL_PIXEL_SIZE] * 10
7229 : (scl_val[XLFD_SCL_AVGWIDTH] > 0 ? scl_val[XLFD_SCL_AVGWIDTH]
7230 : -1));
7231 if (scl_val[XLFD_SCL_AVGWIDTH] < 0)
7232 scl_val[XLFD_SCL_AVGWIDTH] =
7233 (scl_val[XLFD_SCL_PIXEL_SIZE] > 0 ? scl_val[XLFD_SCL_PIXEL_SIZE] * 10
7234 : (scl_val[XLFD_SCL_POINT_SIZE] > 0 ? scl_val[XLFD_SCL_POINT_SIZE]
7235 : -1));
7237 else
7238 scl_val[XLFD_SCL_PIXEL_SIZE] = -1;
7240 pat = xlfdpat_create (pattern);
7241 if (pat == NULL)
7242 return Qnil;
7244 exact = xlfdpat_exact_p (pat);
7246 for (i = 0; i < font_name_count; i++)
7248 if (xlfdpat_match (pat, font_name_table[i]))
7250 font_list = Fcons (build_string (font_name_table[i]), font_list);
7251 if (exact || maxnames > 0 && ++n_fonts >= maxnames)
7252 break;
7254 else if (scl_val[XLFD_SCL_PIXEL_SIZE] > 0
7255 && (ptr = strstr (font_name_table[i], "-0-0-0-0-m-0-")))
7257 int former_len = ptr - font_name_table[i];
7259 scaled = xmalloc (strlen (font_name_table[i]) + 20 + 1);
7260 if (scaled == NULL)
7261 continue;
7262 memcpy (scaled, font_name_table[i], former_len);
7263 sprintf (scaled + former_len,
7264 "-%d-%d-72-72-m-%d-%s",
7265 scl_val[XLFD_SCL_PIXEL_SIZE],
7266 scl_val[XLFD_SCL_POINT_SIZE],
7267 scl_val[XLFD_SCL_AVGWIDTH],
7268 ptr + sizeof ("-0-0-0-0-m-0-") - 1);
7270 if (xlfdpat_match (pat, scaled))
7272 font_list = Fcons (build_string (scaled), font_list);
7273 xfree (scaled);
7274 if (exact || maxnames > 0 && ++n_fonts >= maxnames)
7275 break;
7277 else
7278 xfree (scaled);
7282 xlfdpat_destroy (pat);
7284 return font_list;
7287 /* Return a list of names of available fonts matching PATTERN on frame F.
7289 Frame F null means we have not yet created any frame on Mac, and
7290 consult the first display in x_display_list. MAXNAMES sets a limit
7291 on how many fonts to match. */
7293 Lisp_Object
7294 x_list_fonts (f, pattern, size, maxnames)
7295 struct frame *f;
7296 Lisp_Object pattern;
7297 int size, maxnames;
7299 Lisp_Object list = Qnil, patterns, tem, key;
7300 struct mac_display_info *dpyinfo
7301 = f ? FRAME_MAC_DISPLAY_INFO (f) : x_display_list;
7303 xassert (size <= 0);
7305 patterns = Fassoc (pattern, Valternate_fontname_alist);
7306 if (NILP (patterns))
7307 patterns = Fcons (pattern, Qnil);
7309 for (; CONSP (patterns); patterns = XCDR (patterns))
7311 pattern = XCAR (patterns);
7313 if (!STRINGP (pattern))
7314 continue;
7316 tem = XCAR (XCDR (dpyinfo->name_list_element));
7317 key = Fcons (pattern, make_number (maxnames));
7319 list = Fassoc (key, tem);
7320 if (!NILP (list))
7322 list = Fcdr_safe (list);
7323 /* We have a cashed list. Don't have to get the list again. */
7324 goto label_cached;
7327 BLOCK_INPUT;
7328 list = mac_do_list_fonts (SDATA (pattern), maxnames);
7329 UNBLOCK_INPUT;
7331 /* MAC_TODO: add code for matching outline fonts here */
7333 /* Now store the result in the cache. */
7334 XSETCAR (XCDR (dpyinfo->name_list_element),
7335 Fcons (Fcons (key, list),
7336 XCAR (XCDR (dpyinfo->name_list_element))));
7338 label_cached:
7339 if (NILP (list)) continue; /* Try the remaining alternatives. */
7342 return list;
7346 #if GLYPH_DEBUG
7348 /* Check that FONT is valid on frame F. It is if it can be found in F's
7349 font table. */
7351 static void
7352 x_check_font (f, font)
7353 struct frame *f;
7354 XFontStruct *font;
7356 int i;
7357 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
7359 xassert (font != NULL);
7361 for (i = 0; i < dpyinfo->n_fonts; i++)
7362 if (dpyinfo->font_table[i].name
7363 && font == dpyinfo->font_table[i].font)
7364 break;
7366 xassert (i < dpyinfo->n_fonts);
7369 #endif /* GLYPH_DEBUG != 0 */
7371 /* Set *W to the minimum width, *H to the minimum font height of FONT.
7372 Note: There are (broken) X fonts out there with invalid XFontStruct
7373 min_bounds contents. For example, handa@etl.go.jp reports that
7374 "-adobe-courier-medium-r-normal--*-180-*-*-m-*-iso8859-1" fonts
7375 have font->min_bounds.width == 0. */
7377 static INLINE void
7378 x_font_min_bounds (font, w, h)
7379 MacFontStruct *font;
7380 int *w, *h;
7382 *h = FONT_HEIGHT (font);
7383 *w = font->min_bounds.width;
7387 /* Compute the smallest character width and smallest font height over
7388 all fonts available on frame F. Set the members smallest_char_width
7389 and smallest_font_height in F's x_display_info structure to
7390 the values computed. Value is non-zero if smallest_font_height or
7391 smallest_char_width become smaller than they were before. */
7393 static int
7394 x_compute_min_glyph_bounds (f)
7395 struct frame *f;
7397 int i;
7398 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
7399 MacFontStruct *font;
7400 int old_width = dpyinfo->smallest_char_width;
7401 int old_height = dpyinfo->smallest_font_height;
7403 dpyinfo->smallest_font_height = 100000;
7404 dpyinfo->smallest_char_width = 100000;
7406 for (i = 0; i < dpyinfo->n_fonts; ++i)
7407 if (dpyinfo->font_table[i].name)
7409 struct font_info *fontp = dpyinfo->font_table + i;
7410 int w, h;
7412 font = (MacFontStruct *) fontp->font;
7413 xassert (font != (MacFontStruct *) ~0);
7414 x_font_min_bounds (font, &w, &h);
7416 dpyinfo->smallest_font_height = min (dpyinfo->smallest_font_height, h);
7417 dpyinfo->smallest_char_width = min (dpyinfo->smallest_char_width, w);
7420 xassert (dpyinfo->smallest_char_width > 0
7421 && dpyinfo->smallest_font_height > 0);
7423 return (dpyinfo->n_fonts == 1
7424 || dpyinfo->smallest_char_width < old_width
7425 || dpyinfo->smallest_font_height < old_height);
7429 /* Determine whether given string is a fully-specified XLFD: all 14
7430 fields are present, none is '*'. */
7432 static int
7433 is_fully_specified_xlfd (char *p)
7435 int i;
7436 char *q;
7438 if (*p != '-')
7439 return 0;
7441 for (i = 0; i < 13; i++)
7443 q = strchr (p + 1, '-');
7444 if (q == NULL)
7445 return 0;
7446 if (q - p == 2 && *(p + 1) == '*')
7447 return 0;
7448 p = q;
7451 if (strchr (p + 1, '-') != NULL)
7452 return 0;
7454 if (*(p + 1) == '*' && *(p + 2) == '\0')
7455 return 0;
7457 return 1;
7461 /* XLoadQueryFont creates and returns an internal representation for a
7462 font in a MacFontStruct struct. There is really no concept
7463 corresponding to "loading" a font on the Mac. But we check its
7464 existence and find the font number and all other information for it
7465 and store them in the returned MacFontStruct. */
7467 static MacFontStruct *
7468 XLoadQueryFont (Display *dpy, char *fontname)
7470 int size;
7471 char *name;
7472 Str255 family;
7473 Str31 charset;
7474 SInt16 fontnum;
7475 #if USE_ATSUI
7476 static ATSUFontID font_id;
7477 ATSUStyle mac_style = NULL;
7478 #endif
7479 Style fontface;
7480 #if TARGET_API_MAC_CARBON
7481 TextEncoding encoding;
7482 int scriptcode;
7483 #else
7484 short scriptcode;
7485 #endif
7486 MacFontStruct *font;
7487 XCharStruct *space_bounds = NULL, *pcm;
7489 if (is_fully_specified_xlfd (fontname))
7490 name = fontname;
7491 else
7493 Lisp_Object matched_fonts;
7495 matched_fonts = mac_do_list_fonts (fontname, 1);
7496 if (NILP (matched_fonts))
7497 return NULL;
7498 name = SDATA (XCAR (matched_fonts));
7501 if (parse_x_font_name (name, family, &size, &fontface, charset) == 0)
7502 return NULL;
7504 #if USE_ATSUI
7505 if (strcmp (charset, "iso10646-1") == 0) /* XXX */
7507 OSErr err;
7508 ATSUAttributeTag tags[] = {kATSUFontTag, kATSUSizeTag,
7509 kATSUQDBoldfaceTag, kATSUQDItalicTag};
7510 ByteCount sizes[] = {sizeof (ATSUFontID), sizeof (Fixed),
7511 sizeof (Boolean), sizeof (Boolean)};
7512 static Fixed size_fixed;
7513 static Boolean bold_p, italic_p;
7514 ATSUAttributeValuePtr values[] = {&font_id, &size_fixed,
7515 &bold_p, &italic_p};
7516 ATSUFontFeatureType types[] = {kAllTypographicFeaturesType,
7517 kDiacriticsType};
7518 ATSUFontFeatureSelector selectors[] = {kAllTypeFeaturesOffSelector,
7519 kDecomposeDiacriticsSelector};
7520 Lisp_Object font_id_cons;
7522 font_id_cons = Fgethash (make_unibyte_string (family, strlen (family)),
7523 atsu_font_id_hash, Qnil);
7524 if (NILP (font_id_cons))
7525 return NULL;
7526 font_id = cons_to_long (font_id_cons);
7527 size_fixed = Long2Fix (size);
7528 bold_p = (fontface & bold) != 0;
7529 italic_p = (fontface & italic) != 0;
7530 err = ATSUCreateStyle (&mac_style);
7531 if (err != noErr)
7532 return NULL;
7533 err = ATSUSetFontFeatures (mac_style, sizeof (types) / sizeof (types[0]),
7534 types, selectors);
7535 if (err != noErr)
7536 return NULL;
7537 err = ATSUSetAttributes (mac_style, sizeof (tags) / sizeof (tags[0]),
7538 tags, sizes, values);
7539 fontnum = -1;
7540 scriptcode = kTextEncodingMacUnicode;
7542 else
7543 #endif
7545 Lisp_Object tmp = Fassoc (build_string (family), fm_font_family_alist);
7547 if (NILP (tmp))
7548 return NULL;
7549 fontnum = XINT (XCDR (tmp));
7550 #if TARGET_API_MAC_CARBON
7551 if (FMGetFontFamilyTextEncoding (fontnum, &encoding) != noErr)
7552 return NULL;
7553 scriptcode = GetTextEncodingBase (encoding);
7554 #else
7555 scriptcode = FontToScript (fontnum);
7556 #endif
7559 font = (MacFontStruct *) xmalloc (sizeof (struct MacFontStruct));
7561 font->mac_fontnum = fontnum;
7562 font->mac_fontsize = size;
7563 font->mac_fontface = fontface;
7564 font->mac_scriptcode = scriptcode;
7565 #if USE_ATSUI
7566 font->mac_style = mac_style;
7567 #if USE_CG_TEXT_DRAWING
7568 font->cg_font = NULL;
7569 font->cg_glyphs = NULL;
7570 #endif
7571 #endif
7573 /* Apple Japanese (SJIS) font is listed as both
7574 "*-jisx0208.1983-sjis" (Japanese script) and "*-jisx0201.1976-0"
7575 (Roman script) in init_font_name_table (). The latter should be
7576 treated as a one-byte font. */
7577 if (scriptcode == smJapanese && strcmp (charset, "jisx0201.1976-0") == 0)
7578 font->mac_scriptcode = smRoman;
7580 font->full_name = mac_to_x_fontname (family, size, fontface, charset);
7582 #if USE_ATSUI
7583 if (font->mac_style)
7585 OSErr err;
7586 UniChar c;
7588 font->min_byte1 = 0;
7589 font->max_byte1 = 0xff;
7590 font->min_char_or_byte2 = 0;
7591 font->max_char_or_byte2 = 0xff;
7593 font->bounds.rows = xmalloc (sizeof (XCharStructRow *) * 0x100);
7594 if (font->bounds.rows == NULL)
7596 mac_unload_font (&one_mac_display_info, font);
7597 return NULL;
7599 bzero (font->bounds.rows, sizeof (XCharStructRow *) * 0x100);
7600 font->bounds.rows[0] = xmalloc (sizeof (XCharStructRow));
7601 if (font->bounds.rows[0] == NULL)
7603 mac_unload_font (&one_mac_display_info, font);
7604 return NULL;
7606 bzero (font->bounds.rows[0], sizeof (XCharStructRow));
7608 #if USE_CG_TEXT_DRAWING
7610 FMFontFamily font_family;
7611 FMFontStyle style;
7612 ATSFontRef ats_font;
7614 err = FMGetFontFamilyInstanceFromFont (font_id, &font_family, &style);
7615 if (err == noErr)
7616 err = FMGetFontFromFontFamilyInstance (font_family, fontface,
7617 &font_id, &style);
7618 /* Use CG text drawing if italic/bold is not synthesized. */
7619 if (err == noErr && style == fontface)
7621 ats_font = FMGetATSFontRefFromFont (font_id);
7622 font->cg_font = CGFontCreateWithPlatformFont (&ats_font);
7626 if (font->cg_font)
7627 font->cg_glyphs = xmalloc (sizeof (CGGlyph) * 0x100);
7628 if (font->cg_glyphs)
7629 bzero (font->cg_glyphs, sizeof (CGGlyph) * 0x100);
7630 #endif
7631 space_bounds = font->bounds.rows[0]->per_char + 0x20;
7632 err = mac_query_char_extents (font->mac_style, 0x20,
7633 &font->ascent, &font->descent,
7634 space_bounds,
7635 #if USE_CG_TEXT_DRAWING
7636 (font->cg_glyphs ? font->cg_glyphs + 0x20
7637 : NULL)
7638 #else
7639 NULL
7640 #endif
7642 if (err != noErr)
7644 mac_unload_font (&one_mac_display_info, font);
7645 return NULL;
7647 XCHARSTRUCTROW_SET_CHAR_VALID (font->bounds.rows[0], 0x20);
7649 pcm = font->bounds.rows[0]->per_char;
7650 for (c = 0x21; c <= 0xff; c++)
7652 if (c == 0xad)
7653 /* Soft hyphen is not supported in ATSUI. */
7654 continue;
7655 else if (c == 0x7f)
7657 c = 0x9f;
7658 continue;
7661 mac_query_char_extents (font->mac_style, c, NULL, NULL, pcm + c,
7662 #if USE_CG_TEXT_DRAWING
7663 (font->cg_glyphs ? font->cg_glyphs + c
7664 : NULL)
7665 #else
7666 NULL
7667 #endif
7669 XCHARSTRUCTROW_SET_CHAR_VALID (font->bounds.rows[0], c);
7671 #if USE_CG_TEXT_DRAWING
7672 if (font->cg_glyphs && font->cg_glyphs[c] == 0)
7674 /* Don't use CG text drawing if font substitution occurs in
7675 ASCII or Latin-1 characters. */
7676 CGFontRelease (font->cg_font);
7677 font->cg_font = NULL;
7678 xfree (font->cg_glyphs);
7679 font->cg_glyphs = NULL;
7681 #endif
7684 else
7685 #endif
7687 GrafPtr port;
7688 SInt16 old_fontnum, old_fontsize;
7689 Style old_fontface;
7690 FontInfo the_fontinfo;
7691 int is_two_byte_font;
7693 /* Save the current font number used. */
7694 GetPort (&port);
7695 #if TARGET_API_MAC_CARBON
7696 old_fontnum = GetPortTextFont (port);
7697 old_fontsize = GetPortTextSize (port);
7698 old_fontface = GetPortTextFace (port);
7699 #else
7700 old_fontnum = port->txFont;
7701 old_fontsize = port->txSize;
7702 old_fontface = port->txFace;
7703 #endif
7705 TextFont (fontnum);
7706 TextSize (size);
7707 TextFace (fontface);
7709 GetFontInfo (&the_fontinfo);
7711 font->ascent = the_fontinfo.ascent;
7712 font->descent = the_fontinfo.descent;
7714 is_two_byte_font = (font->mac_scriptcode == smJapanese
7715 || font->mac_scriptcode == smTradChinese
7716 || font->mac_scriptcode == smSimpChinese
7717 || font->mac_scriptcode == smKorean);
7719 if (is_two_byte_font)
7721 int char_width;
7723 font->min_byte1 = 0xa1;
7724 font->max_byte1 = 0xfe;
7725 font->min_char_or_byte2 = 0xa1;
7726 font->max_char_or_byte2 = 0xfe;
7728 /* Use the width of an "ideographic space" of that font
7729 because the_fontinfo.widMax returns the wrong width for
7730 some fonts. */
7731 switch (font->mac_scriptcode)
7733 case smJapanese:
7734 font->min_byte1 = 0x81;
7735 font->max_byte1 = 0xfc;
7736 font->min_char_or_byte2 = 0x40;
7737 font->max_char_or_byte2 = 0xfc;
7738 char_width = StringWidth("\p\x81\x40");
7739 break;
7740 case smTradChinese:
7741 font->min_char_or_byte2 = 0x40;
7742 char_width = StringWidth("\p\xa1\x40");
7743 break;
7744 case smSimpChinese:
7745 char_width = StringWidth("\p\xa1\xa1");
7746 break;
7747 case smKorean:
7748 char_width = StringWidth("\p\xa1\xa1");
7749 break;
7752 font->bounds.per_char = NULL;
7754 if (fontface & italic)
7755 font->max_bounds.rbearing = char_width + 1;
7756 else
7757 font->max_bounds.rbearing = char_width;
7758 font->max_bounds.lbearing = 0;
7759 font->max_bounds.width = char_width;
7760 font->max_bounds.ascent = the_fontinfo.ascent;
7761 font->max_bounds.descent = the_fontinfo.descent;
7763 font->min_bounds = font->max_bounds;
7765 else
7767 int c;
7769 font->min_byte1 = font->max_byte1 = 0;
7770 font->min_char_or_byte2 = 0x20;
7771 font->max_char_or_byte2 = 0xff;
7773 font->bounds.per_char =
7774 xmalloc (sizeof (XCharStruct) * (0xff - 0x20 + 1));
7775 if (font->bounds.per_char == NULL)
7777 mac_unload_font (&one_mac_display_info, font);
7778 return NULL;
7780 bzero (font->bounds.per_char,
7781 sizeof (XCharStruct) * (0xff - 0x20 + 1));
7783 space_bounds = font->bounds.per_char;
7784 mac_query_char_extents (NULL, 0x20, &font->ascent, &font->descent,
7785 space_bounds, NULL);
7787 for (c = 0x21, pcm = space_bounds + 1; c <= 0xff; c++, pcm++)
7788 mac_query_char_extents (NULL, c, NULL, NULL, pcm, NULL);
7791 /* Restore previous font number, size and face. */
7792 TextFont (old_fontnum);
7793 TextSize (old_fontsize);
7794 TextFace (old_fontface);
7797 if (space_bounds)
7799 int c;
7801 font->min_bounds = font->max_bounds = *space_bounds;
7802 for (c = 0x21, pcm = space_bounds + 1; c <= 0x7f; c++, pcm++)
7803 if (pcm->width > 0)
7805 font->min_bounds.lbearing = min (font->min_bounds.lbearing,
7806 pcm->lbearing);
7807 font->min_bounds.rbearing = min (font->min_bounds.rbearing,
7808 pcm->rbearing);
7809 font->min_bounds.width = min (font->min_bounds.width,
7810 pcm->width);
7811 font->min_bounds.ascent = min (font->min_bounds.ascent,
7812 pcm->ascent);
7814 font->max_bounds.lbearing = max (font->max_bounds.lbearing,
7815 pcm->lbearing);
7816 font->max_bounds.rbearing = max (font->max_bounds.rbearing,
7817 pcm->rbearing);
7818 font->max_bounds.width = max (font->max_bounds.width,
7819 pcm->width);
7820 font->max_bounds.ascent = max (font->max_bounds.ascent,
7821 pcm->ascent);
7823 if (
7824 #if USE_ATSUI
7825 font->mac_style == NULL &&
7826 #endif
7827 font->max_bounds.width == font->min_bounds.width
7828 && font->min_bounds.lbearing >= 0
7829 && font->max_bounds.rbearing <= font->max_bounds.width)
7831 /* Fixed width and no overhangs. */
7832 xfree (font->bounds.per_char);
7833 font->bounds.per_char = NULL;
7837 #if !defined (MAC_OS8) || USE_ATSUI
7838 /* AppKit and WebKit do some adjustment to the heights of Courier,
7839 Helvetica, and Times. This only works on the environments where
7840 the XDrawImageString counterpart is never used. */
7841 if (strcmp (family, "courier") == 0 || strcmp (family, "helvetica") == 0
7842 || strcmp (family, "times") == 0)
7843 font->ascent += (font->ascent + font->descent) * .15 + 0.5;
7844 #endif
7846 return font;
7850 void
7851 mac_unload_font (dpyinfo, font)
7852 struct mac_display_info *dpyinfo;
7853 XFontStruct *font;
7855 xfree (font->full_name);
7856 #if USE_ATSUI
7857 if (font->mac_style)
7859 int i;
7861 for (i = font->min_byte1; i <= font->max_byte1; i++)
7862 if (font->bounds.rows[i])
7863 xfree (font->bounds.rows[i]);
7864 xfree (font->bounds.rows);
7865 ATSUDisposeStyle (font->mac_style);
7867 else
7868 #endif
7869 if (font->bounds.per_char)
7870 xfree (font->bounds.per_char);
7871 #if USE_CG_TEXT_DRAWING
7872 if (font->cg_font)
7873 CGFontRelease (font->cg_font);
7874 if (font->cg_glyphs)
7875 xfree (font->cg_glyphs);
7876 #endif
7877 xfree (font);
7881 /* Load font named FONTNAME of the size SIZE for frame F, and return a
7882 pointer to the structure font_info while allocating it dynamically.
7883 If SIZE is 0, load any size of font.
7884 If loading is failed, return NULL. */
7886 struct font_info *
7887 x_load_font (f, fontname, size)
7888 struct frame *f;
7889 register char *fontname;
7890 int size;
7892 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
7893 Lisp_Object font_names;
7895 /* Get a list of all the fonts that match this name. Once we
7896 have a list of matching fonts, we compare them against the fonts
7897 we already have by comparing names. */
7898 font_names = x_list_fonts (f, build_string (fontname), size, 1);
7900 if (!NILP (font_names))
7902 Lisp_Object tail;
7903 int i;
7905 for (i = 0; i < dpyinfo->n_fonts; i++)
7906 for (tail = font_names; CONSP (tail); tail = XCDR (tail))
7907 if (dpyinfo->font_table[i].name
7908 && (!strcmp (dpyinfo->font_table[i].name,
7909 SDATA (XCAR (tail)))
7910 || !strcmp (dpyinfo->font_table[i].full_name,
7911 SDATA (XCAR (tail)))))
7912 return (dpyinfo->font_table + i);
7914 else
7915 return NULL;
7917 /* Load the font and add it to the table. */
7919 char *full_name;
7920 struct MacFontStruct *font;
7921 struct font_info *fontp;
7922 unsigned long value;
7923 int i;
7925 fontname = (char *) SDATA (XCAR (font_names));
7927 BLOCK_INPUT;
7928 font = (MacFontStruct *) XLoadQueryFont (FRAME_MAC_DISPLAY (f), fontname);
7929 UNBLOCK_INPUT;
7930 if (!font)
7931 return NULL;
7933 /* Find a free slot in the font table. */
7934 for (i = 0; i < dpyinfo->n_fonts; ++i)
7935 if (dpyinfo->font_table[i].name == NULL)
7936 break;
7938 /* If no free slot found, maybe enlarge the font table. */
7939 if (i == dpyinfo->n_fonts
7940 && dpyinfo->n_fonts == dpyinfo->font_table_size)
7942 int sz;
7943 dpyinfo->font_table_size = max (16, 2 * dpyinfo->font_table_size);
7944 sz = dpyinfo->font_table_size * sizeof *dpyinfo->font_table;
7945 dpyinfo->font_table
7946 = (struct font_info *) xrealloc (dpyinfo->font_table, sz);
7949 fontp = dpyinfo->font_table + i;
7950 if (i == dpyinfo->n_fonts)
7951 ++dpyinfo->n_fonts;
7953 /* Now fill in the slots of *FONTP. */
7954 BLOCK_INPUT;
7955 bzero (fontp, sizeof (*fontp));
7956 fontp->font = font;
7957 fontp->font_idx = i;
7958 fontp->name = (char *) xmalloc (strlen (fontname) + 1);
7959 bcopy (fontname, fontp->name, strlen (fontname) + 1);
7961 if (font->min_bounds.width == font->max_bounds.width)
7963 /* Fixed width font. */
7964 fontp->average_width = fontp->space_width = font->min_bounds.width;
7966 else
7968 XChar2b char2b;
7969 XCharStruct *pcm;
7971 char2b.byte1 = 0x00, char2b.byte2 = 0x20;
7972 pcm = mac_per_char_metric (font, &char2b, 0);
7973 if (pcm)
7974 fontp->space_width = pcm->width;
7975 else
7976 fontp->space_width = FONT_WIDTH (font);
7978 if (pcm)
7980 int width = pcm->width;
7981 for (char2b.byte2 = 33; char2b.byte2 <= 126; char2b.byte2++)
7982 if ((pcm = mac_per_char_metric (font, &char2b, 0)) != NULL)
7983 width += pcm->width;
7984 fontp->average_width = width / 95;
7986 else
7987 fontp->average_width = FONT_WIDTH (font);
7990 fontp->full_name = (char *) xmalloc (strlen (font->full_name) + 1);
7991 bcopy (font->full_name, fontp->full_name, strlen (font->full_name) + 1);
7993 fontp->size = font->max_bounds.width;
7994 fontp->height = FONT_HEIGHT (font);
7996 /* For some font, ascent and descent in max_bounds field is
7997 larger than the above value. */
7998 int max_height = font->max_bounds.ascent + font->max_bounds.descent;
7999 if (max_height > fontp->height)
8000 fontp->height = max_height;
8003 /* The slot `encoding' specifies how to map a character
8004 code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
8005 the font code-points (0:0x20..0x7F, 1:0xA0..0xFF), or
8006 (0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF,
8007 2:0xA020..0xFF7F). For the moment, we don't know which charset
8008 uses this font. So, we set information in fontp->encoding[1]
8009 which is never used by any charset. If mapping can't be
8010 decided, set FONT_ENCODING_NOT_DECIDED. */
8011 if (font->mac_scriptcode == smJapanese)
8012 fontp->encoding[1] = 4;
8013 else
8015 fontp->encoding[1]
8016 = (font->max_byte1 == 0
8017 /* 1-byte font */
8018 ? (font->min_char_or_byte2 < 0x80
8019 ? (font->max_char_or_byte2 < 0x80
8020 ? 0 /* 0x20..0x7F */
8021 : FONT_ENCODING_NOT_DECIDED) /* 0x20..0xFF */
8022 : 1) /* 0xA0..0xFF */
8023 /* 2-byte font */
8024 : (font->min_byte1 < 0x80
8025 ? (font->max_byte1 < 0x80
8026 ? (font->min_char_or_byte2 < 0x80
8027 ? (font->max_char_or_byte2 < 0x80
8028 ? 0 /* 0x2020..0x7F7F */
8029 : FONT_ENCODING_NOT_DECIDED) /* 0x2020..0x7FFF */
8030 : 3) /* 0x20A0..0x7FFF */
8031 : FONT_ENCODING_NOT_DECIDED) /* 0x20??..0xA0?? */
8032 : (font->min_char_or_byte2 < 0x80
8033 ? (font->max_char_or_byte2 < 0x80
8034 ? 2 /* 0xA020..0xFF7F */
8035 : FONT_ENCODING_NOT_DECIDED) /* 0xA020..0xFFFF */
8036 : 1))); /* 0xA0A0..0xFFFF */
8039 #if 0 /* MAC_TODO: fill these out with more reasonably values */
8040 fontp->baseline_offset
8041 = (XGetFontProperty (font, dpyinfo->Xatom_MULE_BASELINE_OFFSET, &value)
8042 ? (long) value : 0);
8043 fontp->relative_compose
8044 = (XGetFontProperty (font, dpyinfo->Xatom_MULE_RELATIVE_COMPOSE, &value)
8045 ? (long) value : 0);
8046 fontp->default_ascent
8047 = (XGetFontProperty (font, dpyinfo->Xatom_MULE_DEFAULT_ASCENT, &value)
8048 ? (long) value : 0);
8049 #else
8050 fontp->baseline_offset = 0;
8051 fontp->relative_compose = 0;
8052 fontp->default_ascent = 0;
8053 #endif
8055 /* Set global flag fonts_changed_p to non-zero if the font loaded
8056 has a character with a smaller width than any other character
8057 before, or if the font loaded has a smaller height than any
8058 other font loaded before. If this happens, it will make a
8059 glyph matrix reallocation necessary. */
8060 fonts_changed_p |= x_compute_min_glyph_bounds (f);
8061 UNBLOCK_INPUT;
8062 return fontp;
8067 /* Return a pointer to struct font_info of a font named FONTNAME for
8068 frame F. If no such font is loaded, return NULL. */
8070 struct font_info *
8071 x_query_font (f, fontname)
8072 struct frame *f;
8073 register char *fontname;
8075 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
8076 int i;
8078 for (i = 0; i < dpyinfo->n_fonts; i++)
8079 if (dpyinfo->font_table[i].name
8080 && (!strcmp (dpyinfo->font_table[i].name, fontname)
8081 || !strcmp (dpyinfo->font_table[i].full_name, fontname)))
8082 return (dpyinfo->font_table + i);
8083 return NULL;
8087 /* Find a CCL program for a font specified by FONTP, and set the member
8088 `encoder' of the structure. */
8090 void
8091 x_find_ccl_program (fontp)
8092 struct font_info *fontp;
8094 Lisp_Object list, elt;
8096 for (list = Vfont_ccl_encoder_alist; CONSP (list); list = XCDR (list))
8098 elt = XCAR (list);
8099 if (CONSP (elt)
8100 && STRINGP (XCAR (elt))
8101 && (fast_c_string_match_ignore_case (XCAR (elt), fontp->name)
8102 >= 0))
8103 break;
8105 if (! NILP (list))
8107 struct ccl_program *ccl
8108 = (struct ccl_program *) xmalloc (sizeof (struct ccl_program));
8110 if (setup_ccl_program (ccl, XCDR (elt)) < 0)
8111 xfree (ccl);
8112 else
8113 fontp->font_encoder = ccl;
8119 /* The Mac Event loop code */
8121 #if !TARGET_API_MAC_CARBON
8122 #include <Events.h>
8123 #include <Quickdraw.h>
8124 #include <Balloons.h>
8125 #include <Devices.h>
8126 #include <Fonts.h>
8127 #include <Gestalt.h>
8128 #include <Menus.h>
8129 #include <Processes.h>
8130 #include <Sound.h>
8131 #include <ToolUtils.h>
8132 #include <TextUtils.h>
8133 #include <Dialogs.h>
8134 #include <Script.h>
8135 #include <Types.h>
8136 #include <Resources.h>
8138 #if __MWERKS__
8139 #include <unix.h>
8140 #endif
8141 #endif /* ! TARGET_API_MAC_CARBON */
8143 #define M_APPLE 128
8144 #define I_ABOUT 1
8146 #define WINDOW_RESOURCE 128
8147 #define TERM_WINDOW_RESOURCE 129
8149 #define DEFAULT_NUM_COLS 80
8151 #define MIN_DOC_SIZE 64
8152 #define MAX_DOC_SIZE 32767
8154 #define EXTRA_STACK_ALLOC (256 * 1024)
8156 #define ARGV_STRING_LIST_ID 129
8157 #define ABOUT_ALERT_ID 128
8158 #define RAM_TOO_LARGE_ALERT_ID 129
8160 /* Contains the string "reverse", which is a constant for mouse button emu.*/
8161 Lisp_Object Qreverse;
8164 /* Modifier associated with the control key, or nil to ignore. */
8165 Lisp_Object Vmac_control_modifier;
8167 /* Modifier associated with the option key, or nil to ignore. */
8168 Lisp_Object Vmac_option_modifier;
8170 /* Modifier associated with the command key, or nil to ignore. */
8171 Lisp_Object Vmac_command_modifier;
8173 /* Modifier associated with the function key, or nil to ignore. */
8174 Lisp_Object Vmac_function_modifier;
8176 /* True if the option and command modifiers should be used to emulate
8177 a three button mouse */
8178 Lisp_Object Vmac_emulate_three_button_mouse;
8180 #if USE_CARBON_EVENTS
8181 /* Non-zero if the mouse wheel button (i.e. button 4) should map to
8182 mouse-2, instead of mouse-3. */
8183 int mac_wheel_button_is_mouse_2;
8185 /* If non-zero, the Mac "Command" key is passed on to the Mac Toolbox
8186 for processing before Emacs sees it. */
8187 int mac_pass_command_to_system;
8189 /* If non-zero, the Mac "Control" key is passed on to the Mac Toolbox
8190 for processing before Emacs sees it. */
8191 int mac_pass_control_to_system;
8192 #endif
8194 /* Points to the variable `inev' in the function XTread_socket. It is
8195 used for passing an input event to the function back from
8196 Carbon/Apple event handlers. */
8197 static struct input_event *read_socket_inev = NULL;
8199 Point saved_menu_event_location;
8201 /* Apple Events */
8202 #if USE_CARBON_EVENTS
8203 static Lisp_Object Qhicommand;
8204 #endif
8205 extern int mac_ready_for_apple_events;
8206 extern Lisp_Object Qundefined;
8207 extern void init_apple_event_handler P_ ((void));
8208 extern void mac_find_apple_event_spec P_ ((AEEventClass, AEEventID,
8209 Lisp_Object *, Lisp_Object *,
8210 Lisp_Object *));
8211 extern OSErr init_coercion_handler P_ ((void));
8213 #if TARGET_API_MAC_CARBON
8214 /* Drag and Drop */
8215 static pascal OSErr mac_do_track_drag (DragTrackingMessage, WindowPtr, void*, DragReference);
8216 static pascal OSErr mac_do_receive_drag (WindowPtr, void*, DragReference);
8217 static DragTrackingHandlerUPP mac_do_track_dragUPP = NULL;
8218 static DragReceiveHandlerUPP mac_do_receive_dragUPP = NULL;
8219 #endif
8221 #if USE_CARBON_EVENTS
8222 #ifdef MAC_OSX
8223 extern void init_service_handler ();
8224 static Lisp_Object Qservices, Qpaste, Qperform;
8225 #endif
8226 /* Window Event Handler */
8227 static pascal OSStatus mac_handle_window_event (EventHandlerCallRef,
8228 EventRef, void *);
8229 #endif
8230 OSErr install_window_handler (WindowPtr);
8232 extern void init_emacs_passwd_dir ();
8233 extern int emacs_main (int, char **, char **);
8235 extern void initialize_applescript();
8236 extern void terminate_applescript();
8238 static unsigned int
8239 #if USE_CARBON_EVENTS
8240 mac_to_emacs_modifiers (UInt32 mods)
8241 #else
8242 mac_to_emacs_modifiers (EventModifiers mods)
8243 #endif
8245 unsigned int result = 0;
8246 if (mods & shiftKey)
8247 result |= shift_modifier;
8249 /* Deactivated to simplify configuration:
8250 if Vmac_option_modifier is non-NIL, we fully process the Option
8251 key. Otherwise, we only process it if an additional Ctrl or Command
8252 is pressed. That way the system may convert the character to a
8253 composed one.
8254 if ((mods & optionKey) &&
8255 (( !NILP(Vmac_option_modifier) ||
8256 ((mods & cmdKey) || (mods & controlKey))))) */
8258 if (!NILP (Vmac_option_modifier) && (mods & optionKey)) {
8259 Lisp_Object val = Fget(Vmac_option_modifier, Qmodifier_value);
8260 if (INTEGERP(val))
8261 result |= XUINT(val);
8263 if (!NILP (Vmac_command_modifier) && (mods & cmdKey)) {
8264 Lisp_Object val = Fget(Vmac_command_modifier, Qmodifier_value);
8265 if (INTEGERP(val))
8266 result |= XUINT(val);
8268 if (!NILP (Vmac_control_modifier) && (mods & controlKey)) {
8269 Lisp_Object val = Fget(Vmac_control_modifier, Qmodifier_value);
8270 if (INTEGERP(val))
8271 result |= XUINT(val);
8274 #ifdef MAC_OSX
8275 if (!NILP (Vmac_function_modifier) && (mods & kEventKeyModifierFnMask)) {
8276 Lisp_Object val = Fget(Vmac_function_modifier, Qmodifier_value);
8277 if (INTEGERP(val))
8278 result |= XUINT(val);
8280 #endif
8282 return result;
8285 static int
8286 mac_get_emulated_btn ( UInt32 modifiers )
8288 int result = 0;
8289 if (!NILP (Vmac_emulate_three_button_mouse)) {
8290 int cmdIs3 = !EQ (Vmac_emulate_three_button_mouse, Qreverse);
8291 if (modifiers & cmdKey)
8292 result = cmdIs3 ? 2 : 1;
8293 else if (modifiers & optionKey)
8294 result = cmdIs3 ? 1 : 2;
8296 return result;
8299 #if USE_CARBON_EVENTS
8300 /* Obtains the event modifiers from the event ref and then calls
8301 mac_to_emacs_modifiers. */
8302 static UInt32
8303 mac_event_to_emacs_modifiers (EventRef eventRef)
8305 UInt32 mods = 0;
8306 GetEventParameter (eventRef, kEventParamKeyModifiers, typeUInt32, NULL,
8307 sizeof (UInt32), NULL, &mods);
8308 if (!NILP (Vmac_emulate_three_button_mouse) &&
8309 GetEventClass(eventRef) == kEventClassMouse)
8311 mods &= ~(optionKey | cmdKey);
8313 return mac_to_emacs_modifiers (mods);
8316 /* Given an event ref, return the code to use for the mouse button
8317 code in the emacs input_event. */
8318 static int
8319 mac_get_mouse_btn (EventRef ref)
8321 EventMouseButton result = kEventMouseButtonPrimary;
8322 GetEventParameter (ref, kEventParamMouseButton, typeMouseButton, NULL,
8323 sizeof (EventMouseButton), NULL, &result);
8324 switch (result)
8326 case kEventMouseButtonPrimary:
8327 if (NILP (Vmac_emulate_three_button_mouse))
8328 return 0;
8329 else {
8330 UInt32 mods = 0;
8331 GetEventParameter (ref, kEventParamKeyModifiers, typeUInt32, NULL,
8332 sizeof (UInt32), NULL, &mods);
8333 return mac_get_emulated_btn(mods);
8335 case kEventMouseButtonSecondary:
8336 return mac_wheel_button_is_mouse_2 ? 2 : 1;
8337 case kEventMouseButtonTertiary:
8338 case 4: /* 4 is the number for the mouse wheel button */
8339 return mac_wheel_button_is_mouse_2 ? 1 : 2;
8340 default:
8341 return 0;
8345 /* Normally, ConvertEventRefToEventRecord will correctly handle all
8346 events. However the click of the mouse wheel is not converted to a
8347 mouseDown or mouseUp event. Likewise for dead key down events.
8348 This calls ConvertEventRef, but then checks to see if it is a mouse
8349 up/down, or a dead key down carbon event that has not been
8350 converted, and if so, converts it by hand (to be picked up in the
8351 XTread_socket loop). */
8352 static Boolean mac_convert_event_ref (EventRef eventRef, EventRecord *eventRec)
8354 Boolean result = ConvertEventRefToEventRecord (eventRef, eventRec);
8356 if (result)
8357 return result;
8359 switch (GetEventClass (eventRef))
8361 case kEventClassMouse:
8362 switch (GetEventKind (eventRef))
8364 case kEventMouseDown:
8365 eventRec->what = mouseDown;
8366 result = 1;
8367 break;
8369 case kEventMouseUp:
8370 eventRec->what = mouseUp;
8371 result = 1;
8372 break;
8374 default:
8375 break;
8377 break;
8379 case kEventClassKeyboard:
8380 switch (GetEventKind (eventRef))
8382 case kEventRawKeyDown:
8384 unsigned char char_codes;
8385 UInt32 key_code;
8387 eventRec->what = keyDown;
8388 GetEventParameter (eventRef, kEventParamKeyMacCharCodes, typeChar,
8389 NULL, sizeof (char), NULL, &char_codes);
8390 GetEventParameter (eventRef, kEventParamKeyCode, typeUInt32,
8391 NULL, sizeof (UInt32), NULL, &key_code);
8392 eventRec->message = char_codes | ((key_code & 0xff) << 8);
8393 result = 1;
8395 break;
8397 default:
8398 break;
8400 break;
8402 default:
8403 break;
8406 if (result)
8408 /* Need where and when. */
8409 UInt32 mods;
8411 GetEventParameter (eventRef, kEventParamMouseLocation, typeQDPoint,
8412 NULL, sizeof (Point), NULL, &eventRec->where);
8413 /* Use two step process because new event modifiers are 32-bit
8414 and old are 16-bit. Currently, only loss is NumLock & Fn. */
8415 GetEventParameter (eventRef, kEventParamKeyModifiers, typeUInt32,
8416 NULL, sizeof (UInt32), NULL, &mods);
8417 eventRec->modifiers = mods;
8419 eventRec->when = EventTimeToTicks (GetEventTime (eventRef));
8422 return result;
8425 #endif
8427 static void
8428 do_get_menus (void)
8430 Handle menubar_handle;
8431 MenuHandle menu_handle;
8433 menubar_handle = GetNewMBar (128);
8434 if(menubar_handle == NULL)
8435 abort ();
8436 SetMenuBar (menubar_handle);
8437 DrawMenuBar ();
8439 #if !TARGET_API_MAC_CARBON
8440 menu_handle = GetMenuHandle (M_APPLE);
8441 if(menu_handle != NULL)
8442 AppendResMenu (menu_handle,'DRVR');
8443 else
8444 abort ();
8445 #endif
8449 static void
8450 do_init_managers (void)
8452 #if !TARGET_API_MAC_CARBON
8453 InitGraf (&qd.thePort);
8454 InitFonts ();
8455 FlushEvents (everyEvent, 0);
8456 InitWindows ();
8457 InitMenus ();
8458 TEInit ();
8459 InitDialogs (NULL);
8460 #endif /* !TARGET_API_MAC_CARBON */
8461 InitCursor ();
8463 #if !TARGET_API_MAC_CARBON
8464 /* set up some extra stack space for use by emacs */
8465 SetApplLimit ((Ptr) ((long) GetApplLimit () - EXTRA_STACK_ALLOC));
8467 /* MaxApplZone must be called for AppleScript to execute more
8468 complicated scripts */
8469 MaxApplZone ();
8470 MoreMasters ();
8471 #endif /* !TARGET_API_MAC_CARBON */
8474 static void
8475 do_check_ram_size (void)
8477 SInt32 physical_ram_size, logical_ram_size;
8479 if (Gestalt (gestaltPhysicalRAMSize, &physical_ram_size) != noErr
8480 || Gestalt (gestaltLogicalRAMSize, &logical_ram_size) != noErr
8481 || physical_ram_size > (1 << VALBITS)
8482 || logical_ram_size > (1 << VALBITS))
8484 StopAlert (RAM_TOO_LARGE_ALERT_ID, NULL);
8485 exit (1);
8489 static void
8490 do_window_update (WindowPtr win)
8492 struct frame *f = mac_window_to_frame (win);
8494 BeginUpdate (win);
8496 /* The tooltip has been drawn already. Avoid the SET_FRAME_GARBAGED
8497 below. */
8498 if (win != tip_window)
8500 if (f->async_visible == 0)
8502 /* Update events may occur when a frame gets iconified. */
8503 #if 0
8504 f->async_visible = 1;
8505 f->async_iconified = 0;
8506 SET_FRAME_GARBAGED (f);
8507 #endif
8509 else
8511 Rect r;
8512 #if TARGET_API_MAC_CARBON
8513 RgnHandle region = NewRgn ();
8515 GetPortVisibleRegion (GetWindowPort (win), region);
8516 GetRegionBounds (region, &r);
8517 expose_frame (f, r.left, r.top, r.right - r.left, r.bottom - r.top);
8518 UpdateControls (win, region);
8519 DisposeRgn (region);
8520 #else
8521 r = (*win->visRgn)->rgnBBox;
8522 expose_frame (f, r.left, r.top, r.right - r.left, r.bottom - r.top);
8523 UpdateControls (win, win->visRgn);
8524 #endif
8528 EndUpdate (win);
8531 static int
8532 is_emacs_window (WindowPtr win)
8534 Lisp_Object tail, frame;
8536 if (!win)
8537 return 0;
8539 FOR_EACH_FRAME (tail, frame)
8540 if (FRAME_MAC_P (XFRAME (frame)))
8541 if (FRAME_MAC_WINDOW (XFRAME (frame)) == win)
8542 return 1;
8544 return 0;
8547 static void
8548 do_app_resume ()
8550 /* Window-activate events will do the job. */
8553 static void
8554 do_app_suspend ()
8556 /* Window-deactivate events will do the job. */
8560 static void
8561 do_apple_menu (SInt16 menu_item)
8563 #if !TARGET_API_MAC_CARBON
8564 Str255 item_name;
8565 SInt16 da_driver_refnum;
8567 if (menu_item == I_ABOUT)
8568 NoteAlert (ABOUT_ALERT_ID, NULL);
8569 else
8571 GetMenuItemText (GetMenuHandle (M_APPLE), menu_item, item_name);
8572 da_driver_refnum = OpenDeskAcc (item_name);
8574 #endif /* !TARGET_API_MAC_CARBON */
8577 void
8578 do_menu_choice (SInt32 menu_choice)
8580 SInt16 menu_id, menu_item;
8582 menu_id = HiWord (menu_choice);
8583 menu_item = LoWord (menu_choice);
8585 switch (menu_id)
8587 case 0:
8588 break;
8590 case M_APPLE:
8591 do_apple_menu (menu_item);
8592 break;
8594 default:
8596 struct frame *f = mac_focus_frame (&one_mac_display_info);
8597 MenuHandle menu = GetMenuHandle (menu_id);
8598 if (menu)
8600 UInt32 refcon;
8602 GetMenuItemRefCon (menu, menu_item, &refcon);
8603 menubar_selection_callback (f, refcon);
8608 HiliteMenu (0);
8612 /* Handle drags in size box. Based on code contributed by Ben
8613 Mesander and IM - Window Manager A. */
8615 static void
8616 do_grow_window (WindowPtr w, EventRecord *e)
8618 Rect limit_rect;
8619 int rows, columns, width, height;
8620 struct frame *f = mac_window_to_frame (w);
8621 XSizeHints *size_hints = FRAME_SIZE_HINTS (f);
8622 int min_width = MIN_DOC_SIZE, min_height = MIN_DOC_SIZE;
8623 #if TARGET_API_MAC_CARBON
8624 Rect new_rect;
8625 #else
8626 long grow_size;
8627 #endif
8629 if (size_hints->flags & PMinSize)
8631 min_width = size_hints->min_width;
8632 min_height = size_hints->min_height;
8634 SetRect (&limit_rect, min_width, min_height, MAX_DOC_SIZE, MAX_DOC_SIZE);
8636 #if TARGET_API_MAC_CARBON
8637 if (!ResizeWindow (w, e->where, &limit_rect, &new_rect))
8638 return;
8639 height = new_rect.bottom - new_rect.top;
8640 width = new_rect.right - new_rect.left;
8641 #else
8642 grow_size = GrowWindow (w, e->where, &limit_rect);
8643 /* see if it really changed size */
8644 if (grow_size == 0)
8645 return;
8646 height = HiWord (grow_size);
8647 width = LoWord (grow_size);
8648 #endif
8650 if (width != FRAME_PIXEL_WIDTH (f)
8651 || height != FRAME_PIXEL_HEIGHT (f))
8653 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, height);
8654 columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, width);
8656 x_set_window_size (f, 0, columns, rows);
8661 /* Handle clicks in zoom box. Calculation of "standard state" based
8662 on code in IM - Window Manager A and code contributed by Ben
8663 Mesander. The standard state of an Emacs window is 80-characters
8664 wide (DEFAULT_NUM_COLS) and as tall as will fit on the screen. */
8666 static void
8667 do_zoom_window (WindowPtr w, int zoom_in_or_out)
8669 GrafPtr save_port;
8670 Rect zoom_rect, port_rect;
8671 Point top_left;
8672 int w_title_height, columns, rows, width, height;
8673 struct frame *f = mac_window_to_frame (w);
8674 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
8676 #if TARGET_API_MAC_CARBON
8678 Point standard_size;
8680 standard_size.h = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, DEFAULT_NUM_COLS);
8681 standard_size.v = dpyinfo->height;
8683 if (IsWindowInStandardState (w, &standard_size, &zoom_rect))
8684 zoom_in_or_out = inZoomIn;
8685 else
8687 /* Adjust the standard size according to character boundaries. */
8689 columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, zoom_rect.right - zoom_rect.left);
8690 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, zoom_rect.bottom - zoom_rect.top);
8691 standard_size.h = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, columns);
8692 standard_size.v = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
8693 GetWindowBounds (w, kWindowContentRgn, &port_rect);
8694 if (IsWindowInStandardState (w, &standard_size, &zoom_rect)
8695 && port_rect.left == zoom_rect.left
8696 && port_rect.top == zoom_rect.top)
8697 zoom_in_or_out = inZoomIn;
8698 else
8699 zoom_in_or_out = inZoomOut;
8702 ZoomWindowIdeal (w, zoom_in_or_out, &standard_size);
8704 #else /* not TARGET_API_MAC_CARBON */
8705 GetPort (&save_port);
8707 SetPortWindowPort (w);
8709 /* Clear window to avoid flicker. */
8710 EraseRect (&(w->portRect));
8711 if (zoom_in_or_out == inZoomOut)
8713 SetPt (&top_left, w->portRect.left, w->portRect.top);
8714 LocalToGlobal (&top_left);
8716 /* calculate height of window's title bar */
8717 w_title_height = top_left.v - 1
8718 - (**((WindowPeek) w)->strucRgn).rgnBBox.top + GetMBarHeight ();
8720 /* get maximum height of window into zoom_rect.bottom - zoom_rect.top */
8721 zoom_rect = qd.screenBits.bounds;
8722 zoom_rect.top += w_title_height;
8723 InsetRect (&zoom_rect, 8, 4); /* not too tight */
8725 zoom_rect.right = zoom_rect.left
8726 + FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, DEFAULT_NUM_COLS);
8728 /* Adjust the standard size according to character boundaries. */
8729 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, zoom_rect.bottom - zoom_rect.top);
8730 zoom_rect.bottom =
8731 zoom_rect.top + FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
8733 (**((WStateDataHandle) ((WindowPeek) w)->dataHandle)).stdState
8734 = zoom_rect;
8737 ZoomWindow (w, zoom_in_or_out, f == mac_focus_frame (dpyinfo));
8739 SetPort (save_port);
8740 #endif /* not TARGET_API_MAC_CARBON */
8742 /* retrieve window size and update application values */
8743 #if TARGET_API_MAC_CARBON
8744 GetWindowPortBounds (w, &port_rect);
8745 #else
8746 port_rect = w->portRect;
8747 #endif
8748 height = port_rect.bottom - port_rect.top;
8749 width = port_rect.right - port_rect.left;
8751 if (width != FRAME_PIXEL_WIDTH (f)
8752 || height != FRAME_PIXEL_HEIGHT (f))
8754 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, height);
8755 columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, width);
8757 change_frame_size (f, rows, columns, 0, 1, 0);
8758 SET_FRAME_GARBAGED (f);
8759 cancel_mouse_face (f);
8761 FRAME_PIXEL_WIDTH (f) = width;
8762 FRAME_PIXEL_HEIGHT (f) = height;
8764 x_real_positions (f, &f->left_pos, &f->top_pos);
8767 OSErr
8768 mac_store_apple_event (class, id, desc)
8769 Lisp_Object class, id;
8770 const AEDesc *desc;
8772 OSErr err = noErr;
8773 struct input_event buf;
8774 AEDesc *desc_copy;
8776 desc_copy = xmalloc (sizeof (AEDesc));
8777 if (desc_copy == NULL)
8778 err = memFullErr;
8779 else
8780 err = AEDuplicateDesc (desc, desc_copy);
8781 if (err == noErr)
8783 EVENT_INIT (buf);
8785 buf.kind = MAC_APPLE_EVENT;
8786 buf.x = class;
8787 buf.y = id;
8788 buf.code = (int)desc_copy;
8789 XSETFRAME (buf.frame_or_window,
8790 mac_focus_frame (&one_mac_display_info));
8791 buf.arg = Qnil;
8792 kbd_buffer_store_event (&buf);
8795 return err;
8798 Lisp_Object
8799 mac_make_lispy_event_code (code)
8800 int code;
8802 AEDesc *desc = (AEDesc *)code;
8803 Lisp_Object obj;
8805 obj = mac_aedesc_to_lisp (desc);
8806 AEDisposeDesc (desc);
8807 xfree (desc);
8809 return obj;
8812 #if USE_CARBON_EVENTS
8813 static pascal OSStatus
8814 mac_handle_command_event (next_handler, event, data)
8815 EventHandlerCallRef next_handler;
8816 EventRef event;
8817 void *data;
8819 OSStatus result;
8820 OSErr err;
8821 HICommand command;
8822 Lisp_Object class_key, id_key, binding;
8824 result = CallNextEventHandler (next_handler, event);
8825 if (result != eventNotHandledErr)
8826 return result;
8828 GetEventParameter (event, kEventParamDirectObject, typeHICommand, NULL,
8829 sizeof (HICommand), NULL, &command);
8831 if (command.commandID == 0)
8832 return eventNotHandledErr;
8834 /* A HICommand event is mapped to an Apple event whose event class
8835 symbol is `hicommand' and event ID is its command ID. */
8836 class_key = Qhicommand;
8837 mac_find_apple_event_spec (0, command.commandID,
8838 &class_key, &id_key, &binding);
8839 if (!NILP (binding) && !EQ (binding, Qundefined))
8840 if (INTEGERP (binding))
8841 return XINT (binding);
8842 else
8844 AppleEvent apple_event;
8845 UInt32 modifiers;
8846 static EventParamName names[] = {kEventParamDirectObject,
8847 kEventParamKeyModifiers};
8848 static EventParamType types[] = {typeHICommand,
8849 typeUInt32};
8850 err = create_apple_event_from_event_ref (event, 2, names, types,
8851 &apple_event);
8852 if (err == noErr)
8854 err = mac_store_apple_event (class_key, id_key, &apple_event);
8855 AEDisposeDesc (&apple_event);
8857 if (err == noErr)
8858 return noErr;
8861 return eventNotHandledErr;
8864 static OSErr
8865 init_command_handler ()
8867 OSErr err = noErr;
8868 EventTypeSpec specs[] = {{kEventClassCommand, kEventCommandProcess}};
8869 static EventHandlerUPP handle_command_eventUPP = NULL;
8871 if (handle_command_eventUPP == NULL)
8872 handle_command_eventUPP = NewEventHandlerUPP (mac_handle_command_event);
8873 return InstallApplicationEventHandler (handle_command_eventUPP,
8874 GetEventTypeCount (specs), specs,
8875 NULL, NULL);
8878 static pascal OSStatus
8879 mac_handle_window_event (next_handler, event, data)
8880 EventHandlerCallRef next_handler;
8881 EventRef event;
8882 void *data;
8884 WindowPtr wp;
8885 OSStatus result;
8886 UInt32 attributes;
8887 XSizeHints *size_hints;
8889 GetEventParameter (event, kEventParamDirectObject, typeWindowRef,
8890 NULL, sizeof (WindowPtr), NULL, &wp);
8892 switch (GetEventKind (event))
8894 case kEventWindowUpdate:
8895 result = CallNextEventHandler (next_handler, event);
8896 if (result != eventNotHandledErr)
8897 return result;
8899 do_window_update (wp);
8900 return noErr;
8902 case kEventWindowBoundsChanging:
8903 result = CallNextEventHandler (next_handler, event);
8904 if (result != eventNotHandledErr)
8905 return result;
8907 GetEventParameter (event, kEventParamAttributes, typeUInt32,
8908 NULL, sizeof (UInt32), NULL, &attributes);
8909 size_hints = FRAME_SIZE_HINTS (mac_window_to_frame (wp));
8910 if ((attributes & kWindowBoundsChangeUserResize)
8911 && ((size_hints->flags & (PResizeInc | PBaseSize | PMinSize))
8912 == (PResizeInc | PBaseSize | PMinSize)))
8914 Rect bounds;
8915 int width, height;
8917 GetEventParameter (event, kEventParamCurrentBounds,
8918 typeQDRectangle,
8919 NULL, sizeof (Rect), NULL, &bounds);
8920 width = bounds.right - bounds.left;
8921 height = bounds.bottom - bounds.top;
8923 if (width < size_hints->min_width)
8924 width = size_hints->min_width;
8925 else
8926 width = size_hints->base_width
8927 + (int) ((width - size_hints->base_width)
8928 / (float) size_hints->width_inc + .5)
8929 * size_hints->width_inc;
8931 if (height < size_hints->min_height)
8932 height = size_hints->min_height;
8933 else
8934 height = size_hints->base_height
8935 + (int) ((height - size_hints->base_height)
8936 / (float) size_hints->height_inc + .5)
8937 * size_hints->height_inc;
8939 bounds.right = bounds.left + width;
8940 bounds.bottom = bounds.top + height;
8941 SetEventParameter (event, kEventParamCurrentBounds,
8942 typeQDRectangle, sizeof (Rect), &bounds);
8943 return noErr;
8945 break;
8947 case kEventWindowShown:
8948 case kEventWindowHidden:
8949 case kEventWindowExpanded:
8950 case kEventWindowCollapsed:
8951 result = CallNextEventHandler (next_handler, event);
8953 mac_handle_visibility_change (mac_window_to_frame (wp));
8954 return noErr;
8956 break;
8959 return eventNotHandledErr;
8962 static pascal OSStatus
8963 mac_handle_mouse_event (next_handler, event, data)
8964 EventHandlerCallRef next_handler;
8965 EventRef event;
8966 void *data;
8968 OSStatus result;
8970 switch (GetEventKind (event))
8972 case kEventMouseWheelMoved:
8974 WindowPtr wp;
8975 struct frame *f;
8976 EventMouseWheelAxis axis;
8977 SInt32 delta;
8978 Point point;
8980 result = CallNextEventHandler (next_handler, event);
8981 if (result != eventNotHandledErr || read_socket_inev == NULL)
8982 return result;
8984 GetEventParameter (event, kEventParamWindowRef, typeWindowRef,
8985 NULL, sizeof (WindowRef), NULL, &wp);
8986 f = mac_window_to_frame (wp);
8987 if (f != mac_focus_frame (&one_mac_display_info))
8988 break;
8990 GetEventParameter (event, kEventParamMouseWheelAxis,
8991 typeMouseWheelAxis, NULL,
8992 sizeof (EventMouseWheelAxis), NULL, &axis);
8993 if (axis != kEventMouseWheelAxisY)
8994 break;
8996 GetEventParameter (event, kEventParamMouseWheelDelta, typeSInt32,
8997 NULL, sizeof (SInt32), NULL, &delta);
8998 GetEventParameter (event, kEventParamMouseLocation, typeQDPoint,
8999 NULL, sizeof (Point), NULL, &point);
9000 read_socket_inev->kind = WHEEL_EVENT;
9001 read_socket_inev->code = 0;
9002 read_socket_inev->modifiers =
9003 (mac_event_to_emacs_modifiers (event)
9004 | ((delta < 0) ? down_modifier : up_modifier));
9005 SetPortWindowPort (wp);
9006 GlobalToLocal (&point);
9007 XSETINT (read_socket_inev->x, point.h);
9008 XSETINT (read_socket_inev->y, point.v);
9009 XSETFRAME (read_socket_inev->frame_or_window, f);
9011 return noErr;
9013 break;
9015 default:
9016 break;
9019 return eventNotHandledErr;
9022 #ifdef MAC_OSX
9023 OSErr
9024 mac_store_services_event (event)
9025 EventRef event;
9027 OSErr err;
9028 AppleEvent apple_event;
9029 Lisp_Object id_key;
9031 switch (GetEventKind (event))
9033 case kEventServicePaste:
9034 id_key = Qpaste;
9035 err = create_apple_event_from_event_ref (event, 0, NULL, NULL,
9036 &apple_event);
9037 break;
9039 case kEventServicePerform:
9041 static EventParamName names[] = {kEventParamServiceMessageName,
9042 kEventParamServiceUserData};
9043 static EventParamType types[] = {typeCFStringRef,
9044 typeCFStringRef};
9046 id_key = Qperform;
9047 err = create_apple_event_from_event_ref (event, 2, names, types,
9048 &apple_event);
9050 break;
9052 default:
9053 abort ();
9056 if (err == noErr)
9058 err = mac_store_apple_event (Qservices, id_key, &apple_event);
9059 AEDisposeDesc (&apple_event);
9062 return err;
9064 #endif /* MAC_OSX */
9065 #endif /* USE_CARBON_EVENTS */
9068 OSErr
9069 install_window_handler (window)
9070 WindowPtr window;
9072 OSErr err = noErr;
9073 #if USE_CARBON_EVENTS
9074 EventTypeSpec specs_window[] =
9075 {{kEventClassWindow, kEventWindowUpdate},
9076 {kEventClassWindow, kEventWindowBoundsChanging},
9077 {kEventClassWindow, kEventWindowShown},
9078 {kEventClassWindow, kEventWindowHidden},
9079 {kEventClassWindow, kEventWindowExpanded},
9080 {kEventClassWindow, kEventWindowCollapsed}};
9081 EventTypeSpec specs_mouse[] = {{kEventClassMouse, kEventMouseWheelMoved}};
9082 static EventHandlerUPP handle_window_eventUPP = NULL;
9083 static EventHandlerUPP handle_mouse_eventUPP = NULL;
9085 if (handle_window_eventUPP == NULL)
9086 handle_window_eventUPP = NewEventHandlerUPP (mac_handle_window_event);
9087 if (handle_mouse_eventUPP == NULL)
9088 handle_mouse_eventUPP = NewEventHandlerUPP (mac_handle_mouse_event);
9089 err = InstallWindowEventHandler (window, handle_window_eventUPP,
9090 GetEventTypeCount (specs_window),
9091 specs_window, NULL, NULL);
9092 if (err == noErr)
9093 err = InstallWindowEventHandler (window, handle_mouse_eventUPP,
9094 GetEventTypeCount (specs_mouse),
9095 specs_mouse, NULL, NULL);
9096 #endif
9097 #if TARGET_API_MAC_CARBON
9098 if (mac_do_track_dragUPP == NULL)
9099 mac_do_track_dragUPP = NewDragTrackingHandlerUPP (mac_do_track_drag);
9100 if (mac_do_receive_dragUPP == NULL)
9101 mac_do_receive_dragUPP = NewDragReceiveHandlerUPP (mac_do_receive_drag);
9103 if (err == noErr)
9104 err = InstallTrackingHandler (mac_do_track_dragUPP, window, NULL);
9105 if (err == noErr)
9106 err = InstallReceiveHandler (mac_do_receive_dragUPP, window, NULL);
9107 #endif
9108 return err;
9111 void
9112 remove_window_handler (window)
9113 WindowPtr window;
9115 #if TARGET_API_MAC_CARBON
9116 if (mac_do_track_dragUPP)
9117 RemoveTrackingHandler (mac_do_track_dragUPP, window);
9118 if (mac_do_receive_dragUPP)
9119 RemoveReceiveHandler (mac_do_receive_dragUPP, window);
9120 #endif
9123 #if TARGET_API_MAC_CARBON
9124 static pascal OSErr
9125 mac_do_track_drag (DragTrackingMessage message, WindowPtr window,
9126 void *handlerRefCon, DragReference theDrag)
9128 static int can_accept;
9129 short items;
9130 short index;
9131 ItemReference theItem;
9132 FlavorFlags theFlags;
9133 OSErr result;
9135 if (GetFrontWindowOfClass (kMovableModalWindowClass, false))
9136 return dragNotAcceptedErr;
9138 switch (message)
9140 case kDragTrackingEnterHandler:
9141 CountDragItems (theDrag, &items);
9142 can_accept = 0;
9143 for (index = 1; index <= items; index++)
9145 GetDragItemReferenceNumber (theDrag, index, &theItem);
9146 result = GetFlavorFlags (theDrag, theItem, flavorTypeHFS, &theFlags);
9147 if (result == noErr)
9149 can_accept = 1;
9150 break;
9153 break;
9155 case kDragTrackingEnterWindow:
9156 if (can_accept)
9158 RgnHandle hilite_rgn = NewRgn ();
9159 Rect r;
9160 struct frame *f = mac_window_to_frame (window);
9162 GetWindowPortBounds (window, &r);
9163 OffsetRect (&r, -r.left, -r.top);
9164 RectRgn (hilite_rgn, &r);
9165 ShowDragHilite (theDrag, hilite_rgn, true);
9166 DisposeRgn (hilite_rgn);
9167 SetThemeCursor (kThemeCopyArrowCursor);
9169 break;
9171 case kDragTrackingInWindow:
9172 break;
9174 case kDragTrackingLeaveWindow:
9175 if (can_accept)
9177 struct frame *f = mac_window_to_frame (window);
9179 HideDragHilite (theDrag);
9180 SetThemeCursor (kThemeArrowCursor);
9182 break;
9184 case kDragTrackingLeaveHandler:
9185 break;
9188 return noErr;
9191 static pascal OSErr
9192 mac_do_receive_drag (WindowPtr window, void *handlerRefCon,
9193 DragReference theDrag)
9195 short items;
9196 short index;
9197 FlavorFlags theFlags;
9198 Point mouse;
9199 OSErr result;
9200 ItemReference theItem;
9201 HFSFlavor data;
9202 Size size = sizeof (HFSFlavor);
9203 Lisp_Object file_list;
9205 if (GetFrontWindowOfClass (kMovableModalWindowClass, false))
9206 return dragNotAcceptedErr;
9208 file_list = Qnil;
9209 GetDragMouse (theDrag, &mouse, 0L);
9210 CountDragItems (theDrag, &items);
9211 for (index = 1; index <= items; index++)
9213 /* Only handle file references. */
9214 GetDragItemReferenceNumber (theDrag, index, &theItem);
9215 result = GetFlavorFlags (theDrag, theItem, flavorTypeHFS, &theFlags);
9216 if (result == noErr)
9218 OSErr err;
9219 AEDesc desc;
9221 err = GetFlavorData (theDrag, theItem, flavorTypeHFS,
9222 &data, &size, 0L);
9223 if (err == noErr)
9224 err = AECoercePtr (typeFSS, &data.fileSpec, sizeof (FSSpec),
9225 TYPE_FILE_NAME, &desc);
9226 if (err == noErr)
9228 Lisp_Object file;
9230 /* x-dnd functions expect undecoded filenames. */
9231 file = make_uninit_string (AEGetDescDataSize (&desc));
9232 err = AEGetDescData (&desc, SDATA (file), SBYTES (file));
9233 if (err == noErr)
9234 file_list = Fcons (file, file_list);
9235 AEDisposeDesc (&desc);
9239 /* If there are items in the list, construct an event and post it to
9240 the queue like an interrupt using kbd_buffer_store_event. */
9241 if (!NILP (file_list))
9243 struct input_event event;
9244 Lisp_Object frame;
9245 struct frame *f = mac_window_to_frame (window);
9246 SInt16 modifiers;
9248 GlobalToLocal (&mouse);
9249 GetDragModifiers (theDrag, NULL, NULL, &modifiers);
9251 event.kind = DRAG_N_DROP_EVENT;
9252 event.code = 0;
9253 event.modifiers = mac_to_emacs_modifiers (modifiers);
9254 event.timestamp = TickCount () * (1000 / 60);
9255 XSETINT (event.x, mouse.h);
9256 XSETINT (event.y, mouse.v);
9257 XSETFRAME (frame, f);
9258 event.frame_or_window = frame;
9259 event.arg = file_list;
9260 /* Post to the interrupt queue */
9261 kbd_buffer_store_event (&event);
9262 /* MAC_TODO: Mimic behavior of windows by switching contexts to Emacs */
9264 ProcessSerialNumber psn;
9265 GetCurrentProcess (&psn);
9266 SetFrontProcess (&psn);
9269 return noErr;
9271 else
9272 return dragNotAcceptedErr;
9274 #endif
9277 #if __profile__
9278 void
9279 profiler_exit_proc ()
9281 ProfilerDump ("\pEmacs.prof");
9282 ProfilerTerm ();
9284 #endif
9286 /* These few functions implement Emacs as a normal Mac application
9287 (almost): set up the heap and the Toolbox, handle necessary system
9288 events plus a few simple menu events. They also set up Emacs's
9289 access to functions defined in the rest of this file. Emacs uses
9290 function hooks to perform all its terminal I/O. A complete list of
9291 these functions appear in termhooks.h. For what they do, read the
9292 comments there and see also w32term.c and xterm.c. What's
9293 noticeably missing here is the event loop, which is normally
9294 present in most Mac application. After performing the necessary
9295 Mac initializations, main passes off control to emacs_main
9296 (corresponding to main in emacs.c). Emacs_main calls XTread_socket
9297 (defined further below) to read input. This is where
9298 WaitNextEvent/ReceiveNextEvent is called to process Mac events. */
9300 #ifdef MAC_OS8
9301 #undef main
9303 main (void)
9305 #if __profile__ /* is the profiler on? */
9306 if (ProfilerInit(collectDetailed, bestTimeBase, 5000, 200))
9307 exit(1);
9308 #endif
9310 #if __MWERKS__
9311 /* set creator and type for files created by MSL */
9312 _fcreator = 'EMAx';
9313 _ftype = 'TEXT';
9314 #endif
9316 do_init_managers ();
9318 do_get_menus ();
9320 #ifndef USE_LSB_TAG
9321 do_check_ram_size ();
9322 #endif
9324 init_emacs_passwd_dir ();
9326 init_environ ();
9328 init_coercion_handler ();
9330 initialize_applescript ();
9332 init_apple_event_handler ();
9335 char **argv;
9336 int argc = 0;
9338 /* set up argv array from STR# resource */
9339 get_string_list (&argv, ARGV_STRING_LIST_ID);
9340 while (argv[argc])
9341 argc++;
9343 /* free up AppleScript resources on exit */
9344 atexit (terminate_applescript);
9346 #if __profile__ /* is the profiler on? */
9347 atexit (profiler_exit_proc);
9348 #endif
9350 /* 3rd param "envp" never used in emacs_main */
9351 (void) emacs_main (argc, argv, 0);
9354 /* Never reached - real exit in Fkill_emacs */
9355 return 0;
9357 #endif
9359 /* Table for translating Mac keycode to X keysym values. Contributed
9360 by Sudhir Shenoy.
9361 Mapping for special keys is now identical to that in Apple X11
9362 except `clear' (-> <clear>) on the KeyPad, `enter' (-> <kp-enter>)
9363 on the right of the Cmd key on laptops, and fn + `enter' (->
9364 <linefeed>). */
9365 static unsigned char keycode_to_xkeysym_table[] = {
9366 /*0x00*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9367 /*0x10*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9368 /*0x20*/ 0, 0, 0, 0, 0x0d /*return*/, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9370 /*0x30*/ 0x09 /*tab*/, 0 /*0x0020 space*/, 0, 0x08 /*backspace*/,
9371 /*0x34*/ 0x8d /*enter on laptops*/, 0x1b /*escape*/, 0, 0,
9372 /*0x38*/ 0, 0, 0, 0,
9373 /*0x3C*/ 0, 0, 0, 0,
9375 /*0x40*/ 0, 0xae /*kp-.*/, 0, 0xaa /*kp-**/,
9376 /*0x44*/ 0, 0xab /*kp-+*/, 0, 0x0b /*clear*/,
9377 /*0x48*/ 0, 0, 0, 0xaf /*kp-/*/,
9378 /*0x4C*/ 0x8d /*kp-enter*/, 0, 0xad /*kp--*/, 0,
9380 /*0x50*/ 0, 0xbd /*kp-=*/, 0xb0 /*kp-0*/, 0xb1 /*kp-1*/,
9381 /*0x54*/ 0xb2 /*kp-2*/, 0xb3 /*kp-3*/, 0xb4 /*kp-4*/, 0xb5 /*kp-5*/,
9382 /*0x58*/ 0xb6 /*kp-6*/, 0xb7 /*kp-7*/, 0, 0xb8 /*kp-8*/,
9383 /*0x5C*/ 0xb9 /*kp-9*/, 0, 0, 0,
9385 /*0x60*/ 0xc2 /*f5*/, 0xc3 /*f6*/, 0xc4 /*f7*/, 0xc0 /*f3*/,
9386 /*0x64*/ 0xc5 /*f8*/, 0xc6 /*f9*/, 0, 0xc8 /*f11*/,
9387 /*0x68*/ 0, 0xca /*f13*/, 0, 0xcb /*f14*/,
9388 /*0x6C*/ 0, 0xc7 /*f10*/, 0x0a /*fn+enter on laptops*/, 0xc9 /*f12*/,
9390 /*0x70*/ 0, 0xcc /*f15*/, 0x6a /*help*/, 0x50 /*home*/,
9391 /*0x74*/ 0x55 /*pgup*/, 0xff /*delete*/, 0xc1 /*f4*/, 0x57 /*end*/,
9392 /*0x78*/ 0xbf /*f2*/, 0x56 /*pgdown*/, 0xbe /*f1*/, 0x51 /*left*/,
9393 /*0x7C*/ 0x53 /*right*/, 0x54 /*down*/, 0x52 /*up*/, 0
9397 static int
9398 keycode_to_xkeysym (int keyCode, int *xKeySym)
9400 *xKeySym = keycode_to_xkeysym_table [keyCode & 0x7f];
9401 return *xKeySym != 0;
9404 static unsigned char fn_keycode_to_xkeysym_table[] = {
9405 /*0x00*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9406 /*0x10*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9407 /*0x20*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9409 /*0x30*/ 0, 0, 0, 0,
9410 /*0x34*/ 0, 0, 0, 0,
9411 /*0x38*/ 0, 0, 0, 0,
9412 /*0x3C*/ 0, 0, 0, 0,
9414 /*0x40*/ 0, 0x2e /*kp-. = .*/, 0, 0x50 /*kp-* = 'p'*/,
9415 /*0x44*/ 0, '/' /*kp-+*/, 0, 0,
9416 /*0x48*/ 0, 0, 0, 0x30 /*kp-/ = '0'*/,
9417 /*0x4C*/ 0, 0, 0x3b /*kp-- = ';'*/, 0,
9419 /*0x50*/ 0, 0x2d /*kp-= = '-'*/, 0x6d /*kp-0 = 'm'*/, 0x6a /*kp-1 = 'j'*/,
9420 /*0x54*/ 0x6b /*kp-2 = 'k'*/, 0x6c /*kp-3 = 'l'*/, 'u' /*kp-4*/, 'i' /*kp-5*/,
9421 /*0x58*/ 'o' /*kp-6*/, '7' /*kp-7*/, 0, '8' /*kp-8*/,
9422 /*0x5C*/ '9' /*kp-9*/, 0, 0, 0,
9424 /*0x60*/ 0, 0, 0, 0,
9425 /*0x64*/ 0, 0, 0, 0,
9426 /*0x68*/ 0, 0, 0, 0,
9427 /*0x6C*/ 0, 0, 0, 0,
9429 /*0x70*/ 0, 0, 0, 0,
9430 /*0x74*/ 0, 0, 0, 0,
9431 /*0x78*/ 0, 0, 0, 0,
9432 /*0x7C*/ 0, 0, 0, 0
9434 static int
9435 convert_fn_keycode (EventRef eventRef, int keyCode, int *newCode)
9437 #ifdef MAC_OSX
9438 /* Use the special map to translate keys when function modifier is
9439 to be caught. KeyTranslate can't be used in that case.
9440 We can't detect the function key using the input_event.modifiers,
9441 because this uses the high word of an UInt32. Therefore,
9442 we'll just read it out of the original eventRef.
9446 /* TODO / known issues
9448 - Fn-Shift-j is regonized as Fn-j and not Fn-J.
9449 The above table always translates to lower characters. We need to use
9450 the KCHR keyboard resource (KeyTranslate() ) to map k->K and 8->*.
9452 - The table is meant for English language keyboards, and it will work
9453 for many others with the exception of key combinations like Fn-ö on
9454 a German keyboard, which is currently mapped to Fn-;.
9455 How to solve this without keeping separate tables for all keyboards
9456 around? KeyTranslate isn't of much help here, as it only takes a 16-bit
9457 value for keycode with the modifiers in he high byte, i.e. no room for the
9458 Fn modifier. That's why we need the table.
9462 UInt32 mods = 0;
9463 if (!NILP(Vmac_function_modifier))
9465 GetEventParameter (eventRef, kEventParamKeyModifiers, typeUInt32, NULL,
9466 sizeof (UInt32), NULL, &mods);
9467 if (mods & kEventKeyModifierFnMask)
9468 { *newCode = fn_keycode_to_xkeysym_table [keyCode & 0x7f];
9470 return (*newCode != 0);
9473 #endif
9474 return false;
9477 static int
9478 backtranslate_modified_keycode(int mods, int keycode, int def)
9480 EventModifiers mapped_modifiers =
9481 (NILP (Vmac_control_modifier) ? 0 : controlKey)
9482 | (NILP (Vmac_option_modifier) ? 0 : optionKey)
9483 | (NILP (Vmac_command_modifier) ? 0 : cmdKey);
9485 if (mods & mapped_modifiers)
9487 /* This code comes from Keyboard Resource,
9488 Appendix C of IM - Text. This is necessary
9489 since shift is ignored in KCHR table
9490 translation when option or command is pressed.
9491 It also does not translate correctly
9492 control-shift chars like C-% so mask off shift
9493 here also.
9495 Not done for combinations with the option key (alt)
9496 unless it is to be caught by Emacs: this is
9497 to preserve key combinations translated by the OS
9498 such as Alt-3.
9500 /* Mask off modifier keys that are mapped to some Emacs
9501 modifiers. */
9502 int new_modifiers = mods & ~mapped_modifiers;
9503 /* set high byte of keycode to modifier high byte*/
9504 int new_keycode = keycode | new_modifiers;
9505 Ptr kchr_ptr = (Ptr) GetScriptManagerVariable (smKCHRCache);
9506 unsigned long some_state = 0;
9507 return (int) KeyTranslate (kchr_ptr, new_keycode,
9508 &some_state) & 0xff;
9509 /* TO DO: Recognize two separate resulting characters, "for
9510 example, when the user presses Option-E followed by N, you
9511 can map this through the KeyTranslate function using the
9512 U.S. 'KCHR' resource to produce ´n, which KeyTranslate
9513 returns as two characters in the bytes labeled Character code
9514 1 and Character code 2." (from Carbon API doc) */
9517 else
9518 return def;
9522 #if !USE_CARBON_EVENTS
9523 static RgnHandle mouse_region = NULL;
9525 Boolean
9526 mac_wait_next_event (er, sleep_time, dequeue)
9527 EventRecord *er;
9528 UInt32 sleep_time;
9529 Boolean dequeue;
9531 static EventRecord er_buf = {nullEvent};
9532 UInt32 target_tick, current_tick;
9533 EventMask event_mask;
9535 if (mouse_region == NULL)
9536 mouse_region = NewRgn ();
9538 event_mask = everyEvent;
9539 if (!mac_ready_for_apple_events)
9540 event_mask -= highLevelEventMask;
9542 current_tick = TickCount ();
9543 target_tick = current_tick + sleep_time;
9545 if (er_buf.what == nullEvent)
9546 while (!WaitNextEvent (event_mask, &er_buf,
9547 target_tick - current_tick, mouse_region))
9549 current_tick = TickCount ();
9550 if (target_tick <= current_tick)
9551 return false;
9554 *er = er_buf;
9555 if (dequeue)
9556 er_buf.what = nullEvent;
9557 return true;
9559 #endif /* not USE_CARBON_EVENTS */
9561 /* Emacs calls this whenever it wants to read an input event from the
9562 user. */
9564 XTread_socket (sd, expected, hold_quit)
9565 int sd, expected;
9566 struct input_event *hold_quit;
9568 struct input_event inev;
9569 int count = 0;
9570 #if USE_CARBON_EVENTS
9571 EventRef eventRef;
9572 EventTargetRef toolbox_dispatcher;
9573 #endif
9574 EventRecord er;
9575 struct mac_display_info *dpyinfo = &one_mac_display_info;
9577 if (interrupt_input_blocked)
9579 interrupt_input_pending = 1;
9580 return -1;
9583 interrupt_input_pending = 0;
9584 BLOCK_INPUT;
9586 /* So people can tell when we have read the available input. */
9587 input_signal_count++;
9589 ++handling_signal;
9591 #if USE_CARBON_EVENTS
9592 toolbox_dispatcher = GetEventDispatcherTarget ();
9594 while (!ReceiveNextEvent (0, NULL, kEventDurationNoWait,
9595 kEventRemoveFromQueue, &eventRef))
9596 #else /* !USE_CARBON_EVENTS */
9597 while (mac_wait_next_event (&er, 0, true))
9598 #endif /* !USE_CARBON_EVENTS */
9600 int do_help = 0;
9601 struct frame *f;
9602 unsigned long timestamp;
9604 /* It is necessary to set this (additional) argument slot of an
9605 event to nil because keyboard.c protects incompletely
9606 processed event from being garbage collected by placing them
9607 in the kbd_buffer_gcpro vector. */
9608 EVENT_INIT (inev);
9609 inev.kind = NO_EVENT;
9610 inev.arg = Qnil;
9612 #if USE_CARBON_EVENTS
9613 timestamp = GetEventTime (eventRef) / kEventDurationMillisecond;
9614 #else
9615 timestamp = er.when * (1000 / 60); /* ticks to milliseconds */
9616 #endif
9618 #if USE_CARBON_EVENTS
9619 /* Handle new events */
9620 if (!mac_convert_event_ref (eventRef, &er))
9622 /* There used to be a handler for the kEventMouseWheelMoved
9623 event here. But as of Mac OS X 10.4, this kind of event
9624 is not directly posted to the main event queue by
9625 two-finger scrolling on the trackpad. Instead, some
9626 private event is posted and it is converted to a wheel
9627 event by the default handler for the application target.
9628 The converted one can be received by a Carbon event
9629 handler installed on a window target. */
9630 read_socket_inev = &inev;
9631 SendEventToEventTarget (eventRef, toolbox_dispatcher);
9632 read_socket_inev = NULL;
9634 else
9635 #endif /* USE_CARBON_EVENTS */
9636 switch (er.what)
9638 case mouseDown:
9639 case mouseUp:
9641 WindowPtr window_ptr;
9642 ControlPartCode part_code;
9643 int tool_bar_p = 0;
9645 #if USE_CARBON_EVENTS
9646 /* This is needed to send mouse events like aqua window
9647 buttons to the correct handler. */
9648 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
9649 != eventNotHandledErr)
9650 break;
9651 #endif
9652 last_mouse_glyph_frame = 0;
9654 if (dpyinfo->grabbed && last_mouse_frame
9655 && FRAME_LIVE_P (last_mouse_frame))
9657 window_ptr = FRAME_MAC_WINDOW (last_mouse_frame);
9658 part_code = inContent;
9660 else
9662 part_code = FindWindow (er.where, &window_ptr);
9663 if (tip_window && window_ptr == tip_window)
9665 HideWindow (tip_window);
9666 part_code = FindWindow (er.where, &window_ptr);
9670 if (er.what != mouseDown &&
9671 (part_code != inContent || dpyinfo->grabbed == 0))
9672 break;
9674 switch (part_code)
9676 case inMenuBar:
9677 f = mac_focus_frame (dpyinfo);
9678 saved_menu_event_location = er.where;
9679 inev.kind = MENU_BAR_ACTIVATE_EVENT;
9680 XSETFRAME (inev.frame_or_window, f);
9681 break;
9683 case inContent:
9684 if (window_ptr != FRAME_MAC_WINDOW (mac_focus_frame (dpyinfo)))
9685 SelectWindow (window_ptr);
9686 else
9688 ControlPartCode control_part_code;
9689 ControlHandle ch;
9690 Point mouse_loc = er.where;
9691 #ifdef MAC_OSX
9692 ControlKind control_kind;
9693 #endif
9695 f = mac_window_to_frame (window_ptr);
9696 /* convert to local coordinates of new window */
9697 SetPortWindowPort (window_ptr);
9699 GlobalToLocal (&mouse_loc);
9700 #if TARGET_API_MAC_CARBON
9701 ch = FindControlUnderMouse (mouse_loc, window_ptr,
9702 &control_part_code);
9703 #ifdef MAC_OSX
9704 if (ch)
9705 GetControlKind (ch, &control_kind);
9706 #endif
9707 #else
9708 control_part_code = FindControl (mouse_loc, window_ptr,
9709 &ch);
9710 #endif
9712 #if USE_CARBON_EVENTS
9713 inev.code = mac_get_mouse_btn (eventRef);
9714 inev.modifiers = mac_event_to_emacs_modifiers (eventRef);
9715 #else
9716 inev.code = mac_get_emulated_btn (er.modifiers);
9717 inev.modifiers = mac_to_emacs_modifiers (er.modifiers);
9718 #endif
9719 XSETINT (inev.x, mouse_loc.h);
9720 XSETINT (inev.y, mouse_loc.v);
9722 if (dpyinfo->grabbed && tracked_scroll_bar
9723 || ch != 0
9724 #ifndef USE_TOOLKIT_SCROLL_BARS
9725 /* control_part_code becomes kControlNoPart if
9726 a progress indicator is clicked. */
9727 && control_part_code != kControlNoPart
9728 #else /* USE_TOOLKIT_SCROLL_BARS */
9729 #ifdef MAC_OSX
9730 && control_kind.kind == kControlKindScrollBar
9731 #endif /* MAC_OSX */
9732 #endif /* USE_TOOLKIT_SCROLL_BARS */
9735 struct scroll_bar *bar;
9737 if (dpyinfo->grabbed && tracked_scroll_bar)
9739 bar = tracked_scroll_bar;
9740 #ifndef USE_TOOLKIT_SCROLL_BARS
9741 control_part_code = kControlIndicatorPart;
9742 #endif
9744 else
9745 bar = (struct scroll_bar *) GetControlReference (ch);
9746 #ifdef USE_TOOLKIT_SCROLL_BARS
9747 /* Make the "Ctrl-Mouse-2 splits window" work
9748 for toolkit scroll bars. */
9749 if (er.modifiers & controlKey)
9750 x_scroll_bar_handle_click (bar, control_part_code,
9751 &er, &inev);
9752 else if (er.what == mouseDown)
9753 x_scroll_bar_handle_press (bar, control_part_code,
9754 &inev);
9755 else
9756 x_scroll_bar_handle_release (bar, &inev);
9757 #else /* not USE_TOOLKIT_SCROLL_BARS */
9758 x_scroll_bar_handle_click (bar, control_part_code,
9759 &er, &inev);
9760 if (er.what == mouseDown
9761 && control_part_code == kControlIndicatorPart)
9762 tracked_scroll_bar = bar;
9763 else
9764 tracked_scroll_bar = NULL;
9765 #endif /* not USE_TOOLKIT_SCROLL_BARS */
9767 else
9769 Lisp_Object window;
9770 int x = mouse_loc.h;
9771 int y = mouse_loc.v;
9773 window = window_from_coordinates (f, x, y, 0, 0, 0, 1);
9774 if (EQ (window, f->tool_bar_window))
9776 if (er.what == mouseDown)
9777 handle_tool_bar_click (f, x, y, 1, 0);
9778 else
9779 handle_tool_bar_click (f, x, y, 0,
9780 inev.modifiers);
9781 tool_bar_p = 1;
9783 else
9785 XSETFRAME (inev.frame_or_window, f);
9786 inev.kind = MOUSE_CLICK_EVENT;
9790 if (er.what == mouseDown)
9792 dpyinfo->grabbed |= (1 << inev.code);
9793 last_mouse_frame = f;
9795 if (!tool_bar_p)
9796 last_tool_bar_item = -1;
9798 else
9800 if ((dpyinfo->grabbed & (1 << inev.code)) == 0)
9801 /* If a button is released though it was not
9802 previously pressed, that would be because
9803 of multi-button emulation. */
9804 dpyinfo->grabbed = 0;
9805 else
9806 dpyinfo->grabbed &= ~(1 << inev.code);
9809 /* Ignore any mouse motion that happened before
9810 this event; any subsequent mouse-movement Emacs
9811 events should reflect only motion after the
9812 ButtonPress. */
9813 if (f != 0)
9814 f->mouse_moved = 0;
9816 #ifdef USE_TOOLKIT_SCROLL_BARS
9817 if (inev.kind == MOUSE_CLICK_EVENT)
9818 #endif
9819 switch (er.what)
9821 case mouseDown:
9822 inev.modifiers |= down_modifier;
9823 break;
9824 case mouseUp:
9825 inev.modifiers |= up_modifier;
9826 break;
9829 break;
9831 case inDrag:
9832 #if TARGET_API_MAC_CARBON
9833 DragWindow (window_ptr, er.where, NULL);
9834 #else /* not TARGET_API_MAC_CARBON */
9835 DragWindow (window_ptr, er.where, &qd.screenBits.bounds);
9836 #endif /* not TARGET_API_MAC_CARBON */
9837 /* Update the frame parameters. */
9839 struct frame *f = mac_window_to_frame (window_ptr);
9841 if (f && !f->async_iconified)
9842 x_real_positions (f, &f->left_pos, &f->top_pos);
9844 break;
9846 case inGoAway:
9847 if (TrackGoAway (window_ptr, er.where))
9849 inev.kind = DELETE_WINDOW_EVENT;
9850 XSETFRAME (inev.frame_or_window,
9851 mac_window_to_frame (window_ptr));
9853 break;
9855 /* window resize handling added --ben */
9856 case inGrow:
9857 do_grow_window (window_ptr, &er);
9858 break;
9860 /* window zoom handling added --ben */
9861 case inZoomIn:
9862 case inZoomOut:
9863 if (TrackBox (window_ptr, er.where, part_code))
9864 do_zoom_window (window_ptr, part_code);
9865 break;
9867 default:
9868 break;
9871 break;
9873 case updateEvt:
9874 #if USE_CARBON_EVENTS
9875 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
9876 != eventNotHandledErr)
9877 break;
9878 #else
9879 do_window_update ((WindowPtr) er.message);
9880 #endif
9881 break;
9883 case osEvt:
9884 #if USE_CARBON_EVENTS
9885 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
9886 != eventNotHandledErr)
9887 break;
9888 #endif
9889 switch ((er.message >> 24) & 0x000000FF)
9891 case suspendResumeMessage:
9892 if ((er.message & resumeFlag) == 1)
9893 do_app_resume ();
9894 else
9895 do_app_suspend ();
9896 break;
9898 case mouseMovedMessage:
9899 #if !USE_CARBON_EVENTS
9900 SetRectRgn (mouse_region, er.where.h, er.where.v,
9901 er.where.h + 1, er.where.v + 1);
9902 #endif
9903 previous_help_echo_string = help_echo_string;
9904 help_echo_string = Qnil;
9906 if (dpyinfo->grabbed && last_mouse_frame
9907 && FRAME_LIVE_P (last_mouse_frame))
9908 f = last_mouse_frame;
9909 else
9910 f = dpyinfo->x_focus_frame;
9912 if (dpyinfo->mouse_face_hidden)
9914 dpyinfo->mouse_face_hidden = 0;
9915 clear_mouse_face (dpyinfo);
9918 if (f)
9920 WindowPtr wp = FRAME_MAC_WINDOW (f);
9921 Point mouse_pos = er.where;
9923 SetPortWindowPort (wp);
9925 GlobalToLocal (&mouse_pos);
9927 if (dpyinfo->grabbed && tracked_scroll_bar)
9928 #ifdef USE_TOOLKIT_SCROLL_BARS
9929 x_scroll_bar_handle_drag (wp, tracked_scroll_bar,
9930 mouse_pos, &inev);
9931 #else /* not USE_TOOLKIT_SCROLL_BARS */
9932 x_scroll_bar_note_movement (tracked_scroll_bar,
9933 mouse_pos.v
9934 - XINT (tracked_scroll_bar->top),
9935 er.when * (1000 / 60));
9936 #endif /* not USE_TOOLKIT_SCROLL_BARS */
9937 else
9939 /* Generate SELECT_WINDOW_EVENTs when needed. */
9940 if (mouse_autoselect_window)
9942 Lisp_Object window;
9944 window = window_from_coordinates (f,
9945 mouse_pos.h,
9946 mouse_pos.v,
9947 0, 0, 0, 0);
9949 /* Window will be selected only when it is
9950 not selected now and last mouse movement
9951 event was not in it. Minibuffer window
9952 will be selected iff it is active. */
9953 if (WINDOWP (window)
9954 && !EQ (window, last_window)
9955 && !EQ (window, selected_window))
9957 inev.kind = SELECT_WINDOW_EVENT;
9958 inev.frame_or_window = window;
9961 last_window=window;
9963 if (!note_mouse_movement (f, &mouse_pos))
9964 help_echo_string = previous_help_echo_string;
9968 /* If the contents of the global variable
9969 help_echo_string has changed, generate a
9970 HELP_EVENT. */
9971 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
9972 do_help = 1;
9973 break;
9975 break;
9977 case activateEvt:
9979 WindowPtr window_ptr = (WindowPtr) er.message;
9981 #if USE_CARBON_EVENTS
9982 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
9983 != eventNotHandledErr)
9984 break;
9985 #endif
9986 if (window_ptr == tip_window)
9988 HideWindow (tip_window);
9989 break;
9992 if (!is_emacs_window (window_ptr))
9993 break;
9995 if ((er.modifiers & activeFlag) != 0)
9997 /* A window has been activated */
9998 Point mouse_loc = er.where;
10000 x_detect_focus_change (dpyinfo, &er, &inev);
10002 SetPortWindowPort (window_ptr);
10003 GlobalToLocal (&mouse_loc);
10004 /* Window-activated event counts as mouse movement,
10005 so update things that depend on mouse position. */
10006 note_mouse_movement (mac_window_to_frame (window_ptr),
10007 &mouse_loc);
10009 else
10011 /* A window has been deactivated */
10012 #if USE_TOOLKIT_SCROLL_BARS
10013 if (dpyinfo->grabbed && tracked_scroll_bar)
10015 struct input_event event;
10017 EVENT_INIT (event);
10018 event.kind = NO_EVENT;
10019 x_scroll_bar_handle_release (tracked_scroll_bar, &event);
10020 if (event.kind != NO_EVENT)
10022 event.timestamp = timestamp;
10023 kbd_buffer_store_event_hold (&event, hold_quit);
10024 count++;
10027 #endif
10028 dpyinfo->grabbed = 0;
10030 x_detect_focus_change (dpyinfo, &er, &inev);
10032 f = mac_window_to_frame (window_ptr);
10033 if (f == dpyinfo->mouse_face_mouse_frame)
10035 /* If we move outside the frame, then we're
10036 certainly no longer on any text in the
10037 frame. */
10038 clear_mouse_face (dpyinfo);
10039 dpyinfo->mouse_face_mouse_frame = 0;
10042 /* Generate a nil HELP_EVENT to cancel a help-echo.
10043 Do it only if there's something to cancel.
10044 Otherwise, the startup message is cleared when the
10045 mouse leaves the frame. */
10046 if (any_help_event_p)
10047 do_help = -1;
10050 break;
10052 case keyDown:
10053 case autoKey:
10055 int keycode = (er.message & keyCodeMask) >> 8;
10056 int xkeysym;
10058 #if USE_CARBON_EVENTS && defined (MAC_OSX)
10059 /* When using Carbon Events, we need to pass raw keyboard
10060 events to the TSM ourselves. If TSM handles it, it
10061 will pass back noErr, otherwise it will pass back
10062 "eventNotHandledErr" and we can process it
10063 normally. */
10064 if ((mac_pass_command_to_system
10065 || !(er.modifiers & cmdKey))
10066 && (mac_pass_control_to_system
10067 || !(er.modifiers & controlKey))
10068 && (NILP (Vmac_option_modifier)
10069 || !(er.modifiers & optionKey)))
10070 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
10071 != eventNotHandledErr)
10072 break;
10073 #endif
10075 #if 0
10076 if (dpyinfo->x_focus_frame == NULL)
10078 /* Beep if keyboard input occurs when all the frames
10079 are invisible. */
10080 SysBeep (1);
10081 break;
10083 #endif
10086 static SInt16 last_key_script = -1;
10087 SInt16 current_key_script = GetScriptManagerVariable (smKeyScript);
10089 if (last_key_script != current_key_script)
10091 struct input_event event;
10093 EVENT_INIT (event);
10094 event.kind = LANGUAGE_CHANGE_EVENT;
10095 event.arg = Qnil;
10096 event.code = current_key_script;
10097 event.timestamp = timestamp;
10098 kbd_buffer_store_event (&event);
10099 count++;
10101 last_key_script = current_key_script;
10104 ObscureCursor ();
10106 if (!dpyinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
10108 clear_mouse_face (dpyinfo);
10109 dpyinfo->mouse_face_hidden = 1;
10112 /* translate the keycode back to determine the original key */
10113 /* Convert key code if function key is pressed.
10114 Otherwise, if non-ASCII-event, take care of that
10115 without re-translating the key code. */
10116 #if USE_CARBON_EVENTS
10117 if (convert_fn_keycode (eventRef, keycode, &xkeysym))
10119 inev.code = xkeysym;
10120 /* this doesn't work - tried to add shift modifiers */
10121 inev.code =
10122 backtranslate_modified_keycode(er.modifiers & (~0x2200),
10123 xkeysym | 0x80, xkeysym);
10124 inev.kind = ASCII_KEYSTROKE_EVENT;
10126 else
10127 #endif
10128 if (keycode_to_xkeysym (keycode, &xkeysym))
10130 inev.code = 0xff00 | xkeysym;
10131 inev.kind = NON_ASCII_KEYSTROKE_EVENT;
10133 else
10135 inev.code =
10136 backtranslate_modified_keycode(er.modifiers, keycode,
10137 er.message & charCodeMask);
10138 inev.kind = ASCII_KEYSTROKE_EVENT;
10142 #if USE_CARBON_EVENTS
10143 inev.modifiers = mac_event_to_emacs_modifiers (eventRef);
10144 #else
10145 inev.modifiers = mac_to_emacs_modifiers (er.modifiers);
10146 #endif
10147 inev.modifiers |= (extra_keyboard_modifiers
10148 & (meta_modifier | alt_modifier
10149 | hyper_modifier | super_modifier));
10150 XSETFRAME (inev.frame_or_window, mac_focus_frame (dpyinfo));
10151 break;
10153 case kHighLevelEvent:
10154 read_socket_inev = &inev;
10155 AEProcessAppleEvent (&er);
10156 read_socket_inev = NULL;
10157 break;
10159 default:
10160 break;
10162 #if USE_CARBON_EVENTS
10163 ReleaseEvent (eventRef);
10164 #endif
10166 if (inev.kind != NO_EVENT)
10168 inev.timestamp = timestamp;
10169 kbd_buffer_store_event_hold (&inev, hold_quit);
10170 count++;
10173 if (do_help
10174 && !(hold_quit && hold_quit->kind != NO_EVENT))
10176 Lisp_Object frame;
10178 if (f)
10179 XSETFRAME (frame, f);
10180 else
10181 frame = Qnil;
10183 if (do_help > 0)
10185 any_help_event_p = 1;
10186 gen_help_event (help_echo_string, frame, help_echo_window,
10187 help_echo_object, help_echo_pos);
10189 else
10191 help_echo_string = Qnil;
10192 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
10194 count++;
10199 /* If the focus was just given to an autoraising frame,
10200 raise it now. */
10201 /* ??? This ought to be able to handle more than one such frame. */
10202 if (pending_autoraise_frame)
10204 x_raise_frame (pending_autoraise_frame);
10205 pending_autoraise_frame = 0;
10208 #if !USE_CARBON_EVENTS
10209 /* Check which frames are still visible. We do this here because
10210 there doesn't seem to be any direct notification from the Window
10211 Manager that the visibility of a window has changed (at least,
10212 not in all cases). */
10214 Lisp_Object tail, frame;
10216 FOR_EACH_FRAME (tail, frame)
10218 struct frame *f = XFRAME (frame);
10220 /* The tooltip has been drawn already. Avoid the
10221 SET_FRAME_GARBAGED in mac_handle_visibility_change. */
10222 if (EQ (frame, tip_frame))
10223 continue;
10225 if (FRAME_MAC_P (f))
10226 mac_handle_visibility_change (f);
10229 #endif
10231 --handling_signal;
10232 UNBLOCK_INPUT;
10233 return count;
10237 /* Need to override CodeWarrior's input function so no conversion is
10238 done on newlines Otherwise compiled functions in .elc files will be
10239 read incorrectly. Defined in ...:MSL C:MSL
10240 Common:Source:buffer_io.c. */
10241 #ifdef __MWERKS__
10242 void
10243 __convert_to_newlines (unsigned char * p, size_t * n)
10245 #pragma unused(p,n)
10248 void
10249 __convert_from_newlines (unsigned char * p, size_t * n)
10251 #pragma unused(p,n)
10253 #endif
10255 #ifdef MAC_OS8
10256 void
10257 make_mac_terminal_frame (struct frame *f)
10259 Lisp_Object frame;
10260 Rect r;
10262 XSETFRAME (frame, f);
10264 f->output_method = output_mac;
10265 f->output_data.mac = (struct mac_output *)
10266 xmalloc (sizeof (struct mac_output));
10267 bzero (f->output_data.mac, sizeof (struct mac_output));
10269 XSETFRAME (FRAME_KBOARD (f)->Vdefault_minibuffer_frame, f);
10271 FRAME_COLS (f) = 96;
10272 FRAME_LINES (f) = 4;
10274 FRAME_CAN_HAVE_SCROLL_BARS (f) = 1;
10275 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = vertical_scroll_bar_right;
10277 FRAME_DESIRED_CURSOR (f) = FILLED_BOX_CURSOR;
10279 f->output_data.mac->cursor_pixel = 0;
10280 f->output_data.mac->border_pixel = 0x00ff00;
10281 f->output_data.mac->mouse_pixel = 0xff00ff;
10282 f->output_data.mac->cursor_foreground_pixel = 0x0000ff;
10284 f->output_data.mac->text_cursor = kThemeIBeamCursor;
10285 f->output_data.mac->nontext_cursor = kThemeArrowCursor;
10286 f->output_data.mac->modeline_cursor = kThemeArrowCursor;
10287 f->output_data.mac->hand_cursor = kThemePointingHandCursor;
10288 f->output_data.mac->hourglass_cursor = kThemeWatchCursor;
10289 f->output_data.mac->horizontal_drag_cursor = kThemeResizeLeftRightCursor;
10291 FRAME_FONTSET (f) = -1;
10292 f->output_data.mac->explicit_parent = 0;
10293 f->left_pos = 8;
10294 f->top_pos = 32;
10295 f->border_width = 0;
10297 f->internal_border_width = 0;
10299 f->auto_raise = 1;
10300 f->auto_lower = 1;
10302 f->new_text_cols = 0;
10303 f->new_text_lines = 0;
10305 SetRect (&r, f->left_pos, f->top_pos,
10306 f->left_pos + FRAME_PIXEL_WIDTH (f),
10307 f->top_pos + FRAME_PIXEL_HEIGHT (f));
10309 BLOCK_INPUT;
10311 if (!(FRAME_MAC_WINDOW (f) =
10312 NewCWindow (NULL, &r, "\p", true, dBoxProc,
10313 (WindowPtr) -1, 1, (long) f->output_data.mac)))
10314 abort ();
10315 /* so that update events can find this mac_output struct */
10316 f->output_data.mac->mFP = f; /* point back to emacs frame */
10318 UNBLOCK_INPUT;
10320 x_make_gc (f);
10322 /* Need to be initialized for unshow_buffer in window.c. */
10323 selected_window = f->selected_window;
10325 Fmodify_frame_parameters (frame,
10326 Fcons (Fcons (Qfont,
10327 build_string ("-*-monaco-medium-r-*--*-90-*-*-*-*-mac-roman")), Qnil));
10328 Fmodify_frame_parameters (frame,
10329 Fcons (Fcons (Qforeground_color,
10330 build_string ("black")), Qnil));
10331 Fmodify_frame_parameters (frame,
10332 Fcons (Fcons (Qbackground_color,
10333 build_string ("white")), Qnil));
10335 #endif
10338 /***********************************************************************
10339 Initialization
10340 ***********************************************************************/
10342 int mac_initialized = 0;
10344 void
10345 mac_initialize_display_info ()
10347 struct mac_display_info *dpyinfo = &one_mac_display_info;
10348 GDHandle main_device_handle;
10350 bzero (dpyinfo, sizeof (*dpyinfo));
10352 #ifdef MAC_OSX
10353 dpyinfo->mac_id_name
10354 = (char *) xmalloc (SCHARS (Vinvocation_name)
10355 + SCHARS (Vsystem_name)
10356 + 2);
10357 sprintf (dpyinfo->mac_id_name, "%s@%s",
10358 SDATA (Vinvocation_name), SDATA (Vsystem_name));
10359 #else
10360 dpyinfo->mac_id_name = (char *) xmalloc (strlen ("Mac Display") + 1);
10361 strcpy (dpyinfo->mac_id_name, "Mac Display");
10362 #endif
10364 main_device_handle = LMGetMainDevice();
10366 dpyinfo->reference_count = 0;
10367 dpyinfo->resx = 72.0;
10368 dpyinfo->resy = 72.0;
10369 dpyinfo->color_p = TestDeviceAttribute (main_device_handle, gdDevType);
10370 #ifdef MAC_OSX
10371 /* HasDepth returns true if it is possible to have a 32 bit display,
10372 but this may not be what is actually used. Mac OSX can do better.
10373 CGMainDisplayID is only available on OSX 10.2 and higher, but the
10374 header for CGGetActiveDisplayList says that the first display returned
10375 is the active one, so we use that. */
10377 CGDirectDisplayID disp_id[1];
10378 CGDisplayCount disp_count;
10379 CGDisplayErr error_code;
10381 error_code = CGGetActiveDisplayList (1, disp_id, &disp_count);
10382 if (error_code != 0)
10383 error ("No display found, CGGetActiveDisplayList error %d", error_code);
10385 dpyinfo->n_planes = CGDisplayBitsPerPixel (disp_id[0]);
10387 #else
10388 for (dpyinfo->n_planes = 32; dpyinfo->n_planes > 0; dpyinfo->n_planes >>= 1)
10389 if (HasDepth (main_device_handle, dpyinfo->n_planes,
10390 gdDevType, dpyinfo->color_p))
10391 break;
10392 #endif
10393 dpyinfo->height = (**main_device_handle).gdRect.bottom;
10394 dpyinfo->width = (**main_device_handle).gdRect.right;
10395 dpyinfo->grabbed = 0;
10396 dpyinfo->root_window = NULL;
10397 dpyinfo->image_cache = make_image_cache ();
10399 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
10400 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
10401 dpyinfo->mouse_face_face_id = DEFAULT_FACE_ID;
10402 dpyinfo->mouse_face_window = Qnil;
10403 dpyinfo->mouse_face_overlay = Qnil;
10404 dpyinfo->mouse_face_hidden = 0;
10408 static XrmDatabase
10409 mac_make_rdb (xrm_option)
10410 char *xrm_option;
10412 XrmDatabase database;
10414 database = xrm_get_preference_database (NULL);
10415 if (xrm_option)
10416 xrm_merge_string_database (database, xrm_option);
10418 return database;
10421 struct mac_display_info *
10422 mac_term_init (display_name, xrm_option, resource_name)
10423 Lisp_Object display_name;
10424 char *xrm_option;
10425 char *resource_name;
10427 struct mac_display_info *dpyinfo;
10429 BLOCK_INPUT;
10431 if (!mac_initialized)
10433 mac_initialize ();
10434 mac_initialized = 1;
10437 if (x_display_list)
10438 error ("Sorry, this version can only handle one display");
10440 mac_initialize_display_info ();
10442 dpyinfo = &one_mac_display_info;
10444 dpyinfo->xrdb = mac_make_rdb (xrm_option);
10446 /* Put this display on the chain. */
10447 dpyinfo->next = x_display_list;
10448 x_display_list = dpyinfo;
10450 /* Put it on x_display_name_list. */
10451 x_display_name_list = Fcons (Fcons (display_name,
10452 Fcons (Qnil, dpyinfo->xrdb)),
10453 x_display_name_list);
10454 dpyinfo->name_list_element = XCAR (x_display_name_list);
10456 UNBLOCK_INPUT;
10458 return dpyinfo;
10460 /* Get rid of display DPYINFO, assuming all frames are already gone. */
10462 void
10463 x_delete_display (dpyinfo)
10464 struct mac_display_info *dpyinfo;
10466 int i;
10468 /* Discard this display from x_display_name_list and x_display_list.
10469 We can't use Fdelq because that can quit. */
10470 if (! NILP (x_display_name_list)
10471 && EQ (XCAR (x_display_name_list), dpyinfo->name_list_element))
10472 x_display_name_list = XCDR (x_display_name_list);
10473 else
10475 Lisp_Object tail;
10477 tail = x_display_name_list;
10478 while (CONSP (tail) && CONSP (XCDR (tail)))
10480 if (EQ (XCAR (XCDR (tail)), dpyinfo->name_list_element))
10482 XSETCDR (tail, XCDR (XCDR (tail)));
10483 break;
10485 tail = XCDR (tail);
10489 if (x_display_list == dpyinfo)
10490 x_display_list = dpyinfo->next;
10491 else
10493 struct x_display_info *tail;
10495 for (tail = x_display_list; tail; tail = tail->next)
10496 if (tail->next == dpyinfo)
10497 tail->next = tail->next->next;
10500 /* Free the font names in the font table. */
10501 for (i = 0; i < dpyinfo->n_fonts; i++)
10502 if (dpyinfo->font_table[i].name)
10504 if (dpyinfo->font_table[i].name != dpyinfo->font_table[i].full_name)
10505 xfree (dpyinfo->font_table[i].full_name);
10506 xfree (dpyinfo->font_table[i].name);
10509 if (dpyinfo->font_table->font_encoder)
10510 xfree (dpyinfo->font_table->font_encoder);
10512 xfree (dpyinfo->font_table);
10513 xfree (dpyinfo->mac_id_name);
10515 if (x_display_list == 0)
10517 mac_clear_font_name_table ();
10518 bzero (dpyinfo, sizeof (*dpyinfo));
10523 #ifdef MAC_OSX
10524 void
10525 mac_check_bundle()
10527 extern int inhibit_window_system;
10528 extern int noninteractive;
10529 CFBundleRef appsBundle;
10530 pid_t child;
10532 /* No need to test if already -nw*/
10533 if (inhibit_window_system || noninteractive)
10534 return;
10536 appsBundle = CFBundleGetMainBundle();
10537 if (appsBundle != NULL)
10539 CFStringRef cfBI = CFSTR("CFBundleIdentifier");
10540 CFTypeRef res = CFBundleGetValueForInfoDictionaryKey(appsBundle, cfBI);
10541 /* We found the bundle identifier, now we know we are valid. */
10542 if (res != NULL)
10544 CFRelease(res);
10545 return;
10548 /* MAC_TODO: Have this start the bundled executable */
10550 /* For now, prevent the fatal error by bringing it up in the terminal */
10551 inhibit_window_system = 1;
10554 void
10555 MakeMeTheFrontProcess ()
10557 ProcessSerialNumber psn;
10558 OSErr err;
10560 err = GetCurrentProcess (&psn);
10561 if (err == noErr)
10562 (void) SetFrontProcess (&psn);
10565 /***** Code to handle C-g testing *****/
10567 /* Contains the Mac modifier formed from quit_char */
10568 int mac_quit_char_modifiers = 0;
10569 int mac_quit_char_keycode;
10570 extern int quit_char;
10572 static void
10573 mac_determine_quit_char_modifiers()
10575 /* Todo: Determine modifiers from quit_char. */
10576 UInt32 qc_modifiers = ctrl_modifier;
10578 /* Map modifiers */
10579 mac_quit_char_modifiers = 0;
10580 if (qc_modifiers & ctrl_modifier) mac_quit_char_modifiers |= controlKey;
10581 if (qc_modifiers & shift_modifier) mac_quit_char_modifiers |= shiftKey;
10582 if (qc_modifiers & alt_modifier) mac_quit_char_modifiers |= optionKey;
10585 static void
10586 init_quit_char_handler ()
10588 /* TODO: Let this support keys other the 'g' */
10589 mac_quit_char_keycode = 5;
10590 /* Look at <architecture/adb_kb_map.h> for details */
10591 /* http://gemma.apple.com/techpubs/mac/Toolbox/Toolbox-40.html#MARKER-9-184*/
10593 mac_determine_quit_char_modifiers();
10595 #endif /* MAC_OSX */
10597 static void
10598 init_menu_bar ()
10600 #ifdef MAC_OSX
10601 OSErr err;
10602 MenuRef menu;
10603 MenuItemIndex menu_index;
10605 err = GetIndMenuItemWithCommandID (NULL, kHICommandQuit, 1,
10606 &menu, &menu_index);
10607 if (err == noErr)
10608 SetMenuItemCommandKey (menu, menu_index, false, 0);
10609 #if USE_CARBON_EVENTS
10610 EnableMenuCommand (NULL, kHICommandPreferences);
10611 err = GetIndMenuItemWithCommandID (NULL, kHICommandPreferences, 1,
10612 &menu, &menu_index);
10613 if (err == noErr)
10615 SetMenuItemCommandKey (menu, menu_index, false, 0);
10616 InsertMenuItemTextWithCFString (menu, NULL,
10617 0, kMenuItemAttrSeparator, 0);
10618 InsertMenuItemTextWithCFString (menu, CFSTR ("About Emacs"),
10619 0, 0, kHICommandAbout);
10621 #endif /* USE_CARBON_EVENTS */
10622 #else /* !MAC_OSX */
10623 #if USE_CARBON_EVENTS
10624 SetMenuItemCommandID (GetMenuHandle (M_APPLE), I_ABOUT, kHICommandAbout);
10625 #endif
10626 #endif
10630 /* Set up use of X before we make the first connection. */
10632 extern frame_parm_handler mac_frame_parm_handlers[];
10634 static struct redisplay_interface x_redisplay_interface =
10636 mac_frame_parm_handlers,
10637 x_produce_glyphs,
10638 x_write_glyphs,
10639 x_insert_glyphs,
10640 x_clear_end_of_line,
10641 x_scroll_run,
10642 x_after_update_window_line,
10643 x_update_window_begin,
10644 x_update_window_end,
10645 x_cursor_to,
10646 x_flush,
10647 0, /* flush_display_optional */
10648 x_clear_window_mouse_face,
10649 x_get_glyph_overhangs,
10650 x_fix_overlapping_area,
10651 x_draw_fringe_bitmap,
10652 0, /* define_fringe_bitmap */
10653 0, /* destroy_fringe_bitmap */
10654 mac_per_char_metric,
10655 mac_encode_char,
10656 mac_compute_glyph_string_overhangs,
10657 x_draw_glyph_string,
10658 mac_define_frame_cursor,
10659 mac_clear_frame_area,
10660 mac_draw_window_cursor,
10661 mac_draw_vertical_window_border,
10662 mac_shift_glyphs_for_insert
10665 void
10666 mac_initialize ()
10668 rif = &x_redisplay_interface;
10670 clear_frame_hook = x_clear_frame;
10671 ins_del_lines_hook = x_ins_del_lines;
10672 delete_glyphs_hook = x_delete_glyphs;
10673 ring_bell_hook = XTring_bell;
10674 reset_terminal_modes_hook = XTreset_terminal_modes;
10675 set_terminal_modes_hook = XTset_terminal_modes;
10676 update_begin_hook = x_update_begin;
10677 update_end_hook = x_update_end;
10678 set_terminal_window_hook = XTset_terminal_window;
10679 read_socket_hook = XTread_socket;
10680 frame_up_to_date_hook = XTframe_up_to_date;
10681 mouse_position_hook = XTmouse_position;
10682 frame_rehighlight_hook = XTframe_rehighlight;
10683 frame_raise_lower_hook = XTframe_raise_lower;
10685 set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
10686 condemn_scroll_bars_hook = XTcondemn_scroll_bars;
10687 redeem_scroll_bar_hook = XTredeem_scroll_bar;
10688 judge_scroll_bars_hook = XTjudge_scroll_bars;
10690 scroll_region_ok = 1; /* we'll scroll partial frames */
10691 char_ins_del_ok = 1;
10692 line_ins_del_ok = 1; /* we'll just blt 'em */
10693 fast_clear_end_of_line = 1; /* X does this well */
10694 memory_below_frame = 0; /* we don't remember what scrolls
10695 off the bottom */
10696 baud_rate = 19200;
10698 last_tool_bar_item = -1;
10699 any_help_event_p = 0;
10701 /* Try to use interrupt input; if we can't, then start polling. */
10702 Fset_input_mode (Qt, Qnil, Qt, Qnil);
10704 BLOCK_INPUT;
10706 #if TARGET_API_MAC_CARBON
10708 #if USE_CARBON_EVENTS
10709 #ifdef MAC_OSX
10710 init_service_handler ();
10712 init_quit_char_handler ();
10713 #endif /* MAC_OSX */
10715 init_command_handler ();
10717 init_menu_bar ();
10718 #endif /* USE_CARBON_EVENTS */
10720 #ifdef MAC_OSX
10721 init_coercion_handler ();
10723 init_apple_event_handler ();
10725 if (!inhibit_window_system)
10726 MakeMeTheFrontProcess ();
10727 #endif
10728 #endif
10729 UNBLOCK_INPUT;
10733 void
10734 syms_of_macterm ()
10736 #if 0
10737 staticpro (&x_error_message_string);
10738 x_error_message_string = Qnil;
10739 #endif
10741 Qcontrol = intern ("control"); staticpro (&Qcontrol);
10742 Qmeta = intern ("meta"); staticpro (&Qmeta);
10743 Qalt = intern ("alt"); staticpro (&Qalt);
10744 Qhyper = intern ("hyper"); staticpro (&Qhyper);
10745 Qsuper = intern ("super"); staticpro (&Qsuper);
10746 Qmodifier_value = intern ("modifier-value");
10747 staticpro (&Qmodifier_value);
10749 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
10750 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
10751 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
10752 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
10753 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
10755 #if USE_CARBON_EVENTS
10756 Qhicommand = intern ("hicommand"); staticpro (&Qhicommand);
10757 #ifdef MAC_OSX
10758 Qservices = intern ("services"); staticpro (&Qservices);
10759 Qpaste = intern ("paste"); staticpro (&Qpaste);
10760 Qperform = intern ("perform"); staticpro (&Qperform);
10761 #endif
10762 #endif
10764 #ifdef MAC_OSX
10765 Fprovide (intern ("mac-carbon"), Qnil);
10766 #endif
10768 staticpro (&Qreverse);
10769 Qreverse = intern ("reverse");
10771 staticpro (&x_display_name_list);
10772 x_display_name_list = Qnil;
10774 staticpro (&last_mouse_scroll_bar);
10775 last_mouse_scroll_bar = Qnil;
10777 staticpro (&fm_font_family_alist);
10778 fm_font_family_alist = Qnil;
10780 #if USE_ATSUI
10781 staticpro (&atsu_font_id_hash);
10782 atsu_font_id_hash = Qnil;
10783 #endif
10785 /* We don't yet support this, but defining this here avoids whining
10786 from cus-start.el and other places, like "M-x set-variable". */
10787 DEFVAR_BOOL ("x-use-underline-position-properties",
10788 &x_use_underline_position_properties,
10789 doc: /* *Non-nil means make use of UNDERLINE_POSITION font properties.
10790 nil means ignore them. If you encounter fonts with bogus
10791 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
10792 to 4.1, set this to nil.
10794 NOTE: Not supported on Mac yet. */);
10795 x_use_underline_position_properties = 0;
10797 DEFVAR_LISP ("x-toolkit-scroll-bars", &Vx_toolkit_scroll_bars,
10798 doc: /* If not nil, Emacs uses toolkit scroll bars. */);
10799 #ifdef USE_TOOLKIT_SCROLL_BARS
10800 Vx_toolkit_scroll_bars = Qt;
10801 #else
10802 Vx_toolkit_scroll_bars = Qnil;
10803 #endif
10805 staticpro (&last_mouse_motion_frame);
10806 last_mouse_motion_frame = Qnil;
10808 /* Variables to configure modifier key assignment. */
10810 DEFVAR_LISP ("mac-control-modifier", &Vmac_control_modifier,
10811 doc: /* *Modifier key assumed when the Mac control key is pressed.
10812 The value can be `control', `meta', `alt', `hyper', or `super' for the
10813 respective modifier. The default is `control'. */);
10814 Vmac_control_modifier = Qcontrol;
10816 DEFVAR_LISP ("mac-option-modifier", &Vmac_option_modifier,
10817 doc: /* *Modifier key assumed when the Mac alt/option key is pressed.
10818 The value can be `control', `meta', `alt', `hyper', or `super' for the
10819 respective modifier. If the value is nil then the key will act as the
10820 normal Mac control modifier, and the option key can be used to compose
10821 characters depending on the chosen Mac keyboard setting. */);
10822 Vmac_option_modifier = Qnil;
10824 DEFVAR_LISP ("mac-command-modifier", &Vmac_command_modifier,
10825 doc: /* *Modifier key assumed when the Mac command key is pressed.
10826 The value can be `control', `meta', `alt', `hyper', or `super' for the
10827 respective modifier. The default is `meta'. */);
10828 Vmac_command_modifier = Qmeta;
10830 DEFVAR_LISP ("mac-function-modifier", &Vmac_function_modifier,
10831 doc: /* *Modifier key assumed when the Mac function key is pressed.
10832 The value can be `control', `meta', `alt', `hyper', or `super' for the
10833 respective modifier. Note that remapping the function key may lead to
10834 unexpected results for some keys on non-US/GB keyboards. */);
10835 Vmac_function_modifier = Qnil;
10837 DEFVAR_LISP ("mac-emulate-three-button-mouse",
10838 &Vmac_emulate_three_button_mouse,
10839 doc: /* *Specify a way of three button mouse emulation.
10840 The value can be nil, t, or the symbol `reverse'.
10841 nil means that no emulation should be done and the modifiers should be
10842 placed on the mouse-1 event.
10843 t means that when the option-key is held down while pressing the mouse
10844 button, the click will register as mouse-2 and while the command-key
10845 is held down, the click will register as mouse-3.
10846 The symbol `reverse' means that the option-key will register for
10847 mouse-3 and the command-key will register for mouse-2. */);
10848 Vmac_emulate_three_button_mouse = Qnil;
10850 #if USE_CARBON_EVENTS
10851 DEFVAR_BOOL ("mac-wheel-button-is-mouse-2", &mac_wheel_button_is_mouse_2,
10852 doc: /* *Non-nil if the wheel button is mouse-2 and the right click mouse-3.
10853 Otherwise, the right click will be treated as mouse-2 and the wheel
10854 button will be mouse-3. */);
10855 mac_wheel_button_is_mouse_2 = 1;
10857 DEFVAR_BOOL ("mac-pass-command-to-system", &mac_pass_command_to_system,
10858 doc: /* *Non-nil if command key presses are passed on to the Mac Toolbox. */);
10859 mac_pass_command_to_system = 1;
10861 DEFVAR_BOOL ("mac-pass-control-to-system", &mac_pass_control_to_system,
10862 doc: /* *Non-nil if control key presses are passed on to the Mac Toolbox. */);
10863 mac_pass_control_to_system = 1;
10865 #endif
10867 DEFVAR_BOOL ("mac-allow-anti-aliasing", &mac_use_core_graphics,
10868 doc: /* *If non-nil, allow anti-aliasing.
10869 The text will be rendered using Core Graphics text rendering which
10870 may anti-alias the text. */);
10871 mac_use_core_graphics = 0;
10873 /* Register an entry for `mac-roman' so that it can be used when
10874 creating the terminal frame on Mac OS 9 before loading
10875 term/mac-win.elc. */
10876 DEFVAR_LISP ("mac-charset-info-alist", &Vmac_charset_info_alist,
10877 doc: /* Alist of Emacs character sets vs text encodings and coding systems.
10878 Each entry should be of the form:
10880 (CHARSET-NAME TEXT-ENCODING CODING-SYSTEM)
10882 where CHARSET-NAME is a string used in font names to identify the
10883 charset, TEXT-ENCODING is a TextEncodingBase value in Mac, and
10884 CODING_SYSTEM is a coding system corresponding to TEXT-ENCODING. */);
10885 Vmac_charset_info_alist =
10886 Fcons (list3 (build_string ("mac-roman"),
10887 make_number (smRoman), Qnil), Qnil);
10890 /* arch-tag: f2259165-4454-4c04-a029-a133c8af7b5b
10891 (do not change this comment) */