(Caching passphrase): Clean up previous change.
[emacs.git] / src / macterm.c
bloba5a193cb88ca769765d16132c08d4d50b38ea952
1 /* Implementation of GUI terminal on the Mac OS.
2 Copyright (C) 2000, 2001, 2002, 2003, 2004,
3 2005, 2006, 2007 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 "disptab.h"
81 #include "buffer.h"
82 #include "window.h"
83 #include "keyboard.h"
84 #include "intervals.h"
85 #include "atimer.h"
86 #include "keymap.h"
90 /* Non-nil means Emacs uses toolkit scroll bars. */
92 Lisp_Object Vx_toolkit_scroll_bars;
94 /* If non-zero, the text will be rendered using Core Graphics text
95 rendering which may anti-alias the text. */
96 int mac_use_core_graphics;
99 /* Non-zero means that a HELP_EVENT has been generated since Emacs
100 start. */
102 static int any_help_event_p;
104 /* Last window where we saw the mouse. Used by mouse-autoselect-window. */
105 static Lisp_Object last_window;
107 /* Non-zero means make use of UNDERLINE_POSITION font properties.
108 (Not yet supported.) */
109 int x_use_underline_position_properties;
111 /* Non-zero means to draw the underline at the same place as the descent line. */
113 int x_underline_at_descent_line;
115 /* This is a chain of structures for all the X displays currently in
116 use. */
118 struct x_display_info *x_display_list;
120 /* This is a list of cons cells, each of the form (NAME
121 FONT-LIST-CACHE . RESOURCE-DATABASE), one for each element of
122 x_display_list and in the same order. NAME is the name of the
123 frame. FONT-LIST-CACHE records previous values returned by
124 x-list-fonts. RESOURCE-DATABASE preserves the X Resource Database
125 equivalent, which is implemented with a Lisp object, for the
126 display. */
128 Lisp_Object x_display_name_list;
130 /* This is display since Mac does not support multiple ones. */
131 struct mac_display_info one_mac_display_info;
133 /* Frame being updated by update_frame. This is declared in term.c.
134 This is set by update_begin and looked at by all the XT functions.
135 It is zero while not inside an update. In that case, the XT
136 functions assume that `selected_frame' is the frame to apply to. */
138 extern struct frame *updating_frame;
140 /* This is a frame waiting to be auto-raised, within XTread_socket. */
142 struct frame *pending_autoraise_frame;
144 /* Mouse movement.
146 Formerly, we used PointerMotionHintMask (in standard_event_mask)
147 so that we would have to call XQueryPointer after each MotionNotify
148 event to ask for another such event. However, this made mouse tracking
149 slow, and there was a bug that made it eventually stop.
151 Simply asking for MotionNotify all the time seems to work better.
153 In order to avoid asking for motion events and then throwing most
154 of them away or busy-polling the server for mouse positions, we ask
155 the server for pointer motion hints. This means that we get only
156 one event per group of mouse movements. "Groups" are delimited by
157 other kinds of events (focus changes and button clicks, for
158 example), or by XQueryPointer calls; when one of these happens, we
159 get another MotionNotify event the next time the mouse moves. This
160 is at least as efficient as getting motion events when mouse
161 tracking is on, and I suspect only negligibly worse when tracking
162 is off. */
164 /* Where the mouse was last time we reported a mouse event. */
166 static Rect last_mouse_glyph;
167 static FRAME_PTR last_mouse_glyph_frame;
169 /* The scroll bar in which the last X motion event occurred.
171 If the last X motion event occurred in a scroll bar, we set this so
172 XTmouse_position can know whether to report a scroll bar motion or
173 an ordinary motion.
175 If the last X motion event didn't occur in a scroll bar, we set
176 this to Qnil, to tell XTmouse_position to return an ordinary motion
177 event. */
179 static Lisp_Object last_mouse_scroll_bar;
181 /* This is a hack. We would really prefer that XTmouse_position would
182 return the time associated with the position it returns, but there
183 doesn't seem to be any way to wrest the time-stamp from the server
184 along with the position query. So, we just keep track of the time
185 of the last movement we received, and return that in hopes that
186 it's somewhat accurate. */
188 static Time last_mouse_movement_time;
190 struct scroll_bar *tracked_scroll_bar = NULL;
192 /* Incremented by XTread_socket whenever it really tries to read
193 events. */
195 #ifdef __STDC__
196 static int volatile input_signal_count;
197 #else
198 static int input_signal_count;
199 #endif
201 extern Lisp_Object Vsystem_name;
203 extern Lisp_Object Qeql;
205 /* A mask of extra modifier bits to put into every keyboard char. */
207 extern EMACS_INT extra_keyboard_modifiers;
209 /* The keysyms to use for the various modifiers. */
211 static Lisp_Object Qalt, Qhyper, Qsuper, Qcontrol, Qmeta, Qmodifier_value;
213 extern int inhibit_window_system;
215 #if __MRC__ && !TARGET_API_MAC_CARBON
216 QDGlobals qd; /* QuickDraw global information structure. */
217 #endif
219 #define mac_window_to_frame(wp) (((mac_output *) GetWRefCon (wp))->mFP)
221 struct mac_display_info *mac_display_info_for_display (Display *);
222 static void x_update_window_end P_ ((struct window *, int, int));
223 int x_catch_errors P_ ((Display *));
224 void x_uncatch_errors P_ ((Display *, int));
225 void x_lower_frame P_ ((struct frame *));
226 void x_scroll_bar_clear P_ ((struct frame *));
227 int x_had_errors_p P_ ((Display *));
228 void x_wm_set_size_hint P_ ((struct frame *, long, int));
229 void x_raise_frame P_ ((struct frame *));
230 void x_set_window_size P_ ((struct frame *, int, int, int));
231 void x_wm_set_window_state P_ ((struct frame *, int));
232 void x_wm_set_icon_pixmap P_ ((struct frame *, int));
233 void mac_initialize P_ ((void));
234 static void x_font_min_bounds P_ ((XFontStruct *, int *, int *));
235 static int x_compute_min_glyph_bounds P_ ((struct frame *));
236 static void x_update_end P_ ((struct frame *));
237 static void XTframe_up_to_date P_ ((struct frame *));
238 static void XTset_terminal_modes P_ ((void));
239 static void XTreset_terminal_modes P_ ((void));
240 static void x_clear_frame P_ ((void));
241 static void frame_highlight P_ ((struct frame *));
242 static void frame_unhighlight P_ ((struct frame *));
243 static void x_new_focus_frame P_ ((struct x_display_info *, struct frame *));
244 static void mac_focus_changed P_ ((int, struct mac_display_info *,
245 struct frame *, struct input_event *));
246 static void x_detect_focus_change P_ ((struct mac_display_info *,
247 const EventRecord *,
248 struct input_event *));
249 static void XTframe_rehighlight P_ ((struct frame *));
250 static void x_frame_rehighlight P_ ((struct x_display_info *));
251 static void x_draw_hollow_cursor P_ ((struct window *, struct glyph_row *));
252 static void x_draw_bar_cursor P_ ((struct window *, struct glyph_row *, int,
253 enum text_cursor_kinds));
255 static void x_clip_to_row P_ ((struct window *, struct glyph_row *, int, GC));
256 static void x_flush P_ ((struct frame *f));
257 static void x_update_begin P_ ((struct frame *));
258 static void x_update_window_begin P_ ((struct window *));
259 static void x_after_update_window_line P_ ((struct glyph_row *));
260 static void x_scroll_bar_report_motion P_ ((struct frame **, Lisp_Object *,
261 enum scroll_bar_part *,
262 Lisp_Object *, Lisp_Object *,
263 unsigned long *));
265 static int is_emacs_window P_ ((WindowPtr));
266 static XCharStruct *mac_per_char_metric P_ ((XFontStruct *, XChar2b *, int));
267 static void XSetFont P_ ((Display *, GC, XFontStruct *));
269 #define GC_FORE_COLOR(gc) (&(gc)->fore_color)
270 #define GC_BACK_COLOR(gc) (&(gc)->back_color)
271 #define GC_FONT(gc) ((gc)->xgcv.font)
272 #define FRAME_NORMAL_GC(f) ((f)->output_data.mac->normal_gc)
274 #define CG_SET_FILL_COLOR(context, color) \
275 CGContextSetRGBFillColor (context, \
276 RED_FROM_ULONG (color) / 255.0f, \
277 GREEN_FROM_ULONG (color) / 255.0f, \
278 BLUE_FROM_ULONG (color) / 255.0f, 1.0f)
279 #if USE_CG_DRAWING && MAC_OS_X_VERSION_MAX_ALLOWED >= 1030
280 #if MAC_OS_X_VERSION_MIN_REQUIRED == 1020
281 #define CG_SET_FILL_COLOR_MAYBE_WITH_CGCOLOR(context, color, cg_color) \
282 do { \
283 if (CGColorGetTypeID != NULL) \
284 CGContextSetFillColorWithColor (context, cg_color); \
285 else \
286 CG_SET_FILL_COLOR (context, color); \
287 } while (0)
288 #else
289 #define CG_SET_FILL_COLOR_MAYBE_WITH_CGCOLOR(context, color, cg_color) \
290 CGContextSetFillColorWithColor (context, cg_color)
291 #endif
292 #else
293 #define CG_SET_FILL_COLOR_MAYBE_WITH_CGCOLOR(context, color, cg_color) \
294 CG_SET_FILL_COLOR (context, color)
295 #endif
296 #define CG_SET_FILL_COLOR_WITH_GC_FOREGROUND(context, gc) \
297 CG_SET_FILL_COLOR_MAYBE_WITH_CGCOLOR (context, (gc)->xgcv.foreground, \
298 (gc)->cg_fore_color)
299 #define CG_SET_FILL_COLOR_WITH_GC_BACKGROUND(context, gc) \
300 CG_SET_FILL_COLOR_MAYBE_WITH_CGCOLOR (context, (gc)->xgcv.background, \
301 (gc)->cg_back_color)
304 #define CG_SET_STROKE_COLOR(context, color) \
305 CGContextSetRGBStrokeColor (context, \
306 RED_FROM_ULONG (color) / 255.0f, \
307 GREEN_FROM_ULONG (color) / 255.0f, \
308 BLUE_FROM_ULONG (color) / 255.0f, 1.0f)
309 #if USE_CG_DRAWING && MAC_OS_X_VERSION_MAX_ALLOWED >= 1030
310 #if MAC_OS_X_VERSION_MIN_REQUIRED == 1020
311 #define CG_SET_STROKE_COLOR_MAYBE_WITH_CGCOLOR(context, color, cg_color) \
312 do { \
313 if (CGColorGetTypeID != NULL) \
314 CGContextSetStrokeColorWithColor (context, cg_color); \
315 else \
316 CG_SET_STROKE_COLOR (context, color); \
317 } while (0)
318 #else
319 #define CG_SET_STROKE_COLOR_MAYBE_WITH_CGCOLOR(context, color, cg_color) \
320 CGContextSetStrokeColorWithColor (context, cg_color)
321 #endif
322 #else
323 #define CG_SET_STROKE_COLOR_MAYBE_WITH_CGCOLOR(context, color, cg_color) \
324 CG_SET_STROKE_COLOR (context, color)
325 #endif
326 #define CG_SET_STROKE_COLOR_WITH_GC_FOREGROUND(context, gc) \
327 CG_SET_STROKE_COLOR_MAYBE_WITH_CGCOLOR (context, (gc)->xgcv.foreground, \
328 (gc)->cg_fore_color)
330 #if USE_CG_DRAWING
331 #define FRAME_CG_CONTEXT(f) ((f)->output_data.mac->cg_context)
333 /* Fringe bitmaps. */
335 static int max_fringe_bmp = 0;
336 static CGImageRef *fringe_bmp = 0;
338 static CGColorSpaceRef mac_cg_color_space_rgb;
339 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1030
340 static CGColorRef mac_cg_color_black;
341 #endif
343 static void
344 init_cg_color ()
346 mac_cg_color_space_rgb = CGColorSpaceCreateDeviceRGB ();
347 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1030
348 #if MAC_OS_X_VERSION_MIN_REQUIRED == 1020
349 /* Don't check the availability of CGColorCreate; this symbol is
350 defined even in Mac OS X 10.1. */
351 if (CGColorGetTypeID != NULL)
352 #endif
354 float rgba[] = {0.0f, 0.0f, 0.0f, 1.0f};
356 mac_cg_color_black = CGColorCreate (mac_cg_color_space_rgb, rgba);
358 #endif
361 static CGContextRef
362 mac_begin_cg_clip (f, gc)
363 struct frame *f;
364 GC gc;
366 CGContextRef context = FRAME_CG_CONTEXT (f);
368 if (!context)
370 QDBeginCGContext (GetWindowPort (FRAME_MAC_WINDOW (f)), &context);
371 FRAME_CG_CONTEXT (f) = context;
374 CGContextSaveGState (context);
375 CGContextTranslateCTM (context, 0, FRAME_PIXEL_HEIGHT (f));
376 CGContextScaleCTM (context, 1, -1);
377 if (gc && gc->n_clip_rects)
378 CGContextClipToRects (context, gc->clip_rects, gc->n_clip_rects);
380 return context;
383 static void
384 mac_end_cg_clip (f)
385 struct frame *f;
387 CGContextRestoreGState (FRAME_CG_CONTEXT (f));
390 void
391 mac_prepare_for_quickdraw (f)
392 struct frame *f;
394 if (f == NULL)
396 Lisp_Object rest, frame;
397 FOR_EACH_FRAME (rest, frame)
398 if (FRAME_MAC_P (XFRAME (frame)))
399 mac_prepare_for_quickdraw (XFRAME (frame));
401 else
403 CGContextRef context = FRAME_CG_CONTEXT (f);
405 if (context)
407 CGContextSynchronize (context);
408 QDEndCGContext (GetWindowPort (FRAME_MAC_WINDOW (f)),
409 &FRAME_CG_CONTEXT (f));
413 #endif
415 static RgnHandle saved_port_clip_region = NULL;
417 static void
418 mac_begin_clip (gc)
419 GC gc;
421 static RgnHandle new_region = NULL;
423 if (saved_port_clip_region == NULL)
424 saved_port_clip_region = NewRgn ();
425 if (new_region == NULL)
426 new_region = NewRgn ();
428 if (gc->n_clip_rects)
430 GetClip (saved_port_clip_region);
431 SectRgn (saved_port_clip_region, gc->clip_region, new_region);
432 SetClip (new_region);
436 static void
437 mac_end_clip (gc)
438 GC gc;
440 if (gc->n_clip_rects)
441 SetClip (saved_port_clip_region);
445 /* X display function emulation */
447 void
448 XFreePixmap (display, pixmap)
449 Display *display; /* not used */
450 Pixmap pixmap;
452 DisposeGWorld (pixmap);
456 /* Mac version of XDrawLine. */
458 static void
459 mac_draw_line (f, gc, x1, y1, x2, y2)
460 struct frame *f;
461 GC gc;
462 int x1, y1, x2, y2;
464 #if USE_CG_DRAWING
465 CGContextRef context;
466 float gx1 = x1, gy1 = y1, gx2 = x2, gy2 = y2;
468 if (y1 != y2)
469 gx1 += 0.5f, gx2 += 0.5f;
470 if (x1 != x2)
471 gy1 += 0.5f, gy2 += 0.5f;
473 context = mac_begin_cg_clip (f, gc);
474 CG_SET_STROKE_COLOR_WITH_GC_FOREGROUND (context, gc);
475 CGContextBeginPath (context);
476 CGContextMoveToPoint (context, gx1, gy1);
477 CGContextAddLineToPoint (context, gx2, gy2);
478 CGContextClosePath (context);
479 CGContextStrokePath (context);
480 mac_end_cg_clip (f);
481 #else
482 if (x1 == x2)
484 if (y1 > y2)
485 y1--;
486 else if (y2 > y1)
487 y2--;
489 else if (y1 == y2)
491 if (x1 > x2)
492 x1--;
493 else
494 x2--;
497 SetPortWindowPort (FRAME_MAC_WINDOW (f));
499 RGBForeColor (GC_FORE_COLOR (gc));
501 mac_begin_clip (gc);
502 MoveTo (x1, y1);
503 LineTo (x2, y2);
504 mac_end_clip (gc);
505 #endif
508 /* Mac version of XDrawLine (to Pixmap). */
510 void
511 XDrawLine (display, p, gc, x1, y1, x2, y2)
512 Display *display;
513 Pixmap p;
514 GC gc;
515 int x1, y1, x2, y2;
517 CGrafPtr old_port;
518 GDHandle old_gdh;
520 if (x1 == x2)
522 if (y1 > y2)
523 y1--;
524 else if (y2 > y1)
525 y2--;
527 else if (y1 == y2)
529 if (x1 > x2)
530 x1--;
531 else
532 x2--;
535 GetGWorld (&old_port, &old_gdh);
536 SetGWorld (p, NULL);
538 RGBForeColor (GC_FORE_COLOR (gc));
540 LockPixels (GetGWorldPixMap (p));
541 MoveTo (x1, y1);
542 LineTo (x2, y2);
543 UnlockPixels (GetGWorldPixMap (p));
545 SetGWorld (old_port, old_gdh);
549 static void
550 mac_erase_rectangle (f, gc, x, y, width, height)
551 struct frame *f;
552 GC gc;
553 int x, y;
554 unsigned int width, height;
556 #if USE_CG_DRAWING
557 CGContextRef context;
559 context = mac_begin_cg_clip (f, gc);
560 CG_SET_FILL_COLOR_WITH_GC_BACKGROUND (context, gc);
561 CGContextFillRect (context, CGRectMake (x, y, width, height));
562 mac_end_cg_clip (f);
563 #else
564 Rect r;
566 SetPortWindowPort (FRAME_MAC_WINDOW (f));
568 RGBBackColor (GC_BACK_COLOR (gc));
569 SetRect (&r, x, y, x + width, y + height);
571 mac_begin_clip (gc);
572 EraseRect (&r);
573 mac_end_clip (gc);
575 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
576 #endif
580 /* Mac version of XClearArea. */
582 void
583 mac_clear_area (f, x, y, width, height)
584 struct frame *f;
585 int x, y;
586 unsigned int width, height;
588 mac_erase_rectangle (f, FRAME_NORMAL_GC (f), x, y, width, height);
591 /* Mac version of XClearWindow. */
593 static void
594 mac_clear_window (f)
595 struct frame *f;
597 #if USE_CG_DRAWING
598 CGContextRef context;
599 GC gc = FRAME_NORMAL_GC (f);
601 context = mac_begin_cg_clip (f, NULL);
602 CG_SET_FILL_COLOR_WITH_GC_BACKGROUND (context, gc);
603 CGContextFillRect (context, CGRectMake (0, 0, FRAME_PIXEL_WIDTH (f),
604 FRAME_PIXEL_HEIGHT (f)));
605 mac_end_cg_clip (f);
606 #else
607 SetPortWindowPort (FRAME_MAC_WINDOW (f));
609 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
611 #if TARGET_API_MAC_CARBON
613 Rect r;
615 GetWindowPortBounds (FRAME_MAC_WINDOW (f), &r);
616 EraseRect (&r);
618 #else /* not TARGET_API_MAC_CARBON */
619 EraseRect (&(FRAME_MAC_WINDOW (f)->portRect));
620 #endif /* not TARGET_API_MAC_CARBON */
621 #endif
625 /* Mac replacement for XCopyArea. */
627 #if USE_CG_DRAWING
628 static void
629 mac_draw_cg_image (image, f, gc, src_x, src_y, width, height,
630 dest_x, dest_y, overlay_p)
631 CGImageRef image;
632 struct frame *f;
633 GC gc;
634 int src_x, src_y;
635 unsigned int width, height;
636 int dest_x, dest_y, overlay_p;
638 CGContextRef context;
639 float port_height = FRAME_PIXEL_HEIGHT (f);
640 CGRect dest_rect = CGRectMake (dest_x, dest_y, width, height);
642 context = mac_begin_cg_clip (f, gc);
643 if (!overlay_p)
645 CG_SET_FILL_COLOR_WITH_GC_BACKGROUND (context, gc);
646 CGContextFillRect (context, dest_rect);
648 CGContextClipToRect (context, dest_rect);
649 CGContextScaleCTM (context, 1, -1);
650 CGContextTranslateCTM (context, 0, -port_height);
651 if (CGImageIsMask (image))
652 CG_SET_FILL_COLOR_WITH_GC_FOREGROUND (context, gc);
653 CGContextDrawImage (context,
654 CGRectMake (dest_x - src_x,
655 port_height - (dest_y - src_y
656 + CGImageGetHeight (image)),
657 CGImageGetWidth (image),
658 CGImageGetHeight (image)),
659 image);
660 mac_end_cg_clip (f);
663 #else /* !USE_CG_DRAWING */
665 static void
666 mac_draw_bitmap (f, gc, x, y, width, height, bits, overlay_p)
667 struct frame *f;
668 GC gc;
669 int x, y, width, height;
670 unsigned short *bits;
671 int overlay_p;
673 BitMap bitmap;
674 Rect r;
676 bitmap.rowBytes = sizeof(unsigned short);
677 bitmap.baseAddr = (char *)bits;
678 SetRect (&(bitmap.bounds), 0, 0, width, height);
680 SetPortWindowPort (FRAME_MAC_WINDOW (f));
682 RGBForeColor (GC_FORE_COLOR (gc));
683 RGBBackColor (GC_BACK_COLOR (gc));
684 SetRect (&r, x, y, x + width, y + height);
686 mac_begin_clip (gc);
687 #if TARGET_API_MAC_CARBON
689 CGrafPtr port;
691 GetPort (&port);
692 LockPortBits (port);
693 CopyBits (&bitmap, GetPortBitMapForCopyBits (port),
694 &(bitmap.bounds), &r, overlay_p ? srcOr : srcCopy, 0);
695 UnlockPortBits (port);
697 #else /* not TARGET_API_MAC_CARBON */
698 CopyBits (&bitmap, &(FRAME_MAC_WINDOW (f)->portBits), &(bitmap.bounds), &r,
699 overlay_p ? srcOr : srcCopy, 0);
700 #endif /* not TARGET_API_MAC_CARBON */
701 mac_end_clip (gc);
703 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
705 #endif /* !USE_CG_DRAWING */
708 /* Mac replacement for XCreateBitmapFromBitmapData. */
710 static void
711 mac_create_bitmap_from_bitmap_data (bitmap, bits, w, h)
712 BitMap *bitmap;
713 char *bits;
714 int w, h;
716 static const unsigned char swap_nibble[16]
717 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
718 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
719 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
720 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
721 int i, j, w1;
722 char *p;
724 w1 = (w + 7) / 8; /* nb of 8bits elt in X bitmap */
725 bitmap->rowBytes = ((w + 15) / 16) * 2; /* nb of 16bits elt in Mac bitmap */
726 bitmap->baseAddr = xmalloc (bitmap->rowBytes * h);
727 bzero (bitmap->baseAddr, bitmap->rowBytes * h);
728 for (i = 0; i < h; i++)
730 p = bitmap->baseAddr + i * bitmap->rowBytes;
731 for (j = 0; j < w1; j++)
733 /* Bitswap XBM bytes to match how Mac does things. */
734 unsigned char c = *bits++;
735 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
736 | (swap_nibble[(c>>4) & 0xf]));;
740 SetRect (&(bitmap->bounds), 0, 0, w, h);
744 static void
745 mac_free_bitmap (bitmap)
746 BitMap *bitmap;
748 xfree (bitmap->baseAddr);
752 Pixmap
753 XCreatePixmap (display, w, width, height, depth)
754 Display *display; /* not used */
755 WindowPtr w;
756 unsigned int width, height;
757 unsigned int depth;
759 Pixmap pixmap;
760 Rect r;
761 QDErr err;
763 SetPortWindowPort (w);
765 SetRect (&r, 0, 0, width, height);
766 #if !defined (WORDS_BIG_ENDIAN) && USE_CG_DRAWING
767 if (depth == 1)
768 #endif
769 err = NewGWorld (&pixmap, depth, &r, NULL, NULL, 0);
770 #if !defined (WORDS_BIG_ENDIAN) && USE_CG_DRAWING
771 else
772 /* CreateCGImageFromPixMaps requires ARGB format. */
773 err = QTNewGWorld (&pixmap, k32ARGBPixelFormat, &r, NULL, NULL, 0);
774 #endif
775 if (err != noErr)
776 return NULL;
777 return pixmap;
781 Pixmap
782 XCreatePixmapFromBitmapData (display, w, data, width, height, fg, bg, depth)
783 Display *display; /* not used */
784 WindowPtr w;
785 char *data;
786 unsigned int width, height;
787 unsigned long fg, bg;
788 unsigned int depth;
790 Pixmap pixmap;
791 BitMap bitmap;
792 CGrafPtr old_port;
793 GDHandle old_gdh;
794 static GC gc = NULL; /* not reentrant */
796 if (gc == NULL)
797 gc = XCreateGC (display, w, 0, NULL);
799 pixmap = XCreatePixmap (display, w, width, height, depth);
800 if (pixmap == NULL)
801 return NULL;
803 GetGWorld (&old_port, &old_gdh);
804 SetGWorld (pixmap, NULL);
805 mac_create_bitmap_from_bitmap_data (&bitmap, data, width, height);
806 XSetForeground (display, gc, fg);
807 XSetBackground (display, gc, bg);
808 RGBForeColor (GC_FORE_COLOR (gc));
809 RGBBackColor (GC_BACK_COLOR (gc));
810 LockPixels (GetGWorldPixMap (pixmap));
811 #if TARGET_API_MAC_CARBON
812 CopyBits (&bitmap, GetPortBitMapForCopyBits (pixmap),
813 &bitmap.bounds, &bitmap.bounds, srcCopy, 0);
814 #else /* not TARGET_API_MAC_CARBON */
815 CopyBits (&bitmap, &(((GrafPtr)pixmap)->portBits),
816 &bitmap.bounds, &bitmap.bounds, srcCopy, 0);
817 #endif /* not TARGET_API_MAC_CARBON */
818 UnlockPixels (GetGWorldPixMap (pixmap));
819 SetGWorld (old_port, old_gdh);
820 mac_free_bitmap (&bitmap);
822 return pixmap;
826 /* Mac replacement for XFillRectangle. */
828 static void
829 mac_fill_rectangle (f, gc, x, y, width, height)
830 struct frame *f;
831 GC gc;
832 int x, y;
833 unsigned int width, height;
835 #if USE_CG_DRAWING
836 CGContextRef context;
838 context = mac_begin_cg_clip (f, gc);
839 CG_SET_FILL_COLOR_WITH_GC_FOREGROUND (context, gc);
840 CGContextFillRect (context, CGRectMake (x, y, width, height));
841 mac_end_cg_clip (f);
842 #else
843 Rect r;
845 SetPortWindowPort (FRAME_MAC_WINDOW (f));
847 RGBForeColor (GC_FORE_COLOR (gc));
848 SetRect (&r, x, y, x + width, y + height);
850 mac_begin_clip (gc);
851 PaintRect (&r); /* using foreground color of gc */
852 mac_end_clip (gc);
853 #endif
857 /* Mac replacement for XDrawRectangle: dest is a window. */
859 static void
860 mac_draw_rectangle (f, gc, x, y, width, height)
861 struct frame *f;
862 GC gc;
863 int x, y;
864 unsigned int width, height;
866 #if USE_CG_DRAWING
867 CGContextRef context;
869 context = mac_begin_cg_clip (f, gc);
870 CG_SET_STROKE_COLOR_WITH_GC_FOREGROUND (context, gc);
871 CGContextStrokeRect (context,
872 CGRectMake (x + 0.5f, y + 0.5f, width, height));
873 mac_end_cg_clip (f);
874 #else
875 Rect r;
877 SetPortWindowPort (FRAME_MAC_WINDOW (f));
879 RGBForeColor (GC_FORE_COLOR (gc));
880 SetRect (&r, x, y, x + width + 1, y + height + 1);
882 mac_begin_clip (gc);
883 FrameRect (&r); /* using foreground color of gc */
884 mac_end_clip (gc);
885 #endif
889 #if USE_ATSUI
890 static OSStatus
891 atsu_get_text_layout_with_text_ptr (text, text_length, style, text_layout)
892 ConstUniCharArrayPtr text;
893 UniCharCount text_length;
894 ATSUStyle style;
895 ATSUTextLayout *text_layout;
897 OSStatus err;
898 static ATSUTextLayout saved_text_layout = NULL; /* not reentrant */
900 if (saved_text_layout == NULL)
902 static const UniCharCount lengths[] = {kATSUToTextEnd};
903 static const ATSUAttributeTag tags[] = {kATSULineLayoutOptionsTag};
904 static const ByteCount sizes[] = {sizeof (ATSLineLayoutOptions)};
905 static ATSLineLayoutOptions line_layout =
906 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
907 kATSLineDisableAllLayoutOperations | kATSLineUseDeviceMetrics
908 | kATSLineUseQDRendering
909 #else
910 kATSLineIsDisplayOnly | kATSLineFractDisable
911 #endif
913 static const ATSUAttributeValuePtr values[] = {&line_layout};
915 err = ATSUCreateTextLayoutWithTextPtr (text,
916 kATSUFromTextBeginning,
917 kATSUToTextEnd,
918 text_length,
919 1, lengths, &style,
920 &saved_text_layout);
921 if (err == noErr)
922 err = ATSUSetLayoutControls (saved_text_layout,
923 sizeof (tags) / sizeof (tags[0]),
924 tags, sizes, values);
925 /* XXX: Should we do this? */
926 if (err == noErr)
927 err = ATSUSetTransientFontMatching (saved_text_layout, true);
929 else
931 err = ATSUSetRunStyle (saved_text_layout, style,
932 kATSUFromTextBeginning, kATSUToTextEnd);
933 if (err == noErr)
934 err = ATSUSetTextPointerLocation (saved_text_layout, text,
935 kATSUFromTextBeginning,
936 kATSUToTextEnd,
937 text_length);
940 if (err == noErr)
941 *text_layout = saved_text_layout;
942 return err;
944 #endif
947 static void
948 mac_invert_rectangle (f, x, y, width, height)
949 struct frame *f;
950 int x, y;
951 unsigned int width, height;
953 Rect r;
955 #if USE_CG_DRAWING
956 mac_prepare_for_quickdraw (f);
957 #endif
958 SetPortWindowPort (FRAME_MAC_WINDOW (f));
960 SetRect (&r, x, y, x + width, y + height);
962 InvertRect (&r);
966 static void
967 mac_draw_string_common (f, gc, x, y, buf, nchars, bg_width,
968 overstrike_p, bytes_per_char)
969 struct frame *f;
970 GC gc;
971 int x, y;
972 char *buf;
973 int nchars, bg_width, overstrike_p, bytes_per_char;
975 SetPortWindowPort (FRAME_MAC_WINDOW (f));
977 #if USE_ATSUI
978 if (GC_FONT (gc)->mac_style)
980 OSStatus err;
981 ATSUTextLayout text_layout;
983 xassert (bytes_per_char == 2);
985 #ifndef WORDS_BIG_ENDIAN
987 int i;
988 UniChar *text = (UniChar *)buf;
990 for (i = 0; i < nchars; i++)
991 text[i] = EndianU16_BtoN (text[i]);
993 #endif
994 err = atsu_get_text_layout_with_text_ptr ((ConstUniCharArrayPtr)buf,
995 nchars,
996 GC_FONT (gc)->mac_style,
997 &text_layout);
998 if (err != noErr)
999 return;
1000 #ifdef MAC_OSX
1001 if (!mac_use_core_graphics)
1003 #endif
1004 #if USE_CG_DRAWING
1005 mac_prepare_for_quickdraw (f);
1006 #endif
1007 mac_begin_clip (gc);
1008 RGBForeColor (GC_FORE_COLOR (gc));
1009 if (bg_width)
1011 Rect r;
1013 SetRect (&r, x, y - FONT_BASE (GC_FONT (gc)),
1014 x + bg_width, y + FONT_DESCENT (GC_FONT (gc)));
1015 RGBBackColor (GC_BACK_COLOR (gc));
1016 EraseRect (&r);
1017 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
1019 MoveTo (x, y);
1020 ATSUDrawText (text_layout,
1021 kATSUFromTextBeginning, kATSUToTextEnd,
1022 kATSUUseGrafPortPenLoc, kATSUUseGrafPortPenLoc);
1023 if (overstrike_p)
1025 MoveTo (x + 1, y);
1026 ATSUDrawText (text_layout,
1027 kATSUFromTextBeginning, kATSUToTextEnd,
1028 kATSUUseGrafPortPenLoc, kATSUUseGrafPortPenLoc);
1030 mac_end_clip (gc);
1031 #ifdef MAC_OSX
1033 else
1035 CGrafPtr port;
1036 static CGContextRef context;
1037 float port_height = FRAME_PIXEL_HEIGHT (f);
1038 static const ATSUAttributeTag tags[] = {kATSUCGContextTag};
1039 static const ByteCount sizes[] = {sizeof (CGContextRef)};
1040 static const ATSUAttributeValuePtr values[] = {&context};
1042 #if USE_CG_DRAWING
1043 context = mac_begin_cg_clip (f, gc);
1044 #else
1045 GetPort (&port);
1046 QDBeginCGContext (port, &context);
1047 if (gc->n_clip_rects || bg_width)
1049 CGContextTranslateCTM (context, 0, port_height);
1050 CGContextScaleCTM (context, 1, -1);
1051 if (gc->n_clip_rects)
1052 CGContextClipToRects (context, gc->clip_rects,
1053 gc->n_clip_rects);
1054 #endif
1055 if (bg_width)
1057 CG_SET_FILL_COLOR_WITH_GC_BACKGROUND (context, gc);
1058 CGContextFillRect
1059 (context,
1060 CGRectMake (x, y - FONT_BASE (GC_FONT (gc)),
1061 bg_width, FONT_HEIGHT (GC_FONT (gc))));
1063 CGContextScaleCTM (context, 1, -1);
1064 CGContextTranslateCTM (context, 0, -port_height);
1065 #if !USE_CG_DRAWING
1067 #endif
1068 CG_SET_FILL_COLOR_WITH_GC_FOREGROUND (context, gc);
1069 err = ATSUSetLayoutControls (text_layout,
1070 sizeof (tags) / sizeof (tags[0]),
1071 tags, sizes, values);
1072 if (err == noErr)
1074 ATSUDrawText (text_layout,
1075 kATSUFromTextBeginning, kATSUToTextEnd,
1076 Long2Fix (x), Long2Fix (port_height - y));
1077 if (overstrike_p)
1078 ATSUDrawText (text_layout,
1079 kATSUFromTextBeginning, kATSUToTextEnd,
1080 Long2Fix (x + 1), Long2Fix (port_height - y));
1082 #if USE_CG_DRAWING
1083 mac_end_cg_clip (f);
1084 context = NULL;
1085 #else
1086 CGContextSynchronize (context);
1087 QDEndCGContext (port, &context);
1088 #endif
1089 #if 0
1090 /* This doesn't work on Mac OS X 10.1. */
1091 ATSUClearLayoutControls (text_layout,
1092 sizeof (tags) / sizeof (tags[0]), tags);
1093 #else
1094 ATSUSetLayoutControls (text_layout,
1095 sizeof (tags) / sizeof (tags[0]),
1096 tags, sizes, values);
1097 #endif
1099 #endif /* MAC_OSX */
1101 else
1102 #endif /* USE_ATSUI */
1104 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
1105 UInt32 savedFlags;
1107 if (mac_use_core_graphics)
1108 savedFlags = SwapQDTextFlags (kQDUseCGTextRendering);
1109 #endif
1110 #if USE_CG_DRAWING
1111 mac_prepare_for_quickdraw (f);
1112 #endif
1113 mac_begin_clip (gc);
1114 RGBForeColor (GC_FORE_COLOR (gc));
1115 #ifdef MAC_OS8
1116 if (bg_width)
1118 RGBBackColor (GC_BACK_COLOR (gc));
1119 TextMode (srcCopy);
1121 else
1122 TextMode (srcOr);
1123 #else
1124 /* We prefer not to use srcCopy text transfer mode on Mac OS X
1125 because:
1126 - Screen is double-buffered. (In srcCopy mode, a text is
1127 drawn into an offscreen graphics world first. So
1128 performance gain cannot be expected.)
1129 - It lowers rendering quality.
1130 - Some fonts leave garbage on cursor movement. */
1131 if (bg_width)
1133 Rect r;
1135 RGBBackColor (GC_BACK_COLOR (gc));
1136 SetRect (&r, x, y - FONT_BASE (GC_FONT (gc)),
1137 x + bg_width, y + FONT_DESCENT (GC_FONT (gc)));
1138 EraseRect (&r);
1140 TextMode (srcOr);
1141 #endif
1142 TextFont (GC_FONT (gc)->mac_fontnum);
1143 TextSize (GC_FONT (gc)->mac_fontsize);
1144 TextFace (GC_FONT (gc)->mac_fontface);
1145 MoveTo (x, y);
1146 DrawText (buf, 0, nchars * bytes_per_char);
1147 if (overstrike_p)
1149 TextMode (srcOr);
1150 MoveTo (x + 1, y);
1151 DrawText (buf, 0, nchars * bytes_per_char);
1153 if (bg_width)
1154 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
1155 mac_end_clip (gc);
1157 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
1158 if (mac_use_core_graphics)
1159 SwapQDTextFlags(savedFlags);
1160 #endif
1165 /* Mac replacement for XDrawImageString. */
1167 static void
1168 mac_draw_image_string (f, gc, x, y, buf, nchars, bg_width, overstrike_p)
1169 struct frame *f;
1170 GC gc;
1171 int x, y;
1172 char *buf;
1173 int nchars, bg_width, overstrike_p;
1175 mac_draw_string_common (f, gc, x, y, buf, nchars, bg_width,
1176 overstrike_p, 1);
1180 /* Mac replacement for XDrawImageString16. */
1182 static void
1183 mac_draw_image_string_16 (f, gc, x, y, buf, nchars, bg_width, overstrike_p)
1184 struct frame *f;
1185 GC gc;
1186 int x, y;
1187 XChar2b *buf;
1188 int nchars, bg_width, overstrike_p;
1190 mac_draw_string_common (f, gc, x, y, (char *) buf, nchars, bg_width,
1191 overstrike_p, 2);
1195 /* Mac replacement for XQueryTextExtents, but takes a character. If
1196 STYLE is NULL, measurement is done by QuickDraw Text routines for
1197 the font of the current graphics port. If CG_GLYPH is not NULL,
1198 *CG_GLYPH is set to the glyph ID or 0 if it cannot be obtained. */
1200 static OSStatus
1201 mac_query_char_extents (style, c,
1202 font_ascent_return, font_descent_return,
1203 overall_return, cg_glyph)
1204 #if USE_ATSUI
1205 ATSUStyle style;
1206 #else
1207 void *style;
1208 #endif
1209 int c;
1210 int *font_ascent_return, *font_descent_return;
1211 XCharStruct *overall_return;
1212 #if USE_CG_TEXT_DRAWING
1213 CGGlyph *cg_glyph;
1214 #else
1215 void *cg_glyph;
1216 #endif
1218 OSStatus err = noErr;
1219 int width;
1220 Rect char_bounds;
1222 #if USE_ATSUI
1223 if (style)
1225 ATSUTextLayout text_layout;
1226 UniChar ch = c;
1228 err = atsu_get_text_layout_with_text_ptr (&ch, 1, style, &text_layout);
1229 if (err == noErr
1230 && (font_ascent_return || font_descent_return || overall_return))
1232 ATSTrapezoid glyph_bounds;
1234 err = ATSUGetGlyphBounds (text_layout, 0, 0,
1235 kATSUFromTextBeginning, kATSUToTextEnd,
1236 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
1237 kATSUseFractionalOrigins,
1238 #else
1239 kATSUseDeviceOrigins,
1240 #endif
1241 1, &glyph_bounds, NULL);
1242 if (err == noErr)
1244 xassert (glyph_bounds.lowerRight.x - glyph_bounds.lowerLeft.x
1245 == glyph_bounds.upperRight.x - glyph_bounds.upperLeft.x);
1247 width = Fix2Long (glyph_bounds.upperRight.x
1248 - glyph_bounds.upperLeft.x);
1249 if (font_ascent_return)
1250 *font_ascent_return = -Fix2Long (glyph_bounds.upperLeft.y);
1251 if (font_descent_return)
1252 *font_descent_return = Fix2Long (glyph_bounds.lowerLeft.y);
1255 if (err == noErr && overall_return)
1257 err = ATSUMeasureTextImage (text_layout,
1258 kATSUFromTextBeginning, kATSUToTextEnd,
1259 0, 0, &char_bounds);
1260 if (err == noErr)
1261 STORE_XCHARSTRUCT (*overall_return, width, char_bounds);
1262 #if USE_CG_TEXT_DRAWING
1263 if (err == noErr && cg_glyph)
1265 OSStatus err1;
1266 ATSUGlyphInfoArray glyph_info_array;
1267 ByteCount count = sizeof (ATSUGlyphInfoArray);
1269 err1 = ATSUMatchFontsToText (text_layout, kATSUFromTextBeginning,
1270 kATSUToTextEnd, NULL, NULL, NULL);
1271 if (err1 == noErr)
1272 err1 = ATSUGetGlyphInfo (text_layout, kATSUFromTextBeginning,
1273 kATSUToTextEnd, &count,
1274 &glyph_info_array);
1275 if (err1 == noErr
1276 /* Make sure that we don't have to make layout
1277 adjustments. */
1278 && glyph_info_array.glyphs[0].deltaY == 0.0f
1279 && glyph_info_array.glyphs[0].idealX == 0.0f
1280 && glyph_info_array.glyphs[0].screenX == 0)
1282 xassert (glyph_info_array.glyphs[0].glyphID);
1283 *cg_glyph = glyph_info_array.glyphs[0].glyphID;
1285 else
1286 *cg_glyph = 0;
1288 #endif
1291 else
1292 #endif
1294 if (font_ascent_return || font_descent_return)
1296 FontInfo font_info;
1298 GetFontInfo (&font_info);
1299 if (font_ascent_return)
1300 *font_ascent_return = font_info.ascent;
1301 if (font_descent_return)
1302 *font_descent_return = font_info.descent;
1304 if (overall_return)
1306 char ch = c;
1308 width = CharWidth (ch);
1309 QDTextBounds (1, &ch, &char_bounds);
1310 STORE_XCHARSTRUCT (*overall_return, width, char_bounds);
1314 return err;
1318 /* Mac replacement for XTextExtents16. Only sets horizontal metrics. */
1320 static int
1321 mac_text_extents_16 (font_struct, string, nchars, overall_return)
1322 XFontStruct *font_struct;
1323 XChar2b *string;
1324 int nchars;
1325 XCharStruct *overall_return;
1327 int i;
1328 short width = 0, lbearing = 0, rbearing = 0;
1329 XCharStruct *pcm;
1331 for (i = 0; i < nchars; i++)
1333 pcm = mac_per_char_metric (font_struct, string, 0);
1334 if (pcm == NULL)
1335 width += FONT_WIDTH (font_struct);
1336 else
1338 lbearing = min (lbearing, width + pcm->lbearing);
1339 rbearing = max (rbearing, width + pcm->rbearing);
1340 width += pcm->width;
1342 string++;
1345 overall_return->lbearing = lbearing;
1346 overall_return->rbearing = rbearing;
1347 overall_return->width = width;
1349 /* What's the meaning of the return value of XTextExtents16? */
1353 #if USE_CG_TEXT_DRAWING
1354 static int cg_text_anti_aliasing_threshold = 8;
1356 static void
1357 init_cg_text_anti_aliasing_threshold ()
1359 int threshold;
1360 Boolean valid_p;
1362 threshold =
1363 CFPreferencesGetAppIntegerValue (CFSTR ("AppleAntiAliasingThreshold"),
1364 kCFPreferencesCurrentApplication,
1365 &valid_p);
1366 if (valid_p)
1367 cg_text_anti_aliasing_threshold = threshold;
1370 static int
1371 mac_draw_image_string_cg (f, gc, x, y, buf, nchars, bg_width, overstrike_p)
1372 struct frame *f;
1373 GC gc;
1374 int x, y;
1375 XChar2b *buf;
1376 int nchars, bg_width, overstrike_p;
1378 CGrafPtr port;
1379 float port_height, gx, gy;
1380 int i;
1381 CGContextRef context;
1382 CGGlyph *glyphs;
1383 CGSize *advances;
1385 if (!mac_use_core_graphics || GC_FONT (gc)->cg_font == NULL)
1386 return 0;
1388 port = GetWindowPort (FRAME_MAC_WINDOW (f));
1389 port_height = FRAME_PIXEL_HEIGHT (f);
1390 gx = x;
1391 gy = port_height - y;
1392 glyphs = (CGGlyph *)buf;
1393 advances = alloca (sizeof (CGSize) * nchars);
1394 if (advances == NULL)
1395 return 0;
1396 for (i = 0; i < nchars; i++)
1398 XCharStruct *pcm = mac_per_char_metric (GC_FONT (gc), buf, 0);
1400 advances[i].width = pcm->width;
1401 advances[i].height = 0;
1402 glyphs[i] = GC_FONT (gc)->cg_glyphs[buf->byte2];
1403 buf++;
1406 #if USE_CG_DRAWING
1407 context = mac_begin_cg_clip (f, gc);
1408 #else
1409 QDBeginCGContext (port, &context);
1410 if (gc->n_clip_rects || bg_width)
1412 CGContextTranslateCTM (context, 0, port_height);
1413 CGContextScaleCTM (context, 1, -1);
1414 if (gc->n_clip_rects)
1415 CGContextClipToRects (context, gc->clip_rects, gc->n_clip_rects);
1416 #endif
1417 if (bg_width)
1419 CG_SET_FILL_COLOR_WITH_GC_BACKGROUND (context, gc);
1420 CGContextFillRect
1421 (context,
1422 CGRectMake (gx, y - FONT_BASE (GC_FONT (gc)),
1423 bg_width, FONT_HEIGHT (GC_FONT (gc))));
1425 CGContextScaleCTM (context, 1, -1);
1426 CGContextTranslateCTM (context, 0, -port_height);
1427 #if !USE_CG_DRAWING
1429 #endif
1430 CG_SET_FILL_COLOR_WITH_GC_FOREGROUND (context, gc);
1431 CGContextSetFont (context, GC_FONT (gc)->cg_font);
1432 CGContextSetFontSize (context, GC_FONT (gc)->mac_fontsize);
1433 if (GC_FONT (gc)->mac_fontsize <= cg_text_anti_aliasing_threshold)
1434 CGContextSetShouldAntialias (context, false);
1435 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1030
1436 #if MAC_OS_X_VERSION_MIN_REQUIRED == 1020
1437 if (CGContextShowGlyphsWithAdvances != NULL)
1438 #endif
1440 CGContextSetTextPosition (context, gx, gy);
1441 CGContextShowGlyphsWithAdvances (context, glyphs, advances, nchars);
1442 if (overstrike_p)
1444 CGContextSetTextPosition (context, gx + 1.0f, gy);
1445 CGContextShowGlyphsWithAdvances (context, glyphs, advances, nchars);
1448 #if MAC_OS_X_VERSION_MIN_REQUIRED == 1020
1449 else
1450 #endif
1451 #endif /* MAC_OS_X_VERSION_MAX_ALLOWED >= 1030 */
1452 #if MAC_OS_X_VERSION_MAX_ALLOWED < 1030 || MAC_OS_X_VERSION_MIN_REQUIRED == 1020
1454 for (i = 0; i < nchars; i++)
1456 CGContextShowGlyphsAtPoint (context, gx, gy, glyphs + i, 1);
1457 if (overstrike_p)
1458 CGContextShowGlyphsAtPoint (context, gx + 1.0f, gy, glyphs + i, 1);
1459 gx += advances[i].width;
1462 #endif
1463 #if USE_CG_DRAWING
1464 mac_end_cg_clip (f);
1465 #else
1466 CGContextSynchronize (context);
1467 QDEndCGContext (port, &context);
1468 #endif
1470 return 1;
1472 #endif
1475 #if !USE_CG_DRAWING
1476 /* Mac replacement for XCopyArea: dest must be window. */
1478 static void
1479 mac_copy_area (src, f, gc, src_x, src_y, width, height, dest_x, dest_y)
1480 Pixmap src;
1481 struct frame *f;
1482 GC gc;
1483 int src_x, src_y;
1484 unsigned int width, height;
1485 int dest_x, dest_y;
1487 Rect src_r, dest_r;
1489 SetPortWindowPort (FRAME_MAC_WINDOW (f));
1491 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
1492 SetRect (&dest_r, dest_x, dest_y, dest_x + width, dest_y + height);
1494 ForeColor (blackColor);
1495 BackColor (whiteColor);
1497 mac_begin_clip (gc);
1498 LockPixels (GetGWorldPixMap (src));
1499 #if TARGET_API_MAC_CARBON
1501 CGrafPtr port;
1503 GetPort (&port);
1504 LockPortBits (port);
1505 CopyBits (GetPortBitMapForCopyBits (src),
1506 GetPortBitMapForCopyBits (port),
1507 &src_r, &dest_r, srcCopy, 0);
1508 UnlockPortBits (port);
1510 #else /* not TARGET_API_MAC_CARBON */
1511 CopyBits (&(((GrafPtr)src)->portBits), &(FRAME_MAC_WINDOW (f)->portBits),
1512 &src_r, &dest_r, srcCopy, 0);
1513 #endif /* not TARGET_API_MAC_CARBON */
1514 UnlockPixels (GetGWorldPixMap (src));
1515 mac_end_clip (gc);
1517 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
1521 static void
1522 mac_copy_area_with_mask (src, mask, f, gc, src_x, src_y,
1523 width, height, dest_x, dest_y)
1524 Pixmap src, mask;
1525 struct frame *f;
1526 GC gc;
1527 int src_x, src_y;
1528 unsigned int width, height;
1529 int dest_x, dest_y;
1531 Rect src_r, dest_r;
1533 SetPortWindowPort (FRAME_MAC_WINDOW (f));
1535 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
1536 SetRect (&dest_r, dest_x, dest_y, dest_x + width, dest_y + height);
1538 ForeColor (blackColor);
1539 BackColor (whiteColor);
1541 mac_begin_clip (gc);
1542 LockPixels (GetGWorldPixMap (src));
1543 LockPixels (GetGWorldPixMap (mask));
1544 #if TARGET_API_MAC_CARBON
1546 CGrafPtr port;
1548 GetPort (&port);
1549 LockPortBits (port);
1550 CopyMask (GetPortBitMapForCopyBits (src), GetPortBitMapForCopyBits (mask),
1551 GetPortBitMapForCopyBits (port),
1552 &src_r, &src_r, &dest_r);
1553 UnlockPortBits (port);
1555 #else /* not TARGET_API_MAC_CARBON */
1556 CopyMask (&(((GrafPtr)src)->portBits), &(((GrafPtr)mask)->portBits),
1557 &(FRAME_MAC_WINDOW (f)->portBits), &src_r, &src_r, &dest_r);
1558 #endif /* not TARGET_API_MAC_CARBON */
1559 UnlockPixels (GetGWorldPixMap (mask));
1560 UnlockPixels (GetGWorldPixMap (src));
1561 mac_end_clip (gc);
1563 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
1565 #endif /* !USE_CG_DRAWING */
1568 /* Mac replacement for XCopyArea: used only for scrolling. */
1570 static void
1571 mac_scroll_area (f, gc, src_x, src_y, width, height, dest_x, dest_y)
1572 struct frame *f;
1573 GC gc;
1574 int src_x, src_y;
1575 unsigned int width, height;
1576 int dest_x, dest_y;
1578 #if TARGET_API_MAC_CARBON
1579 Rect src_r;
1580 RgnHandle dummy = NewRgn (); /* For avoiding update events. */
1582 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
1583 #if USE_CG_DRAWING
1584 mac_prepare_for_quickdraw (f);
1585 #endif
1586 ScrollWindowRect (FRAME_MAC_WINDOW (f),
1587 &src_r, dest_x - src_x, dest_y - src_y,
1588 kScrollWindowNoOptions, dummy);
1589 DisposeRgn (dummy);
1590 #else /* not TARGET_API_MAC_CARBON */
1591 Rect src_r, dest_r;
1592 WindowPtr w = FRAME_MAC_WINDOW (f);
1594 SetPort (w);
1596 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
1597 SetRect (&dest_r, dest_x, dest_y, dest_x + width, dest_y + height);
1599 /* In Color QuickDraw, set ForeColor and BackColor as follows to avoid
1600 color mapping in CopyBits. Otherwise, it will be slow. */
1601 ForeColor (blackColor);
1602 BackColor (whiteColor);
1603 mac_begin_clip (gc);
1604 CopyBits (&(w->portBits), &(w->portBits), &src_r, &dest_r, srcCopy, 0);
1605 mac_end_clip (gc);
1607 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
1608 #endif /* not TARGET_API_MAC_CARBON */
1612 /* Mac replacement for XChangeGC. */
1614 static void
1615 XChangeGC (display, gc, mask, xgcv)
1616 Display *display;
1617 GC gc;
1618 unsigned long mask;
1619 XGCValues *xgcv;
1621 if (mask & GCForeground)
1622 XSetForeground (display, gc, xgcv->foreground);
1623 if (mask & GCBackground)
1624 XSetBackground (display, gc, xgcv->background);
1625 if (mask & GCFont)
1626 XSetFont (display, gc, xgcv->font);
1630 /* Mac replacement for XCreateGC. */
1633 XCreateGC (display, d, mask, xgcv)
1634 Display *display;
1635 void *d;
1636 unsigned long mask;
1637 XGCValues *xgcv;
1639 GC gc = xmalloc (sizeof (*gc));
1641 bzero (gc, sizeof (*gc));
1642 #if USE_CG_DRAWING && MAC_OS_X_VERSION_MAX_ALLOWED >= 1030
1643 #if MAC_OS_X_VERSION_MIN_REQUIRED == 1020
1644 if (CGColorGetTypeID != NULL)
1645 #endif
1647 gc->cg_fore_color = gc->cg_back_color = mac_cg_color_black;
1648 CGColorRetain (gc->cg_fore_color);
1649 CGColorRetain (gc->cg_back_color);
1651 #endif
1652 XChangeGC (display, gc, mask, xgcv);
1654 return gc;
1658 /* Used in xfaces.c. */
1660 void
1661 XFreeGC (display, gc)
1662 Display *display;
1663 GC gc;
1665 if (gc->clip_region)
1666 DisposeRgn (gc->clip_region);
1667 #if USE_CG_DRAWING && MAC_OS_X_VERSION_MAX_ALLOWED >= 1030
1668 #if MAC_OS_X_VERSION_MIN_REQUIRED == 1020
1669 if (CGColorGetTypeID != NULL)
1670 #endif
1672 CGColorRelease (gc->cg_fore_color);
1673 CGColorRelease (gc->cg_back_color);
1675 #endif
1676 xfree (gc);
1680 /* Mac replacement for XGetGCValues. */
1682 static void
1683 XGetGCValues (display, gc, mask, xgcv)
1684 Display *display;
1685 GC gc;
1686 unsigned long mask;
1687 XGCValues *xgcv;
1689 if (mask & GCForeground)
1690 xgcv->foreground = gc->xgcv.foreground;
1691 if (mask & GCBackground)
1692 xgcv->background = gc->xgcv.background;
1693 if (mask & GCFont)
1694 xgcv->font = gc->xgcv.font;
1698 /* Mac replacement for XSetForeground. */
1700 void
1701 XSetForeground (display, gc, color)
1702 Display *display;
1703 GC gc;
1704 unsigned long color;
1706 if (gc->xgcv.foreground != color)
1708 gc->xgcv.foreground = color;
1709 gc->fore_color.red = RED16_FROM_ULONG (color);
1710 gc->fore_color.green = GREEN16_FROM_ULONG (color);
1711 gc->fore_color.blue = BLUE16_FROM_ULONG (color);
1712 #if USE_CG_DRAWING && MAC_OS_X_VERSION_MAX_ALLOWED >= 1030
1713 #if MAC_OS_X_VERSION_MIN_REQUIRED == 1020
1714 if (CGColorGetTypeID != NULL)
1715 #endif
1717 CGColorRelease (gc->cg_fore_color);
1718 if (color == 0)
1720 gc->cg_fore_color = mac_cg_color_black;
1721 CGColorRetain (gc->cg_fore_color);
1723 else
1725 float rgba[4];
1727 rgba[0] = gc->fore_color.red / 65535.0f;
1728 rgba[1] = gc->fore_color.green / 65535.0f;
1729 rgba[2] = gc->fore_color.blue / 65535.0f;
1730 rgba[3] = 1.0f;
1731 gc->cg_fore_color = CGColorCreate (mac_cg_color_space_rgb, rgba);
1734 #endif
1739 /* Mac replacement for XSetBackground. */
1741 void
1742 XSetBackground (display, gc, color)
1743 Display *display;
1744 GC gc;
1745 unsigned long color;
1747 if (gc->xgcv.background != color)
1749 gc->xgcv.background = color;
1750 gc->back_color.red = RED16_FROM_ULONG (color);
1751 gc->back_color.green = GREEN16_FROM_ULONG (color);
1752 gc->back_color.blue = BLUE16_FROM_ULONG (color);
1753 #if USE_CG_DRAWING && MAC_OS_X_VERSION_MAX_ALLOWED >= 1030
1754 #if MAC_OS_X_VERSION_MIN_REQUIRED == 1020
1755 if (CGColorGetTypeID != NULL)
1756 #endif
1758 CGColorRelease (gc->cg_back_color);
1759 if (color == 0)
1761 gc->cg_back_color = mac_cg_color_black;
1762 CGColorRetain (gc->cg_back_color);
1764 else
1766 float rgba[4];
1768 rgba[0] = gc->back_color.red / 65535.0f;
1769 rgba[1] = gc->back_color.green / 65535.0f;
1770 rgba[2] = gc->back_color.blue / 65535.0f;
1771 rgba[3] = 1.0f;
1772 gc->cg_back_color = CGColorCreate (mac_cg_color_space_rgb, rgba);
1775 #endif
1780 /* Mac replacement for XSetFont. */
1782 static void
1783 XSetFont (display, gc, font)
1784 Display *display;
1785 GC gc;
1786 XFontStruct *font;
1788 gc->xgcv.font = font;
1792 /* Mac replacement for XSetClipRectangles. */
1794 static void
1795 mac_set_clip_rectangles (display, gc, rectangles, n)
1796 Display *display;
1797 GC gc;
1798 Rect *rectangles;
1799 int n;
1801 int i;
1803 xassert (n >= 0 && n <= MAX_CLIP_RECTS);
1805 gc->n_clip_rects = n;
1806 if (n > 0)
1808 if (gc->clip_region == NULL)
1809 gc->clip_region = NewRgn ();
1810 RectRgn (gc->clip_region, rectangles);
1811 if (n > 1)
1813 RgnHandle region = NewRgn ();
1815 for (i = 1; i < n; i++)
1817 RectRgn (region, rectangles + i);
1818 UnionRgn (gc->clip_region, region, gc->clip_region);
1820 DisposeRgn (region);
1823 #if defined (MAC_OSX) && (USE_ATSUI || USE_CG_DRAWING)
1824 for (i = 0; i < n; i++)
1826 Rect *rect = rectangles + i;
1828 gc->clip_rects[i] = CGRectMake (rect->left, rect->top,
1829 rect->right - rect->left,
1830 rect->bottom - rect->top);
1832 #endif
1836 /* Mac replacement for XSetClipMask. */
1838 static INLINE void
1839 mac_reset_clip_rectangles (display, gc)
1840 Display *display;
1841 GC gc;
1843 gc->n_clip_rects = 0;
1847 /* Mac replacement for XSetWindowBackground. */
1849 void
1850 XSetWindowBackground (display, w, color)
1851 Display *display;
1852 WindowPtr w;
1853 unsigned long color;
1855 #if !TARGET_API_MAC_CARBON
1856 AuxWinHandle aw_handle;
1857 CTabHandle ctab_handle;
1858 ColorSpecPtr ct_table;
1859 short ct_size;
1860 #endif
1861 RGBColor bg_color;
1863 bg_color.red = RED16_FROM_ULONG (color);
1864 bg_color.green = GREEN16_FROM_ULONG (color);
1865 bg_color.blue = BLUE16_FROM_ULONG (color);
1867 #if TARGET_API_MAC_CARBON
1868 SetWindowContentColor (w, &bg_color);
1869 #else
1870 if (GetAuxWin (w, &aw_handle))
1872 ctab_handle = (*aw_handle)->awCTable;
1873 HandToHand ((Handle *) &ctab_handle);
1874 ct_table = (*ctab_handle)->ctTable;
1875 ct_size = (*ctab_handle)->ctSize;
1876 while (ct_size > -1)
1878 if (ct_table->value == 0)
1880 ct_table->rgb = bg_color;
1881 CTabChanged (ctab_handle);
1882 SetWinColor (w, (WCTabHandle) ctab_handle);
1884 ct_size--;
1887 #endif
1890 /* Flush display of frame F, or of all frames if F is null. */
1892 static void
1893 x_flush (f)
1894 struct frame *f;
1896 #if TARGET_API_MAC_CARBON
1897 BLOCK_INPUT;
1898 #if USE_CG_DRAWING
1899 mac_prepare_for_quickdraw (f);
1900 #endif
1901 if (f)
1902 QDFlushPortBuffer (GetWindowPort (FRAME_MAC_WINDOW (f)), NULL);
1903 else
1904 QDFlushPortBuffer (GetQDGlobalsThePort (), NULL);
1905 UNBLOCK_INPUT;
1906 #endif
1910 /* Remove calls to XFlush by defining XFlush to an empty replacement.
1911 Calls to XFlush should be unnecessary because the X output buffer
1912 is flushed automatically as needed by calls to XPending,
1913 XNextEvent, or XWindowEvent according to the XFlush man page.
1914 XTread_socket calls XPending. Removing XFlush improves
1915 performance. */
1917 #define XFlush(DISPLAY) (void) 0
1919 #if USE_CG_DRAWING
1920 static void
1921 mac_flush_display_optional (f)
1922 struct frame *f;
1924 BLOCK_INPUT;
1925 mac_prepare_for_quickdraw (f);
1926 UNBLOCK_INPUT;
1928 #endif
1930 /***********************************************************************
1931 Starting and ending an update
1932 ***********************************************************************/
1934 /* Start an update of frame F. This function is installed as a hook
1935 for update_begin, i.e. it is called when update_begin is called.
1936 This function is called prior to calls to x_update_window_begin for
1937 each window being updated. */
1939 static void
1940 x_update_begin (f)
1941 struct frame *f;
1943 #if TARGET_API_MAC_CARBON
1944 /* During update of a frame, availability of input events is
1945 periodically checked with ReceiveNextEvent if
1946 redisplay-dont-pause is nil. That normally flushes window buffer
1947 changes for every check, and thus screen update looks waving even
1948 if no input is available. So we disable screen updates during
1949 update of a frame. */
1950 BLOCK_INPUT;
1951 DisableScreenUpdates ();
1952 UNBLOCK_INPUT;
1953 #endif
1957 /* Start update of window W. Set the global variable updated_window
1958 to the window being updated and set output_cursor to the cursor
1959 position of W. */
1961 static void
1962 x_update_window_begin (w)
1963 struct window *w;
1965 struct frame *f = XFRAME (WINDOW_FRAME (w));
1966 struct mac_display_info *display_info = FRAME_MAC_DISPLAY_INFO (f);
1968 updated_window = w;
1969 set_output_cursor (&w->cursor);
1971 BLOCK_INPUT;
1973 if (f == display_info->mouse_face_mouse_frame)
1975 /* Don't do highlighting for mouse motion during the update. */
1976 display_info->mouse_face_defer = 1;
1978 /* If F needs to be redrawn, simply forget about any prior mouse
1979 highlighting. */
1980 if (FRAME_GARBAGED_P (f))
1981 display_info->mouse_face_window = Qnil;
1983 #if 0 /* Rows in a current matrix containing glyphs in mouse-face have
1984 their mouse_face_p flag set, which means that they are always
1985 unequal to rows in a desired matrix which never have that
1986 flag set. So, rows containing mouse-face glyphs are never
1987 scrolled, and we don't have to switch the mouse highlight off
1988 here to prevent it from being scrolled. */
1990 /* Can we tell that this update does not affect the window
1991 where the mouse highlight is? If so, no need to turn off.
1992 Likewise, don't do anything if the frame is garbaged;
1993 in that case, the frame's current matrix that we would use
1994 is all wrong, and we will redisplay that line anyway. */
1995 if (!NILP (display_info->mouse_face_window)
1996 && w == XWINDOW (display_info->mouse_face_window))
1998 int i;
2000 for (i = 0; i < w->desired_matrix->nrows; ++i)
2001 if (MATRIX_ROW_ENABLED_P (w->desired_matrix, i))
2002 break;
2004 if (i < w->desired_matrix->nrows)
2005 clear_mouse_face (display_info);
2007 #endif /* 0 */
2010 UNBLOCK_INPUT;
2014 /* Draw a vertical window border from (x,y0) to (x,y1) */
2016 static void
2017 mac_draw_vertical_window_border (w, x, y0, y1)
2018 struct window *w;
2019 int x, y0, y1;
2021 struct frame *f = XFRAME (WINDOW_FRAME (w));
2022 struct face *face;
2024 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2025 if (face)
2026 XSetForeground (FRAME_MAC_DISPLAY (f), f->output_data.mac->normal_gc,
2027 face->foreground);
2029 mac_draw_line (f, f->output_data.mac->normal_gc, x, y0, x, y1);
2032 /* End update of window W (which is equal to updated_window).
2034 Draw vertical borders between horizontally adjacent windows, and
2035 display W's cursor if CURSOR_ON_P is non-zero.
2037 MOUSE_FACE_OVERWRITTEN_P non-zero means that some row containing
2038 glyphs in mouse-face were overwritten. In that case we have to
2039 make sure that the mouse-highlight is properly redrawn.
2041 W may be a menu bar pseudo-window in case we don't have X toolkit
2042 support. Such windows don't have a cursor, so don't display it
2043 here. */
2045 static void
2046 x_update_window_end (w, cursor_on_p, mouse_face_overwritten_p)
2047 struct window *w;
2048 int cursor_on_p, mouse_face_overwritten_p;
2050 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (XFRAME (w->frame));
2052 if (!w->pseudo_window_p)
2054 BLOCK_INPUT;
2056 if (cursor_on_p)
2057 display_and_set_cursor (w, 1, output_cursor.hpos,
2058 output_cursor.vpos,
2059 output_cursor.x, output_cursor.y);
2061 if (draw_window_fringes (w, 1))
2062 x_draw_vertical_border (w);
2064 UNBLOCK_INPUT;
2067 /* If a row with mouse-face was overwritten, arrange for
2068 XTframe_up_to_date to redisplay the mouse highlight. */
2069 if (mouse_face_overwritten_p)
2071 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
2072 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
2073 dpyinfo->mouse_face_window = Qnil;
2076 updated_window = NULL;
2080 /* End update of frame F. This function is installed as a hook in
2081 update_end. */
2083 static void
2084 x_update_end (f)
2085 struct frame *f;
2087 /* Mouse highlight may be displayed again. */
2088 FRAME_MAC_DISPLAY_INFO (f)->mouse_face_defer = 0;
2090 BLOCK_INPUT;
2091 #if TARGET_API_MAC_CARBON
2092 EnableScreenUpdates ();
2093 #endif
2094 XFlush (FRAME_MAC_DISPLAY (f));
2095 UNBLOCK_INPUT;
2099 /* This function is called from various places in xdisp.c whenever a
2100 complete update has been performed. The global variable
2101 updated_window is not available here. */
2103 static void
2104 XTframe_up_to_date (f)
2105 struct frame *f;
2107 if (FRAME_MAC_P (f))
2109 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
2111 if (dpyinfo->mouse_face_deferred_gc
2112 || f == dpyinfo->mouse_face_mouse_frame)
2114 BLOCK_INPUT;
2115 if (dpyinfo->mouse_face_mouse_frame)
2116 note_mouse_highlight (dpyinfo->mouse_face_mouse_frame,
2117 dpyinfo->mouse_face_mouse_x,
2118 dpyinfo->mouse_face_mouse_y);
2119 dpyinfo->mouse_face_deferred_gc = 0;
2120 UNBLOCK_INPUT;
2126 /* Draw truncation mark bitmaps, continuation mark bitmaps, overlay
2127 arrow bitmaps, or clear the fringes if no bitmaps are required
2128 before DESIRED_ROW is made current. The window being updated is
2129 found in updated_window. This function is called from
2130 update_window_line only if it is known that there are differences
2131 between bitmaps to be drawn between current row and DESIRED_ROW. */
2133 static void
2134 x_after_update_window_line (desired_row)
2135 struct glyph_row *desired_row;
2137 struct window *w = updated_window;
2138 struct frame *f;
2139 int width, height;
2141 xassert (w);
2143 if (!desired_row->mode_line_p && !w->pseudo_window_p)
2144 desired_row->redraw_fringe_bitmaps_p = 1;
2146 /* When a window has disappeared, make sure that no rest of
2147 full-width rows stays visible in the internal border. Could
2148 check here if updated_window is the leftmost/rightmost window,
2149 but I guess it's not worth doing since vertically split windows
2150 are almost never used, internal border is rarely set, and the
2151 overhead is very small. */
2152 if (windows_or_buffers_changed
2153 && desired_row->full_width_p
2154 && (f = XFRAME (w->frame),
2155 width = FRAME_INTERNAL_BORDER_WIDTH (f),
2156 width != 0)
2157 && (height = desired_row->visible_height,
2158 height > 0))
2160 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2162 /* Internal border is drawn below the tool bar. */
2163 if (WINDOWP (f->tool_bar_window)
2164 && w == XWINDOW (f->tool_bar_window))
2165 y -= width;
2167 BLOCK_INPUT;
2168 mac_clear_area (f, 0, y, width, height);
2169 mac_clear_area (f, FRAME_PIXEL_WIDTH (f) - width, y, width, height);
2170 UNBLOCK_INPUT;
2175 /* Draw the bitmap WHICH in one of the left or right fringes of
2176 window W. ROW is the glyph row for which to display the bitmap; it
2177 determines the vertical position at which the bitmap has to be
2178 drawn. */
2180 static void
2181 x_draw_fringe_bitmap (w, row, p)
2182 struct window *w;
2183 struct glyph_row *row;
2184 struct draw_fringe_bitmap_params *p;
2186 struct frame *f = XFRAME (WINDOW_FRAME (w));
2187 Display *display = FRAME_MAC_DISPLAY (f);
2188 struct face *face = p->face;
2189 int rowY;
2191 /* Must clip because of partially visible lines. */
2192 rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
2193 if (p->y < rowY)
2195 /* Adjust position of "bottom aligned" bitmap on partially
2196 visible last row. */
2197 int oldY = row->y;
2198 int oldVH = row->visible_height;
2199 row->visible_height = p->h;
2200 row->y -= rowY - p->y;
2201 x_clip_to_row (w, row, -1, face->gc);
2202 row->y = oldY;
2203 row->visible_height = oldVH;
2205 else
2206 x_clip_to_row (w, row, -1, face->gc);
2208 if (p->bx >= 0 && !p->overlay_p)
2210 #if 0 /* MAC_TODO: stipple */
2211 /* In case the same realized face is used for fringes and
2212 for something displayed in the text (e.g. face `region' on
2213 mono-displays, the fill style may have been changed to
2214 FillSolid in x_draw_glyph_string_background. */
2215 if (face->stipple)
2216 XSetFillStyle (FRAME_X_DISPLAY (f), face->gc, FillOpaqueStippled);
2217 else
2218 XSetForeground (FRAME_X_DISPLAY (f), face->gc, face->background);
2219 #endif
2221 mac_erase_rectangle (f, face->gc, p->bx, p->by, p->nx, p->ny);
2223 #if 0 /* MAC_TODO: stipple */
2224 if (!face->stipple)
2225 XSetForeground (FRAME_X_DISPLAY (f), face->gc, face->foreground);
2226 #endif
2229 if (p->which
2230 #if USE_CG_DRAWING
2231 && p->which < max_fringe_bmp
2232 #endif
2235 XGCValues gcv;
2237 XGetGCValues (display, face->gc, GCForeground, &gcv);
2238 XSetForeground (display, face->gc,
2239 (p->cursor_p
2240 ? (p->overlay_p ? face->background
2241 : f->output_data.mac->cursor_pixel)
2242 : face->foreground));
2243 #if USE_CG_DRAWING
2244 mac_draw_cg_image (fringe_bmp[p->which], f, face->gc, 0, p->dh,
2245 p->wd, p->h, p->x, p->y, p->overlay_p);
2246 #else
2247 mac_draw_bitmap (f, face->gc, p->x, p->y,
2248 p->wd, p->h, p->bits + p->dh, p->overlay_p);
2249 #endif
2250 XSetForeground (display, face->gc, gcv.foreground);
2253 mac_reset_clip_rectangles (display, face->gc);
2256 #if USE_CG_DRAWING
2257 static void
2258 mac_define_fringe_bitmap (which, bits, h, wd)
2259 int which;
2260 unsigned short *bits;
2261 int h, wd;
2263 int i;
2264 CGDataProviderRef provider;
2266 if (which >= max_fringe_bmp)
2268 i = max_fringe_bmp;
2269 max_fringe_bmp = which + 20;
2270 fringe_bmp = (CGImageRef *) xrealloc (fringe_bmp, max_fringe_bmp * sizeof (CGImageRef));
2271 while (i < max_fringe_bmp)
2272 fringe_bmp[i++] = 0;
2275 for (i = 0; i < h; i++)
2276 bits[i] = ~bits[i];
2277 provider = CGDataProviderCreateWithData (NULL, bits,
2278 sizeof (unsigned short) * h, NULL);
2279 if (provider)
2281 fringe_bmp[which] = CGImageMaskCreate (wd, h, 1, 1,
2282 sizeof (unsigned short),
2283 provider, NULL, 0);
2284 CGDataProviderRelease (provider);
2288 static void
2289 mac_destroy_fringe_bitmap (which)
2290 int which;
2292 if (which >= max_fringe_bmp)
2293 return;
2295 if (fringe_bmp[which])
2296 CGImageRelease (fringe_bmp[which]);
2297 fringe_bmp[which] = 0;
2299 #endif
2302 /* This is called when starting Emacs and when restarting after
2303 suspend. When starting Emacs, no window is mapped. And nothing
2304 must be done to Emacs's own window if it is suspended (though that
2305 rarely happens). */
2307 static void
2308 XTset_terminal_modes ()
2312 /* This is called when exiting or suspending Emacs. Exiting will make
2313 the windows go away, and suspending requires no action. */
2315 static void
2316 XTreset_terminal_modes ()
2322 /***********************************************************************
2323 Display Iterator
2324 ***********************************************************************/
2326 /* Function prototypes of this page. */
2328 static XCharStruct *x_per_char_metric P_ ((XFontStruct *, XChar2b *));
2329 static int mac_encode_char P_ ((int, XChar2b *, struct font_info *, int *));
2332 static void
2333 pcm_init (pcm, count)
2334 XCharStruct *pcm;
2335 int count;
2337 bzero (pcm, sizeof (XCharStruct) * count);
2338 while (--count >= 0)
2340 pcm->descent = PCM_INVALID;
2341 pcm++;
2345 static enum pcm_status
2346 pcm_get_status (pcm)
2347 const XCharStruct *pcm;
2349 int height = pcm->ascent + pcm->descent;
2351 /* Negative height means some special status. */
2352 return height >= 0 ? PCM_VALID : height;
2355 /* Get metrics of character CHAR2B in FONT. Value is null if CHAR2B
2356 is not contained in the font. */
2358 static INLINE XCharStruct *
2359 x_per_char_metric (font, char2b)
2360 XFontStruct *font;
2361 XChar2b *char2b;
2363 /* The result metric information. */
2364 XCharStruct *pcm = NULL;
2366 xassert (font && char2b);
2368 #if USE_ATSUI
2369 if (font->mac_style)
2371 XCharStruct **row = font->bounds.rows + char2b->byte1;
2373 if (*row == NULL)
2375 *row = xmalloc (sizeof (XCharStruct) * 0x100);
2376 pcm_init (*row, 0x100);
2378 pcm = *row + char2b->byte2;
2379 if (pcm_get_status (pcm) != PCM_VALID)
2381 BLOCK_INPUT;
2382 mac_query_char_extents (font->mac_style,
2383 (char2b->byte1 << 8) + char2b->byte2,
2384 NULL, NULL, pcm, NULL);
2385 UNBLOCK_INPUT;
2388 else
2390 #endif
2391 if (font->bounds.per_char != NULL)
2393 if (font->min_byte1 == 0 && font->max_byte1 == 0)
2395 /* min_char_or_byte2 specifies the linear character index
2396 corresponding to the first element of the per_char array,
2397 max_char_or_byte2 is the index of the last character. A
2398 character with non-zero CHAR2B->byte1 is not in the font.
2399 A character with byte2 less than min_char_or_byte2 or
2400 greater max_char_or_byte2 is not in the font. */
2401 if (char2b->byte1 == 0
2402 && char2b->byte2 >= font->min_char_or_byte2
2403 && char2b->byte2 <= font->max_char_or_byte2)
2404 pcm = font->bounds.per_char
2405 + (char2b->byte2 - font->min_char_or_byte2);
2407 else
2409 /* If either min_byte1 or max_byte1 are nonzero, both
2410 min_char_or_byte2 and max_char_or_byte2 are less than
2411 256, and the 2-byte character index values corresponding
2412 to the per_char array element N (counting from 0) are:
2414 byte1 = N/D + min_byte1
2415 byte2 = N\D + min_char_or_byte2
2417 where:
2419 D = max_char_or_byte2 - min_char_or_byte2 + 1
2420 / = integer division
2421 \ = integer modulus */
2422 if (char2b->byte1 >= font->min_byte1
2423 && char2b->byte1 <= font->max_byte1
2424 && char2b->byte2 >= font->min_char_or_byte2
2425 && char2b->byte2 <= font->max_char_or_byte2)
2427 pcm = (font->bounds.per_char
2428 + ((font->max_char_or_byte2 - font->min_char_or_byte2 + 1)
2429 * (char2b->byte1 - font->min_byte1))
2430 + (char2b->byte2 - font->min_char_or_byte2));
2434 else
2436 /* If the per_char pointer is null, all glyphs between the first
2437 and last character indexes inclusive have the same
2438 information, as given by both min_bounds and max_bounds. */
2439 if (char2b->byte2 >= font->min_char_or_byte2
2440 && char2b->byte2 <= font->max_char_or_byte2)
2441 pcm = &font->max_bounds;
2443 #if USE_ATSUI
2445 #endif
2447 return ((pcm == NULL
2448 || (pcm->width == 0
2449 #if 0 /* Show hollow boxes for zero-width glyphs such as combining diacritics. */
2450 && (pcm->rbearing - pcm->lbearing) == 0
2451 #endif
2453 ? NULL : pcm);
2456 /* RIF:
2459 static XCharStruct *
2460 mac_per_char_metric (font, char2b, font_type)
2461 XFontStruct *font;
2462 XChar2b *char2b;
2463 int font_type;
2465 return x_per_char_metric (font, char2b);
2468 /* RIF:
2469 Encode CHAR2B using encoding information from FONT_INFO. CHAR2B is
2470 the two-byte form of C. Encoding is returned in *CHAR2B. */
2472 static int
2473 mac_encode_char (c, char2b, font_info, two_byte_p)
2474 int c;
2475 XChar2b *char2b;
2476 struct font_info *font_info;
2477 int *two_byte_p;
2479 int charset = CHAR_CHARSET (c);
2480 XFontStruct *font = font_info->font;
2482 /* FONT_INFO may define a scheme by which to encode byte1 and byte2.
2483 This may be either a program in a special encoder language or a
2484 fixed encoding. */
2485 if (font_info->font_encoder)
2487 /* It's a program. */
2488 struct ccl_program *ccl = font_info->font_encoder;
2490 check_ccl_update (ccl);
2491 if (CHARSET_DIMENSION (charset) == 1)
2493 ccl->reg[0] = charset;
2494 ccl->reg[1] = char2b->byte2;
2495 ccl->reg[2] = -1;
2497 else
2499 ccl->reg[0] = charset;
2500 ccl->reg[1] = char2b->byte1;
2501 ccl->reg[2] = char2b->byte2;
2504 ccl_driver (ccl, NULL, NULL, 0, 0, NULL);
2506 /* We assume that MSBs are appropriately set/reset by CCL
2507 program. */
2508 if (font->max_byte1 == 0) /* 1-byte font */
2509 char2b->byte1 = 0, char2b->byte2 = ccl->reg[1];
2510 else
2511 char2b->byte1 = ccl->reg[1], char2b->byte2 = ccl->reg[2];
2513 else if (font_info->encoding[charset])
2515 /* Fixed encoding scheme. See fontset.h for the meaning of the
2516 encoding numbers. */
2517 int enc = font_info->encoding[charset];
2519 if ((enc == 1 || enc == 2)
2520 && CHARSET_DIMENSION (charset) == 2)
2521 char2b->byte1 |= 0x80;
2523 if (enc == 1 || enc == 3)
2524 char2b->byte2 |= 0x80;
2526 if (enc == 4)
2528 int sjis1, sjis2;
2530 ENCODE_SJIS (char2b->byte1, char2b->byte2, sjis1, sjis2);
2531 char2b->byte1 = sjis1;
2532 char2b->byte2 = sjis2;
2536 if (two_byte_p)
2537 *two_byte_p = ((XFontStruct *) (font_info->font))->max_byte1 > 0;
2539 return FONT_TYPE_UNKNOWN;
2544 /***********************************************************************
2545 Glyph display
2546 ***********************************************************************/
2550 static void x_set_glyph_string_clipping P_ ((struct glyph_string *));
2551 static void x_set_glyph_string_gc P_ ((struct glyph_string *));
2552 static void x_draw_glyph_string_background P_ ((struct glyph_string *,
2553 int));
2554 static void x_draw_glyph_string_foreground P_ ((struct glyph_string *));
2555 static void x_draw_composite_glyph_string_foreground P_ ((struct glyph_string *));
2556 static void x_draw_glyph_string_box P_ ((struct glyph_string *));
2557 static void x_draw_glyph_string P_ ((struct glyph_string *));
2558 static void mac_compute_glyph_string_overhangs P_ ((struct glyph_string *));
2559 static void x_set_cursor_gc P_ ((struct glyph_string *));
2560 static void x_set_mode_line_face_gc P_ ((struct glyph_string *));
2561 static void x_set_mouse_face_gc P_ ((struct glyph_string *));
2562 /*static int x_alloc_lighter_color P_ ((struct frame *, Display *, Colormap,
2563 unsigned long *, double, int));*/
2564 static void x_setup_relief_color P_ ((struct frame *, struct relief *,
2565 double, int, unsigned long));
2566 static void x_setup_relief_colors P_ ((struct glyph_string *));
2567 static void x_draw_image_glyph_string P_ ((struct glyph_string *));
2568 static void x_draw_image_relief P_ ((struct glyph_string *));
2569 static void x_draw_image_foreground P_ ((struct glyph_string *));
2570 static void x_clear_glyph_string_rect P_ ((struct glyph_string *, int,
2571 int, int, int));
2572 static void x_draw_relief_rect P_ ((struct frame *, int, int, int, int,
2573 int, int, int, int, int, int,
2574 Rect *));
2575 static void x_draw_box_rect P_ ((struct glyph_string *, int, int, int, int,
2576 int, int, int, Rect *));
2578 #if GLYPH_DEBUG
2579 static void x_check_font P_ ((struct frame *, XFontStruct *));
2580 #endif
2583 /* Set S->gc to a suitable GC for drawing glyph string S in cursor
2584 face. */
2586 static void
2587 x_set_cursor_gc (s)
2588 struct glyph_string *s;
2590 if (s->font == FRAME_FONT (s->f)
2591 && s->face->background == FRAME_BACKGROUND_PIXEL (s->f)
2592 && s->face->foreground == FRAME_FOREGROUND_PIXEL (s->f)
2593 && !s->cmp)
2594 s->gc = s->f->output_data.mac->cursor_gc;
2595 else
2597 /* Cursor on non-default face: must merge. */
2598 XGCValues xgcv;
2599 unsigned long mask;
2601 xgcv.background = s->f->output_data.mac->cursor_pixel;
2602 xgcv.foreground = s->face->background;
2604 /* If the glyph would be invisible, try a different foreground. */
2605 if (xgcv.foreground == xgcv.background)
2606 xgcv.foreground = s->face->foreground;
2607 if (xgcv.foreground == xgcv.background)
2608 xgcv.foreground = s->f->output_data.mac->cursor_foreground_pixel;
2609 if (xgcv.foreground == xgcv.background)
2610 xgcv.foreground = s->face->foreground;
2612 /* Make sure the cursor is distinct from text in this face. */
2613 if (xgcv.background == s->face->background
2614 && xgcv.foreground == s->face->foreground)
2616 xgcv.background = s->face->foreground;
2617 xgcv.foreground = s->face->background;
2620 IF_DEBUG (x_check_font (s->f, s->font));
2621 xgcv.font = s->font;
2622 mask = GCForeground | GCBackground | GCFont;
2624 if (FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc)
2625 XChangeGC (s->display, FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc,
2626 mask, &xgcv);
2627 else
2628 FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc
2629 = XCreateGC (s->display, s->window, mask, &xgcv);
2631 s->gc = FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc;
2636 /* Set up S->gc of glyph string S for drawing text in mouse face. */
2638 static void
2639 x_set_mouse_face_gc (s)
2640 struct glyph_string *s;
2642 int face_id;
2643 struct face *face;
2645 /* What face has to be used last for the mouse face? */
2646 face_id = FRAME_X_DISPLAY_INFO (s->f)->mouse_face_face_id;
2647 face = FACE_FROM_ID (s->f, face_id);
2648 if (face == NULL)
2649 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2651 if (s->first_glyph->type == CHAR_GLYPH)
2652 face_id = FACE_FOR_CHAR (s->f, face, s->first_glyph->u.ch);
2653 else
2654 face_id = FACE_FOR_CHAR (s->f, face, 0);
2655 s->face = FACE_FROM_ID (s->f, face_id);
2656 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
2658 /* If font in this face is same as S->font, use it. */
2659 if (s->font == s->face->font)
2660 s->gc = s->face->gc;
2661 else
2663 /* Otherwise construct scratch_cursor_gc with values from FACE
2664 but font FONT. */
2665 XGCValues xgcv;
2666 unsigned long mask;
2668 xgcv.background = s->face->background;
2669 xgcv.foreground = s->face->foreground;
2670 IF_DEBUG (x_check_font (s->f, s->font));
2671 xgcv.font = s->font;
2672 mask = GCForeground | GCBackground | GCFont;
2674 if (FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc)
2675 XChangeGC (s->display, FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc,
2676 mask, &xgcv);
2677 else
2678 FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc
2679 = XCreateGC (s->display, s->window, mask, &xgcv);
2681 s->gc = FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc;
2684 xassert (s->gc != 0);
2688 /* Set S->gc of glyph string S to a GC suitable for drawing a mode line.
2689 Faces to use in the mode line have already been computed when the
2690 matrix was built, so there isn't much to do, here. */
2692 static INLINE void
2693 x_set_mode_line_face_gc (s)
2694 struct glyph_string *s;
2696 s->gc = s->face->gc;
2700 /* Set S->gc of glyph string S for drawing that glyph string. Set
2701 S->stippled_p to a non-zero value if the face of S has a stipple
2702 pattern. */
2704 static INLINE void
2705 x_set_glyph_string_gc (s)
2706 struct glyph_string *s;
2708 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
2710 if (s->hl == DRAW_NORMAL_TEXT)
2712 s->gc = s->face->gc;
2713 s->stippled_p = s->face->stipple != 0;
2715 else if (s->hl == DRAW_INVERSE_VIDEO)
2717 x_set_mode_line_face_gc (s);
2718 s->stippled_p = s->face->stipple != 0;
2720 else if (s->hl == DRAW_CURSOR)
2722 x_set_cursor_gc (s);
2723 s->stippled_p = 0;
2725 else if (s->hl == DRAW_MOUSE_FACE)
2727 x_set_mouse_face_gc (s);
2728 s->stippled_p = s->face->stipple != 0;
2730 else if (s->hl == DRAW_IMAGE_RAISED
2731 || s->hl == DRAW_IMAGE_SUNKEN)
2733 s->gc = s->face->gc;
2734 s->stippled_p = s->face->stipple != 0;
2736 else
2738 s->gc = s->face->gc;
2739 s->stippled_p = s->face->stipple != 0;
2742 /* GC must have been set. */
2743 xassert (s->gc != 0);
2747 /* Set clipping for output of glyph string S. S may be part of a mode
2748 line or menu if we don't have X toolkit support. */
2750 static INLINE void
2751 x_set_glyph_string_clipping (s)
2752 struct glyph_string *s;
2754 Rect rects[MAX_CLIP_RECTS];
2755 int n;
2757 n = get_glyph_string_clip_rects (s, rects, MAX_CLIP_RECTS);
2758 mac_set_clip_rectangles (s->display, s->gc, rects, n);
2762 /* RIF:
2763 Compute left and right overhang of glyph string S. If S is a glyph
2764 string for a composition, assume overhangs don't exist. */
2766 static void
2767 mac_compute_glyph_string_overhangs (s)
2768 struct glyph_string *s;
2770 if (!(s->cmp == NULL
2771 && s->first_glyph->type == CHAR_GLYPH))
2772 return;
2774 if (!s->two_byte_p
2775 #if USE_ATSUI
2776 || s->font->mac_style
2777 #endif
2780 XCharStruct cs;
2782 mac_text_extents_16 (s->font, s->char2b, s->nchars, &cs);
2783 s->right_overhang = cs.rbearing > cs.width ? cs.rbearing - cs.width : 0;
2784 s->left_overhang = cs.lbearing < 0 ? -cs.lbearing : 0;
2786 else
2788 Rect r;
2789 MacFontStruct *font = s->font;
2791 #if USE_CG_DRAWING
2792 mac_prepare_for_quickdraw (s->f);
2793 #endif
2794 SetPortWindowPort (FRAME_MAC_WINDOW (s->f));
2796 TextFont (font->mac_fontnum);
2797 TextSize (font->mac_fontsize);
2798 TextFace (font->mac_fontface);
2800 QDTextBounds (s->nchars * 2, (char *)s->char2b, &r);
2802 s->right_overhang = r.right > s->width ? r.right - s->width : 0;
2803 s->left_overhang = r.left < 0 ? -r.left : 0;
2808 /* Fill rectangle X, Y, W, H with background color of glyph string S. */
2810 static INLINE void
2811 x_clear_glyph_string_rect (s, x, y, w, h)
2812 struct glyph_string *s;
2813 int x, y, w, h;
2815 mac_erase_rectangle (s->f, s->gc, x, y, w, h);
2819 /* Draw the background of glyph_string S. If S->background_filled_p
2820 is non-zero don't draw it. FORCE_P non-zero means draw the
2821 background even if it wouldn't be drawn normally. This is used
2822 when a string preceding S draws into the background of S, or S
2823 contains the first component of a composition. */
2825 static void
2826 x_draw_glyph_string_background (s, force_p)
2827 struct glyph_string *s;
2828 int force_p;
2830 /* Nothing to do if background has already been drawn or if it
2831 shouldn't be drawn in the first place. */
2832 if (!s->background_filled_p)
2834 int box_line_width = max (s->face->box_line_width, 0);
2836 #if 0 /* MAC_TODO: stipple */
2837 if (s->stippled_p)
2839 /* Fill background with a stipple pattern. */
2840 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2841 XFillRectangle (s->display, s->window, s->gc, s->x,
2842 s->y + box_line_width,
2843 s->background_width,
2844 s->height - 2 * box_line_width);
2845 XSetFillStyle (s->display, s->gc, FillSolid);
2846 s->background_filled_p = 1;
2848 else
2849 #endif
2850 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2851 || s->font_not_found_p
2852 || s->extends_to_end_of_line_p
2853 || force_p)
2855 x_clear_glyph_string_rect (s, s->x, s->y + box_line_width,
2856 s->background_width,
2857 s->height - 2 * box_line_width);
2858 s->background_filled_p = 1;
2864 /* Draw the foreground of glyph string S. */
2866 static void
2867 x_draw_glyph_string_foreground (s)
2868 struct glyph_string *s;
2870 int i, x, bg_width;
2872 /* If first glyph of S has a left box line, start drawing the text
2873 of S to the right of that box line. */
2874 if (s->face->box != FACE_NO_BOX
2875 && s->first_glyph->left_box_line_p)
2876 x = s->x + abs (s->face->box_line_width);
2877 else
2878 x = s->x;
2880 /* Draw characters of S as rectangles if S's font could not be
2881 loaded. */
2882 if (s->font_not_found_p)
2884 for (i = 0; i < s->nchars; ++i)
2886 struct glyph *g = s->first_glyph + i;
2887 mac_draw_rectangle (s->f, s->gc, x, s->y,
2888 g->pixel_width - 1, s->height - 1);
2889 x += g->pixel_width;
2892 else
2894 char *char1b = (char *) s->char2b;
2895 int boff = s->font_info->baseline_offset;
2897 if (s->font_info->vertical_centering)
2898 boff = VCENTER_BASELINE_OFFSET (s->font, s->f) - boff;
2900 /* If we can use 8-bit functions, condense S->char2b. */
2901 if (!s->two_byte_p
2902 #if USE_ATSUI
2903 && GC_FONT (s->gc)->mac_style == NULL
2904 #endif
2906 for (i = 0; i < s->nchars; ++i)
2907 char1b[i] = s->char2b[i].byte2;
2909 /* Draw text with XDrawString if background has already been
2910 filled. Otherwise, use XDrawImageString. (Note that
2911 XDrawImageString is usually faster than XDrawString.) Always
2912 use XDrawImageString when drawing the cursor so that there is
2913 no chance that characters under a box cursor are invisible. */
2914 if (s->for_overlaps
2915 || (s->background_filled_p && s->hl != DRAW_CURSOR))
2916 bg_width = 0; /* Corresponds to XDrawString. */
2917 else
2918 bg_width = s->background_width; /* Corresponds to XDrawImageString. */
2920 if (s->two_byte_p
2921 #if USE_ATSUI
2922 || GC_FONT (s->gc)->mac_style
2923 #endif
2925 #if USE_CG_TEXT_DRAWING
2926 if (!s->two_byte_p
2927 && mac_draw_image_string_cg (s->f, s->gc, x, s->ybase - boff,
2928 s->char2b, s->nchars, bg_width,
2929 s->face->overstrike))
2931 else
2932 #endif
2933 mac_draw_image_string_16 (s->f, s->gc, x, s->ybase - boff,
2934 s->char2b, s->nchars, bg_width,
2935 s->face->overstrike);
2936 else
2937 mac_draw_image_string (s->f, s->gc, x, s->ybase - boff,
2938 char1b, s->nchars, bg_width,
2939 s->face->overstrike);
2943 /* Draw the foreground of composite glyph string S. */
2945 static void
2946 x_draw_composite_glyph_string_foreground (s)
2947 struct glyph_string *s;
2949 int i, x;
2951 /* If first glyph of S has a left box line, start drawing the text
2952 of S to the right of that box line. */
2953 if (s->face->box != FACE_NO_BOX
2954 && s->first_glyph->left_box_line_p)
2955 x = s->x + abs (s->face->box_line_width);
2956 else
2957 x = s->x;
2959 /* S is a glyph string for a composition. S->gidx is the index of
2960 the first character drawn for glyphs of this composition.
2961 S->gidx == 0 means we are drawing the very first character of
2962 this composition. */
2964 /* Draw a rectangle for the composition if the font for the very
2965 first character of the composition could not be loaded. */
2966 if (s->font_not_found_p)
2968 if (s->gidx == 0)
2969 mac_draw_rectangle (s->f, s->gc, x, s->y,
2970 s->width - 1, s->height - 1);
2972 else
2974 for (i = 0; i < s->nchars; i++, ++s->gidx)
2975 mac_draw_image_string_16 (s->f, s->gc,
2976 x + s->cmp->offsets[s->gidx * 2],
2977 s->ybase - s->cmp->offsets[s->gidx * 2 + 1],
2978 s->char2b + i, 1, 0, s->face->overstrike);
2983 #ifdef USE_X_TOOLKIT
2985 static struct frame *x_frame_of_widget P_ ((Widget));
2988 /* Return the frame on which widget WIDGET is used.. Abort if frame
2989 cannot be determined. */
2991 static struct frame *
2992 x_frame_of_widget (widget)
2993 Widget widget;
2995 struct x_display_info *dpyinfo;
2996 Lisp_Object tail;
2997 struct frame *f;
2999 dpyinfo = x_display_info_for_display (XtDisplay (widget));
3001 /* Find the top-level shell of the widget. Note that this function
3002 can be called when the widget is not yet realized, so XtWindow
3003 (widget) == 0. That's the reason we can't simply use
3004 x_any_window_to_frame. */
3005 while (!XtIsTopLevelShell (widget))
3006 widget = XtParent (widget);
3008 /* Look for a frame with that top-level widget. Allocate the color
3009 on that frame to get the right gamma correction value. */
3010 for (tail = Vframe_list; GC_CONSP (tail); tail = XCDR (tail))
3011 if (GC_FRAMEP (XCAR (tail))
3012 && (f = XFRAME (XCAR (tail)),
3013 (f->output_data.nothing != 1
3014 && FRAME_X_DISPLAY_INFO (f) == dpyinfo))
3015 && f->output_data.x->widget == widget)
3016 return f;
3018 abort ();
3022 /* Allocate the color COLOR->pixel on the screen and display of
3023 widget WIDGET in colormap CMAP. If an exact match cannot be
3024 allocated, try the nearest color available. Value is non-zero
3025 if successful. This is called from lwlib. */
3028 x_alloc_nearest_color_for_widget (widget, cmap, color)
3029 Widget widget;
3030 Colormap cmap;
3031 XColor *color;
3033 struct frame *f = x_frame_of_widget (widget);
3034 return x_alloc_nearest_color (f, cmap, color);
3038 #endif /* USE_X_TOOLKIT */
3040 #if 0 /* MAC_TODO */
3042 /* Allocate the color COLOR->pixel on SCREEN of DISPLAY, colormap
3043 CMAP. If an exact match can't be allocated, try the nearest color
3044 available. Value is non-zero if successful. Set *COLOR to the
3045 color allocated. */
3048 x_alloc_nearest_color (f, cmap, color)
3049 struct frame *f;
3050 Colormap cmap;
3051 XColor *color;
3053 Display *display = FRAME_X_DISPLAY (f);
3054 Screen *screen = FRAME_X_SCREEN (f);
3055 int rc;
3057 gamma_correct (f, color);
3058 rc = XAllocColor (display, cmap, color);
3059 if (rc == 0)
3061 /* If we got to this point, the colormap is full, so we're going
3062 to try to get the next closest color. The algorithm used is
3063 a least-squares matching, which is what X uses for closest
3064 color matching with StaticColor visuals. */
3065 int nearest, i;
3066 unsigned long nearest_delta = ~0;
3067 int ncells = XDisplayCells (display, XScreenNumberOfScreen (screen));
3068 XColor *cells = (XColor *) alloca (ncells * sizeof *cells);
3070 for (i = 0; i < ncells; ++i)
3071 cells[i].pixel = i;
3072 XQueryColors (display, cmap, cells, ncells);
3074 for (nearest = i = 0; i < ncells; ++i)
3076 long dred = (color->red >> 8) - (cells[i].red >> 8);
3077 long dgreen = (color->green >> 8) - (cells[i].green >> 8);
3078 long dblue = (color->blue >> 8) - (cells[i].blue >> 8);
3079 unsigned long delta = dred * dred + dgreen * dgreen + dblue * dblue;
3081 if (delta < nearest_delta)
3083 nearest = i;
3084 nearest_delta = delta;
3088 color->red = cells[nearest].red;
3089 color->green = cells[nearest].green;
3090 color->blue = cells[nearest].blue;
3091 rc = XAllocColor (display, cmap, color);
3094 #ifdef DEBUG_X_COLORS
3095 if (rc)
3096 register_color (color->pixel);
3097 #endif /* DEBUG_X_COLORS */
3099 return rc;
3103 /* Allocate color PIXEL on frame F. PIXEL must already be allocated.
3104 It's necessary to do this instead of just using PIXEL directly to
3105 get color reference counts right. */
3107 unsigned long
3108 x_copy_color (f, pixel)
3109 struct frame *f;
3110 unsigned long pixel;
3112 XColor color;
3114 color.pixel = pixel;
3115 BLOCK_INPUT;
3116 XQueryColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
3117 XAllocColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
3118 UNBLOCK_INPUT;
3119 #ifdef DEBUG_X_COLORS
3120 register_color (pixel);
3121 #endif
3122 return color.pixel;
3126 /* Allocate color PIXEL on display DPY. PIXEL must already be allocated.
3127 It's necessary to do this instead of just using PIXEL directly to
3128 get color reference counts right. */
3130 unsigned long
3131 x_copy_dpy_color (dpy, cmap, pixel)
3132 Display *dpy;
3133 Colormap cmap;
3134 unsigned long pixel;
3136 XColor color;
3138 color.pixel = pixel;
3139 BLOCK_INPUT;
3140 XQueryColor (dpy, cmap, &color);
3141 XAllocColor (dpy, cmap, &color);
3142 UNBLOCK_INPUT;
3143 #ifdef DEBUG_X_COLORS
3144 register_color (pixel);
3145 #endif
3146 return color.pixel;
3149 #endif /* MAC_TODO */
3152 /* Brightness beyond which a color won't have its highlight brightness
3153 boosted.
3155 Nominally, highlight colors for `3d' faces are calculated by
3156 brightening an object's color by a constant scale factor, but this
3157 doesn't yield good results for dark colors, so for colors who's
3158 brightness is less than this value (on a scale of 0-255) have to
3159 use an additional additive factor.
3161 The value here is set so that the default menu-bar/mode-line color
3162 (grey75) will not have its highlights changed at all. */
3163 #define HIGHLIGHT_COLOR_DARK_BOOST_LIMIT 187
3166 /* Allocate a color which is lighter or darker than *COLOR by FACTOR
3167 or DELTA. Try a color with RGB values multiplied by FACTOR first.
3168 If this produces the same color as COLOR, try a color where all RGB
3169 values have DELTA added. Return the allocated color in *COLOR.
3170 DISPLAY is the X display, CMAP is the colormap to operate on.
3171 Value is non-zero if successful. */
3173 static int
3174 mac_alloc_lighter_color (f, color, factor, delta)
3175 struct frame *f;
3176 unsigned long *color;
3177 double factor;
3178 int delta;
3180 unsigned long new;
3181 long bright;
3183 /* On Mac, RGB values are 0-255, not 0-65535, so scale delta. */
3184 delta /= 256;
3186 /* Change RGB values by specified FACTOR. Avoid overflow! */
3187 xassert (factor >= 0);
3188 new = RGB_TO_ULONG (min (0xff, (int) (factor * RED_FROM_ULONG (*color))),
3189 min (0xff, (int) (factor * GREEN_FROM_ULONG (*color))),
3190 min (0xff, (int) (factor * BLUE_FROM_ULONG (*color))));
3192 /* Calculate brightness of COLOR. */
3193 bright = (2 * RED_FROM_ULONG (*color) + 3 * GREEN_FROM_ULONG (*color)
3194 + BLUE_FROM_ULONG (*color)) / 6;
3196 /* We only boost colors that are darker than
3197 HIGHLIGHT_COLOR_DARK_BOOST_LIMIT. */
3198 if (bright < HIGHLIGHT_COLOR_DARK_BOOST_LIMIT)
3199 /* Make an additive adjustment to NEW, because it's dark enough so
3200 that scaling by FACTOR alone isn't enough. */
3202 /* How far below the limit this color is (0 - 1, 1 being darker). */
3203 double dimness = 1 - (double)bright / HIGHLIGHT_COLOR_DARK_BOOST_LIMIT;
3204 /* The additive adjustment. */
3205 int min_delta = delta * dimness * factor / 2;
3207 if (factor < 1)
3208 new = RGB_TO_ULONG (max (0, min (0xff, (int) (RED_FROM_ULONG (*color)) - min_delta)),
3209 max (0, min (0xff, (int) (GREEN_FROM_ULONG (*color)) - min_delta)),
3210 max (0, min (0xff, (int) (BLUE_FROM_ULONG (*color)) - min_delta)));
3211 else
3212 new = RGB_TO_ULONG (max (0, min (0xff, (int) (min_delta + RED_FROM_ULONG (*color)))),
3213 max (0, min (0xff, (int) (min_delta + GREEN_FROM_ULONG (*color)))),
3214 max (0, min (0xff, (int) (min_delta + BLUE_FROM_ULONG (*color)))));
3217 if (new == *color)
3218 new = RGB_TO_ULONG (max (0, min (0xff, (int) (delta + RED_FROM_ULONG (*color)))),
3219 max (0, min (0xff, (int) (delta + GREEN_FROM_ULONG (*color)))),
3220 max (0, min (0xff, (int) (delta + BLUE_FROM_ULONG (*color)))));
3222 /* MAC_TODO: Map to palette and retry with delta if same? */
3223 /* MAC_TODO: Free colors (if using palette)? */
3225 if (new == *color)
3226 return 0;
3228 *color = new;
3230 return 1;
3234 /* Set up the foreground color for drawing relief lines of glyph
3235 string S. RELIEF is a pointer to a struct relief containing the GC
3236 with which lines will be drawn. Use a color that is FACTOR or
3237 DELTA lighter or darker than the relief's background which is found
3238 in S->f->output_data.x->relief_background. If such a color cannot
3239 be allocated, use DEFAULT_PIXEL, instead. */
3241 static void
3242 x_setup_relief_color (f, relief, factor, delta, default_pixel)
3243 struct frame *f;
3244 struct relief *relief;
3245 double factor;
3246 int delta;
3247 unsigned long default_pixel;
3249 XGCValues xgcv;
3250 struct mac_output *di = f->output_data.mac;
3251 unsigned long mask = GCForeground;
3252 unsigned long pixel;
3253 unsigned long background = di->relief_background;
3254 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
3256 /* MAC_TODO: Free colors (if using palette)? */
3258 /* Allocate new color. */
3259 xgcv.foreground = default_pixel;
3260 pixel = background;
3261 if (dpyinfo->n_planes != 1
3262 && mac_alloc_lighter_color (f, &pixel, factor, delta))
3264 relief->allocated_p = 1;
3265 xgcv.foreground = relief->pixel = pixel;
3268 if (relief->gc == 0)
3270 #if 0 /* MAC_TODO: stipple */
3271 xgcv.stipple = dpyinfo->gray;
3272 mask |= GCStipple;
3273 #endif
3274 relief->gc = XCreateGC (NULL, FRAME_MAC_WINDOW (f), mask, &xgcv);
3276 else
3277 XChangeGC (NULL, relief->gc, mask, &xgcv);
3281 /* Set up colors for the relief lines around glyph string S. */
3283 static void
3284 x_setup_relief_colors (s)
3285 struct glyph_string *s;
3287 struct mac_output *di = s->f->output_data.mac;
3288 unsigned long color;
3290 if (s->face->use_box_color_for_shadows_p)
3291 color = s->face->box_color;
3292 else if (s->first_glyph->type == IMAGE_GLYPH
3293 && s->img->pixmap
3294 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
3295 color = IMAGE_BACKGROUND (s->img, s->f, 0);
3296 else
3298 XGCValues xgcv;
3300 /* Get the background color of the face. */
3301 XGetGCValues (s->display, s->gc, GCBackground, &xgcv);
3302 color = xgcv.background;
3305 if (di->white_relief.gc == 0
3306 || color != di->relief_background)
3308 di->relief_background = color;
3309 x_setup_relief_color (s->f, &di->white_relief, 1.2, 0x8000,
3310 WHITE_PIX_DEFAULT (s->f));
3311 x_setup_relief_color (s->f, &di->black_relief, 0.6, 0x4000,
3312 BLACK_PIX_DEFAULT (s->f));
3317 /* Draw a relief on frame F inside the rectangle given by LEFT_X,
3318 TOP_Y, RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the relief
3319 to draw, it must be >= 0. RAISED_P non-zero means draw a raised
3320 relief. LEFT_P non-zero means draw a relief on the left side of
3321 the rectangle. RIGHT_P non-zero means draw a relief on the right
3322 side of the rectangle. CLIP_RECT is the clipping rectangle to use
3323 when drawing. */
3325 static void
3326 x_draw_relief_rect (f, left_x, top_y, right_x, bottom_y, width,
3327 raised_p, top_p, bot_p, left_p, right_p, clip_rect)
3328 struct frame *f;
3329 int left_x, top_y, right_x, bottom_y, width;
3330 int top_p, bot_p, left_p, right_p, raised_p;
3331 Rect *clip_rect;
3333 Display *dpy = FRAME_MAC_DISPLAY (f);
3334 int i;
3335 GC gc;
3337 if (raised_p)
3338 gc = f->output_data.mac->white_relief.gc;
3339 else
3340 gc = f->output_data.mac->black_relief.gc;
3341 mac_set_clip_rectangles (dpy, gc, clip_rect, 1);
3343 /* Top. */
3344 if (top_p)
3345 for (i = 0; i < width; ++i)
3346 mac_draw_line (f, gc,
3347 left_x + i * left_p, top_y + i,
3348 right_x + 1 - i * right_p, top_y + i);
3350 /* Left. */
3351 if (left_p)
3352 for (i = 0; i < width; ++i)
3353 mac_draw_line (f, gc,
3354 left_x + i, top_y + i, left_x + i, bottom_y - i + 1);
3356 mac_reset_clip_rectangles (dpy, gc);
3357 if (raised_p)
3358 gc = f->output_data.mac->black_relief.gc;
3359 else
3360 gc = f->output_data.mac->white_relief.gc;
3361 mac_set_clip_rectangles (dpy, gc, clip_rect, 1);
3363 /* Bottom. */
3364 if (bot_p)
3365 for (i = 0; i < width; ++i)
3366 mac_draw_line (f, gc,
3367 left_x + i * left_p, bottom_y - i,
3368 right_x + 1 - i * right_p, bottom_y - i);
3370 /* Right. */
3371 if (right_p)
3372 for (i = 0; i < width; ++i)
3373 mac_draw_line (f, gc,
3374 right_x - i, top_y + i + 1, right_x - i, bottom_y - i);
3376 mac_reset_clip_rectangles (dpy, gc);
3380 /* Draw a box on frame F inside the rectangle given by LEFT_X, TOP_Y,
3381 RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the lines to
3382 draw, it must be >= 0. LEFT_P non-zero means draw a line on the
3383 left side of the rectangle. RIGHT_P non-zero means draw a line
3384 on the right side of the rectangle. CLIP_RECT is the clipping
3385 rectangle to use when drawing. */
3387 static void
3388 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
3389 left_p, right_p, clip_rect)
3390 struct glyph_string *s;
3391 int left_x, top_y, right_x, bottom_y, width, left_p, right_p;
3392 Rect *clip_rect;
3394 XGCValues xgcv;
3396 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3397 XSetForeground (s->display, s->gc, s->face->box_color);
3398 mac_set_clip_rectangles (s->display, s->gc, clip_rect, 1);
3400 /* Top. */
3401 mac_fill_rectangle (s->f, s->gc, left_x, top_y,
3402 right_x - left_x + 1, width);
3404 /* Left. */
3405 if (left_p)
3406 mac_fill_rectangle (s->f, s->gc, left_x, top_y,
3407 width, bottom_y - top_y + 1);
3409 /* Bottom. */
3410 mac_fill_rectangle (s->f, s->gc, left_x, bottom_y - width + 1,
3411 right_x - left_x + 1, width);
3413 /* Right. */
3414 if (right_p)
3415 mac_fill_rectangle (s->f, s->gc, right_x - width + 1,
3416 top_y, width, bottom_y - top_y + 1);
3418 XSetForeground (s->display, s->gc, xgcv.foreground);
3419 mac_reset_clip_rectangles (s->display, s->gc);
3423 /* Draw a box around glyph string S. */
3425 static void
3426 x_draw_glyph_string_box (s)
3427 struct glyph_string *s;
3429 int width, left_x, right_x, top_y, bottom_y, last_x, raised_p;
3430 int left_p, right_p;
3431 struct glyph *last_glyph;
3432 Rect clip_rect;
3434 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
3435 ? WINDOW_RIGHT_EDGE_X (s->w)
3436 : window_box_right (s->w, s->area));
3438 /* The glyph that may have a right box line. */
3439 last_glyph = (s->cmp || s->img
3440 ? s->first_glyph
3441 : s->first_glyph + s->nchars - 1);
3443 width = abs (s->face->box_line_width);
3444 raised_p = s->face->box == FACE_RAISED_BOX;
3445 left_x = s->x;
3446 right_x = (s->row->full_width_p && s->extends_to_end_of_line_p
3447 ? last_x - 1
3448 : min (last_x, s->x + s->background_width) - 1);
3449 top_y = s->y;
3450 bottom_y = top_y + s->height - 1;
3452 left_p = (s->first_glyph->left_box_line_p
3453 || (s->hl == DRAW_MOUSE_FACE
3454 && (s->prev == NULL
3455 || s->prev->hl != s->hl)));
3456 right_p = (last_glyph->right_box_line_p
3457 || (s->hl == DRAW_MOUSE_FACE
3458 && (s->next == NULL
3459 || s->next->hl != s->hl)));
3461 get_glyph_string_clip_rect (s, &clip_rect);
3463 if (s->face->box == FACE_SIMPLE_BOX)
3464 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
3465 left_p, right_p, &clip_rect);
3466 else
3468 x_setup_relief_colors (s);
3469 x_draw_relief_rect (s->f, left_x, top_y, right_x, bottom_y,
3470 width, raised_p, 1, 1, left_p, right_p, &clip_rect);
3475 /* Draw foreground of image glyph string S. */
3477 static void
3478 x_draw_image_foreground (s)
3479 struct glyph_string *s;
3481 int x = s->x;
3482 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3484 /* If first glyph of S has a left box line, start drawing it to the
3485 right of that line. */
3486 if (s->face->box != FACE_NO_BOX
3487 && s->first_glyph->left_box_line_p
3488 && s->slice.x == 0)
3489 x += abs (s->face->box_line_width);
3491 /* If there is a margin around the image, adjust x- and y-position
3492 by that margin. */
3493 if (s->slice.x == 0)
3494 x += s->img->hmargin;
3495 if (s->slice.y == 0)
3496 y += s->img->vmargin;
3498 if (s->img->pixmap)
3500 x_set_glyph_string_clipping (s);
3502 #if USE_CG_DRAWING
3503 mac_draw_cg_image (s->img->data.ptr_val,
3504 s->f, s->gc, s->slice.x, s->slice.y,
3505 s->slice.width, s->slice.height, x, y, 1);
3506 #endif
3507 if (s->img->mask)
3508 #if !USE_CG_DRAWING
3509 mac_copy_area_with_mask (s->img->pixmap, s->img->mask,
3510 s->f, s->gc, s->slice.x, s->slice.y,
3511 s->slice.width, s->slice.height, x, y);
3512 #else
3514 #endif
3515 else
3517 #if !USE_CG_DRAWING
3518 mac_copy_area (s->img->pixmap,
3519 s->f, s->gc, s->slice.x, s->slice.y,
3520 s->slice.width, s->slice.height, x, y);
3521 #endif
3523 /* When the image has a mask, we can expect that at
3524 least part of a mouse highlight or a block cursor will
3525 be visible. If the image doesn't have a mask, make
3526 a block cursor visible by drawing a rectangle around
3527 the image. I believe it's looking better if we do
3528 nothing here for mouse-face. */
3529 if (s->hl == DRAW_CURSOR)
3531 int r = s->img->relief;
3532 if (r < 0) r = -r;
3533 mac_draw_rectangle (s->f, s->gc, x - r, y - r,
3534 s->slice.width + r*2 - 1,
3535 s->slice.height + r*2 - 1);
3539 else
3540 /* Draw a rectangle if image could not be loaded. */
3541 mac_draw_rectangle (s->f, s->gc, x, y,
3542 s->slice.width - 1, s->slice.height - 1);
3546 /* Draw a relief around the image glyph string S. */
3548 static void
3549 x_draw_image_relief (s)
3550 struct glyph_string *s;
3552 int x0, y0, x1, y1, thick, raised_p;
3553 Rect r;
3554 int x = s->x;
3555 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3557 /* If first glyph of S has a left box line, start drawing it to the
3558 right of that line. */
3559 if (s->face->box != FACE_NO_BOX
3560 && s->first_glyph->left_box_line_p
3561 && s->slice.x == 0)
3562 x += abs (s->face->box_line_width);
3564 /* If there is a margin around the image, adjust x- and y-position
3565 by that margin. */
3566 if (s->slice.x == 0)
3567 x += s->img->hmargin;
3568 if (s->slice.y == 0)
3569 y += s->img->vmargin;
3571 if (s->hl == DRAW_IMAGE_SUNKEN
3572 || s->hl == DRAW_IMAGE_RAISED)
3574 thick = tool_bar_button_relief >= 0 ? tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3575 raised_p = s->hl == DRAW_IMAGE_RAISED;
3577 else
3579 thick = abs (s->img->relief);
3580 raised_p = s->img->relief > 0;
3583 x0 = x - thick;
3584 y0 = y - thick;
3585 x1 = x + s->slice.width + thick - 1;
3586 y1 = y + s->slice.height + thick - 1;
3588 x_setup_relief_colors (s);
3589 get_glyph_string_clip_rect (s, &r);
3590 x_draw_relief_rect (s->f, x0, y0, x1, y1, thick, raised_p,
3591 s->slice.y == 0,
3592 s->slice.y + s->slice.height == s->img->height,
3593 s->slice.x == 0,
3594 s->slice.x + s->slice.width == s->img->width,
3595 &r);
3599 /* Draw part of the background of glyph string S. X, Y, W, and H
3600 give the rectangle to draw. */
3602 static void
3603 x_draw_glyph_string_bg_rect (s, x, y, w, h)
3604 struct glyph_string *s;
3605 int x, y, w, h;
3607 #if 0 /* MAC_TODO: stipple */
3608 if (s->stippled_p)
3610 /* Fill background with a stipple pattern. */
3611 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
3612 XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
3613 XSetFillStyle (s->display, s->gc, FillSolid);
3615 else
3616 #endif /* MAC_TODO */
3617 x_clear_glyph_string_rect (s, x, y, w, h);
3621 /* Draw image glyph string S.
3623 s->y
3624 s->x +-------------------------
3625 | s->face->box
3627 | +-------------------------
3628 | | s->img->margin
3630 | | +-------------------
3631 | | | the image
3635 static void
3636 x_draw_image_glyph_string (s)
3637 struct glyph_string *s;
3639 int x, y;
3640 int box_line_hwidth = abs (s->face->box_line_width);
3641 int box_line_vwidth = max (s->face->box_line_width, 0);
3642 int height;
3644 height = s->height - 2 * box_line_vwidth;
3647 /* Fill background with face under the image. Do it only if row is
3648 taller than image or if image has a clip mask to reduce
3649 flickering. */
3650 s->stippled_p = s->face->stipple != 0;
3651 if (height > s->slice.height
3652 || s->img->hmargin
3653 || s->img->vmargin
3654 || s->img->mask
3655 || s->img->pixmap == 0
3656 || s->width != s->background_width)
3658 x = s->x;
3659 if (s->first_glyph->left_box_line_p
3660 && s->slice.x == 0)
3661 x += box_line_hwidth;
3663 y = s->y;
3664 if (s->slice.y == 0)
3665 y += box_line_vwidth;
3667 x_draw_glyph_string_bg_rect (s, x, y, s->background_width, height);
3669 s->background_filled_p = 1;
3672 /* Draw the foreground. */
3673 x_draw_image_foreground (s);
3675 /* If we must draw a relief around the image, do it. */
3676 if (s->img->relief
3677 || s->hl == DRAW_IMAGE_RAISED
3678 || s->hl == DRAW_IMAGE_SUNKEN)
3679 x_draw_image_relief (s);
3683 /* Draw stretch glyph string S. */
3685 static void
3686 x_draw_stretch_glyph_string (s)
3687 struct glyph_string *s;
3689 xassert (s->first_glyph->type == STRETCH_GLYPH);
3690 s->stippled_p = s->face->stipple != 0;
3692 if (s->hl == DRAW_CURSOR
3693 && !x_stretch_cursor_p)
3695 /* If `x-stretch-block-cursor' is nil, don't draw a block cursor
3696 as wide as the stretch glyph. */
3697 int width, background_width = s->background_width;
3698 int x = s->x, left_x = window_box_left_offset (s->w, TEXT_AREA);
3700 if (x < left_x)
3702 background_width -= left_x - x;
3703 x = left_x;
3705 width = min (FRAME_COLUMN_WIDTH (s->f), background_width);
3707 /* Draw cursor. */
3708 x_draw_glyph_string_bg_rect (s, x, s->y, width, s->height);
3710 /* Clear rest using the GC of the original non-cursor face. */
3711 if (width < background_width)
3713 int y = s->y;
3714 int w = background_width - width, h = s->height;
3715 Rect r;
3716 GC gc;
3718 x += width;
3719 if (s->row->mouse_face_p
3720 && cursor_in_mouse_face_p (s->w))
3722 x_set_mouse_face_gc (s);
3723 gc = s->gc;
3725 else
3726 gc = s->face->gc;
3728 get_glyph_string_clip_rect (s, &r);
3729 mac_set_clip_rectangles (s->display, gc, &r, 1);
3731 #if 0 /* MAC_TODO: stipple */
3732 if (s->face->stipple)
3734 /* Fill background with a stipple pattern. */
3735 XSetFillStyle (s->display, gc, FillOpaqueStippled);
3736 XFillRectangle (s->display, s->window, gc, x, y, w, h);
3737 XSetFillStyle (s->display, gc, FillSolid);
3739 else
3740 #endif /* MAC_TODO */
3741 mac_erase_rectangle (s->f, gc, x, y, w, h);
3744 else if (!s->background_filled_p)
3746 int background_width = s->background_width;
3747 int x = s->x, left_x = window_box_left_offset (s->w, TEXT_AREA);
3749 /* Don't draw into left margin, fringe or scrollbar area
3750 except for header line and mode line. */
3751 if (x < left_x && !s->row->mode_line_p)
3753 background_width -= left_x - x;
3754 x = left_x;
3756 if (background_width > 0)
3757 x_draw_glyph_string_bg_rect (s, x, s->y, background_width, s->height);
3760 s->background_filled_p = 1;
3764 /* Draw glyph string S. */
3766 static void
3767 x_draw_glyph_string (s)
3768 struct glyph_string *s;
3770 int relief_drawn_p = 0;
3772 /* If S draws into the background of its successor that does not
3773 draw a cursor, draw the background of the successor first so that
3774 S can draw into it. This makes S->next use XDrawString instead
3775 of XDrawImageString. */
3776 if (s->next && s->right_overhang && !s->for_overlaps
3777 && s->next->hl != DRAW_CURSOR)
3779 xassert (s->next->img == NULL);
3780 x_set_glyph_string_gc (s->next);
3781 x_set_glyph_string_clipping (s->next);
3782 x_draw_glyph_string_background (s->next, 1);
3785 /* Set up S->gc, set clipping and draw S. */
3786 x_set_glyph_string_gc (s);
3788 /* Draw relief (if any) in advance for char/composition so that the
3789 glyph string can be drawn over it. */
3790 if (!s->for_overlaps
3791 && s->face->box != FACE_NO_BOX
3792 && (s->first_glyph->type == CHAR_GLYPH
3793 || s->first_glyph->type == COMPOSITE_GLYPH))
3796 x_set_glyph_string_clipping (s);
3797 x_draw_glyph_string_background (s, 1);
3798 x_draw_glyph_string_box (s);
3799 x_set_glyph_string_clipping (s);
3800 relief_drawn_p = 1;
3802 else
3803 x_set_glyph_string_clipping (s);
3805 switch (s->first_glyph->type)
3807 case IMAGE_GLYPH:
3808 x_draw_image_glyph_string (s);
3809 break;
3811 case STRETCH_GLYPH:
3812 x_draw_stretch_glyph_string (s);
3813 break;
3815 case CHAR_GLYPH:
3816 if (s->for_overlaps)
3817 s->background_filled_p = 1;
3818 else
3819 x_draw_glyph_string_background (s, 0);
3820 x_draw_glyph_string_foreground (s);
3821 break;
3823 case COMPOSITE_GLYPH:
3824 if (s->for_overlaps || s->gidx > 0)
3825 s->background_filled_p = 1;
3826 else
3827 x_draw_glyph_string_background (s, 1);
3828 x_draw_composite_glyph_string_foreground (s);
3829 break;
3831 default:
3832 abort ();
3835 if (!s->for_overlaps)
3837 /* Draw underline. */
3838 if (s->face->underline_p)
3840 unsigned long tem, h;
3841 int y;
3843 #if 0
3844 /* Get the underline thickness. Default is 1 pixel. */
3845 if (!XGetFontProperty (s->font, XA_UNDERLINE_THICKNESS, &h))
3846 #endif
3847 h = 1;
3849 y = s->y + s->height - h;
3850 if (!x_underline_at_descent_line)
3852 /* Get the underline position. This is the recommended
3853 vertical offset in pixels from the baseline to the top of
3854 the underline. This is a signed value according to the
3855 specs, and its default is
3857 ROUND ((maximum descent) / 2), with
3858 ROUND(x) = floor (x + 0.5) */
3860 #if 0
3861 if (x_use_underline_position_properties
3862 && XGetFontProperty (s->font, XA_UNDERLINE_POSITION, &tem))
3863 y = s->ybase + (long) tem;
3864 else
3865 #endif
3866 if (s->face->font)
3867 y = s->ybase + (s->face->font->max_bounds.descent + 1) / 2;
3870 if (s->face->underline_defaulted_p)
3871 mac_fill_rectangle (s->f, s->gc, s->x, y,
3872 s->background_width, h);
3873 else
3875 XGCValues xgcv;
3876 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3877 XSetForeground (s->display, s->gc, s->face->underline_color);
3878 mac_fill_rectangle (s->f, s->gc, s->x, y,
3879 s->background_width, h);
3880 XSetForeground (s->display, s->gc, xgcv.foreground);
3884 /* Draw overline. */
3885 if (s->face->overline_p)
3887 unsigned long dy = 0, h = 1;
3889 if (s->face->overline_color_defaulted_p)
3890 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3891 s->background_width, h);
3892 else
3894 XGCValues xgcv;
3895 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3896 XSetForeground (s->display, s->gc, s->face->overline_color);
3897 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3898 s->background_width, h);
3899 XSetForeground (s->display, s->gc, xgcv.foreground);
3903 /* Draw strike-through. */
3904 if (s->face->strike_through_p)
3906 unsigned long h = 1;
3907 unsigned long dy = (s->height - h) / 2;
3909 if (s->face->strike_through_color_defaulted_p)
3910 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3911 s->width, h);
3912 else
3914 XGCValues xgcv;
3915 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3916 XSetForeground (s->display, s->gc, s->face->strike_through_color);
3917 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3918 s->width, h);
3919 XSetForeground (s->display, s->gc, xgcv.foreground);
3923 /* Draw relief if not yet drawn. */
3924 if (!relief_drawn_p && s->face->box != FACE_NO_BOX)
3925 x_draw_glyph_string_box (s);
3928 /* Reset clipping. */
3929 mac_reset_clip_rectangles (s->display, s->gc);
3932 /* Shift display to make room for inserted glyphs. */
3934 void
3935 mac_shift_glyphs_for_insert (f, x, y, width, height, shift_by)
3936 struct frame *f;
3937 int x, y, width, height, shift_by;
3939 mac_scroll_area (f, f->output_data.mac->normal_gc,
3940 x, y, width, height,
3941 x + shift_by, y);
3944 /* Delete N glyphs at the nominal cursor position. Not implemented
3945 for X frames. */
3947 static void
3948 x_delete_glyphs (n)
3949 register int n;
3951 abort ();
3955 /* Clear entire frame. If updating_frame is non-null, clear that
3956 frame. Otherwise clear the selected frame. */
3958 static void
3959 x_clear_frame ()
3961 struct frame *f;
3963 if (updating_frame)
3964 f = updating_frame;
3965 else
3966 f = SELECTED_FRAME ();
3968 /* Clearing the frame will erase any cursor, so mark them all as no
3969 longer visible. */
3970 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
3971 output_cursor.hpos = output_cursor.vpos = 0;
3972 output_cursor.x = -1;
3974 /* We don't set the output cursor here because there will always
3975 follow an explicit cursor_to. */
3976 BLOCK_INPUT;
3977 mac_clear_window (f);
3979 /* We have to clear the scroll bars, too. If we have changed
3980 colors or something like that, then they should be notified. */
3981 x_scroll_bar_clear (f);
3983 XFlush (FRAME_MAC_DISPLAY (f));
3984 UNBLOCK_INPUT;
3989 /* Invert the middle quarter of the frame for .15 sec. */
3991 /* We use the select system call to do the waiting, so we have to make
3992 sure it's available. If it isn't, we just won't do visual bells. */
3994 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
3997 /* Subtract the `struct timeval' values X and Y, storing the result in
3998 *RESULT. Return 1 if the difference is negative, otherwise 0. */
4000 static int
4001 timeval_subtract (result, x, y)
4002 struct timeval *result, x, y;
4004 /* Perform the carry for the later subtraction by updating y. This
4005 is safer because on some systems the tv_sec member is unsigned. */
4006 if (x.tv_usec < y.tv_usec)
4008 int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
4009 y.tv_usec -= 1000000 * nsec;
4010 y.tv_sec += nsec;
4013 if (x.tv_usec - y.tv_usec > 1000000)
4015 int nsec = (y.tv_usec - x.tv_usec) / 1000000;
4016 y.tv_usec += 1000000 * nsec;
4017 y.tv_sec -= nsec;
4020 /* Compute the time remaining to wait. tv_usec is certainly
4021 positive. */
4022 result->tv_sec = x.tv_sec - y.tv_sec;
4023 result->tv_usec = x.tv_usec - y.tv_usec;
4025 /* Return indication of whether the result should be considered
4026 negative. */
4027 return x.tv_sec < y.tv_sec;
4030 void
4031 XTflash (f)
4032 struct frame *f;
4034 /* Get the height not including a menu bar widget. */
4035 int height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, FRAME_LINES (f));
4036 /* Height of each line to flash. */
4037 int flash_height = FRAME_LINE_HEIGHT (f);
4038 /* These will be the left and right margins of the rectangles. */
4039 int flash_left = FRAME_INTERNAL_BORDER_WIDTH (f);
4040 int flash_right = FRAME_PIXEL_WIDTH (f) - FRAME_INTERNAL_BORDER_WIDTH (f);
4042 int width;
4044 /* Don't flash the area between a scroll bar and the frame
4045 edge it is next to. */
4046 switch (FRAME_VERTICAL_SCROLL_BAR_TYPE (f))
4048 case vertical_scroll_bar_left:
4049 flash_left += VERTICAL_SCROLL_BAR_WIDTH_TRIM;
4050 break;
4052 case vertical_scroll_bar_right:
4053 flash_right -= VERTICAL_SCROLL_BAR_WIDTH_TRIM;
4054 break;
4056 default:
4057 break;
4060 width = flash_right - flash_left;
4062 BLOCK_INPUT;
4064 /* If window is tall, flash top and bottom line. */
4065 if (height > 3 * FRAME_LINE_HEIGHT (f))
4067 mac_invert_rectangle (f, flash_left,
4068 (FRAME_INTERNAL_BORDER_WIDTH (f)
4069 + FRAME_TOOL_BAR_LINES (f) * FRAME_LINE_HEIGHT (f)),
4070 width, flash_height);
4071 mac_invert_rectangle (f, flash_left,
4072 (height - flash_height
4073 - FRAME_INTERNAL_BORDER_WIDTH (f)),
4074 width, flash_height);
4076 else
4077 /* If it is short, flash it all. */
4078 mac_invert_rectangle (f, flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
4079 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
4081 x_flush (f);
4084 struct timeval wakeup;
4086 EMACS_GET_TIME (wakeup);
4088 /* Compute time to wait until, propagating carry from usecs. */
4089 wakeup.tv_usec += 150000;
4090 wakeup.tv_sec += (wakeup.tv_usec / 1000000);
4091 wakeup.tv_usec %= 1000000;
4093 /* Keep waiting until past the time wakeup or any input gets
4094 available. */
4095 while (! detect_input_pending ())
4097 struct timeval current;
4098 struct timeval timeout;
4100 EMACS_GET_TIME (current);
4102 /* Break if result would be negative. */
4103 if (timeval_subtract (&current, wakeup, current))
4104 break;
4106 /* How long `select' should wait. */
4107 timeout.tv_sec = 0;
4108 timeout.tv_usec = 10000;
4110 /* Try to wait that long--but we might wake up sooner. */
4111 select (0, NULL, NULL, NULL, &timeout);
4115 /* If window is tall, flash top and bottom line. */
4116 if (height > 3 * FRAME_LINE_HEIGHT (f))
4118 mac_invert_rectangle (f, flash_left,
4119 (FRAME_INTERNAL_BORDER_WIDTH (f)
4120 + FRAME_TOOL_BAR_LINES (f) * FRAME_LINE_HEIGHT (f)),
4121 width, flash_height);
4122 mac_invert_rectangle (f, flash_left,
4123 (height - flash_height
4124 - FRAME_INTERNAL_BORDER_WIDTH (f)),
4125 width, flash_height);
4127 else
4128 /* If it is short, flash it all. */
4129 mac_invert_rectangle (f, flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
4130 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
4132 x_flush (f);
4134 UNBLOCK_INPUT;
4137 #endif /* defined (HAVE_TIMEVAL) && defined (HAVE_SELECT) */
4140 /* Make audible bell. */
4142 void
4143 XTring_bell ()
4145 struct frame *f = SELECTED_FRAME ();
4147 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
4148 if (visible_bell)
4149 XTflash (f);
4150 else
4151 #endif
4153 BLOCK_INPUT;
4154 SysBeep (1);
4155 XFlush (FRAME_MAC_DISPLAY (f));
4156 UNBLOCK_INPUT;
4161 /* Specify how many text lines, from the top of the window,
4162 should be affected by insert-lines and delete-lines operations.
4163 This, and those operations, are used only within an update
4164 that is bounded by calls to x_update_begin and x_update_end. */
4166 static void
4167 XTset_terminal_window (n)
4168 register int n;
4170 /* This function intentionally left blank. */
4175 /***********************************************************************
4176 Line Dance
4177 ***********************************************************************/
4179 /* Perform an insert-lines or delete-lines operation, inserting N
4180 lines or deleting -N lines at vertical position VPOS. */
4182 static void
4183 x_ins_del_lines (vpos, n)
4184 int vpos, n;
4186 abort ();
4190 /* Scroll part of the display as described by RUN. */
4192 static void
4193 x_scroll_run (w, run)
4194 struct window *w;
4195 struct run *run;
4197 struct frame *f = XFRAME (w->frame);
4198 int x, y, width, height, from_y, to_y, bottom_y;
4200 /* Get frame-relative bounding box of the text display area of W,
4201 without mode lines. Include in this box the left and right
4202 fringe of W. */
4203 window_box (w, -1, &x, &y, &width, &height);
4205 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
4206 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
4207 bottom_y = y + height;
4209 if (to_y < from_y)
4211 /* Scrolling up. Make sure we don't copy part of the mode
4212 line at the bottom. */
4213 if (from_y + run->height > bottom_y)
4214 height = bottom_y - from_y;
4215 else
4216 height = run->height;
4218 else
4220 /* Scolling down. Make sure we don't copy over the mode line.
4221 at the bottom. */
4222 if (to_y + run->height > bottom_y)
4223 height = bottom_y - to_y;
4224 else
4225 height = run->height;
4228 BLOCK_INPUT;
4230 /* Cursor off. Will be switched on again in x_update_window_end. */
4231 updated_window = w;
4232 x_clear_cursor (w);
4234 mac_scroll_area (f, f->output_data.mac->normal_gc,
4235 x, from_y,
4236 width, height,
4237 x, to_y);
4239 UNBLOCK_INPUT;
4244 /***********************************************************************
4245 Exposure Events
4246 ***********************************************************************/
4249 static void
4250 frame_highlight (f)
4251 struct frame *f;
4253 OSErr err;
4254 ControlRef root_control;
4256 BLOCK_INPUT;
4257 err = GetRootControl (FRAME_MAC_WINDOW (f), &root_control);
4258 if (err == noErr)
4259 ActivateControl (root_control);
4260 UNBLOCK_INPUT;
4261 x_update_cursor (f, 1);
4264 static void
4265 frame_unhighlight (f)
4266 struct frame *f;
4268 OSErr err;
4269 ControlRef root_control;
4271 BLOCK_INPUT;
4272 err = GetRootControl (FRAME_MAC_WINDOW (f), &root_control);
4273 if (err == noErr)
4274 DeactivateControl (root_control);
4275 UNBLOCK_INPUT;
4276 x_update_cursor (f, 1);
4279 /* The focus has changed. Update the frames as necessary to reflect
4280 the new situation. Note that we can't change the selected frame
4281 here, because the Lisp code we are interrupting might become confused.
4282 Each event gets marked with the frame in which it occurred, so the
4283 Lisp code can tell when the switch took place by examining the events. */
4285 static void
4286 x_new_focus_frame (dpyinfo, frame)
4287 struct x_display_info *dpyinfo;
4288 struct frame *frame;
4290 struct frame *old_focus = dpyinfo->x_focus_frame;
4292 if (frame != dpyinfo->x_focus_frame)
4294 /* Set this before calling other routines, so that they see
4295 the correct value of x_focus_frame. */
4296 dpyinfo->x_focus_frame = frame;
4298 if (old_focus && old_focus->auto_lower)
4299 x_lower_frame (old_focus);
4301 #if 0
4302 selected_frame = frame;
4303 XSETFRAME (XWINDOW (selected_frame->selected_window)->frame,
4304 selected_frame);
4305 Fselect_window (selected_frame->selected_window, Qnil);
4306 choose_minibuf_frame ();
4307 #endif /* ! 0 */
4309 if (dpyinfo->x_focus_frame && dpyinfo->x_focus_frame->auto_raise)
4310 pending_autoraise_frame = dpyinfo->x_focus_frame;
4311 else
4312 pending_autoraise_frame = 0;
4314 #if USE_MAC_FONT_PANEL
4315 if (frame)
4316 mac_set_font_info_for_selection (frame, DEFAULT_FACE_ID, 0);
4317 #endif
4320 x_frame_rehighlight (dpyinfo);
4323 /* Handle FocusIn and FocusOut state changes for FRAME.
4324 If FRAME has focus and there exists more than one frame, puts
4325 a FOCUS_IN_EVENT into *BUFP. */
4327 static void
4328 mac_focus_changed (type, dpyinfo, frame, bufp)
4329 int type;
4330 struct mac_display_info *dpyinfo;
4331 struct frame *frame;
4332 struct input_event *bufp;
4334 if (type == activeFlag)
4336 if (dpyinfo->x_focus_event_frame != frame)
4338 x_new_focus_frame (dpyinfo, frame);
4339 dpyinfo->x_focus_event_frame = frame;
4341 /* Don't stop displaying the initial startup message
4342 for a switch-frame event we don't need. */
4343 if (GC_NILP (Vterminal_frame)
4344 && GC_CONSP (Vframe_list)
4345 && !GC_NILP (XCDR (Vframe_list)))
4347 bufp->kind = FOCUS_IN_EVENT;
4348 XSETFRAME (bufp->frame_or_window, frame);
4352 else
4354 if (dpyinfo->x_focus_event_frame == frame)
4356 dpyinfo->x_focus_event_frame = 0;
4357 x_new_focus_frame (dpyinfo, 0);
4362 /* The focus may have changed. Figure out if it is a real focus change,
4363 by checking both FocusIn/Out and Enter/LeaveNotify events.
4365 Returns FOCUS_IN_EVENT event in *BUFP. */
4367 static void
4368 x_detect_focus_change (dpyinfo, event, bufp)
4369 struct mac_display_info *dpyinfo;
4370 const EventRecord *event;
4371 struct input_event *bufp;
4373 struct frame *frame;
4375 frame = mac_window_to_frame ((WindowPtr) event->message);
4376 if (! frame)
4377 return;
4379 /* On Mac, this is only called from focus events, so no switch needed. */
4380 mac_focus_changed ((event->modifiers & activeFlag),
4381 dpyinfo, frame, bufp);
4385 /* Handle an event saying the mouse has moved out of an Emacs frame. */
4387 void
4388 x_mouse_leave (dpyinfo)
4389 struct x_display_info *dpyinfo;
4391 x_new_focus_frame (dpyinfo, dpyinfo->x_focus_event_frame);
4394 /* The focus has changed, or we have redirected a frame's focus to
4395 another frame (this happens when a frame uses a surrogate
4396 mini-buffer frame). Shift the highlight as appropriate.
4398 The FRAME argument doesn't necessarily have anything to do with which
4399 frame is being highlighted or un-highlighted; we only use it to find
4400 the appropriate X display info. */
4402 static void
4403 XTframe_rehighlight (frame)
4404 struct frame *frame;
4406 x_frame_rehighlight (FRAME_X_DISPLAY_INFO (frame));
4409 static void
4410 x_frame_rehighlight (dpyinfo)
4411 struct x_display_info *dpyinfo;
4413 struct frame *old_highlight = dpyinfo->x_highlight_frame;
4415 if (dpyinfo->x_focus_frame)
4417 dpyinfo->x_highlight_frame
4418 = ((GC_FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame)))
4419 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
4420 : dpyinfo->x_focus_frame);
4421 if (! FRAME_LIVE_P (dpyinfo->x_highlight_frame))
4423 FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
4424 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
4427 else
4428 dpyinfo->x_highlight_frame = 0;
4430 if (dpyinfo->x_highlight_frame != old_highlight)
4432 if (old_highlight)
4433 frame_unhighlight (old_highlight);
4434 if (dpyinfo->x_highlight_frame)
4435 frame_highlight (dpyinfo->x_highlight_frame);
4441 /* Convert a keysym to its name. */
4443 char *
4444 x_get_keysym_name (keysym)
4445 int keysym;
4447 char *value;
4449 BLOCK_INPUT;
4450 #if 0
4451 value = XKeysymToString (keysym);
4452 #else
4453 value = 0;
4454 #endif
4455 UNBLOCK_INPUT;
4457 return value;
4462 /* Function to report a mouse movement to the mainstream Emacs code.
4463 The input handler calls this.
4465 We have received a mouse movement event, which is given in *event.
4466 If the mouse is over a different glyph than it was last time, tell
4467 the mainstream emacs code by setting mouse_moved. If not, ask for
4468 another motion event, so we can check again the next time it moves. */
4470 static Point last_mouse_motion_position;
4471 static Lisp_Object last_mouse_motion_frame;
4473 static int
4474 note_mouse_movement (frame, pos)
4475 FRAME_PTR frame;
4476 Point *pos;
4478 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (frame);
4479 #if TARGET_API_MAC_CARBON
4480 Rect r;
4481 #endif
4483 last_mouse_movement_time = TickCount () * (1000 / 60); /* to milliseconds */
4484 last_mouse_motion_position = *pos;
4485 XSETFRAME (last_mouse_motion_frame, frame);
4487 if (frame == dpyinfo->mouse_face_mouse_frame
4488 #if TARGET_API_MAC_CARBON
4489 && !PtInRect (*pos, GetWindowPortBounds (FRAME_MAC_WINDOW (frame), &r))
4490 #else
4491 && !PtInRect (*pos, &FRAME_MAC_WINDOW (frame)->portRect)
4492 #endif
4495 /* This case corresponds to LeaveNotify in X11. If we move
4496 outside the frame, then we're certainly no longer on any text
4497 in the frame. */
4498 clear_mouse_face (dpyinfo);
4499 dpyinfo->mouse_face_mouse_frame = 0;
4500 if (!dpyinfo->grabbed)
4501 rif->define_frame_cursor (frame,
4502 frame->output_data.mac->nontext_cursor);
4505 /* Has the mouse moved off the glyph it was on at the last sighting? */
4506 if (frame != last_mouse_glyph_frame
4507 || !PtInRect (*pos, &last_mouse_glyph))
4509 frame->mouse_moved = 1;
4510 last_mouse_scroll_bar = Qnil;
4511 note_mouse_highlight (frame, pos->h, pos->v);
4512 /* Remember which glyph we're now on. */
4513 remember_mouse_glyph (frame, pos->h, pos->v, &last_mouse_glyph);
4514 last_mouse_glyph_frame = frame;
4515 return 1;
4518 return 0;
4522 /************************************************************************
4523 Mouse Face
4524 ************************************************************************/
4526 /* MAC TODO: This should be called from somewhere (or removed) ++KFS */
4528 static void
4529 redo_mouse_highlight ()
4531 if (!NILP (last_mouse_motion_frame)
4532 && FRAME_LIVE_P (XFRAME (last_mouse_motion_frame)))
4533 note_mouse_highlight (XFRAME (last_mouse_motion_frame),
4534 last_mouse_motion_position.h,
4535 last_mouse_motion_position.v);
4539 static struct frame *
4540 mac_focus_frame (dpyinfo)
4541 struct mac_display_info *dpyinfo;
4543 if (dpyinfo->x_focus_frame)
4544 return dpyinfo->x_focus_frame;
4545 else
4546 /* Mac version may get events, such as a menu bar click, even when
4547 all the frames are invisible. In this case, we regard the
4548 event came to the selected frame. */
4549 return SELECTED_FRAME ();
4553 /* Return the current position of the mouse.
4554 *FP should be a frame which indicates which display to ask about.
4556 If the mouse movement started in a scroll bar, set *FP, *BAR_WINDOW,
4557 and *PART to the frame, window, and scroll bar part that the mouse
4558 is over. Set *X and *Y to the portion and whole of the mouse's
4559 position on the scroll bar.
4561 If the mouse movement started elsewhere, set *FP to the frame the
4562 mouse is on, *BAR_WINDOW to nil, and *X and *Y to the character cell
4563 the mouse is over.
4565 Set *TIME to the server time-stamp for the time at which the mouse
4566 was at this position.
4568 Don't store anything if we don't have a valid set of values to report.
4570 This clears the mouse_moved flag, so we can wait for the next mouse
4571 movement. */
4573 static void
4574 XTmouse_position (fp, insist, bar_window, part, x, y, time)
4575 FRAME_PTR *fp;
4576 int insist;
4577 Lisp_Object *bar_window;
4578 enum scroll_bar_part *part;
4579 Lisp_Object *x, *y;
4580 unsigned long *time;
4582 FRAME_PTR f1;
4584 BLOCK_INPUT;
4586 if (! NILP (last_mouse_scroll_bar) && insist == 0)
4587 x_scroll_bar_report_motion (fp, bar_window, part, x, y, time);
4588 else
4590 Lisp_Object frame, tail;
4592 /* Clear the mouse-moved flag for every frame on this display. */
4593 FOR_EACH_FRAME (tail, frame)
4594 XFRAME (frame)->mouse_moved = 0;
4596 last_mouse_scroll_bar = Qnil;
4598 if (FRAME_MAC_DISPLAY_INFO (*fp)->grabbed && last_mouse_frame
4599 && FRAME_LIVE_P (last_mouse_frame))
4600 f1 = last_mouse_frame;
4601 else
4602 f1 = mac_focus_frame (FRAME_MAC_DISPLAY_INFO (*fp));
4604 if (f1)
4606 /* Ok, we found a frame. Store all the values.
4607 last_mouse_glyph is a rectangle used to reduce the
4608 generation of mouse events. To not miss any motion
4609 events, we must divide the frame into rectangles of the
4610 size of the smallest character that could be displayed
4611 on it, i.e. into the same rectangles that matrices on
4612 the frame are divided into. */
4613 Point mouse_pos;
4615 SetPortWindowPort (FRAME_MAC_WINDOW (f1));
4616 GetMouse (&mouse_pos);
4617 remember_mouse_glyph (f1, mouse_pos.h, mouse_pos.v,
4618 &last_mouse_glyph);
4619 last_mouse_glyph_frame = f1;
4621 *bar_window = Qnil;
4622 *part = 0;
4623 *fp = f1;
4624 XSETINT (*x, mouse_pos.h);
4625 XSETINT (*y, mouse_pos.v);
4626 *time = last_mouse_movement_time;
4630 UNBLOCK_INPUT;
4634 /************************************************************************
4635 Toolkit scroll bars
4636 ************************************************************************/
4638 #ifdef USE_TOOLKIT_SCROLL_BARS
4640 static pascal void scroll_bar_timer_callback P_ ((EventLoopTimerRef, void *));
4641 static OSStatus install_scroll_bar_timer P_ ((void));
4642 static OSStatus set_scroll_bar_timer P_ ((EventTimerInterval));
4643 static int control_part_code_to_scroll_bar_part P_ ((ControlPartCode));
4644 static void construct_scroll_bar_click P_ ((struct scroll_bar *, int,
4645 struct input_event *));
4646 static OSStatus get_control_part_bounds P_ ((ControlHandle, ControlPartCode,
4647 Rect *));
4648 static void x_scroll_bar_handle_press P_ ((struct scroll_bar *,
4649 ControlPartCode, Point,
4650 struct input_event *));
4651 static void x_scroll_bar_handle_release P_ ((struct scroll_bar *,
4652 struct input_event *));
4653 static void x_scroll_bar_handle_drag P_ ((WindowPtr, struct scroll_bar *,
4654 Point, struct input_event *));
4655 static void x_set_toolkit_scroll_bar_thumb P_ ((struct scroll_bar *,
4656 int, int, int));
4658 /* Last scroll bar part sent in x_scroll_bar_handle_*. */
4660 static int last_scroll_bar_part;
4662 static EventLoopTimerRef scroll_bar_timer;
4664 static int scroll_bar_timer_event_posted_p;
4666 #define SCROLL_BAR_FIRST_DELAY 0.5
4667 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
4669 static pascal void
4670 scroll_bar_timer_callback (timer, data)
4671 EventLoopTimerRef timer;
4672 void *data;
4674 OSStatus err;
4676 err = mac_post_mouse_moved_event ();
4677 if (err == noErr)
4678 scroll_bar_timer_event_posted_p = 1;
4681 static OSStatus
4682 install_scroll_bar_timer ()
4684 static EventLoopTimerUPP scroll_bar_timer_callbackUPP = NULL;
4686 if (scroll_bar_timer_callbackUPP == NULL)
4687 scroll_bar_timer_callbackUPP =
4688 NewEventLoopTimerUPP (scroll_bar_timer_callback);
4690 if (scroll_bar_timer == NULL)
4691 /* Mac OS X and CarbonLib 1.5 and later allow us to specify
4692 kEventDurationForever as delays. */
4693 return
4694 InstallEventLoopTimer (GetCurrentEventLoop (),
4695 kEventDurationForever, kEventDurationForever,
4696 scroll_bar_timer_callbackUPP, NULL,
4697 &scroll_bar_timer);
4700 static OSStatus
4701 set_scroll_bar_timer (delay)
4702 EventTimerInterval delay;
4704 if (scroll_bar_timer == NULL)
4705 install_scroll_bar_timer ();
4707 scroll_bar_timer_event_posted_p = 0;
4709 return SetEventLoopTimerNextFireTime (scroll_bar_timer, delay);
4712 static int
4713 control_part_code_to_scroll_bar_part (part_code)
4714 ControlPartCode part_code;
4716 switch (part_code)
4718 case kControlUpButtonPart: return scroll_bar_up_arrow;
4719 case kControlDownButtonPart: return scroll_bar_down_arrow;
4720 case kControlPageUpPart: return scroll_bar_above_handle;
4721 case kControlPageDownPart: return scroll_bar_below_handle;
4722 case kControlIndicatorPart: return scroll_bar_handle;
4725 return -1;
4728 static void
4729 construct_scroll_bar_click (bar, part, bufp)
4730 struct scroll_bar *bar;
4731 int part;
4732 struct input_event *bufp;
4734 bufp->kind = SCROLL_BAR_CLICK_EVENT;
4735 bufp->frame_or_window = bar->window;
4736 bufp->arg = Qnil;
4737 bufp->part = part;
4738 bufp->code = 0;
4739 XSETINT (bufp->x, 0);
4740 XSETINT (bufp->y, 0);
4741 bufp->modifiers = 0;
4744 static OSStatus
4745 get_control_part_bounds (ch, part_code, rect)
4746 ControlHandle ch;
4747 ControlPartCode part_code;
4748 Rect *rect;
4750 RgnHandle region = NewRgn ();
4751 OSStatus err;
4753 err = GetControlRegion (ch, part_code, region);
4754 if (err == noErr)
4755 GetRegionBounds (region, rect);
4756 DisposeRgn (region);
4758 return err;
4761 static void
4762 x_scroll_bar_handle_press (bar, part_code, mouse_pos, bufp)
4763 struct scroll_bar *bar;
4764 ControlPartCode part_code;
4765 Point mouse_pos;
4766 struct input_event *bufp;
4768 int part = control_part_code_to_scroll_bar_part (part_code);
4770 if (part < 0)
4771 return;
4773 if (part != scroll_bar_handle)
4775 construct_scroll_bar_click (bar, part, bufp);
4776 HiliteControl (SCROLL_BAR_CONTROL_HANDLE (bar), part_code);
4777 set_scroll_bar_timer (SCROLL_BAR_FIRST_DELAY);
4778 bar->dragging = Qnil;
4780 else
4782 Rect r;
4784 get_control_part_bounds (SCROLL_BAR_CONTROL_HANDLE (bar),
4785 kControlIndicatorPart, &r);
4786 XSETINT (bar->dragging, - (mouse_pos.v - r.top) - 1);
4789 last_scroll_bar_part = part;
4790 tracked_scroll_bar = bar;
4793 static void
4794 x_scroll_bar_handle_release (bar, bufp)
4795 struct scroll_bar *bar;
4796 struct input_event *bufp;
4798 if (last_scroll_bar_part != scroll_bar_handle
4799 || (INTEGERP (bar->dragging) && XINT (bar->dragging) >= 0))
4800 construct_scroll_bar_click (bar, scroll_bar_end_scroll, bufp);
4802 HiliteControl (SCROLL_BAR_CONTROL_HANDLE (bar), 0);
4803 set_scroll_bar_timer (kEventDurationForever);
4805 last_scroll_bar_part = -1;
4806 bar->dragging = Qnil;
4807 tracked_scroll_bar = NULL;
4810 static void
4811 x_scroll_bar_handle_drag (win, bar, mouse_pos, bufp)
4812 WindowPtr win;
4813 struct scroll_bar *bar;
4814 Point mouse_pos;
4815 struct input_event *bufp;
4817 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4819 if (last_scroll_bar_part == scroll_bar_handle)
4821 int top, top_range;
4822 Rect r;
4824 get_control_part_bounds (SCROLL_BAR_CONTROL_HANDLE (bar),
4825 kControlIndicatorPart, &r);
4827 if (INTEGERP (bar->dragging) && XINT (bar->dragging) < 0)
4828 XSETINT (bar->dragging, - (XINT (bar->dragging) + 1));
4830 top = mouse_pos.v - XINT (bar->dragging) - XINT (bar->track_top);
4831 top_range = XINT (bar->track_height) - XINT (bar->min_handle);
4833 if (top < 0)
4834 top = 0;
4835 if (top > top_range)
4836 top = top_range;
4838 construct_scroll_bar_click (bar, scroll_bar_handle, bufp);
4839 XSETINT (bufp->x, top);
4840 XSETINT (bufp->y, top_range);
4842 else
4844 ControlPartCode part_code;
4845 int unhilite_p = 0, part;
4847 if (ch != FindControlUnderMouse (mouse_pos, win, &part_code))
4848 unhilite_p = 1;
4849 else
4851 part = control_part_code_to_scroll_bar_part (part_code);
4853 switch (last_scroll_bar_part)
4855 case scroll_bar_above_handle:
4856 case scroll_bar_below_handle:
4857 if (part != scroll_bar_above_handle
4858 && part != scroll_bar_below_handle)
4859 unhilite_p = 1;
4860 break;
4862 case scroll_bar_up_arrow:
4863 case scroll_bar_down_arrow:
4864 if (part != scroll_bar_up_arrow
4865 && part != scroll_bar_down_arrow)
4866 unhilite_p = 1;
4867 break;
4871 if (unhilite_p)
4872 HiliteControl (SCROLL_BAR_CONTROL_HANDLE (bar), 0);
4873 else if (part != last_scroll_bar_part
4874 || scroll_bar_timer_event_posted_p)
4876 construct_scroll_bar_click (bar, part, bufp);
4877 last_scroll_bar_part = part;
4878 HiliteControl (SCROLL_BAR_CONTROL_HANDLE (bar), part_code);
4879 set_scroll_bar_timer (SCROLL_BAR_CONTINUOUS_DELAY);
4884 /* Set the thumb size and position of scroll bar BAR. We are currently
4885 displaying PORTION out of a whole WHOLE, and our position POSITION. */
4887 static void
4888 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole)
4889 struct scroll_bar *bar;
4890 int portion, position, whole;
4892 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4893 int value, viewsize, maximum;
4895 if (XINT (bar->track_height) == 0)
4896 return;
4898 if (whole <= portion)
4899 value = 0, viewsize = 1, maximum = 0;
4900 else
4902 float scale;
4904 maximum = XINT (bar->track_height) - XINT (bar->min_handle);
4905 scale = (float) maximum / (whole - portion);
4906 value = position * scale + 0.5f;
4907 viewsize = (int) (portion * scale + 0.5f) + XINT (bar->min_handle);
4910 BLOCK_INPUT;
4912 if (GetControlViewSize (ch) != viewsize
4913 || GetControl32BitValue (ch) != value
4914 || GetControl32BitMaximum (ch) != maximum)
4916 /* Temporarily hide the scroll bar to avoid multiple redraws. */
4917 SetControlVisibility (ch, false, false);
4919 SetControl32BitMaximum (ch, maximum);
4920 SetControl32BitValue (ch, value);
4921 SetControlViewSize (ch, viewsize);
4923 SetControlVisibility (ch, true, true);
4926 UNBLOCK_INPUT;
4929 #endif /* USE_TOOLKIT_SCROLL_BARS */
4933 /************************************************************************
4934 Scroll bars, general
4935 ************************************************************************/
4937 /* Create a scroll bar and return the scroll bar vector for it. W is
4938 the Emacs window on which to create the scroll bar. TOP, LEFT,
4939 WIDTH and HEIGHT are the pixel coordinates and dimensions of the
4940 scroll bar. */
4942 static struct scroll_bar *
4943 x_scroll_bar_create (w, top, left, width, height, disp_top, disp_height)
4944 struct window *w;
4945 int top, left, width, height, disp_top, disp_height;
4947 struct frame *f = XFRAME (w->frame);
4948 struct scroll_bar *bar
4949 = XSCROLL_BAR (Fmake_vector (make_number (SCROLL_BAR_VEC_SIZE), Qnil));
4950 Rect r;
4951 ControlHandle ch;
4953 BLOCK_INPUT;
4955 r.left = left;
4956 r.top = disp_top;
4957 r.right = left + width;
4958 r.bottom = disp_top + disp_height;
4960 #if USE_CG_DRAWING
4961 mac_prepare_for_quickdraw (f);
4962 #endif
4963 #if TARGET_API_MAC_CARBON
4964 ch = NewControl (FRAME_MAC_WINDOW (f), &r, "\p",
4965 #ifdef USE_TOOLKIT_SCROLL_BARS
4966 false,
4967 #else
4968 width < disp_height,
4969 #endif
4970 0, 0, 0, kControlScrollBarProc, (long) bar);
4971 #else
4972 ch = NewControl (FRAME_MAC_WINDOW (f), &r, "\p", width < disp_height,
4973 0, 0, 0, scrollBarProc, (long) bar);
4974 #endif
4975 SET_SCROLL_BAR_CONTROL_HANDLE (bar, ch);
4977 XSETWINDOW (bar->window, w);
4978 XSETINT (bar->top, top);
4979 XSETINT (bar->left, left);
4980 XSETINT (bar->width, width);
4981 XSETINT (bar->height, height);
4982 XSETINT (bar->start, 0);
4983 XSETINT (bar->end, 0);
4984 bar->dragging = Qnil;
4985 #ifdef USE_TOOLKIT_SCROLL_BARS
4986 bar->track_top = Qnil;
4987 bar->track_height = Qnil;
4988 bar->min_handle = Qnil;
4989 #endif
4991 /* Add bar to its frame's list of scroll bars. */
4992 bar->next = FRAME_SCROLL_BARS (f);
4993 bar->prev = Qnil;
4994 XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
4995 if (!NILP (bar->next))
4996 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
4998 UNBLOCK_INPUT;
4999 return bar;
5003 /* Draw BAR's handle in the proper position.
5005 If the handle is already drawn from START to END, don't bother
5006 redrawing it, unless REBUILD is non-zero; in that case, always
5007 redraw it. (REBUILD is handy for drawing the handle after expose
5008 events.)
5010 Normally, we want to constrain the start and end of the handle to
5011 fit inside its rectangle, but if the user is dragging the scroll
5012 bar handle, we want to let them drag it down all the way, so that
5013 the bar's top is as far down as it goes; otherwise, there's no way
5014 to move to the very end of the buffer. */
5016 #ifndef USE_TOOLKIT_SCROLL_BARS
5018 static void
5019 x_scroll_bar_set_handle (bar, start, end, rebuild)
5020 struct scroll_bar *bar;
5021 int start, end;
5022 int rebuild;
5024 int dragging = ! NILP (bar->dragging);
5025 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
5026 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5027 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, XINT (bar->height));
5028 int length = end - start;
5030 /* If the display is already accurate, do nothing. */
5031 if (! rebuild
5032 && start == XINT (bar->start)
5033 && end == XINT (bar->end))
5034 return;
5036 BLOCK_INPUT;
5038 /* Make sure the values are reasonable, and try to preserve the
5039 distance between start and end. */
5040 if (start < 0)
5041 start = 0;
5042 else if (start > top_range)
5043 start = top_range;
5044 end = start + length;
5046 if (end < start)
5047 end = start;
5048 else if (end > top_range && ! dragging)
5049 end = top_range;
5051 /* Store the adjusted setting in the scroll bar. */
5052 XSETINT (bar->start, start);
5053 XSETINT (bar->end, end);
5055 /* Clip the end position, just for display. */
5056 if (end > top_range)
5057 end = top_range;
5059 /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels below
5060 top positions, to make sure the handle is always at least that
5061 many pixels tall. */
5062 end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
5064 SetControlMinimum (ch, 0);
5065 /* Don't inadvertently activate deactivated scroll bars */
5066 if (GetControlMaximum (ch) != -1)
5067 SetControlMaximum (ch, top_range + VERTICAL_SCROLL_BAR_MIN_HANDLE
5068 - (end - start));
5069 SetControlValue (ch, start);
5070 #if TARGET_API_MAC_CARBON
5071 SetControlViewSize (ch, end - start);
5072 #endif
5074 UNBLOCK_INPUT;
5077 #endif /* !USE_TOOLKIT_SCROLL_BARS */
5079 /* Destroy scroll bar BAR, and set its Emacs window's scroll bar to
5080 nil. */
5082 static void
5083 x_scroll_bar_remove (bar)
5084 struct scroll_bar *bar;
5086 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5088 BLOCK_INPUT;
5090 #if USE_CG_DRAWING
5091 mac_prepare_for_quickdraw (f);
5092 #endif
5093 /* Destroy the Mac scroll bar control */
5094 DisposeControl (SCROLL_BAR_CONTROL_HANDLE (bar));
5096 /* Disassociate this scroll bar from its window. */
5097 XWINDOW (bar->window)->vertical_scroll_bar = Qnil;
5099 UNBLOCK_INPUT;
5103 /* Set the handle of the vertical scroll bar for WINDOW to indicate
5104 that we are displaying PORTION characters out of a total of WHOLE
5105 characters, starting at POSITION. If WINDOW has no scroll bar,
5106 create one. */
5108 static void
5109 XTset_vertical_scroll_bar (w, portion, whole, position)
5110 struct window *w;
5111 int portion, whole, position;
5113 struct frame *f = XFRAME (w->frame);
5114 struct scroll_bar *bar;
5115 int top, height, left, sb_left, width, sb_width, disp_top, disp_height;
5116 int window_y, window_height;
5118 /* Get window dimensions. */
5119 window_box (w, -1, 0, &window_y, 0, &window_height);
5120 top = window_y;
5121 width = WINDOW_CONFIG_SCROLL_BAR_COLS (w) * FRAME_COLUMN_WIDTH (f);
5122 height = window_height;
5124 /* Compute the left edge of the scroll bar area. */
5125 left = WINDOW_SCROLL_BAR_AREA_X (w);
5127 /* Compute the width of the scroll bar which might be less than
5128 the width of the area reserved for the scroll bar. */
5129 if (WINDOW_CONFIG_SCROLL_BAR_WIDTH (w) > 0)
5130 sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
5131 else
5132 sb_width = width;
5134 /* Compute the left edge of the scroll bar. */
5135 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
5136 sb_left = left;
5137 else
5138 sb_left = left + width - sb_width;
5140 /* Adjustments according to Inside Macintosh to make it look nice */
5141 disp_top = top;
5142 disp_height = height;
5143 #ifdef MAC_OS8
5144 if (disp_top == 0)
5146 disp_top = -1;
5147 disp_height++;
5149 else if (disp_top == FRAME_PIXEL_HEIGHT (f) - 16)
5151 disp_top++;
5152 disp_height--;
5155 if (sb_left + sb_width == FRAME_PIXEL_WIDTH (f))
5156 sb_left++;
5157 #endif
5159 /* Does the scroll bar exist yet? */
5160 if (NILP (w->vertical_scroll_bar))
5162 BLOCK_INPUT;
5163 mac_clear_area (f, left, top, width, height);
5164 UNBLOCK_INPUT;
5165 bar = x_scroll_bar_create (w, top, sb_left, sb_width, height, disp_top,
5166 disp_height);
5167 XSETVECTOR (w->vertical_scroll_bar, bar);
5169 else
5171 /* It may just need to be moved and resized. */
5172 ControlHandle ch;
5174 bar = XSCROLL_BAR (w->vertical_scroll_bar);
5175 ch = SCROLL_BAR_CONTROL_HANDLE (bar);
5177 BLOCK_INPUT;
5179 /* If already correctly positioned, do nothing. */
5180 if (!(XINT (bar->left) == sb_left
5181 && XINT (bar->top) == top
5182 && XINT (bar->width) == sb_width
5183 && XINT (bar->height) == height))
5185 /* Since toolkit scroll bars are smaller than the space reserved
5186 for them on the frame, we have to clear "under" them. */
5187 mac_clear_area (f, left, top, width, height);
5189 #if USE_CG_DRAWING
5190 mac_prepare_for_quickdraw (f);
5191 #endif
5192 HideControl (ch);
5193 MoveControl (ch, sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM, disp_top);
5194 SizeControl (ch, sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
5195 disp_height);
5196 #ifndef USE_TOOLKIT_SCROLL_BARS
5197 if (sb_width < disp_height)
5198 ShowControl (ch);
5199 #endif
5201 /* Remember new settings. */
5202 XSETINT (bar->left, sb_left);
5203 XSETINT (bar->top, top);
5204 XSETINT (bar->width, sb_width);
5205 XSETINT (bar->height, height);
5206 #ifdef USE_TOOLKIT_SCROLL_BARS
5207 bar->track_top = Qnil;
5208 bar->track_height = Qnil;
5209 bar->min_handle = Qnil;
5210 #endif
5213 UNBLOCK_INPUT;
5216 #ifdef USE_TOOLKIT_SCROLL_BARS
5217 if (NILP (bar->track_top))
5219 if (sb_width >= disp_height
5220 #ifdef MAC_OSX
5221 || sb_width < MAC_AQUA_SMALL_VERTICAL_SCROLL_BAR_WIDTH
5222 #endif
5225 XSETINT (bar->track_top, 0);
5226 XSETINT (bar->track_height, 0);
5227 XSETINT (bar->min_handle, 0);
5229 else
5231 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
5232 Rect r0, r1;
5234 BLOCK_INPUT;
5236 SetControl32BitMinimum (ch, 0);
5237 SetControl32BitMaximum (ch, 1 << 30);
5238 SetControlViewSize (ch, 1);
5240 /* Move the scroll bar thumb to the top. */
5241 SetControl32BitValue (ch, 0);
5242 get_control_part_bounds (ch, kControlIndicatorPart, &r0);
5244 /* Move the scroll bar thumb to the bottom. */
5245 SetControl32BitValue (ch, 1 << 30);
5246 get_control_part_bounds (ch, kControlIndicatorPart, &r1);
5248 UnionRect (&r0, &r1, &r0);
5249 XSETINT (bar->track_top, r0.top);
5250 XSETINT (bar->track_height, r0.bottom - r0.top);
5251 XSETINT (bar->min_handle, r1.bottom - r1.top);
5253 /* Don't show the scroll bar if its height is not enough to
5254 display the scroll bar thumb. */
5255 if (r0.bottom - r0.top > 0)
5256 ShowControl (ch);
5258 UNBLOCK_INPUT;
5262 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
5263 #else /* not USE_TOOLKIT_SCROLL_BARS */
5264 /* Set the scroll bar's current state, unless we're currently being
5265 dragged. */
5266 if (NILP (bar->dragging))
5268 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, height);
5270 if (whole == 0)
5271 x_scroll_bar_set_handle (bar, 0, top_range, 0);
5272 else
5274 int start = ((double) position * top_range) / whole;
5275 int end = ((double) (position + portion) * top_range) / whole;
5276 x_scroll_bar_set_handle (bar, start, end, 0);
5279 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5283 /* The following three hooks are used when we're doing a thorough
5284 redisplay of the frame. We don't explicitly know which scroll bars
5285 are going to be deleted, because keeping track of when windows go
5286 away is a real pain - "Can you say set-window-configuration, boys
5287 and girls?" Instead, we just assert at the beginning of redisplay
5288 that *all* scroll bars are to be removed, and then save a scroll bar
5289 from the fiery pit when we actually redisplay its window. */
5291 /* Arrange for all scroll bars on FRAME to be removed at the next call
5292 to `*judge_scroll_bars_hook'. A scroll bar may be spared if
5293 `*redeem_scroll_bar_hook' is applied to its window before the judgment. */
5295 static void
5296 XTcondemn_scroll_bars (frame)
5297 FRAME_PTR frame;
5299 /* Transfer all the scroll bars to FRAME_CONDEMNED_SCROLL_BARS. */
5300 while (! NILP (FRAME_SCROLL_BARS (frame)))
5302 Lisp_Object bar;
5303 bar = FRAME_SCROLL_BARS (frame);
5304 FRAME_SCROLL_BARS (frame) = XSCROLL_BAR (bar)->next;
5305 XSCROLL_BAR (bar)->next = FRAME_CONDEMNED_SCROLL_BARS (frame);
5306 XSCROLL_BAR (bar)->prev = Qnil;
5307 if (! NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
5308 XSCROLL_BAR (FRAME_CONDEMNED_SCROLL_BARS (frame))->prev = bar;
5309 FRAME_CONDEMNED_SCROLL_BARS (frame) = bar;
5314 /* Un-mark WINDOW's scroll bar for deletion in this judgment cycle.
5315 Note that WINDOW isn't necessarily condemned at all. */
5317 static void
5318 XTredeem_scroll_bar (window)
5319 struct window *window;
5321 struct scroll_bar *bar;
5322 struct frame *f;
5324 /* We can't redeem this window's scroll bar if it doesn't have one. */
5325 if (NILP (window->vertical_scroll_bar))
5326 abort ();
5328 bar = XSCROLL_BAR (window->vertical_scroll_bar);
5330 /* Unlink it from the condemned list. */
5331 f = XFRAME (WINDOW_FRAME (window));
5332 if (NILP (bar->prev))
5334 /* If the prev pointer is nil, it must be the first in one of
5335 the lists. */
5336 if (EQ (FRAME_SCROLL_BARS (f), window->vertical_scroll_bar))
5337 /* It's not condemned. Everything's fine. */
5338 return;
5339 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
5340 window->vertical_scroll_bar))
5341 FRAME_CONDEMNED_SCROLL_BARS (f) = bar->next;
5342 else
5343 /* If its prev pointer is nil, it must be at the front of
5344 one or the other! */
5345 abort ();
5347 else
5348 XSCROLL_BAR (bar->prev)->next = bar->next;
5350 if (! NILP (bar->next))
5351 XSCROLL_BAR (bar->next)->prev = bar->prev;
5353 bar->next = FRAME_SCROLL_BARS (f);
5354 bar->prev = Qnil;
5355 XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
5356 if (! NILP (bar->next))
5357 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
5360 /* Remove all scroll bars on FRAME that haven't been saved since the
5361 last call to `*condemn_scroll_bars_hook'. */
5363 static void
5364 XTjudge_scroll_bars (f)
5365 FRAME_PTR f;
5367 Lisp_Object bar, next;
5369 bar = FRAME_CONDEMNED_SCROLL_BARS (f);
5371 /* Clear out the condemned list now so we won't try to process any
5372 more events on the hapless scroll bars. */
5373 FRAME_CONDEMNED_SCROLL_BARS (f) = Qnil;
5375 for (; ! NILP (bar); bar = next)
5377 struct scroll_bar *b = XSCROLL_BAR (bar);
5379 x_scroll_bar_remove (b);
5381 next = b->next;
5382 b->next = b->prev = Qnil;
5385 /* Now there should be no references to the condemned scroll bars,
5386 and they should get garbage-collected. */
5390 /* Handle a mouse click on the scroll bar BAR. If *EMACS_EVENT's kind
5391 is set to something other than NO_EVENT, it is enqueued.
5393 This may be called from a signal handler, so we have to ignore GC
5394 mark bits. */
5396 static void
5397 x_scroll_bar_handle_click (bar, part_code, er, bufp)
5398 struct scroll_bar *bar;
5399 ControlPartCode part_code;
5400 const EventRecord *er;
5401 struct input_event *bufp;
5403 int win_y, top_range;
5405 if (! GC_WINDOWP (bar->window))
5406 abort ();
5408 bufp->kind = SCROLL_BAR_CLICK_EVENT;
5409 bufp->frame_or_window = bar->window;
5410 bufp->arg = Qnil;
5412 bar->dragging = Qnil;
5414 switch (part_code)
5416 case kControlUpButtonPart:
5417 bufp->part = scroll_bar_up_arrow;
5418 break;
5419 case kControlDownButtonPart:
5420 bufp->part = scroll_bar_down_arrow;
5421 break;
5422 case kControlPageUpPart:
5423 bufp->part = scroll_bar_above_handle;
5424 break;
5425 case kControlPageDownPart:
5426 bufp->part = scroll_bar_below_handle;
5427 break;
5428 #if TARGET_API_MAC_CARBON
5429 default:
5430 #else
5431 case kControlIndicatorPart:
5432 #endif
5433 if (er->what == mouseDown)
5434 bar->dragging = make_number (0);
5435 XSETVECTOR (last_mouse_scroll_bar, bar);
5436 bufp->part = scroll_bar_handle;
5437 break;
5440 win_y = XINT (bufp->y) - XINT (bar->top);
5441 top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (0/*dummy*/, XINT (bar->height));
5443 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
5445 win_y -= 24;
5447 if (! NILP (bar->dragging))
5448 win_y -= XINT (bar->dragging);
5450 if (win_y < 0)
5451 win_y = 0;
5452 if (win_y > top_range)
5453 win_y = top_range;
5455 XSETINT (bufp->x, win_y);
5456 XSETINT (bufp->y, top_range);
5459 #ifndef USE_TOOLKIT_SCROLL_BARS
5461 /* Handle some mouse motion while someone is dragging the scroll bar.
5463 This may be called from a signal handler, so we have to ignore GC
5464 mark bits. */
5466 static void
5467 x_scroll_bar_note_movement (bar, y_pos, t)
5468 struct scroll_bar *bar;
5469 int y_pos;
5470 Time t;
5472 FRAME_PTR f = XFRAME (XWINDOW (bar->window)->frame);
5474 last_mouse_movement_time = t;
5476 f->mouse_moved = 1;
5477 XSETVECTOR (last_mouse_scroll_bar, bar);
5479 /* If we're dragging the bar, display it. */
5480 if (! GC_NILP (bar->dragging))
5482 /* Where should the handle be now? */
5483 int new_start = y_pos - 24;
5485 if (new_start != XINT (bar->start))
5487 int new_end = new_start + (XINT (bar->end) - XINT (bar->start));
5489 x_scroll_bar_set_handle (bar, new_start, new_end, 0);
5494 #endif /* !USE_TOOLKIT_SCROLL_BARS */
5496 /* Return information to the user about the current position of the mouse
5497 on the scroll bar. */
5499 static void
5500 x_scroll_bar_report_motion (fp, bar_window, part, x, y, time)
5501 FRAME_PTR *fp;
5502 Lisp_Object *bar_window;
5503 enum scroll_bar_part *part;
5504 Lisp_Object *x, *y;
5505 unsigned long *time;
5507 struct scroll_bar *bar = XSCROLL_BAR (last_mouse_scroll_bar);
5508 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
5509 #if TARGET_API_MAC_CARBON
5510 WindowPtr wp = GetControlOwner (ch);
5511 #else
5512 WindowPtr wp = (*ch)->contrlOwner;
5513 #endif
5514 Point mouse_pos;
5515 struct frame *f = mac_window_to_frame (wp);
5516 int win_y, top_range;
5518 SetPortWindowPort (wp);
5520 GetMouse (&mouse_pos);
5522 win_y = mouse_pos.v - XINT (bar->top);
5523 top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, XINT (bar->height));
5525 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
5527 win_y -= 24;
5529 if (! NILP (bar->dragging))
5530 win_y -= XINT (bar->dragging);
5532 if (win_y < 0)
5533 win_y = 0;
5534 if (win_y > top_range)
5535 win_y = top_range;
5537 *fp = f;
5538 *bar_window = bar->window;
5540 if (! NILP (bar->dragging))
5541 *part = scroll_bar_handle;
5542 else if (win_y < XINT (bar->start))
5543 *part = scroll_bar_above_handle;
5544 else if (win_y < XINT (bar->end) + VERTICAL_SCROLL_BAR_MIN_HANDLE)
5545 *part = scroll_bar_handle;
5546 else
5547 *part = scroll_bar_below_handle;
5549 XSETINT (*x, win_y);
5550 XSETINT (*y, top_range);
5552 f->mouse_moved = 0;
5553 last_mouse_scroll_bar = Qnil;
5555 *time = last_mouse_movement_time;
5559 /* The screen has been cleared so we may have changed foreground or
5560 background colors, and the scroll bars may need to be redrawn.
5561 Clear out the scroll bars, and ask for expose events, so we can
5562 redraw them. */
5564 void
5565 x_scroll_bar_clear (f)
5566 FRAME_PTR f;
5568 XTcondemn_scroll_bars (f);
5569 XTjudge_scroll_bars (f);
5573 /***********************************************************************
5574 Text Cursor
5575 ***********************************************************************/
5577 /* Set clipping for output in glyph row ROW. W is the window in which
5578 we operate. GC is the graphics context to set clipping in.
5580 ROW may be a text row or, e.g., a mode line. Text rows must be
5581 clipped to the interior of the window dedicated to text display,
5582 mode lines must be clipped to the whole window. */
5584 static void
5585 x_clip_to_row (w, row, area, gc)
5586 struct window *w;
5587 struct glyph_row *row;
5588 int area;
5589 GC gc;
5591 struct frame *f = XFRAME (WINDOW_FRAME (w));
5592 Rect clip_rect;
5593 int window_x, window_y, window_width;
5595 window_box (w, area, &window_x, &window_y, &window_width, 0);
5597 clip_rect.left = window_x;
5598 clip_rect.top = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
5599 clip_rect.top = max (clip_rect.top, window_y);
5600 clip_rect.right = clip_rect.left + window_width;
5601 clip_rect.bottom = clip_rect.top + row->visible_height;
5603 mac_set_clip_rectangles (FRAME_MAC_DISPLAY (f), gc, &clip_rect, 1);
5607 /* Draw a hollow box cursor on window W in glyph row ROW. */
5609 static void
5610 x_draw_hollow_cursor (w, row)
5611 struct window *w;
5612 struct glyph_row *row;
5614 struct frame *f = XFRAME (WINDOW_FRAME (w));
5615 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
5616 Display *dpy = FRAME_MAC_DISPLAY (f);
5617 int x, y, wd, h;
5618 XGCValues xgcv;
5619 struct glyph *cursor_glyph;
5620 GC gc;
5622 /* Get the glyph the cursor is on. If we can't tell because
5623 the current matrix is invalid or such, give up. */
5624 cursor_glyph = get_phys_cursor_glyph (w);
5625 if (cursor_glyph == NULL)
5626 return;
5628 /* Compute frame-relative coordinates for phys cursor. */
5629 get_phys_cursor_geometry (w, row, cursor_glyph, &x, &y, &h);
5630 wd = w->phys_cursor_width;
5632 /* The foreground of cursor_gc is typically the same as the normal
5633 background color, which can cause the cursor box to be invisible. */
5634 xgcv.foreground = f->output_data.mac->cursor_pixel;
5635 if (dpyinfo->scratch_cursor_gc)
5636 XChangeGC (dpy, dpyinfo->scratch_cursor_gc, GCForeground, &xgcv);
5637 else
5638 dpyinfo->scratch_cursor_gc = XCreateGC (dpy, FRAME_MAC_WINDOW (f),
5639 GCForeground, &xgcv);
5640 gc = dpyinfo->scratch_cursor_gc;
5642 /* Set clipping, draw the rectangle, and reset clipping again. */
5643 x_clip_to_row (w, row, TEXT_AREA, gc);
5644 mac_draw_rectangle (f, gc, x, y, wd, h - 1);
5645 mac_reset_clip_rectangles (dpy, gc);
5649 /* Draw a bar cursor on window W in glyph row ROW.
5651 Implementation note: One would like to draw a bar cursor with an
5652 angle equal to the one given by the font property XA_ITALIC_ANGLE.
5653 Unfortunately, I didn't find a font yet that has this property set.
5654 --gerd. */
5656 static void
5657 x_draw_bar_cursor (w, row, width, kind)
5658 struct window *w;
5659 struct glyph_row *row;
5660 int width;
5661 enum text_cursor_kinds kind;
5663 struct frame *f = XFRAME (w->frame);
5664 struct glyph *cursor_glyph;
5666 /* If cursor is out of bounds, don't draw garbage. This can happen
5667 in mini-buffer windows when switching between echo area glyphs
5668 and mini-buffer. */
5669 cursor_glyph = get_phys_cursor_glyph (w);
5670 if (cursor_glyph == NULL)
5671 return;
5673 /* If on an image, draw like a normal cursor. That's usually better
5674 visible than drawing a bar, esp. if the image is large so that
5675 the bar might not be in the window. */
5676 if (cursor_glyph->type == IMAGE_GLYPH)
5678 struct glyph_row *row;
5679 row = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos);
5680 draw_phys_cursor_glyph (w, row, DRAW_CURSOR);
5682 else
5684 Display *dpy = FRAME_MAC_DISPLAY (f);
5685 Window window = FRAME_MAC_WINDOW (f);
5686 GC gc = FRAME_MAC_DISPLAY_INFO (f)->scratch_cursor_gc;
5687 unsigned long mask = GCForeground | GCBackground;
5688 struct face *face = FACE_FROM_ID (f, cursor_glyph->face_id);
5689 XGCValues xgcv;
5691 /* If the glyph's background equals the color we normally draw
5692 the bar cursor in, the bar cursor in its normal color is
5693 invisible. Use the glyph's foreground color instead in this
5694 case, on the assumption that the glyph's colors are chosen so
5695 that the glyph is legible. */
5696 if (face->background == f->output_data.mac->cursor_pixel)
5697 xgcv.background = xgcv.foreground = face->foreground;
5698 else
5699 xgcv.background = xgcv.foreground = f->output_data.mac->cursor_pixel;
5701 if (gc)
5702 XChangeGC (dpy, gc, mask, &xgcv);
5703 else
5705 gc = XCreateGC (dpy, window, mask, &xgcv);
5706 FRAME_MAC_DISPLAY_INFO (f)->scratch_cursor_gc = gc;
5709 if (width < 0)
5710 width = FRAME_CURSOR_WIDTH (f);
5711 width = min (cursor_glyph->pixel_width, width);
5713 w->phys_cursor_width = width;
5714 x_clip_to_row (w, row, TEXT_AREA, gc);
5716 if (kind == BAR_CURSOR)
5717 mac_fill_rectangle (f, gc,
5718 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x),
5719 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
5720 width, row->height);
5721 else
5722 mac_fill_rectangle (f, gc,
5723 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x),
5724 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y +
5725 row->height - width),
5726 cursor_glyph->pixel_width,
5727 width);
5729 mac_reset_clip_rectangles (dpy, gc);
5734 /* RIF: Define cursor CURSOR on frame F. */
5736 static void
5737 mac_define_frame_cursor (f, cursor)
5738 struct frame *f;
5739 Cursor cursor;
5741 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
5743 if (dpyinfo->x_focus_frame == f)
5744 SetThemeCursor (cursor);
5748 /* RIF: Clear area on frame F. */
5750 static void
5751 mac_clear_frame_area (f, x, y, width, height)
5752 struct frame *f;
5753 int x, y, width, height;
5755 mac_clear_area (f, x, y, width, height);
5759 /* RIF: Draw cursor on window W. */
5761 static void
5762 mac_draw_window_cursor (w, glyph_row, x, y, cursor_type, cursor_width, on_p, active_p)
5763 struct window *w;
5764 struct glyph_row *glyph_row;
5765 int x, y;
5766 int cursor_type, cursor_width;
5767 int on_p, active_p;
5769 if (on_p)
5771 w->phys_cursor_type = cursor_type;
5772 w->phys_cursor_on_p = 1;
5774 if (glyph_row->exact_window_width_line_p
5775 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
5777 glyph_row->cursor_in_fringe_p = 1;
5778 draw_fringe_bitmap (w, glyph_row, 0);
5780 else
5781 switch (cursor_type)
5783 case HOLLOW_BOX_CURSOR:
5784 x_draw_hollow_cursor (w, glyph_row);
5785 break;
5787 case FILLED_BOX_CURSOR:
5788 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
5789 break;
5791 case BAR_CURSOR:
5792 x_draw_bar_cursor (w, glyph_row, cursor_width, BAR_CURSOR);
5793 break;
5795 case HBAR_CURSOR:
5796 x_draw_bar_cursor (w, glyph_row, cursor_width, HBAR_CURSOR);
5797 break;
5799 case NO_CURSOR:
5800 w->phys_cursor_width = 0;
5801 break;
5803 default:
5804 abort ();
5810 /* Icons. */
5812 #if 0 /* MAC_TODO: no icon support yet. */
5814 x_bitmap_icon (f, icon)
5815 struct frame *f;
5816 Lisp_Object icon;
5818 HANDLE hicon;
5820 if (FRAME_W32_WINDOW (f) == 0)
5821 return 1;
5823 if (NILP (icon))
5824 hicon = LoadIcon (hinst, EMACS_CLASS);
5825 else if (STRINGP (icon))
5826 hicon = LoadImage (NULL, (LPCTSTR) SDATA (icon), IMAGE_ICON, 0, 0,
5827 LR_DEFAULTSIZE | LR_LOADFROMFILE);
5828 else if (SYMBOLP (icon))
5830 LPCTSTR name;
5832 if (EQ (icon, intern ("application")))
5833 name = (LPCTSTR) IDI_APPLICATION;
5834 else if (EQ (icon, intern ("hand")))
5835 name = (LPCTSTR) IDI_HAND;
5836 else if (EQ (icon, intern ("question")))
5837 name = (LPCTSTR) IDI_QUESTION;
5838 else if (EQ (icon, intern ("exclamation")))
5839 name = (LPCTSTR) IDI_EXCLAMATION;
5840 else if (EQ (icon, intern ("asterisk")))
5841 name = (LPCTSTR) IDI_ASTERISK;
5842 else if (EQ (icon, intern ("winlogo")))
5843 name = (LPCTSTR) IDI_WINLOGO;
5844 else
5845 return 1;
5847 hicon = LoadIcon (NULL, name);
5849 else
5850 return 1;
5852 if (hicon == NULL)
5853 return 1;
5855 PostMessage (FRAME_W32_WINDOW (f), WM_SETICON, (WPARAM) ICON_BIG,
5856 (LPARAM) hicon);
5858 return 0;
5860 #endif /* MAC_TODO */
5862 /************************************************************************
5863 Handling X errors
5864 ************************************************************************/
5866 /* Display Error Handling functions not used on W32. Listing them here
5867 helps diff stay in step when comparing w32term.c with xterm.c.
5869 x_error_catcher (display, error)
5870 x_catch_errors (dpy)
5871 x_catch_errors_unwind (old_val)
5872 x_check_errors (dpy, format)
5873 x_had_errors_p (dpy)
5874 x_clear_errors (dpy)
5875 x_uncatch_errors (dpy, count)
5876 x_trace_wire ()
5877 x_connection_signal (signalnum)
5878 x_connection_closed (dpy, error_message)
5879 x_error_quitter (display, error)
5880 x_error_handler (display, error)
5881 x_io_error_quitter (display)
5886 /* Changing the font of the frame. */
5888 /* Give frame F the font named FONTNAME as its default font, and
5889 return the full name of that font. FONTNAME may be a wildcard
5890 pattern; in that case, we choose some font that fits the pattern.
5891 The return value shows which font we chose. */
5893 Lisp_Object
5894 x_new_font (f, fontname)
5895 struct frame *f;
5896 register char *fontname;
5898 struct font_info *fontp
5899 = FS_LOAD_FONT (f, 0, fontname, -1);
5901 if (!fontp)
5902 return Qnil;
5904 FRAME_FONT (f) = (XFontStruct *) (fontp->font);
5905 FRAME_BASELINE_OFFSET (f) = fontp->baseline_offset;
5906 FRAME_FONTSET (f) = -1;
5908 FRAME_COLUMN_WIDTH (f) = fontp->average_width;
5909 FRAME_SPACE_WIDTH (f) = fontp->space_width;
5910 FRAME_LINE_HEIGHT (f) = FONT_HEIGHT (FRAME_FONT (f));
5912 compute_fringe_widths (f, 1);
5914 /* Compute the scroll bar width in character columns. */
5915 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
5917 int wid = FRAME_COLUMN_WIDTH (f);
5918 FRAME_CONFIG_SCROLL_BAR_COLS (f)
5919 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid-1) / wid;
5921 else
5923 int wid = FRAME_COLUMN_WIDTH (f);
5924 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
5927 /* Now make the frame display the given font. */
5928 if (FRAME_MAC_WINDOW (f) != 0)
5930 XSetFont (FRAME_MAC_DISPLAY (f), f->output_data.mac->normal_gc,
5931 FRAME_FONT (f));
5932 XSetFont (FRAME_MAC_DISPLAY (f), f->output_data.mac->reverse_gc,
5933 FRAME_FONT (f));
5934 XSetFont (FRAME_MAC_DISPLAY (f), f->output_data.mac->cursor_gc,
5935 FRAME_FONT (f));
5937 /* Don't change the size of a tip frame; there's no point in
5938 doing it because it's done in Fx_show_tip, and it leads to
5939 problems because the tip frame has no widget. */
5940 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
5941 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
5944 return build_string (fontp->full_name);
5947 /* Give frame F the fontset named FONTSETNAME as its default font, and
5948 return the full name of that fontset. FONTSETNAME may be a wildcard
5949 pattern; in that case, we choose some fontset that fits the pattern.
5950 The return value shows which fontset we chose. */
5952 Lisp_Object
5953 x_new_fontset (f, fontsetname)
5954 struct frame *f;
5955 char *fontsetname;
5957 int fontset = fs_query_fontset (build_string (fontsetname), 0);
5958 Lisp_Object result;
5960 if (fontset < 0)
5961 return Qnil;
5963 if (FRAME_FONTSET (f) == fontset)
5964 /* This fontset is already set in frame F. There's nothing more
5965 to do. */
5966 return fontset_name (fontset);
5968 result = x_new_font (f, (SDATA (fontset_ascii (fontset))));
5970 if (!STRINGP (result))
5971 /* Can't load ASCII font. */
5972 return Qnil;
5974 /* Since x_new_font doesn't update any fontset information, do it now. */
5975 FRAME_FONTSET (f) = fontset;
5977 return build_string (fontsetname);
5981 /***********************************************************************
5982 TODO: W32 Input Methods
5983 ***********************************************************************/
5984 /* Listing missing functions from xterm.c helps diff stay in step.
5986 xim_destroy_callback (xim, client_data, call_data)
5987 xim_open_dpy (dpyinfo, resource_name)
5988 struct xim_inst_t
5989 xim_instantiate_callback (display, client_data, call_data)
5990 xim_initialize (dpyinfo, resource_name)
5991 xim_close_dpy (dpyinfo)
5996 void
5997 mac_get_window_bounds (f, inner, outer)
5998 struct frame *f;
5999 Rect *inner, *outer;
6001 #if TARGET_API_MAC_CARBON
6002 GetWindowBounds (FRAME_MAC_WINDOW (f), kWindowContentRgn, inner);
6003 GetWindowBounds (FRAME_MAC_WINDOW (f), kWindowStructureRgn, outer);
6004 #else /* not TARGET_API_MAC_CARBON */
6005 RgnHandle region = NewRgn ();
6007 GetWindowRegion (FRAME_MAC_WINDOW (f), kWindowContentRgn, region);
6008 *inner = (*region)->rgnBBox;
6009 GetWindowRegion (FRAME_MAC_WINDOW (f), kWindowStructureRgn, region);
6010 *outer = (*region)->rgnBBox;
6011 DisposeRgn (region);
6012 #endif /* not TARGET_API_MAC_CARBON */
6015 static void
6016 mac_handle_origin_change (f)
6017 struct frame *f;
6019 x_real_positions (f, &f->left_pos, &f->top_pos);
6022 static void
6023 mac_handle_size_change (f, pixelwidth, pixelheight)
6024 struct frame *f;
6025 int pixelwidth, pixelheight;
6027 int cols, rows;
6029 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, pixelwidth);
6030 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, pixelheight);
6032 if (cols != FRAME_COLS (f)
6033 || rows != FRAME_LINES (f)
6034 || pixelwidth != FRAME_PIXEL_WIDTH (f)
6035 || pixelheight != FRAME_PIXEL_HEIGHT (f))
6037 /* We pass 1 for DELAY since we can't run Lisp code inside of
6038 a BLOCK_INPUT. */
6039 change_frame_size (f, rows, cols, 0, 1, 0);
6040 FRAME_PIXEL_WIDTH (f) = pixelwidth;
6041 FRAME_PIXEL_HEIGHT (f) = pixelheight;
6042 SET_FRAME_GARBAGED (f);
6044 /* If cursor was outside the new size, mark it as off. */
6045 mark_window_cursors_off (XWINDOW (f->root_window));
6047 /* Clear out any recollection of where the mouse highlighting
6048 was, since it might be in a place that's outside the new
6049 frame size. Actually checking whether it is outside is a
6050 pain in the neck, so don't try--just let the highlighting be
6051 done afresh with new size. */
6052 cancel_mouse_face (f);
6054 #if TARGET_API_MAC_CARBON
6055 if (f->output_data.mac->hourglass_control)
6057 #if USE_CG_DRAWING
6058 mac_prepare_for_quickdraw (f);
6059 #endif
6060 MoveControl (f->output_data.mac->hourglass_control,
6061 pixelwidth - HOURGLASS_WIDTH, 0);
6063 #endif
6068 /* Calculate the absolute position in frame F
6069 from its current recorded position values and gravity. */
6071 void
6072 x_calc_absolute_position (f)
6073 struct frame *f;
6075 int width_diff = 0, height_diff = 0;
6076 int flags = f->size_hint_flags;
6077 Rect inner, outer;
6079 /* We have nothing to do if the current position
6080 is already for the top-left corner. */
6081 if (! ((flags & XNegative) || (flags & YNegative)))
6082 return;
6084 /* Find the offsets of the outside upper-left corner of
6085 the inner window, with respect to the outer window. */
6086 mac_get_window_bounds (f, &inner, &outer);
6088 width_diff = (outer.right - outer.left) - (inner.right - inner.left);
6089 height_diff = (outer.bottom - outer.top) - (inner.bottom - inner.top);
6091 /* Treat negative positions as relative to the leftmost bottommost
6092 position that fits on the screen. */
6093 if (flags & XNegative)
6094 f->left_pos = (FRAME_MAC_DISPLAY_INFO (f)->width
6095 - width_diff
6096 - FRAME_PIXEL_WIDTH (f)
6097 + f->left_pos);
6099 if (flags & YNegative)
6100 f->top_pos = (FRAME_MAC_DISPLAY_INFO (f)->height
6101 - height_diff
6102 - FRAME_PIXEL_HEIGHT (f)
6103 + f->top_pos);
6105 /* The left_pos and top_pos
6106 are now relative to the top and left screen edges,
6107 so the flags should correspond. */
6108 f->size_hint_flags &= ~ (XNegative | YNegative);
6111 /* CHANGE_GRAVITY is 1 when calling from Fset_frame_position,
6112 to really change the position, and 0 when calling from
6113 x_make_frame_visible (in that case, XOFF and YOFF are the current
6114 position values). It is -1 when calling from x_set_frame_parameters,
6115 which means, do adjust for borders but don't change the gravity. */
6117 void
6118 x_set_offset (f, xoff, yoff, change_gravity)
6119 struct frame *f;
6120 register int xoff, yoff;
6121 int change_gravity;
6123 if (change_gravity > 0)
6125 f->top_pos = yoff;
6126 f->left_pos = xoff;
6127 f->size_hint_flags &= ~ (XNegative | YNegative);
6128 if (xoff < 0)
6129 f->size_hint_flags |= XNegative;
6130 if (yoff < 0)
6131 f->size_hint_flags |= YNegative;
6132 f->win_gravity = NorthWestGravity;
6134 x_calc_absolute_position (f);
6136 BLOCK_INPUT;
6137 x_wm_set_size_hint (f, (long) 0, 0);
6139 #if TARGET_API_MAC_CARBON
6140 MoveWindowStructure (FRAME_MAC_WINDOW (f), f->left_pos, f->top_pos);
6141 /* If the title bar is completely outside the screen, adjust the
6142 position. */
6143 ConstrainWindowToScreen (FRAME_MAC_WINDOW (f), kWindowTitleBarRgn,
6144 kWindowConstrainMoveRegardlessOfFit
6145 | kWindowConstrainAllowPartial, NULL, NULL);
6146 #if USE_CARBON_EVENTS
6147 if (!NILP (tip_frame) && XFRAME (tip_frame) == f)
6148 #endif
6149 mac_handle_origin_change (f);
6150 #else
6152 Rect inner, outer, screen_rect, dummy;
6153 RgnHandle region = NewRgn ();
6155 mac_get_window_bounds (f, &inner, &outer);
6156 f->x_pixels_diff = inner.left - outer.left;
6157 f->y_pixels_diff = inner.top - outer.top;
6158 MoveWindow (FRAME_MAC_WINDOW (f), f->left_pos + f->x_pixels_diff,
6159 f->top_pos + f->y_pixels_diff, false);
6161 /* If the title bar is completely outside the screen, adjust the
6162 position. The variable `outer' holds the title bar rectangle.
6163 The variable `inner' holds slightly smaller one than `outer',
6164 so that the calculation of overlapping may not become too
6165 strict. */
6166 GetWindowRegion (FRAME_MAC_WINDOW (f), kWindowTitleBarRgn, region);
6167 outer = (*region)->rgnBBox;
6168 DisposeRgn (region);
6169 inner = outer;
6170 InsetRect (&inner, 8, 8);
6171 screen_rect = qd.screenBits.bounds;
6172 screen_rect.top += GetMBarHeight ();
6174 if (!SectRect (&inner, &screen_rect, &dummy))
6176 if (inner.right <= screen_rect.left)
6177 f->left_pos = screen_rect.left;
6178 else if (inner.left >= screen_rect.right)
6179 f->left_pos = screen_rect.right - (outer.right - outer.left);
6181 if (inner.bottom <= screen_rect.top)
6182 f->top_pos = screen_rect.top;
6183 else if (inner.top >= screen_rect.bottom)
6184 f->top_pos = screen_rect.bottom - (outer.bottom - outer.top);
6186 MoveWindow (FRAME_MAC_WINDOW (f), f->left_pos + f->x_pixels_diff,
6187 f->top_pos + f->y_pixels_diff, false);
6190 #endif
6192 UNBLOCK_INPUT;
6195 /* Call this to change the size of frame F's x-window.
6196 If CHANGE_GRAVITY is 1, we change to top-left-corner window gravity
6197 for this size change and subsequent size changes.
6198 Otherwise we leave the window gravity unchanged. */
6200 void
6201 x_set_window_size (f, change_gravity, cols, rows)
6202 struct frame *f;
6203 int change_gravity;
6204 int cols, rows;
6206 int pixelwidth, pixelheight;
6208 BLOCK_INPUT;
6210 check_frame_size (f, &rows, &cols);
6211 f->scroll_bar_actual_width
6212 = FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f);
6214 compute_fringe_widths (f, 0);
6216 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols);
6217 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
6219 f->win_gravity = NorthWestGravity;
6220 x_wm_set_size_hint (f, (long) 0, 0);
6222 SizeWindow (FRAME_MAC_WINDOW (f), pixelwidth, pixelheight, 0);
6224 #if USE_CARBON_EVENTS
6225 if (!NILP (tip_frame) && f == XFRAME (tip_frame))
6226 #endif
6227 mac_handle_size_change (f, pixelwidth, pixelheight);
6229 if (f->output_data.mac->internal_border_width
6230 != FRAME_INTERNAL_BORDER_WIDTH (f))
6232 mac_clear_window (f);
6233 f->output_data.mac->internal_border_width
6234 = FRAME_INTERNAL_BORDER_WIDTH (f);
6237 SET_FRAME_GARBAGED (f);
6239 UNBLOCK_INPUT;
6242 /* Mouse warping. */
6244 void x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y);
6246 void
6247 x_set_mouse_position (f, x, y)
6248 struct frame *f;
6249 int x, y;
6251 int pix_x, pix_y;
6253 pix_x = FRAME_COL_TO_PIXEL_X (f, x) + FRAME_COLUMN_WIDTH (f) / 2;
6254 pix_y = FRAME_LINE_TO_PIXEL_Y (f, y) + FRAME_LINE_HEIGHT (f) / 2;
6256 if (pix_x < 0) pix_x = 0;
6257 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
6259 if (pix_y < 0) pix_y = 0;
6260 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
6262 x_set_mouse_pixel_position (f, pix_x, pix_y);
6265 void
6266 x_set_mouse_pixel_position (f, pix_x, pix_y)
6267 struct frame *f;
6268 int pix_x, pix_y;
6270 #ifdef MAC_OSX
6271 Point p;
6272 CGPoint point;
6274 BLOCK_INPUT;
6275 SetPortWindowPort (FRAME_MAC_WINDOW (f));
6276 p.h = pix_x;
6277 p.v = pix_y;
6278 LocalToGlobal (&p);
6279 point.x = p.h;
6280 point.y = p.v;
6281 CGWarpMouseCursorPosition (point);
6282 UNBLOCK_INPUT;
6283 #else
6284 #if 0 /* MAC_TODO: LMSetMouseLocation and CursorDeviceMoveTo are non-Carbon */
6285 BLOCK_INPUT;
6287 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
6288 0, 0, 0, 0, pix_x, pix_y);
6289 UNBLOCK_INPUT;
6290 #endif
6291 #endif
6294 /* focus shifting, raising and lowering. */
6296 void
6297 x_focus_on_frame (f)
6298 struct frame *f;
6300 #if 0 /* This proves to be unpleasant. */
6301 x_raise_frame (f);
6302 #endif
6303 #if 0
6304 /* I don't think that the ICCCM allows programs to do things like this
6305 without the interaction of the window manager. Whatever you end up
6306 doing with this code, do it to x_unfocus_frame too. */
6307 XSetInputFocus (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
6308 RevertToPointerRoot, CurrentTime);
6309 #endif /* ! 0 */
6312 void
6313 x_unfocus_frame (f)
6314 struct frame *f;
6318 /* Raise frame F. */
6320 void
6321 x_raise_frame (f)
6322 struct frame *f;
6324 if (f->async_visible)
6326 BLOCK_INPUT;
6327 BringToFront (FRAME_MAC_WINDOW (f));
6328 UNBLOCK_INPUT;
6332 /* Lower frame F. */
6334 void
6335 x_lower_frame (f)
6336 struct frame *f;
6338 if (f->async_visible)
6340 BLOCK_INPUT;
6341 SendBehind (FRAME_MAC_WINDOW (f), NULL);
6342 UNBLOCK_INPUT;
6346 static void
6347 XTframe_raise_lower (f, raise_flag)
6348 FRAME_PTR f;
6349 int raise_flag;
6351 if (raise_flag)
6352 x_raise_frame (f);
6353 else
6354 x_lower_frame (f);
6357 /* Change of visibility. */
6359 static void
6360 mac_handle_visibility_change (f)
6361 struct frame *f;
6363 WindowPtr wp = FRAME_MAC_WINDOW (f);
6364 int visible = 0, iconified = 0;
6365 struct input_event buf;
6367 if (IsWindowVisible (wp))
6369 if (IsWindowCollapsed (wp))
6370 iconified = 1;
6371 else
6372 visible = 1;
6375 if (!f->async_visible && visible)
6377 if (f->iconified)
6379 /* wait_reading_process_output will notice this and update
6380 the frame's display structures. If we were made
6381 invisible, we should not set garbaged, because that stops
6382 redrawing on Update events. */
6383 SET_FRAME_GARBAGED (f);
6385 EVENT_INIT (buf);
6386 buf.kind = DEICONIFY_EVENT;
6387 XSETFRAME (buf.frame_or_window, f);
6388 buf.arg = Qnil;
6389 kbd_buffer_store_event (&buf);
6391 else if (! NILP (Vframe_list) && ! NILP (XCDR (Vframe_list)))
6392 /* Force a redisplay sooner or later to update the
6393 frame titles in case this is the second frame. */
6394 record_asynch_buffer_change ();
6396 else if (f->async_visible && !visible)
6397 if (iconified)
6399 EVENT_INIT (buf);
6400 buf.kind = ICONIFY_EVENT;
6401 XSETFRAME (buf.frame_or_window, f);
6402 buf.arg = Qnil;
6403 kbd_buffer_store_event (&buf);
6406 f->async_visible = visible;
6407 f->async_iconified = iconified;
6410 /* This tries to wait until the frame is really visible.
6411 However, if the window manager asks the user where to position
6412 the frame, this will return before the user finishes doing that.
6413 The frame will not actually be visible at that time,
6414 but it will become visible later when the window manager
6415 finishes with it. */
6417 void
6418 x_make_frame_visible (f)
6419 struct frame *f;
6421 BLOCK_INPUT;
6423 if (! FRAME_VISIBLE_P (f))
6425 /* We test FRAME_GARBAGED_P here to make sure we don't
6426 call x_set_offset a second time
6427 if we get to x_make_frame_visible a second time
6428 before the window gets really visible. */
6429 if (! FRAME_ICONIFIED_P (f)
6430 && ! f->output_data.mac->asked_for_visible)
6432 #if TARGET_API_MAC_CARBON
6433 if (!(FRAME_SIZE_HINTS (f)->flags & (USPosition | PPosition)))
6435 struct frame *sf = SELECTED_FRAME ();
6436 if (!FRAME_MAC_P (sf))
6437 RepositionWindow (FRAME_MAC_WINDOW (f), NULL,
6438 kWindowCenterOnMainScreen);
6439 else
6440 RepositionWindow (FRAME_MAC_WINDOW (f),
6441 FRAME_MAC_WINDOW (sf),
6442 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
6443 kWindowCascadeStartAtParentWindowScreen
6444 #else
6445 kWindowCascadeOnParentWindowScreen
6446 #endif
6448 #if USE_CARBON_EVENTS
6449 if (!NILP (tip_frame) && f == XFRAME (tip_frame))
6450 #endif
6451 mac_handle_origin_change (f);
6453 else
6454 #endif
6455 x_set_offset (f, f->left_pos, f->top_pos, 0);
6458 f->output_data.mac->asked_for_visible = 1;
6460 CollapseWindow (FRAME_MAC_WINDOW (f), false);
6461 ShowWindow (FRAME_MAC_WINDOW (f));
6464 XFlush (FRAME_MAC_DISPLAY (f));
6466 /* Synchronize to ensure Emacs knows the frame is visible
6467 before we do anything else. We do this loop with input not blocked
6468 so that incoming events are handled. */
6470 Lisp_Object frame;
6471 int count;
6473 /* This must come after we set COUNT. */
6474 UNBLOCK_INPUT;
6476 XSETFRAME (frame, f);
6478 /* Wait until the frame is visible. Process X events until a
6479 MapNotify event has been seen, or until we think we won't get a
6480 MapNotify at all.. */
6481 for (count = input_signal_count + 10;
6482 input_signal_count < count && !FRAME_VISIBLE_P (f);)
6484 /* Force processing of queued events. */
6485 x_sync (f);
6487 /* Machines that do polling rather than SIGIO have been
6488 observed to go into a busy-wait here. So we'll fake an
6489 alarm signal to let the handler know that there's something
6490 to be read. We used to raise a real alarm, but it seems
6491 that the handler isn't always enabled here. This is
6492 probably a bug. */
6493 if (input_polling_used ())
6495 /* It could be confusing if a real alarm arrives while
6496 processing the fake one. Turn it off and let the
6497 handler reset it. */
6498 extern void poll_for_input_1 P_ ((void));
6499 int old_poll_suppress_count = poll_suppress_count;
6500 poll_suppress_count = 1;
6501 poll_for_input_1 ();
6502 poll_suppress_count = old_poll_suppress_count;
6505 /* See if a MapNotify event has been processed. */
6506 FRAME_SAMPLE_VISIBILITY (f);
6511 /* Change from mapped state to withdrawn state. */
6513 /* Make the frame visible (mapped and not iconified). */
6515 void
6516 x_make_frame_invisible (f)
6517 struct frame *f;
6519 /* A deactivate event does not occur when the last visible frame is
6520 made invisible. So if we clear the highlight here, it will not
6521 be rehighlighted when it is made visible. */
6522 #if 0
6523 /* Don't keep the highlight on an invisible frame. */
6524 if (FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame == f)
6525 FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame = 0;
6526 #endif
6528 BLOCK_INPUT;
6530 /* Before unmapping the window, update the WM_SIZE_HINTS property to claim
6531 that the current position of the window is user-specified, rather than
6532 program-specified, so that when the window is mapped again, it will be
6533 placed at the same location, without forcing the user to position it
6534 by hand again (they have already done that once for this window.) */
6535 x_wm_set_size_hint (f, (long) 0, 1);
6537 HideWindow (FRAME_MAC_WINDOW (f));
6539 UNBLOCK_INPUT;
6541 #if !USE_CARBON_EVENTS
6542 mac_handle_visibility_change (f);
6543 #endif
6546 /* Change window state from mapped to iconified. */
6548 void
6549 x_iconify_frame (f)
6550 struct frame *f;
6552 OSStatus err;
6554 /* A deactivate event does not occur when the last visible frame is
6555 iconified. So if we clear the highlight here, it will not be
6556 rehighlighted when it is deiconified. */
6557 #if 0
6558 /* Don't keep the highlight on an invisible frame. */
6559 if (FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame == f)
6560 FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame = 0;
6561 #endif
6563 if (f->async_iconified)
6564 return;
6566 BLOCK_INPUT;
6568 FRAME_SAMPLE_VISIBILITY (f);
6570 if (! FRAME_VISIBLE_P (f))
6571 ShowWindow (FRAME_MAC_WINDOW (f));
6573 err = CollapseWindow (FRAME_MAC_WINDOW (f), true);
6575 UNBLOCK_INPUT;
6577 if (err != noErr)
6578 error ("Can't notify window manager of iconification");
6580 #if !USE_CARBON_EVENTS
6581 mac_handle_visibility_change (f);
6582 #endif
6586 /* Free X resources of frame F. */
6588 void
6589 x_free_frame_resources (f)
6590 struct frame *f;
6592 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
6593 WindowPtr wp = FRAME_MAC_WINDOW (f);
6595 BLOCK_INPUT;
6597 if (wp != tip_window)
6598 remove_window_handler (wp);
6600 #if USE_CG_DRAWING
6601 mac_prepare_for_quickdraw (f);
6602 #endif
6603 DisposeWindow (wp);
6604 if (wp == tip_window)
6605 /* Neither WaitNextEvent nor ReceiveNextEvent receives `window
6606 closed' event. So we reset tip_window here. */
6607 tip_window = NULL;
6609 free_frame_menubar (f);
6611 if (FRAME_FACE_CACHE (f))
6612 free_frame_faces (f);
6614 x_free_gcs (f);
6616 if (FRAME_SIZE_HINTS (f))
6617 xfree (FRAME_SIZE_HINTS (f));
6619 xfree (f->output_data.mac);
6620 f->output_data.mac = NULL;
6622 if (f == dpyinfo->x_focus_frame)
6624 dpyinfo->x_focus_frame = 0;
6625 #if USE_MAC_FONT_PANEL
6626 mac_set_font_info_for_selection (NULL, DEFAULT_FACE_ID, 0);
6627 #endif
6629 if (f == dpyinfo->x_focus_event_frame)
6630 dpyinfo->x_focus_event_frame = 0;
6631 if (f == dpyinfo->x_highlight_frame)
6632 dpyinfo->x_highlight_frame = 0;
6634 if (f == dpyinfo->mouse_face_mouse_frame)
6636 dpyinfo->mouse_face_beg_row
6637 = dpyinfo->mouse_face_beg_col = -1;
6638 dpyinfo->mouse_face_end_row
6639 = dpyinfo->mouse_face_end_col = -1;
6640 dpyinfo->mouse_face_window = Qnil;
6641 dpyinfo->mouse_face_deferred_gc = 0;
6642 dpyinfo->mouse_face_mouse_frame = 0;
6645 UNBLOCK_INPUT;
6649 /* Destroy the X window of frame F. */
6651 void
6652 x_destroy_window (f)
6653 struct frame *f;
6655 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
6657 x_free_frame_resources (f);
6659 dpyinfo->reference_count--;
6663 /* Setting window manager hints. */
6665 /* Set the normal size hints for the window manager, for frame F.
6666 FLAGS is the flags word to use--or 0 meaning preserve the flags
6667 that the window now has.
6668 If USER_POSITION is nonzero, we set the USPosition
6669 flag (this is useful when FLAGS is 0). */
6670 void
6671 x_wm_set_size_hint (f, flags, user_position)
6672 struct frame *f;
6673 long flags;
6674 int user_position;
6676 int base_width, base_height, width_inc, height_inc;
6677 int min_rows = 0, min_cols = 0;
6678 XSizeHints *size_hints;
6680 base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
6681 base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
6682 width_inc = FRAME_COLUMN_WIDTH (f);
6683 height_inc = FRAME_LINE_HEIGHT (f);
6685 check_frame_size (f, &min_rows, &min_cols);
6687 size_hints = FRAME_SIZE_HINTS (f);
6688 if (size_hints == NULL)
6690 size_hints = FRAME_SIZE_HINTS (f) = xmalloc (sizeof (XSizeHints));
6691 bzero (size_hints, sizeof (XSizeHints));
6694 size_hints->flags |= PResizeInc | PMinSize | PBaseSize ;
6695 size_hints->width_inc = width_inc;
6696 size_hints->height_inc = height_inc;
6697 size_hints->min_width = base_width + min_cols * width_inc;
6698 size_hints->min_height = base_height + min_rows * height_inc;
6699 size_hints->base_width = base_width;
6700 size_hints->base_height = base_height;
6702 if (flags)
6703 size_hints->flags = flags;
6704 else if (user_position)
6706 size_hints->flags &= ~ PPosition;
6707 size_hints->flags |= USPosition;
6711 #if 0 /* MAC_TODO: hide application instead of iconify? */
6712 /* Used for IconicState or NormalState */
6714 void
6715 x_wm_set_window_state (f, state)
6716 struct frame *f;
6717 int state;
6719 #ifdef USE_X_TOOLKIT
6720 Arg al[1];
6722 XtSetArg (al[0], XtNinitialState, state);
6723 XtSetValues (f->output_data.x->widget, al, 1);
6724 #else /* not USE_X_TOOLKIT */
6725 Window window = FRAME_X_WINDOW (f);
6727 f->output_data.x->wm_hints.flags |= StateHint;
6728 f->output_data.x->wm_hints.initial_state = state;
6730 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
6731 #endif /* not USE_X_TOOLKIT */
6734 void
6735 x_wm_set_icon_pixmap (f, pixmap_id)
6736 struct frame *f;
6737 int pixmap_id;
6739 Pixmap icon_pixmap;
6741 #ifndef USE_X_TOOLKIT
6742 Window window = FRAME_X_WINDOW (f);
6743 #endif
6745 if (pixmap_id > 0)
6747 icon_pixmap = x_bitmap_pixmap (f, pixmap_id);
6748 f->output_data.x->wm_hints.icon_pixmap = icon_pixmap;
6750 else
6752 /* It seems there is no way to turn off use of an icon pixmap.
6753 The following line does it, only if no icon has yet been created,
6754 for some window managers. But with mwm it crashes.
6755 Some people say it should clear the IconPixmapHint bit in this case,
6756 but that doesn't work, and the X consortium said it isn't the
6757 right thing at all. Since there is no way to win,
6758 best to explicitly give up. */
6759 #if 0
6760 f->output_data.x->wm_hints.icon_pixmap = None;
6761 #else
6762 return;
6763 #endif
6766 #ifdef USE_X_TOOLKIT /* same as in x_wm_set_window_state. */
6769 Arg al[1];
6770 XtSetArg (al[0], XtNiconPixmap, icon_pixmap);
6771 XtSetValues (f->output_data.x->widget, al, 1);
6774 #else /* not USE_X_TOOLKIT */
6776 f->output_data.x->wm_hints.flags |= IconPixmapHint;
6777 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
6779 #endif /* not USE_X_TOOLKIT */
6782 #endif /* MAC_TODO */
6784 void
6785 x_wm_set_icon_position (f, icon_x, icon_y)
6786 struct frame *f;
6787 int icon_x, icon_y;
6789 #if 0 /* MAC_TODO: no icons on Mac */
6790 #ifdef USE_X_TOOLKIT
6791 Window window = XtWindow (f->output_data.x->widget);
6792 #else
6793 Window window = FRAME_X_WINDOW (f);
6794 #endif
6796 f->output_data.x->wm_hints.flags |= IconPositionHint;
6797 f->output_data.x->wm_hints.icon_x = icon_x;
6798 f->output_data.x->wm_hints.icon_y = icon_y;
6800 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
6801 #endif /* MAC_TODO */
6805 /***********************************************************************
6806 XLFD Pattern Match
6807 ***********************************************************************/
6809 /* An XLFD pattern is divided into blocks delimited by '*'. This
6810 structure holds information for each block. */
6811 struct xlfdpat_block
6813 /* Length of the pattern string in this block. Non-zero except for
6814 the first and the last blocks. */
6815 int len;
6817 /* Pattern string except the last character in this block. The last
6818 character is replaced with NUL in order to use it as a
6819 sentinel. */
6820 unsigned char *pattern;
6822 /* Last character of the pattern string. Must not be '?'. */
6823 unsigned char last_char;
6825 /* One of the tables for the Boyer-Moore string search. It
6826 specifies the number of positions to proceed for each character
6827 with which the match fails. */
6828 int skip[256];
6830 /* The skip value for the last character in the above `skip' is
6831 assigned to `infinity' in order to simplify a loop condition.
6832 The original value is saved here. */
6833 int last_char_skip;
6836 struct xlfdpat
6838 /* Normalized pattern string. "Normalized" means that capital
6839 letters are lowered, blocks are not empty except the first and
6840 the last ones, and trailing '?'s in a block that is not the last
6841 one are moved to the next one. The last character in each block
6842 is replaced with NUL. */
6843 unsigned char *buf;
6845 /* Number of characters except '*'s and trailing '?'s in the
6846 normalized pattern string. */
6847 int nchars;
6849 /* Number of trailing '?'s in the normalized pattern string. */
6850 int trailing_anychars;
6852 /* Number of blocks and information for each block. The latter is
6853 NULL if the pattern is exact (no '*' or '?' in it). */
6854 int nblocks;
6855 struct xlfdpat_block *blocks;
6858 static void
6859 xlfdpat_destroy (pat)
6860 struct xlfdpat *pat;
6862 if (pat)
6864 if (pat->buf)
6866 if (pat->blocks)
6867 xfree (pat->blocks);
6868 xfree (pat->buf);
6870 xfree (pat);
6874 static struct xlfdpat *
6875 xlfdpat_create (pattern)
6876 const char *pattern;
6878 struct xlfdpat *pat;
6879 int nblocks, i, skip;
6880 unsigned char last_char, *p, *q, *anychar_head;
6881 const unsigned char *ptr;
6882 struct xlfdpat_block *blk;
6884 pat = xmalloc (sizeof (struct xlfdpat));
6885 pat->buf = xmalloc (strlen (pattern) + 1);
6887 /* Normalize the pattern string and store it to `pat->buf'. */
6888 nblocks = 0;
6889 anychar_head = NULL;
6890 q = pat->buf;
6891 last_char = '\0';
6892 for (ptr = pattern; *ptr; ptr++)
6894 unsigned char c = *ptr;
6896 if (c == '*')
6897 if (last_char == '*')
6898 /* ...a** -> ...a* */
6899 continue;
6900 else
6902 if (last_char == '?')
6904 if (anychar_head > pat->buf && *(anychar_head - 1) == '*')
6905 /* ...*??* -> ...*?? */
6906 continue;
6907 else
6908 /* ...a??* -> ...a*?? */
6910 *anychar_head++ = '*';
6911 c = '?';
6914 nblocks++;
6916 else if (c == '?')
6918 if (last_char != '?')
6919 anychar_head = q;
6921 else
6922 /* On Mac OS X 10.3, tolower also converts non-ASCII
6923 characters for some locales. */
6924 if (isascii (c))
6925 c = tolower (c);
6927 *q++ = last_char = c;
6929 *q = '\0';
6930 nblocks++;
6931 pat->nblocks = nblocks;
6932 if (last_char != '?')
6933 pat->trailing_anychars = 0;
6934 else
6936 pat->trailing_anychars = q - anychar_head;
6937 q = anychar_head;
6939 pat->nchars = q - pat->buf - (nblocks - 1);
6941 if (anychar_head == NULL && nblocks == 1)
6943 /* The pattern is exact. */
6944 pat->blocks = NULL;
6945 return pat;
6948 pat->blocks = xmalloc (sizeof (struct xlfdpat_block) * nblocks);
6950 /* Divide the normalized pattern into blocks. */
6951 p = pat->buf;
6952 for (blk = pat->blocks; blk < pat->blocks + nblocks - 1; blk++)
6954 blk->pattern = p;
6955 while (*p != '*')
6956 p++;
6957 blk->len = p - blk->pattern;
6958 p++;
6960 blk->pattern = p;
6961 blk->len = q - blk->pattern;
6963 /* Setup a table for the Boyer-Moore string search. */
6964 for (blk = pat->blocks; blk < pat->blocks + nblocks; blk++)
6965 if (blk->len != 0)
6967 blk->last_char = blk->pattern[blk->len - 1];
6968 blk->pattern[blk->len - 1] = '\0';
6970 for (skip = 1; skip < blk->len; skip++)
6971 if (blk->pattern[blk->len - skip - 1] == '?')
6972 break;
6974 for (i = 0; i < 256; i++)
6975 blk->skip[i] = skip;
6977 p = blk->pattern + (blk->len - skip);
6978 while (--skip > 0)
6979 blk->skip[*p++] = skip;
6981 blk->last_char_skip = blk->skip[blk->last_char];
6984 return pat;
6987 static INLINE int
6988 xlfdpat_exact_p (pat)
6989 struct xlfdpat *pat;
6991 return pat->blocks == NULL;
6994 /* Return the first string in STRING + 0, ..., STRING + START_MAX such
6995 that the pattern in *BLK matches with its prefix. Return NULL
6996 there is no such strings. STRING must be lowered in advance. */
6998 static const char *
6999 xlfdpat_block_match_1 (blk, string, start_max)
7000 struct xlfdpat_block *blk;
7001 const unsigned char *string;
7002 int start_max;
7004 int start, infinity;
7005 unsigned char *p;
7006 const unsigned char *s;
7008 xassert (blk->len > 0);
7009 xassert (start_max + blk->len <= strlen (string));
7010 xassert (blk->last_char != '?');
7012 /* See the comments in the function `boyer_moore' (search.c) for the
7013 use of `infinity'. */
7014 infinity = start_max + blk->len + 1;
7015 blk->skip[blk->last_char] = infinity;
7017 start = 0;
7020 /* Check the last character of the pattern. */
7021 s = string + blk->len - 1;
7024 start += blk->skip[*(s + start)];
7026 while (start <= start_max);
7028 if (start < infinity)
7029 /* Couldn't find the last character. */
7030 return NULL;
7032 /* No less than `infinity' means we could find the last
7033 character at `s[start - infinity]'. */
7034 start -= infinity;
7036 /* Check the remaining characters. We prefer making no-'?'
7037 cases faster because the use of '?' is really rare. */
7038 p = blk->pattern;
7039 s = string + start;
7042 while (*p++ == *s++)
7045 while (*(p - 1) == '?');
7047 if (*(p - 1) == '\0')
7048 /* Matched. */
7049 return string + start;
7051 /* Didn't match. */
7052 start += blk->last_char_skip;
7054 while (start <= start_max);
7056 return NULL;
7059 #define xlfdpat_block_match(b, s, m) \
7060 ((b)->len == 1 ? memchr ((s), (b)->last_char, (m) + 1) \
7061 : xlfdpat_block_match_1 (b, s, m))
7063 /* Check if XLFD pattern PAT, which is generated by `xlfdpat_create',
7064 matches with STRING. STRING must be lowered in advance. */
7066 static int
7067 xlfdpat_match (pat, string)
7068 struct xlfdpat *pat;
7069 const unsigned char *string;
7071 int str_len, nblocks, i, start_max;
7072 struct xlfdpat_block *blk;
7073 const unsigned char *s;
7075 xassert (pat->nblocks > 0);
7077 if (xlfdpat_exact_p (pat))
7078 return strcmp (pat->buf, string) == 0;
7080 /* The number of the characters in the string must not be smaller
7081 than that in the pattern. */
7082 str_len = strlen (string);
7083 if (str_len < pat->nchars + pat->trailing_anychars)
7084 return 0;
7086 /* Chop off the trailing '?'s. */
7087 str_len -= pat->trailing_anychars;
7089 /* The last block. When it is non-empty, it must match at the end
7090 of the string. */
7091 nblocks = pat->nblocks;
7092 blk = pat->blocks + (nblocks - 1);
7093 if (nblocks == 1)
7094 /* The last block is also the first one. */
7095 return (str_len == blk->len
7096 && (blk->len == 0 || xlfdpat_block_match (blk, string, 0)));
7097 else if (blk->len != 0)
7098 if (!xlfdpat_block_match (blk, string + (str_len - blk->len), 0))
7099 return 0;
7101 /* The first block. When it is non-empty, it must match at the
7102 beginning of the string. */
7103 blk = pat->blocks;
7104 if (blk->len != 0)
7106 s = xlfdpat_block_match (blk, string, 0);
7107 if (s == NULL)
7108 return 0;
7109 string = s + blk->len;
7112 /* The rest of the blocks. */
7113 start_max = str_len - pat->nchars;
7114 for (i = 1, blk++; i < nblocks - 1; i++, blk++)
7116 s = xlfdpat_block_match (blk, string, start_max);
7117 if (s == NULL)
7118 return 0;
7119 start_max -= s - string;
7120 string = s + blk->len;
7123 return 1;
7127 /***********************************************************************
7128 Fonts
7129 ***********************************************************************/
7131 /* Return a pointer to struct font_info of font FONT_IDX of frame F. */
7133 struct font_info *
7134 x_get_font_info (f, font_idx)
7135 FRAME_PTR f;
7136 int font_idx;
7138 return (FRAME_MAC_FONT_TABLE (f) + font_idx);
7141 /* the global font name table */
7142 static char **font_name_table = NULL;
7143 static int font_name_table_size = 0;
7144 static int font_name_count = 0;
7146 /* Alist linking font family names to Font Manager font family
7147 references (which can also be used as QuickDraw font IDs). We use
7148 an alist because hash tables are not ready when the terminal frame
7149 for Mac OS Classic is created. */
7150 static Lisp_Object fm_font_family_alist;
7151 #if USE_ATSUI
7152 /* Hash table linking font family names to ATSU font IDs. */
7153 static Lisp_Object atsu_font_id_hash;
7154 /* Alist linking Font Manager style to face attributes. */
7155 static Lisp_Object fm_style_face_attributes_alist;
7156 extern Lisp_Object QCfamily, QCweight, QCslant, Qnormal, Qbold, Qitalic;
7157 #endif
7159 /* Alist linking character set strings to Mac text encoding and Emacs
7160 coding system. */
7161 static Lisp_Object Vmac_charset_info_alist;
7163 static Lisp_Object
7164 create_text_encoding_info_alist ()
7166 Lisp_Object result = Qnil, rest;
7168 for (rest = Vmac_charset_info_alist; CONSP (rest); rest = XCDR (rest))
7170 Lisp_Object charset_info = XCAR (rest);
7171 Lisp_Object charset, coding_system, text_encoding;
7172 Lisp_Object existing_info;
7174 if (!(CONSP (charset_info)
7175 && STRINGP (charset = XCAR (charset_info))
7176 && CONSP (XCDR (charset_info))
7177 && INTEGERP (text_encoding = XCAR (XCDR (charset_info)))
7178 && CONSP (XCDR (XCDR (charset_info)))
7179 && SYMBOLP (coding_system = XCAR (XCDR (XCDR (charset_info))))))
7180 continue;
7182 existing_info = assq_no_quit (text_encoding, result);
7183 if (NILP (existing_info))
7184 result = Fcons (list3 (text_encoding, coding_system, charset),
7185 result);
7186 else
7187 if (NILP (Fmember (charset, XCDR (XCDR (existing_info)))))
7188 XSETCDR (XCDR (existing_info),
7189 Fcons (charset, XCDR (XCDR (existing_info))));
7192 return result;
7196 static void
7197 decode_mac_font_name (name, size, coding_system)
7198 char *name;
7199 int size;
7200 Lisp_Object coding_system;
7202 struct coding_system coding;
7203 char *buf, *p;
7205 if (!NILP (coding_system) && !NILP (Fcoding_system_p (coding_system)))
7207 for (p = name; *p; p++)
7208 if (!isascii (*p) || iscntrl (*p))
7209 break;
7211 if (*p)
7213 setup_coding_system (coding_system, &coding);
7214 coding.src_multibyte = 0;
7215 coding.dst_multibyte = 1;
7216 coding.mode |= CODING_MODE_LAST_BLOCK;
7217 coding.composing = COMPOSITION_DISABLED;
7218 buf = (char *) alloca (size);
7220 decode_coding (&coding, name, buf, strlen (name), size - 1);
7221 bcopy (buf, name, coding.produced);
7222 name[coding.produced] = '\0';
7226 /* If there's just one occurrence of '-' in the family name, it is
7227 replaced with '_'. (More than one occurrence of '-' means a
7228 "FOUNDRY-FAMILY-CHARSET"-style name.) */
7229 p = strchr (name, '-');
7230 if (p && strchr (p + 1, '-') == NULL)
7231 *p = '_';
7233 for (p = name; *p; p++)
7234 /* On Mac OS X 10.3, tolower also converts non-ASCII characters
7235 for some locales. */
7236 if (isascii (*p))
7237 *p = tolower (*p);
7241 static char *
7242 mac_to_x_fontname (name, size, style, charset)
7243 const char *name;
7244 int size;
7245 Style style;
7246 char *charset;
7248 Str31 foundry, cs;
7249 Str255 family;
7250 char xf[256], *result;
7251 unsigned char *p;
7253 if (sscanf (name, "%31[^-]-%255[^-]-%31s", foundry, family, cs) == 3)
7254 charset = cs;
7255 else
7257 strcpy(foundry, "Apple");
7258 strcpy(family, name);
7261 sprintf (xf, "%s-%c-normal--%d-%d-%d-%d-m-%d-%s",
7262 style & bold ? "bold" : "medium", style & italic ? 'i' : 'r',
7263 size, size * 10, size ? 72 : 0, size ? 72 : 0, size * 10, charset);
7265 result = xmalloc (strlen (foundry) + strlen (family) + strlen (xf) + 3 + 1);
7266 sprintf (result, "-%s-%s-%s", foundry, family, xf);
7267 for (p = result; *p; p++)
7268 /* On Mac OS X 10.3, tolower also converts non-ASCII characters
7269 for some locales. */
7270 if (isascii (*p))
7271 *p = tolower (*p);
7272 return result;
7276 /* Parse fully-specified and instantiated X11 font spec XF, and store
7277 the results to FAMILY, *SIZE, *STYLE, and CHARSET. Return 1 if the
7278 parsing succeeded, and 0 otherwise. For FAMILY and CHARSET, the
7279 caller must allocate at least 256 and 32 bytes respectively. For
7280 ordinary Mac fonts, the value stored to FAMILY should just be their
7281 names, like "monaco", "Taipei", etc. Fonts converted from the GNU
7282 intlfonts collection contain their charset designation in their
7283 names, like "ETL-Fixed-iso8859-1", "ETL-Fixed-koi8-r", etc. Both
7284 types of font names are handled accordingly. */
7286 const int kDefaultFontSize = 12;
7288 static int
7289 parse_x_font_name (xf, family, size, style, charset)
7290 const char *xf;
7291 char *family;
7292 int *size;
7293 Style *style;
7294 char *charset;
7296 Str31 foundry, weight;
7297 int point_size, avgwidth;
7298 char slant[2], *p;
7300 if (sscanf (xf, "-%31[^-]-%255[^-]-%31[^-]-%1[^-]-%*[^-]-%*[^-]-%d-%d-%*[^-]-%*[^-]-%*c-%d-%31s",
7301 foundry, family, weight, slant, size,
7302 &point_size, &avgwidth, charset) != 8
7303 && sscanf (xf, "-%31[^-]-%255[^-]-%31[^-]-%1[^-]-%*[^-]--%d-%d-%*[^-]-%*[^-]-%*c-%d-%31s",
7304 foundry, family, weight, slant, size,
7305 &point_size, &avgwidth, charset) != 8)
7306 return 0;
7308 if (*size == 0)
7310 if (point_size > 0)
7311 *size = point_size / 10;
7312 else if (avgwidth > 0)
7313 *size = avgwidth / 10;
7315 if (*size == 0)
7316 *size = kDefaultFontSize;
7318 *style = normal;
7319 if (strcmp (weight, "bold") == 0)
7320 *style |= bold;
7321 if (*slant == 'i')
7322 *style |= italic;
7324 if (NILP (Fassoc (build_string (charset), Vmac_charset_info_alist)))
7326 int foundry_len = strlen (foundry), family_len = strlen (family);
7328 if (foundry_len + family_len + strlen (charset) + 2 < sizeof (Str255))
7330 /* Like sprintf (family, "%s-%s-%s", foundry, family, charset),
7331 but take overlap into account. */
7332 memmove (family + foundry_len + 1, family, family_len);
7333 memcpy (family, foundry, foundry_len);
7334 family[foundry_len] = '-';
7335 family[foundry_len + 1 + family_len] = '-';
7336 strcpy (family + foundry_len + 1 + family_len + 1, charset);
7338 else
7339 return 0;
7342 for (p = family; *p; p++)
7343 /* On Mac OS X 10.3, tolower also converts non-ASCII characters
7344 for some locales. */
7345 if (isascii (*p))
7346 *p = tolower (*p);
7348 return 1;
7352 static void
7353 add_font_name_table_entry (char *font_name)
7355 if (font_name_table_size == 0)
7357 font_name_table_size = 256;
7358 font_name_table = (char **)
7359 xmalloc (font_name_table_size * sizeof (char *));
7361 else if (font_name_count + 1 >= font_name_table_size)
7363 font_name_table_size *= 2;
7364 font_name_table = (char **)
7365 xrealloc (font_name_table,
7366 font_name_table_size * sizeof (char *));
7369 font_name_table[font_name_count++] = font_name;
7372 static void
7373 add_mac_font_name (name, size, style, charset)
7374 const char *name;
7375 int size;
7376 Style style;
7377 const char *charset;
7379 if (size > 0)
7380 add_font_name_table_entry (mac_to_x_fontname (name, size, style, charset));
7381 else
7383 add_font_name_table_entry (mac_to_x_fontname (name, 0, style, charset));
7384 add_font_name_table_entry (mac_to_x_fontname (name, 0, italic, charset));
7385 add_font_name_table_entry (mac_to_x_fontname (name, 0, bold, charset));
7386 add_font_name_table_entry (mac_to_x_fontname (name, 0, italic | bold,
7387 charset));
7391 #if USE_ATSUI
7392 static FMFontStyle
7393 fm_get_style_from_font (font)
7394 FMFont font;
7396 OSStatus err;
7397 FMFontStyle style = normal;
7398 ByteCount len;
7399 UInt16 mac_style;
7400 FMFontFamily font_family;
7401 #define FONT_HEADER_MAC_STYLE_OFFSET (4*4 + 2*2 + 8*2 + 2*4)
7403 /* FMGetFontFamilyInstanceFromFont returns `normal' as the style of
7404 some font (e.g., Optima) even if it is `bold'. */
7405 err = FMGetFontTable (font, 'head', FONT_HEADER_MAC_STYLE_OFFSET,
7406 sizeof (mac_style), &mac_style, &len);
7407 if (err == noErr
7408 && len >= FONT_HEADER_MAC_STYLE_OFFSET + sizeof (mac_style))
7409 style = EndianU16_BtoN (mac_style);
7410 else
7411 FMGetFontFamilyInstanceFromFont (font, &font_family, &style);
7413 return style;
7416 static ATSUFontID
7417 atsu_find_font_from_family_name (family)
7418 const char *family;
7420 struct Lisp_Hash_Table *h = XHASH_TABLE (atsu_font_id_hash);
7421 unsigned hash_code;
7422 int i;
7423 Lisp_Object rest, best;
7424 FMFontStyle min_style, style;
7426 i = hash_lookup (h, make_unibyte_string (family, strlen (family)),
7427 &hash_code);
7428 if (i < 0)
7429 return kATSUInvalidFontID;
7431 rest = HASH_VALUE (h, i);
7432 if (INTEGERP (rest) || (CONSP (rest) && INTEGERP (XCDR (rest))))
7433 return cons_to_long (rest);
7435 rest = Fnreverse (rest);
7436 best = XCAR (rest);
7437 rest = XCDR (rest);
7438 if (!NILP (rest)
7439 && (min_style = fm_get_style_from_font (cons_to_long (best))) != normal)
7442 style = fm_get_style_from_font (cons_to_long (XCAR (rest)));
7443 if (style < min_style)
7445 best = XCAR (rest);
7446 if (style == normal)
7447 break;
7448 else
7449 min_style = style;
7451 rest = XCDR (rest);
7453 while (!NILP (rest));
7455 HASH_VALUE (h, i) = best;
7456 return cons_to_long (best);
7459 static Lisp_Object
7460 fm_style_to_face_attributes (fm_style)
7461 FMFontStyle fm_style;
7463 Lisp_Object tem;
7465 fm_style &= (bold | italic);
7466 tem = assq_no_quit (make_number (fm_style),
7467 fm_style_face_attributes_alist);
7468 if (!NILP (tem))
7469 return XCDR (tem);
7471 tem = list4 (QCweight, fm_style & bold ? Qbold : Qnormal,
7472 QCslant, fm_style & italic ? Qitalic : Qnormal);
7473 fm_style_face_attributes_alist =
7474 Fcons (Fcons (make_number (fm_style), tem),
7475 fm_style_face_attributes_alist);
7477 return tem;
7480 static Lisp_Object
7481 atsu_find_font_family_name (font_id)
7482 ATSUFontID font_id;
7484 OSStatus err;
7485 ByteCount len;
7486 Lisp_Object family = Qnil;
7488 err = ATSUFindFontName (font_id, kFontFamilyName,
7489 kFontMacintoshPlatform, kFontNoScript,
7490 kFontNoLanguage, 0, NULL, &len, NULL);
7491 if (err == noErr)
7493 family = make_uninit_string (len);
7494 err = ATSUFindFontName (font_id, kFontFamilyName,
7495 kFontMacintoshPlatform, kFontNoScript,
7496 kFontNoLanguage, len, SDATA (family),
7497 NULL, NULL);
7499 if (err == noErr)
7500 decode_mac_font_name (SDATA (family), len + 1, Qnil);
7502 return family;
7505 Lisp_Object
7506 mac_atsu_font_face_attributes (font_id)
7507 ATSUFontID font_id;
7509 Lisp_Object family, style_attrs;
7511 family = atsu_find_font_family_name (font_id);
7512 if (NILP (family))
7513 return Qnil;
7514 style_attrs = fm_style_to_face_attributes (fm_get_style_from_font (font_id));
7515 return Fcons (QCfamily, Fcons (family, style_attrs));
7517 #endif
7519 /* Sets up the table font_name_table to contain the list of all fonts
7520 in the system the first time the table is used so that the Resource
7521 Manager need not be accessed every time this information is
7522 needed. */
7524 static void
7525 init_font_name_table ()
7527 #if TARGET_API_MAC_CARBON
7528 FMFontFamilyIterator ffi;
7529 FMFontFamilyInstanceIterator ffii;
7530 FMFontFamily ff;
7531 Lisp_Object text_encoding_info_alist;
7532 struct gcpro gcpro1;
7534 text_encoding_info_alist = create_text_encoding_info_alist ();
7536 #if USE_ATSUI
7537 #if USE_CG_TEXT_DRAWING
7538 init_cg_text_anti_aliasing_threshold ();
7539 #endif
7540 if (!NILP (assq_no_quit (make_number (kTextEncodingMacUnicode),
7541 text_encoding_info_alist)))
7543 OSStatus err;
7544 struct Lisp_Hash_Table *h;
7545 unsigned hash_code;
7546 ItemCount nfonts, i;
7547 ATSUFontID *font_ids = NULL;
7548 Lisp_Object prev_family = Qnil;
7549 int j;
7551 atsu_font_id_hash =
7552 make_hash_table (Qequal, make_number (DEFAULT_HASH_SIZE),
7553 make_float (DEFAULT_REHASH_SIZE),
7554 make_float (DEFAULT_REHASH_THRESHOLD),
7555 Qnil, Qnil, Qnil);;
7556 h = XHASH_TABLE (atsu_font_id_hash);
7558 err = ATSUFontCount (&nfonts);
7559 if (err == noErr)
7561 font_ids = xmalloc (sizeof (ATSUFontID) * nfonts);
7562 err = ATSUGetFontIDs (font_ids, nfonts, NULL);
7564 if (err == noErr)
7565 for (i = 0; i < nfonts; i++)
7567 Lisp_Object family;
7569 family = atsu_find_font_family_name (font_ids[i]);
7570 if (NILP (family) || SREF (family, 0) == '.')
7571 continue;
7572 if (!NILP (Fequal (prev_family, family)))
7573 family = prev_family;
7574 else
7575 j = hash_lookup (h, family, &hash_code);
7576 if (j < 0)
7578 add_mac_font_name (SDATA (family), 0, normal, "iso10646-1");
7579 j = hash_put (h, family, Fcons (long_to_cons (font_ids[i]),
7580 Qnil), hash_code);
7582 else if (EQ (prev_family, family))
7583 HASH_VALUE (h, j) = Fcons (long_to_cons (font_ids[i]),
7584 HASH_VALUE (h, j));
7585 prev_family = family;
7587 if (font_ids)
7588 xfree (font_ids);
7590 #endif
7592 /* Create a dummy instance iterator here to avoid creating and
7593 destroying it in the loop. */
7594 if (FMCreateFontFamilyInstanceIterator (0, &ffii) != noErr)
7595 return;
7596 /* Create an iterator to enumerate the font families. */
7597 if (FMCreateFontFamilyIterator (NULL, NULL, kFMDefaultOptions, &ffi)
7598 != noErr)
7600 FMDisposeFontFamilyInstanceIterator (&ffii);
7601 return;
7604 GCPRO1 (text_encoding_info_alist);
7606 while (FMGetNextFontFamily (&ffi, &ff) == noErr)
7608 Str255 name;
7609 FMFont font;
7610 FMFontStyle style;
7611 FMFontSize size;
7612 TextEncoding encoding;
7613 TextEncodingBase sc;
7614 Lisp_Object text_encoding_info, family;
7616 if (FMGetFontFamilyName (ff, name) != noErr)
7617 continue;
7618 p2cstr (name);
7619 if (*name == '.')
7620 continue;
7622 if (FMGetFontFamilyTextEncoding (ff, &encoding) != noErr)
7623 continue;
7624 sc = GetTextEncodingBase (encoding);
7625 text_encoding_info = assq_no_quit (make_number (sc),
7626 text_encoding_info_alist);
7627 if (NILP (text_encoding_info))
7628 text_encoding_info = assq_no_quit (make_number (kTextEncodingMacRoman),
7629 text_encoding_info_alist);
7630 decode_mac_font_name (name, sizeof (name),
7631 XCAR (XCDR (text_encoding_info)));
7632 family = build_string (name);
7633 if (!NILP (Fassoc (family, fm_font_family_alist)))
7634 continue;
7635 fm_font_family_alist = Fcons (Fcons (family, make_number (ff)),
7636 fm_font_family_alist);
7638 /* Point the instance iterator at the current font family. */
7639 if (FMResetFontFamilyInstanceIterator (ff, &ffii) != noErr)
7640 continue;
7642 while (FMGetNextFontFamilyInstance (&ffii, &font, &style, &size)
7643 == noErr)
7645 Lisp_Object rest = XCDR (XCDR (text_encoding_info));
7647 if (size > 0 || style == normal)
7648 for (; !NILP (rest); rest = XCDR (rest))
7649 add_mac_font_name (name, size, style, SDATA (XCAR (rest)));
7653 UNGCPRO;
7655 /* Dispose of the iterators. */
7656 FMDisposeFontFamilyIterator (&ffi);
7657 FMDisposeFontFamilyInstanceIterator (&ffii);
7658 #else /* !TARGET_API_MAC_CARBON */
7659 GrafPtr port;
7660 SInt16 fontnum, old_fontnum;
7661 int num_mac_fonts = CountResources('FOND');
7662 int i, j;
7663 Handle font_handle, font_handle_2;
7664 short id, scriptcode;
7665 ResType type;
7666 Str255 name;
7667 struct FontAssoc *fat;
7668 struct AsscEntry *assc_entry;
7669 Lisp_Object text_encoding_info_alist, text_encoding_info, family;
7670 struct gcpro gcpro1;
7672 GetPort (&port); /* save the current font number used */
7673 old_fontnum = port->txFont;
7675 text_encoding_info_alist = create_text_encoding_info_alist ();
7677 GCPRO1 (text_encoding_info_alist);
7679 for (i = 1; i <= num_mac_fonts; i++) /* get all available fonts */
7681 font_handle = GetIndResource ('FOND', i);
7682 if (!font_handle)
7683 continue;
7685 GetResInfo (font_handle, &id, &type, name);
7686 GetFNum (name, &fontnum);
7687 p2cstr (name);
7688 if (fontnum == 0 || *name == '.')
7689 continue;
7691 TextFont (fontnum);
7692 scriptcode = FontToScript (fontnum);
7693 text_encoding_info = assq_no_quit (make_number (scriptcode),
7694 text_encoding_info_alist);
7695 if (NILP (text_encoding_info))
7696 text_encoding_info = assq_no_quit (make_number (smRoman),
7697 text_encoding_info_alist);
7698 decode_mac_font_name (name, sizeof (name),
7699 XCAR (XCDR (text_encoding_info)));
7700 family = build_string (name);
7701 if (!NILP (Fassoc (family, fm_font_family_alist)))
7702 continue;
7703 fm_font_family_alist = Fcons (Fcons (family, make_number (fontnum)),
7704 fm_font_family_alist);
7707 HLock (font_handle);
7709 if (GetResourceSizeOnDisk (font_handle)
7710 >= sizeof (struct FamRec))
7712 fat = (struct FontAssoc *) (*font_handle
7713 + sizeof (struct FamRec));
7714 assc_entry
7715 = (struct AsscEntry *) (*font_handle
7716 + sizeof (struct FamRec)
7717 + sizeof (struct FontAssoc));
7719 for (j = 0; j <= fat->numAssoc; j++, assc_entry++)
7721 Lisp_Object rest = XCDR (XCDR (text_encoding_info));
7723 for (; !NILP (rest); rest = XCDR (rest))
7724 add_mac_font_name (name, assc_entry->fontSize,
7725 assc_entry->fontStyle,
7726 SDATA (XCAR (rest)));
7730 HUnlock (font_handle);
7731 font_handle_2 = GetNextFOND (font_handle);
7732 ReleaseResource (font_handle);
7733 font_handle = font_handle_2;
7735 while (ResError () == noErr && font_handle);
7738 UNGCPRO;
7740 TextFont (old_fontnum);
7741 #endif /* !TARGET_API_MAC_CARBON */
7745 void
7746 mac_clear_font_name_table ()
7748 int i;
7750 for (i = 0; i < font_name_count; i++)
7751 xfree (font_name_table[i]);
7752 xfree (font_name_table);
7753 font_name_table = NULL;
7754 font_name_table_size = font_name_count = 0;
7755 fm_font_family_alist = Qnil;
7759 enum xlfd_scalable_field_index
7761 XLFD_SCL_PIXEL_SIZE,
7762 XLFD_SCL_POINT_SIZE,
7763 XLFD_SCL_AVGWIDTH,
7764 XLFD_SCL_LAST
7767 static const int xlfd_scalable_fields[] =
7769 6, /* PIXEL_SIZE */
7770 7, /* POINT_SIZE */
7771 11, /* AVGWIDTH */
7775 static Lisp_Object
7776 mac_do_list_fonts (pattern, maxnames)
7777 const char *pattern;
7778 int maxnames;
7780 int i, n_fonts = 0;
7781 Lisp_Object font_list = Qnil;
7782 struct xlfdpat *pat;
7783 char *scaled;
7784 const char *ptr;
7785 int scl_val[XLFD_SCL_LAST], *val;
7786 const int *field;
7787 int exact;
7789 if (font_name_table == NULL) /* Initialize when first used. */
7790 init_font_name_table ();
7792 for (i = 0; i < XLFD_SCL_LAST; i++)
7793 scl_val[i] = -1;
7795 /* If the pattern contains 14 dashes and one of PIXEL_SIZE,
7796 POINT_SIZE, and AVGWIDTH fields is explicitly specified, scalable
7797 fonts are scaled according to the specified size. */
7798 ptr = pattern;
7799 i = 0;
7800 field = xlfd_scalable_fields;
7801 val = scl_val;
7802 if (*ptr == '-')
7805 ptr++;
7806 if (i == *field)
7808 if ('0' <= *ptr && *ptr <= '9')
7810 *val = *ptr++ - '0';
7811 while ('0' <= *ptr && *ptr <= '9' && *val < 10000)
7812 *val = *val * 10 + *ptr++ - '0';
7813 if (*ptr != '-')
7814 *val = -1;
7816 field++;
7817 val++;
7819 ptr = strchr (ptr, '-');
7820 i++;
7822 while (ptr && i < 14);
7824 if (i == 14 && ptr == NULL)
7826 if (scl_val[XLFD_SCL_PIXEL_SIZE] < 0)
7827 scl_val[XLFD_SCL_PIXEL_SIZE] =
7828 (scl_val[XLFD_SCL_POINT_SIZE] > 0 ? scl_val[XLFD_SCL_POINT_SIZE] / 10
7829 : (scl_val[XLFD_SCL_AVGWIDTH] > 0 ? scl_val[XLFD_SCL_AVGWIDTH] / 10
7830 : -1));
7831 if (scl_val[XLFD_SCL_POINT_SIZE] < 0)
7832 scl_val[XLFD_SCL_POINT_SIZE] =
7833 (scl_val[XLFD_SCL_PIXEL_SIZE] > 0 ? scl_val[XLFD_SCL_PIXEL_SIZE] * 10
7834 : (scl_val[XLFD_SCL_AVGWIDTH] > 0 ? scl_val[XLFD_SCL_AVGWIDTH]
7835 : -1));
7836 if (scl_val[XLFD_SCL_AVGWIDTH] < 0)
7837 scl_val[XLFD_SCL_AVGWIDTH] =
7838 (scl_val[XLFD_SCL_PIXEL_SIZE] > 0 ? scl_val[XLFD_SCL_PIXEL_SIZE] * 10
7839 : (scl_val[XLFD_SCL_POINT_SIZE] > 0 ? scl_val[XLFD_SCL_POINT_SIZE]
7840 : -1));
7842 else
7843 scl_val[XLFD_SCL_PIXEL_SIZE] = -1;
7845 pat = xlfdpat_create (pattern);
7846 if (pat == NULL)
7847 return Qnil;
7849 exact = xlfdpat_exact_p (pat);
7851 for (i = 0; i < font_name_count; i++)
7853 if (xlfdpat_match (pat, font_name_table[i]))
7855 font_list = Fcons (build_string (font_name_table[i]), font_list);
7856 if (exact || (maxnames > 0 && ++n_fonts >= maxnames))
7857 break;
7859 else if (scl_val[XLFD_SCL_PIXEL_SIZE] > 0
7860 && (ptr = strstr (font_name_table[i], "-0-0-0-0-m-0-")))
7862 int former_len = ptr - font_name_table[i];
7864 scaled = xmalloc (strlen (font_name_table[i]) + 20 + 1);
7865 memcpy (scaled, font_name_table[i], former_len);
7866 sprintf (scaled + former_len,
7867 "-%d-%d-72-72-m-%d-%s",
7868 scl_val[XLFD_SCL_PIXEL_SIZE],
7869 scl_val[XLFD_SCL_POINT_SIZE],
7870 scl_val[XLFD_SCL_AVGWIDTH],
7871 ptr + sizeof ("-0-0-0-0-m-0-") - 1);
7873 if (xlfdpat_match (pat, scaled))
7875 font_list = Fcons (build_string (scaled), font_list);
7876 xfree (scaled);
7877 if (exact || (maxnames > 0 && ++n_fonts >= maxnames))
7878 break;
7880 else
7881 xfree (scaled);
7885 xlfdpat_destroy (pat);
7887 return font_list;
7890 /* Return a list of names of available fonts matching PATTERN on frame F.
7892 Frame F null means we have not yet created any frame on Mac, and
7893 consult the first display in x_display_list. MAXNAMES sets a limit
7894 on how many fonts to match. */
7896 Lisp_Object
7897 x_list_fonts (f, pattern, size, maxnames)
7898 struct frame *f;
7899 Lisp_Object pattern;
7900 int size, maxnames;
7902 Lisp_Object list = Qnil, patterns, tem, key;
7903 struct mac_display_info *dpyinfo
7904 = f ? FRAME_MAC_DISPLAY_INFO (f) : x_display_list;
7906 xassert (size <= 0);
7908 patterns = Fassoc (pattern, Valternate_fontname_alist);
7909 if (NILP (patterns))
7910 patterns = Fcons (pattern, Qnil);
7912 for (; CONSP (patterns); patterns = XCDR (patterns))
7914 pattern = XCAR (patterns);
7916 if (!STRINGP (pattern))
7917 continue;
7919 tem = XCAR (XCDR (dpyinfo->name_list_element));
7920 key = Fcons (pattern, make_number (maxnames));
7922 list = Fassoc (key, tem);
7923 if (!NILP (list))
7925 list = Fcdr_safe (list);
7926 /* We have a cashed list. Don't have to get the list again. */
7927 goto label_cached;
7930 BLOCK_INPUT;
7931 list = mac_do_list_fonts (SDATA (pattern), maxnames);
7932 UNBLOCK_INPUT;
7934 /* MAC_TODO: add code for matching outline fonts here */
7936 /* Now store the result in the cache. */
7937 XSETCAR (XCDR (dpyinfo->name_list_element),
7938 Fcons (Fcons (key, list),
7939 XCAR (XCDR (dpyinfo->name_list_element))));
7941 label_cached:
7942 if (NILP (list)) continue; /* Try the remaining alternatives. */
7945 return list;
7949 #if GLYPH_DEBUG
7951 /* Check that FONT is valid on frame F. It is if it can be found in F's
7952 font table. */
7954 static void
7955 x_check_font (f, font)
7956 struct frame *f;
7957 XFontStruct *font;
7959 int i;
7960 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
7962 xassert (font != NULL);
7964 for (i = 0; i < dpyinfo->n_fonts; i++)
7965 if (dpyinfo->font_table[i].name
7966 && font == dpyinfo->font_table[i].font)
7967 break;
7969 xassert (i < dpyinfo->n_fonts);
7972 #endif /* GLYPH_DEBUG != 0 */
7974 /* Set *W to the minimum width, *H to the minimum font height of FONT.
7975 Note: There are (broken) X fonts out there with invalid XFontStruct
7976 min_bounds contents. For example, handa@etl.go.jp reports that
7977 "-adobe-courier-medium-r-normal--*-180-*-*-m-*-iso8859-1" fonts
7978 have font->min_bounds.width == 0. */
7980 static INLINE void
7981 x_font_min_bounds (font, w, h)
7982 MacFontStruct *font;
7983 int *w, *h;
7985 *h = FONT_HEIGHT (font);
7986 *w = font->min_bounds.width;
7990 /* Compute the smallest character width and smallest font height over
7991 all fonts available on frame F. Set the members smallest_char_width
7992 and smallest_font_height in F's x_display_info structure to
7993 the values computed. Value is non-zero if smallest_font_height or
7994 smallest_char_width become smaller than they were before. */
7996 static int
7997 x_compute_min_glyph_bounds (f)
7998 struct frame *f;
8000 int i;
8001 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
8002 MacFontStruct *font;
8003 int old_width = dpyinfo->smallest_char_width;
8004 int old_height = dpyinfo->smallest_font_height;
8006 dpyinfo->smallest_font_height = 100000;
8007 dpyinfo->smallest_char_width = 100000;
8009 for (i = 0; i < dpyinfo->n_fonts; ++i)
8010 if (dpyinfo->font_table[i].name)
8012 struct font_info *fontp = dpyinfo->font_table + i;
8013 int w, h;
8015 font = (MacFontStruct *) fontp->font;
8016 xassert (font != (MacFontStruct *) ~0);
8017 x_font_min_bounds (font, &w, &h);
8019 dpyinfo->smallest_font_height = min (dpyinfo->smallest_font_height, h);
8020 dpyinfo->smallest_char_width = min (dpyinfo->smallest_char_width, w);
8023 xassert (dpyinfo->smallest_char_width > 0
8024 && dpyinfo->smallest_font_height > 0);
8026 return (dpyinfo->n_fonts == 1
8027 || dpyinfo->smallest_char_width < old_width
8028 || dpyinfo->smallest_font_height < old_height);
8032 /* Determine whether given string is a fully-specified XLFD: all 14
8033 fields are present, none is '*'. */
8035 static int
8036 is_fully_specified_xlfd (p)
8037 const char *p;
8039 int i;
8040 char *q;
8042 if (*p != '-')
8043 return 0;
8045 for (i = 0; i < 13; i++)
8047 q = strchr (p + 1, '-');
8048 if (q == NULL)
8049 return 0;
8050 if (q - p == 2 && *(p + 1) == '*')
8051 return 0;
8052 p = q;
8055 if (strchr (p + 1, '-') != NULL)
8056 return 0;
8058 if (*(p + 1) == '*' && *(p + 2) == '\0')
8059 return 0;
8061 return 1;
8065 /* mac_load_query_font creates and returns an internal representation
8066 for a font in a MacFontStruct struct. There is really no concept
8067 corresponding to "loading" a font on the Mac. But we check its
8068 existence and find the font number and all other information for it
8069 and store them in the returned MacFontStruct. */
8071 static MacFontStruct *
8072 mac_load_query_font (f, fontname)
8073 struct frame *f;
8074 char *fontname;
8076 int size;
8077 char *name;
8078 Str255 family;
8079 Str31 charset;
8080 SInt16 fontnum;
8081 #if USE_ATSUI
8082 static ATSUFontID font_id;
8083 ATSUStyle mac_style = NULL;
8084 #endif
8085 Style fontface;
8086 #if TARGET_API_MAC_CARBON
8087 TextEncoding encoding;
8088 int scriptcode;
8089 #else
8090 short scriptcode;
8091 #endif
8092 MacFontStruct *font;
8093 XCharStruct *space_bounds = NULL, *pcm;
8095 if (is_fully_specified_xlfd (fontname))
8096 name = fontname;
8097 else
8099 Lisp_Object matched_fonts;
8101 matched_fonts = mac_do_list_fonts (fontname, 1);
8102 if (NILP (matched_fonts))
8103 return NULL;
8104 name = SDATA (XCAR (matched_fonts));
8107 if (parse_x_font_name (name, family, &size, &fontface, charset) == 0)
8108 return NULL;
8110 #if USE_ATSUI
8111 if (strcmp (charset, "iso10646-1") == 0) /* XXX */
8113 OSStatus err;
8114 static const ATSUAttributeTag tags[] =
8115 {kATSUFontTag, kATSUSizeTag,
8116 kATSUQDBoldfaceTag, kATSUQDItalicTag};
8117 static const ByteCount sizes[] =
8118 {sizeof (ATSUFontID), sizeof (Fixed),
8119 sizeof (Boolean), sizeof (Boolean)};
8120 static Fixed size_fixed;
8121 static Boolean bold_p, italic_p;
8122 static const ATSUAttributeValuePtr values[] =
8123 {&font_id, &size_fixed,
8124 &bold_p, &italic_p};
8125 static const ATSUFontFeatureType types[] =
8126 {kAllTypographicFeaturesType, kDiacriticsType};
8127 static const ATSUFontFeatureSelector selectors[] =
8128 {kAllTypeFeaturesOffSelector, kDecomposeDiacriticsSelector};
8129 FMFontStyle style;
8131 font_id = atsu_find_font_from_family_name (family);
8132 if (font_id == kATSUInvalidFontID)
8133 return;
8134 size_fixed = Long2Fix (size);
8135 bold_p = (fontface & bold) != 0;
8136 italic_p = (fontface & italic) != 0;
8137 err = ATSUCreateStyle (&mac_style);
8138 if (err != noErr)
8139 return NULL;
8140 err = ATSUSetFontFeatures (mac_style, sizeof (types) / sizeof (types[0]),
8141 types, selectors);
8142 if (err != noErr)
8143 return NULL;
8144 err = ATSUSetAttributes (mac_style, sizeof (tags) / sizeof (tags[0]),
8145 tags, sizes, values);
8146 if (err != noErr)
8147 return NULL;
8148 err = FMGetFontFamilyInstanceFromFont (font_id, &fontnum, &style);
8149 if (err != noErr)
8150 fontnum = -1;
8151 scriptcode = kTextEncodingMacUnicode;
8153 else
8154 #endif
8156 Lisp_Object tmp = Fassoc (build_string (family), fm_font_family_alist);
8158 if (NILP (tmp))
8159 return NULL;
8160 fontnum = XINT (XCDR (tmp));
8161 #if TARGET_API_MAC_CARBON
8162 if (FMGetFontFamilyTextEncoding (fontnum, &encoding) != noErr)
8163 return NULL;
8164 scriptcode = GetTextEncodingBase (encoding);
8165 #else
8166 scriptcode = FontToScript (fontnum);
8167 #endif
8170 font = (MacFontStruct *) xmalloc (sizeof (struct MacFontStruct));
8172 font->mac_fontnum = fontnum;
8173 font->mac_fontsize = size;
8174 font->mac_fontface = fontface;
8175 font->mac_scriptcode = scriptcode;
8176 #if USE_ATSUI
8177 font->mac_style = mac_style;
8178 #if USE_CG_TEXT_DRAWING
8179 font->cg_font = NULL;
8180 font->cg_glyphs = NULL;
8181 #endif
8182 #endif
8184 /* Apple Japanese (SJIS) font is listed as both
8185 "*-jisx0208.1983-sjis" (Japanese script) and "*-jisx0201.1976-0"
8186 (Roman script) in init_font_name_table (). The latter should be
8187 treated as a one-byte font. */
8188 if (scriptcode == smJapanese && strcmp (charset, "jisx0201.1976-0") == 0)
8189 font->mac_scriptcode = smRoman;
8191 font->full_name = mac_to_x_fontname (family, size, fontface, charset);
8193 #if USE_ATSUI
8194 if (font->mac_style)
8196 OSStatus err;
8197 UniChar c;
8199 font->min_byte1 = 0;
8200 font->max_byte1 = 0xff;
8201 font->min_char_or_byte2 = 0;
8202 font->max_char_or_byte2 = 0xff;
8204 font->bounds.rows = xmalloc (sizeof (XCharStruct *) * 0x100);
8205 bzero (font->bounds.rows, sizeof (XCharStruct *) * 0x100);
8206 font->bounds.rows[0] = xmalloc (sizeof (XCharStruct) * 0x100);
8207 pcm_init (font->bounds.rows[0], 0x100);
8209 #if USE_CG_TEXT_DRAWING
8210 if (fontnum != -1)
8212 FMFontStyle style;
8213 ATSFontRef ats_font;
8215 err = FMGetFontFromFontFamilyInstance (fontnum, fontface,
8216 &font_id, &style);
8217 /* Use CG text drawing if italic/bold is not synthesized. */
8218 if (err == noErr && style == fontface)
8220 ats_font = FMGetATSFontRefFromFont (font_id);
8221 font->cg_font = CGFontCreateWithPlatformFont (&ats_font);
8225 if (font->cg_font)
8227 font->cg_glyphs = xmalloc (sizeof (CGGlyph) * 0x100);
8228 bzero (font->cg_glyphs, sizeof (CGGlyph) * 0x100);
8230 #endif
8231 space_bounds = font->bounds.rows[0] + 0x20;
8232 err = mac_query_char_extents (font->mac_style, 0x20,
8233 &font->ascent, &font->descent,
8234 space_bounds,
8235 #if USE_CG_TEXT_DRAWING
8236 (font->cg_glyphs ? font->cg_glyphs + 0x20
8237 : NULL)
8238 #else
8239 NULL
8240 #endif
8242 if (err != noErr
8243 || space_bounds->width <= 0 || FONT_HEIGHT (font) <= 0)
8245 mac_unload_font (&one_mac_display_info, font);
8246 return NULL;
8249 pcm = font->bounds.rows[0];
8250 for (c = 0x21; c <= 0xff; c++)
8252 if (c == 0xad)
8253 /* Soft hyphen is not supported in ATSUI. */
8254 continue;
8255 else if (c == 0x7f)
8257 #if USE_CG_TEXT_DRAWING
8258 if (font->cg_glyphs)
8260 c = 0x9f;
8261 pcm = NULL;
8262 continue;
8264 #endif
8265 break;
8268 mac_query_char_extents (font->mac_style, c, NULL, NULL,
8269 pcm ? pcm + c : NULL,
8270 #if USE_CG_TEXT_DRAWING
8271 (font->cg_glyphs ? font->cg_glyphs + c
8272 : NULL)
8273 #else
8274 NULL
8275 #endif
8278 #if USE_CG_TEXT_DRAWING
8279 if (font->cg_glyphs && font->cg_glyphs[c] == 0)
8281 /* Don't use CG text drawing if font substitution occurs in
8282 ASCII or Latin-1 characters. */
8283 CGFontRelease (font->cg_font);
8284 font->cg_font = NULL;
8285 xfree (font->cg_glyphs);
8286 font->cg_glyphs = NULL;
8287 if (pcm == NULL)
8288 break;
8290 #endif
8293 else
8294 #endif
8296 OSStatus err;
8297 FontInfo the_fontinfo;
8298 int is_two_byte_font;
8300 #if USE_CG_DRAWING
8301 mac_prepare_for_quickdraw (f);
8302 #endif
8303 SetPortWindowPort (FRAME_MAC_WINDOW (f));
8305 TextFont (fontnum);
8306 TextSize (size);
8307 TextFace (fontface);
8309 GetFontInfo (&the_fontinfo);
8311 font->ascent = the_fontinfo.ascent;
8312 font->descent = the_fontinfo.descent;
8314 is_two_byte_font = (font->mac_scriptcode == smJapanese
8315 || font->mac_scriptcode == smTradChinese
8316 || font->mac_scriptcode == smSimpChinese
8317 || font->mac_scriptcode == smKorean);
8319 if (is_two_byte_font)
8321 int char_width;
8323 font->min_byte1 = 0xa1;
8324 font->max_byte1 = 0xfe;
8325 font->min_char_or_byte2 = 0xa1;
8326 font->max_char_or_byte2 = 0xfe;
8328 /* Use the width of an "ideographic space" of that font
8329 because the_fontinfo.widMax returns the wrong width for
8330 some fonts. */
8331 switch (font->mac_scriptcode)
8333 case smJapanese:
8334 font->min_byte1 = 0x81;
8335 font->max_byte1 = 0xfc;
8336 font->min_char_or_byte2 = 0x40;
8337 font->max_char_or_byte2 = 0xfc;
8338 char_width = StringWidth("\p\x81\x40");
8339 break;
8340 case smTradChinese:
8341 font->min_char_or_byte2 = 0x40;
8342 char_width = StringWidth("\p\xa1\x40");
8343 break;
8344 case smSimpChinese:
8345 char_width = StringWidth("\p\xa1\xa1");
8346 break;
8347 case smKorean:
8348 char_width = StringWidth("\p\xa1\xa1");
8349 break;
8352 font->bounds.per_char = NULL;
8354 if (fontface & italic)
8355 font->max_bounds.rbearing = char_width + 1;
8356 else
8357 font->max_bounds.rbearing = char_width;
8358 font->max_bounds.lbearing = 0;
8359 font->max_bounds.width = char_width;
8360 font->max_bounds.ascent = the_fontinfo.ascent;
8361 font->max_bounds.descent = the_fontinfo.descent;
8363 font->min_bounds = font->max_bounds;
8365 else
8367 int c;
8369 font->min_byte1 = font->max_byte1 = 0;
8370 font->min_char_or_byte2 = 0x20;
8371 font->max_char_or_byte2 = 0xff;
8373 font->bounds.per_char =
8374 xmalloc (sizeof (XCharStruct) * (0xff - 0x20 + 1));
8375 bzero (font->bounds.per_char,
8376 sizeof (XCharStruct) * (0xff - 0x20 + 1));
8378 space_bounds = font->bounds.per_char;
8379 err = mac_query_char_extents (NULL, 0x20, &font->ascent,
8380 &font->descent, space_bounds, NULL);
8381 if (err != noErr || space_bounds->width <= 0)
8383 mac_unload_font (&one_mac_display_info, font);
8384 return NULL;
8387 for (c = 0x21, pcm = space_bounds + 1; c <= 0xff; c++, pcm++)
8388 mac_query_char_extents (NULL, c, NULL, NULL, pcm, NULL);
8392 if (space_bounds)
8394 int c;
8396 font->min_bounds = font->max_bounds = *space_bounds;
8397 for (c = 0x21, pcm = space_bounds + 1; c <= 0x7f; c++, pcm++)
8398 if (pcm->width > 0)
8400 font->min_bounds.lbearing = min (font->min_bounds.lbearing,
8401 pcm->lbearing);
8402 font->min_bounds.rbearing = min (font->min_bounds.rbearing,
8403 pcm->rbearing);
8404 font->min_bounds.width = min (font->min_bounds.width,
8405 pcm->width);
8406 font->min_bounds.ascent = min (font->min_bounds.ascent,
8407 pcm->ascent);
8408 font->min_bounds.descent = min (font->min_bounds.descent,
8409 pcm->descent);
8411 font->max_bounds.lbearing = max (font->max_bounds.lbearing,
8412 pcm->lbearing);
8413 font->max_bounds.rbearing = max (font->max_bounds.rbearing,
8414 pcm->rbearing);
8415 font->max_bounds.width = max (font->max_bounds.width,
8416 pcm->width);
8417 font->max_bounds.ascent = max (font->max_bounds.ascent,
8418 pcm->ascent);
8419 font->max_bounds.descent = max (font->max_bounds.descent,
8420 pcm->descent);
8422 if (
8423 #if USE_ATSUI
8424 font->mac_style == NULL &&
8425 #endif
8426 font->max_bounds.width == font->min_bounds.width
8427 && font->min_bounds.lbearing >= 0
8428 && font->max_bounds.rbearing <= font->max_bounds.width)
8430 /* Fixed width and no overhangs. */
8431 xfree (font->bounds.per_char);
8432 font->bounds.per_char = NULL;
8436 #if !defined (MAC_OS8) || USE_ATSUI
8437 /* AppKit and WebKit do some adjustment to the heights of Courier,
8438 Helvetica, and Times. This only works on the environments where
8439 srcCopy text transfer mode is never used. */
8440 if (
8441 #ifdef MAC_OS8 /* implies USE_ATSUI */
8442 font->mac_style &&
8443 #endif
8444 (strcmp (family, "courier") == 0 || strcmp (family, "helvetica") == 0
8445 || strcmp (family, "times") == 0))
8446 font->ascent += (font->ascent + font->descent) * .15 + 0.5;
8447 #endif
8449 return font;
8453 void
8454 mac_unload_font (dpyinfo, font)
8455 struct mac_display_info *dpyinfo;
8456 XFontStruct *font;
8458 xfree (font->full_name);
8459 #if USE_ATSUI
8460 if (font->mac_style)
8462 int i;
8464 for (i = font->min_byte1; i <= font->max_byte1; i++)
8465 if (font->bounds.rows[i])
8466 xfree (font->bounds.rows[i]);
8467 xfree (font->bounds.rows);
8468 ATSUDisposeStyle (font->mac_style);
8470 else
8471 #endif
8472 if (font->bounds.per_char)
8473 xfree (font->bounds.per_char);
8474 #if USE_CG_TEXT_DRAWING
8475 if (font->cg_font)
8476 CGFontRelease (font->cg_font);
8477 if (font->cg_glyphs)
8478 xfree (font->cg_glyphs);
8479 #endif
8480 xfree (font);
8484 /* Load font named FONTNAME of the size SIZE for frame F, and return a
8485 pointer to the structure font_info while allocating it dynamically.
8486 If SIZE is 0, load any size of font.
8487 If loading is failed, return NULL. */
8489 struct font_info *
8490 x_load_font (f, fontname, size)
8491 struct frame *f;
8492 register char *fontname;
8493 int size;
8495 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
8496 Lisp_Object font_names;
8498 /* Get a list of all the fonts that match this name. Once we
8499 have a list of matching fonts, we compare them against the fonts
8500 we already have by comparing names. */
8501 font_names = x_list_fonts (f, build_string (fontname), size, 1);
8503 if (!NILP (font_names))
8505 Lisp_Object tail;
8506 int i;
8508 for (i = 0; i < dpyinfo->n_fonts; i++)
8509 for (tail = font_names; CONSP (tail); tail = XCDR (tail))
8510 if (dpyinfo->font_table[i].name
8511 && (!strcmp (dpyinfo->font_table[i].name,
8512 SDATA (XCAR (tail)))
8513 || !strcmp (dpyinfo->font_table[i].full_name,
8514 SDATA (XCAR (tail)))))
8515 return (dpyinfo->font_table + i);
8517 else
8518 return NULL;
8520 /* Load the font and add it to the table. */
8522 struct MacFontStruct *font;
8523 struct font_info *fontp;
8524 int i;
8526 fontname = (char *) SDATA (XCAR (font_names));
8528 BLOCK_INPUT;
8529 font = mac_load_query_font (f, fontname);
8530 UNBLOCK_INPUT;
8531 if (!font)
8532 return NULL;
8534 /* Find a free slot in the font table. */
8535 for (i = 0; i < dpyinfo->n_fonts; ++i)
8536 if (dpyinfo->font_table[i].name == NULL)
8537 break;
8539 /* If no free slot found, maybe enlarge the font table. */
8540 if (i == dpyinfo->n_fonts
8541 && dpyinfo->n_fonts == dpyinfo->font_table_size)
8543 int sz;
8544 dpyinfo->font_table_size = max (16, 2 * dpyinfo->font_table_size);
8545 sz = dpyinfo->font_table_size * sizeof *dpyinfo->font_table;
8546 dpyinfo->font_table
8547 = (struct font_info *) xrealloc (dpyinfo->font_table, sz);
8550 fontp = dpyinfo->font_table + i;
8551 if (i == dpyinfo->n_fonts)
8552 ++dpyinfo->n_fonts;
8554 /* Now fill in the slots of *FONTP. */
8555 BLOCK_INPUT;
8556 bzero (fontp, sizeof (*fontp));
8557 fontp->font = font;
8558 fontp->font_idx = i;
8559 fontp->name = (char *) xmalloc (strlen (fontname) + 1);
8560 bcopy (fontname, fontp->name, strlen (fontname) + 1);
8562 if (font->min_bounds.width == font->max_bounds.width)
8564 /* Fixed width font. */
8565 fontp->average_width = fontp->space_width = font->min_bounds.width;
8567 else
8569 XChar2b char2b;
8570 XCharStruct *pcm;
8572 char2b.byte1 = 0x00, char2b.byte2 = 0x20;
8573 pcm = mac_per_char_metric (font, &char2b, 0);
8574 if (pcm)
8575 fontp->space_width = pcm->width;
8576 else
8577 fontp->space_width = FONT_WIDTH (font);
8579 if (pcm)
8581 int width = pcm->width;
8582 for (char2b.byte2 = 33; char2b.byte2 <= 126; char2b.byte2++)
8583 if ((pcm = mac_per_char_metric (font, &char2b, 0)) != NULL)
8584 width += pcm->width;
8585 fontp->average_width = width / 95;
8587 else
8588 fontp->average_width = FONT_WIDTH (font);
8591 fontp->full_name = (char *) xmalloc (strlen (font->full_name) + 1);
8592 bcopy (font->full_name, fontp->full_name, strlen (font->full_name) + 1);
8594 fontp->size = font->max_bounds.width;
8595 fontp->height = FONT_HEIGHT (font);
8597 /* For some font, ascent and descent in max_bounds field is
8598 larger than the above value. */
8599 int max_height = font->max_bounds.ascent + font->max_bounds.descent;
8600 if (max_height > fontp->height)
8601 fontp->height = max_height;
8604 /* The slot `encoding' specifies how to map a character
8605 code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
8606 the font code-points (0:0x20..0x7F, 1:0xA0..0xFF), or
8607 (0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF,
8608 2:0xA020..0xFF7F). For the moment, we don't know which charset
8609 uses this font. So, we set information in fontp->encoding[1]
8610 which is never used by any charset. If mapping can't be
8611 decided, set FONT_ENCODING_NOT_DECIDED. */
8612 if (font->mac_scriptcode == smJapanese)
8613 fontp->encoding[1] = 4;
8614 else
8616 fontp->encoding[1]
8617 = (font->max_byte1 == 0
8618 /* 1-byte font */
8619 ? (font->min_char_or_byte2 < 0x80
8620 ? (font->max_char_or_byte2 < 0x80
8621 ? 0 /* 0x20..0x7F */
8622 : FONT_ENCODING_NOT_DECIDED) /* 0x20..0xFF */
8623 : 1) /* 0xA0..0xFF */
8624 /* 2-byte font */
8625 : (font->min_byte1 < 0x80
8626 ? (font->max_byte1 < 0x80
8627 ? (font->min_char_or_byte2 < 0x80
8628 ? (font->max_char_or_byte2 < 0x80
8629 ? 0 /* 0x2020..0x7F7F */
8630 : FONT_ENCODING_NOT_DECIDED) /* 0x2020..0x7FFF */
8631 : 3) /* 0x20A0..0x7FFF */
8632 : FONT_ENCODING_NOT_DECIDED) /* 0x20??..0xA0?? */
8633 : (font->min_char_or_byte2 < 0x80
8634 ? (font->max_char_or_byte2 < 0x80
8635 ? 2 /* 0xA020..0xFF7F */
8636 : FONT_ENCODING_NOT_DECIDED) /* 0xA020..0xFFFF */
8637 : 1))); /* 0xA0A0..0xFFFF */
8640 #if 0 /* MAC_TODO: fill these out with more reasonably values */
8641 fontp->baseline_offset
8642 = (XGetFontProperty (font, dpyinfo->Xatom_MULE_BASELINE_OFFSET, &value)
8643 ? (long) value : 0);
8644 fontp->relative_compose
8645 = (XGetFontProperty (font, dpyinfo->Xatom_MULE_RELATIVE_COMPOSE, &value)
8646 ? (long) value : 0);
8647 fontp->default_ascent
8648 = (XGetFontProperty (font, dpyinfo->Xatom_MULE_DEFAULT_ASCENT, &value)
8649 ? (long) value : 0);
8650 #else
8651 fontp->baseline_offset = 0;
8652 fontp->relative_compose = 0;
8653 fontp->default_ascent = 0;
8654 #endif
8656 /* Set global flag fonts_changed_p to non-zero if the font loaded
8657 has a character with a smaller width than any other character
8658 before, or if the font loaded has a smaller height than any
8659 other font loaded before. If this happens, it will make a
8660 glyph matrix reallocation necessary. */
8661 fonts_changed_p |= x_compute_min_glyph_bounds (f);
8662 UNBLOCK_INPUT;
8663 return fontp;
8668 /* Return a pointer to struct font_info of a font named FONTNAME for
8669 frame F. If no such font is loaded, return NULL. */
8671 struct font_info *
8672 x_query_font (f, fontname)
8673 struct frame *f;
8674 register char *fontname;
8676 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
8677 int i;
8679 for (i = 0; i < dpyinfo->n_fonts; i++)
8680 if (dpyinfo->font_table[i].name
8681 && (!xstricmp (dpyinfo->font_table[i].name, fontname)
8682 || !xstricmp (dpyinfo->font_table[i].full_name, fontname)))
8683 return (dpyinfo->font_table + i);
8684 return NULL;
8688 /* Find a CCL program for a font specified by FONTP, and set the member
8689 `encoder' of the structure. */
8691 void
8692 x_find_ccl_program (fontp)
8693 struct font_info *fontp;
8695 Lisp_Object list, elt;
8697 for (list = Vfont_ccl_encoder_alist; CONSP (list); list = XCDR (list))
8699 elt = XCAR (list);
8700 if (CONSP (elt)
8701 && STRINGP (XCAR (elt))
8702 && (fast_c_string_match_ignore_case (XCAR (elt), fontp->name)
8703 >= 0))
8704 break;
8706 if (! NILP (list))
8708 struct ccl_program *ccl
8709 = (struct ccl_program *) xmalloc (sizeof (struct ccl_program));
8711 if (setup_ccl_program (ccl, XCDR (elt)) < 0)
8712 xfree (ccl);
8713 else
8714 fontp->font_encoder = ccl;
8718 #if USE_MAC_FONT_PANEL
8719 /* Whether Font Panel has been shown before. The first call to font
8720 panel functions (FPIsFontPanelVisible, SetFontInfoForSelection) is
8721 slow. This variable is used for deferring such a call as much as
8722 possible. */
8723 static int font_panel_shown_p = 0;
8726 mac_font_panel_visible_p ()
8728 return font_panel_shown_p && FPIsFontPanelVisible ();
8731 OSStatus
8732 mac_show_hide_font_panel ()
8734 font_panel_shown_p = 1;
8736 return FPShowHideFontPanel ();
8739 OSStatus
8740 mac_set_font_info_for_selection (f, face_id, c)
8741 struct frame *f;
8742 int face_id, c;
8744 OSStatus err;
8745 EventTargetRef target = NULL;
8746 XFontStruct *font = NULL;
8748 if (!mac_font_panel_visible_p ())
8749 return noErr;
8751 if (f)
8753 target = GetWindowEventTarget (FRAME_MAC_WINDOW (f));
8755 if (FRAME_FACE_CACHE (f) && CHAR_VALID_P (c, 0))
8757 struct face *face;
8759 face_id = FACE_FOR_CHAR (f, FACE_FROM_ID (f, face_id), c);
8760 face = FACE_FROM_ID (f, face_id);
8761 font = face->font;
8765 if (font == NULL)
8766 err = SetFontInfoForSelection (kFontSelectionATSUIType, 0, NULL, target);
8767 else
8769 if (font->mac_fontnum != -1)
8771 FontSelectionQDStyle qd_style;
8773 qd_style.version = kFontSelectionQDStyleVersionZero;
8774 qd_style.instance.fontFamily = font->mac_fontnum;
8775 qd_style.instance.fontStyle = font->mac_fontface;
8776 qd_style.size = font->mac_fontsize;
8777 qd_style.hasColor = false;
8779 err = SetFontInfoForSelection (kFontSelectionQDType,
8780 1, &qd_style, target);
8782 else
8783 err = SetFontInfoForSelection (kFontSelectionATSUIType,
8784 1, &font->mac_style, target);
8787 return err;
8789 #endif
8792 /* The Mac Event loop code */
8794 #if !TARGET_API_MAC_CARBON
8795 #include <Events.h>
8796 #include <Quickdraw.h>
8797 #include <Balloons.h>
8798 #include <Devices.h>
8799 #include <Fonts.h>
8800 #include <Gestalt.h>
8801 #include <Menus.h>
8802 #include <Processes.h>
8803 #include <Sound.h>
8804 #include <ToolUtils.h>
8805 #include <TextUtils.h>
8806 #include <Dialogs.h>
8807 #include <Script.h>
8808 #include <Types.h>
8809 #include <Resources.h>
8811 #if __MWERKS__
8812 #include <unix.h>
8813 #endif
8814 #endif /* ! TARGET_API_MAC_CARBON */
8816 #define M_APPLE 234
8817 #define I_ABOUT 1
8819 #define DEFAULT_NUM_COLS 80
8821 #define MIN_DOC_SIZE 64
8822 #define MAX_DOC_SIZE 32767
8824 #define EXTRA_STACK_ALLOC (256 * 1024)
8826 #define ARGV_STRING_LIST_ID 129
8827 #define ABOUT_ALERT_ID 128
8828 #define RAM_TOO_LARGE_ALERT_ID 129
8830 /* Contains the string "reverse", which is a constant for mouse button emu.*/
8831 Lisp_Object Qreverse;
8834 /* Modifier associated with the control key, or nil to ignore. */
8835 Lisp_Object Vmac_control_modifier;
8837 /* Modifier associated with the option key, or nil to ignore. */
8838 Lisp_Object Vmac_option_modifier;
8840 /* Modifier associated with the command key, or nil to ignore. */
8841 Lisp_Object Vmac_command_modifier;
8843 /* Modifier associated with the function key, or nil to ignore. */
8844 Lisp_Object Vmac_function_modifier;
8846 /* True if the option and command modifiers should be used to emulate
8847 a three button mouse */
8848 Lisp_Object Vmac_emulate_three_button_mouse;
8850 #if USE_CARBON_EVENTS
8851 /* Non-zero if the mouse wheel button (i.e. button 4) should map to
8852 mouse-2, instead of mouse-3. */
8853 int mac_wheel_button_is_mouse_2;
8855 /* If non-zero, the Mac "Command" key is passed on to the Mac Toolbox
8856 for processing before Emacs sees it. */
8857 int mac_pass_command_to_system;
8859 /* If non-zero, the Mac "Control" key is passed on to the Mac Toolbox
8860 for processing before Emacs sees it. */
8861 int mac_pass_control_to_system;
8862 #endif
8864 /* Points to the variable `inev' in the function XTread_socket. It is
8865 used for passing an input event to the function back from
8866 Carbon/Apple event handlers. */
8867 static struct input_event *read_socket_inev = NULL;
8869 Point saved_menu_event_location;
8871 /* Apple Events */
8872 #if USE_CARBON_EVENTS
8873 static Lisp_Object Qhi_command;
8874 #ifdef MAC_OSX
8875 extern Lisp_Object Qwindow;
8876 static Lisp_Object Qtoolbar_switch_mode;
8877 #endif
8878 #if USE_MAC_FONT_PANEL
8879 extern Lisp_Object Qfont;
8880 static Lisp_Object Qpanel_closed, Qselection;
8881 #endif
8882 #if USE_MAC_TSM
8883 static TSMDocumentID tsm_document_id;
8884 static Lisp_Object Qtext_input;
8885 static Lisp_Object Qupdate_active_input_area, Qunicode_for_key_event;
8886 static Lisp_Object Vmac_ts_active_input_overlay;
8887 extern Lisp_Object Qbefore_string;
8888 static Lisp_Object Vmac_ts_script_language_on_focus;
8889 static Lisp_Object saved_ts_script_language_on_focus;
8890 static ScriptLanguageRecord saved_ts_language;
8891 static Component saved_ts_component;
8892 #endif
8893 #endif
8894 extern int mac_ready_for_apple_events;
8895 extern Lisp_Object Qundefined;
8896 extern void init_apple_event_handler P_ ((void));
8897 extern void mac_find_apple_event_spec P_ ((AEEventClass, AEEventID,
8898 Lisp_Object *, Lisp_Object *,
8899 Lisp_Object *));
8900 extern OSErr init_coercion_handler P_ ((void));
8902 /* Drag and Drop */
8903 extern OSErr install_drag_handler P_ ((WindowRef));
8904 extern void remove_drag_handler P_ ((WindowRef));
8906 /* Showing help echo string during menu tracking */
8907 extern OSStatus install_menu_target_item_handler P_ ((WindowPtr));
8909 #if USE_CARBON_EVENTS
8910 #ifdef MAC_OSX
8911 extern void init_service_handler ();
8912 static Lisp_Object Qservice, Qpaste, Qperform;
8913 #endif
8915 /* Window Event Handler */
8916 static pascal OSStatus mac_handle_window_event (EventHandlerCallRef,
8917 EventRef, void *);
8918 #endif
8919 OSStatus install_window_handler (WindowPtr);
8921 extern void init_emacs_passwd_dir ();
8922 extern int emacs_main (int, char **, char **);
8924 extern void initialize_applescript();
8925 extern void terminate_applescript();
8927 /* Table for translating Mac keycode to X keysym values. Contributed
8928 by Sudhir Shenoy.
8929 Mapping for special keys is now identical to that in Apple X11
8930 except `clear' (-> <clear>) on the KeyPad, `enter' (-> <kp-enter>)
8931 on the right of the Cmd key on laptops, and fn + `enter' (->
8932 <linefeed>). */
8933 static const unsigned char keycode_to_xkeysym_table[] = {
8934 /*0x00*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8935 /*0x10*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8936 /*0x20*/ 0, 0, 0, 0, 0x0d /*return*/, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8938 /*0x30*/ 0x09 /*tab*/, 0 /*0x0020 space*/, 0, 0x08 /*backspace*/,
8939 /*0x34*/ 0x8d /*enter on laptops*/, 0x1b /*escape*/, 0, 0,
8940 /*0x38*/ 0, 0, 0, 0,
8941 /*0x3C*/ 0, 0, 0, 0,
8943 /*0x40*/ 0, 0xae /*kp-decimal*/, 0, 0xaa /*kp-multiply*/,
8944 /*0x44*/ 0, 0xab /*kp-add*/, 0, 0x0b /*clear*/,
8945 /*0x48*/ 0, 0, 0, 0xaf /*kp-divide*/,
8946 /*0x4C*/ 0x8d /*kp-enter*/, 0, 0xad /*kp-subtract*/, 0,
8948 /*0x50*/ 0, 0xbd /*kp-equal*/, 0xb0 /*kp-0*/, 0xb1 /*kp-1*/,
8949 /*0x54*/ 0xb2 /*kp-2*/, 0xb3 /*kp-3*/, 0xb4 /*kp-4*/, 0xb5 /*kp-5*/,
8950 /*0x58*/ 0xb6 /*kp-6*/, 0xb7 /*kp-7*/, 0, 0xb8 /*kp-8*/,
8951 /*0x5C*/ 0xb9 /*kp-9*/, 0, 0, 0,
8953 /*0x60*/ 0xc2 /*f5*/, 0xc3 /*f6*/, 0xc4 /*f7*/, 0xc0 /*f3*/,
8954 /*0x64*/ 0xc5 /*f8*/, 0xc6 /*f9*/, 0, 0xc8 /*f11*/,
8955 /*0x68*/ 0, 0xca /*f13*/, 0xcd /*f16*/, 0xcb /*f14*/,
8956 /*0x6C*/ 0, 0xc7 /*f10*/, 0x0a /*fn+enter on laptops*/, 0xc9 /*f12*/,
8958 /*0x70*/ 0, 0xcc /*f15*/, 0x6a /*help*/, 0x50 /*home*/,
8959 /*0x74*/ 0x55 /*pgup*/, 0xff /*delete*/, 0xc1 /*f4*/, 0x57 /*end*/,
8960 /*0x78*/ 0xbf /*f2*/, 0x56 /*pgdown*/, 0xbe /*f1*/, 0x51 /*left*/,
8961 /*0x7C*/ 0x53 /*right*/, 0x54 /*down*/, 0x52 /*up*/, 0
8964 #ifdef MAC_OSX
8965 /* Table for translating Mac keycode with the laptop `fn' key to that
8966 without it. Destination symbols in comments are keys on US
8967 keyboard, and they may not be the same on other types of keyboards.
8968 If the destination is identical to the source (f1 ... f12), it
8969 doesn't map `fn' key to a modifier. */
8970 static const unsigned char fn_keycode_to_keycode_table[] = {
8971 /*0x00*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8972 /*0x10*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8973 /*0x20*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8975 /*0x30*/ 0, 0, 0, 0,
8976 /*0x34*/ 0, 0, 0, 0,
8977 /*0x38*/ 0, 0, 0, 0,
8978 /*0x3C*/ 0, 0, 0, 0,
8980 /*0x40*/ 0, 0x2f /*kp-decimal -> '.'*/, 0, 0x23 /*kp-multiply -> 'p'*/,
8981 /*0x44*/ 0, 0x2c /*kp-add -> '/'*/, 0, 0x16 /*clear -> '6'*/,
8982 /*0x48*/ 0, 0, 0, 0x1d /*kp-/ -> '0'*/,
8983 /*0x4C*/ 0x24 /*kp-enter -> return*/, 0, 0x29 /*kp-subtract -> ';'*/, 0,
8985 /*0x50*/ 0, 0x1b /*kp-equal -> '-'*/, 0x2e /*kp-0 -> 'm'*/, 0x26 /*kp-1 -> 'j'*/,
8986 /*0x54*/ 0x28 /*kp-2 -> 'k'*/, 0x25 /*kp-3 -> 'l'*/, 0x20 /*kp-4 -> 'u'*/, 0x22 /*kp-5 ->'i'*/,
8987 /*0x58*/ 0x1f /*kp-6 -> 'o'*/, 0x1a /*kp-7 -> '7'*/, 0, 0x1c /*kp-8 -> '8'*/,
8988 /*0x5C*/ 0x19 /*kp-9 -> '9'*/, 0, 0, 0,
8990 /*0x60*/ 0x60 /*f5 = f5*/, 0x61 /*f6 = f6*/, 0x62 /*f7 = f7*/, 0x63 /*f3 = f3*/,
8991 /*0x64*/ 0x64 /*f8 = f8*/, 0x65 /*f9 = f9*/, 0, 0x67 /*f11 = f11*/,
8992 /*0x68*/ 0, 0, 0, 0,
8993 /*0x6C*/ 0, 0x6d /*f10 = f10*/, 0, 0x6f /*f12 = f12*/,
8995 /*0x70*/ 0, 0, 0, 0x7b /*home -> left*/,
8996 /*0x74*/ 0x7e /*pgup -> up*/, 0x33 /*delete -> backspace*/, 0x76 /*f4 = f4*/, 0x7c /*end -> right*/,
8997 /*0x78*/ 0x78 /*f2 = f2*/, 0x7d /*pgdown -> down*/, 0x7a /*f1 = f1*/, 0,
8998 /*0x7C*/ 0, 0, 0, 0
9000 #endif /* MAC_OSX */
9002 static int
9003 #if USE_CARBON_EVENTS
9004 mac_to_emacs_modifiers (UInt32 mods)
9005 #else
9006 mac_to_emacs_modifiers (EventModifiers mods)
9007 #endif
9009 unsigned int result = 0;
9010 if (mods & shiftKey)
9011 result |= shift_modifier;
9013 /* Deactivated to simplify configuration:
9014 if Vmac_option_modifier is non-NIL, we fully process the Option
9015 key. Otherwise, we only process it if an additional Ctrl or Command
9016 is pressed. That way the system may convert the character to a
9017 composed one.
9018 if ((mods & optionKey) &&
9019 (( !NILP(Vmac_option_modifier) ||
9020 ((mods & cmdKey) || (mods & controlKey))))) */
9022 if (!NILP (Vmac_option_modifier) && (mods & optionKey)) {
9023 Lisp_Object val = Fget(Vmac_option_modifier, Qmodifier_value);
9024 if (INTEGERP(val))
9025 result |= XUINT(val);
9027 if (!NILP (Vmac_command_modifier) && (mods & cmdKey)) {
9028 Lisp_Object val = Fget(Vmac_command_modifier, Qmodifier_value);
9029 if (INTEGERP(val))
9030 result |= XUINT(val);
9032 if (!NILP (Vmac_control_modifier) && (mods & controlKey)) {
9033 Lisp_Object val = Fget(Vmac_control_modifier, Qmodifier_value);
9034 if (INTEGERP(val))
9035 result |= XUINT(val);
9038 #ifdef MAC_OSX
9039 if (!NILP (Vmac_function_modifier) && (mods & kEventKeyModifierFnMask)) {
9040 Lisp_Object val = Fget(Vmac_function_modifier, Qmodifier_value);
9041 if (INTEGERP(val))
9042 result |= XUINT(val);
9044 #endif
9046 return result;
9049 static UInt32
9050 mac_mapped_modifiers (modifiers)
9051 UInt32 modifiers;
9053 UInt32 mapped_modifiers_all =
9054 (NILP (Vmac_control_modifier) ? 0 : controlKey)
9055 | (NILP (Vmac_option_modifier) ? 0 : optionKey)
9056 | (NILP (Vmac_command_modifier) ? 0 : cmdKey);
9058 #ifdef MAC_OSX
9059 mapped_modifiers_all |=
9060 (NILP (Vmac_function_modifier) ? 0 : kEventKeyModifierFnMask);
9061 #endif
9063 return mapped_modifiers_all & modifiers;
9066 static int
9067 mac_get_emulated_btn ( UInt32 modifiers )
9069 int result = 0;
9070 if (!NILP (Vmac_emulate_three_button_mouse)) {
9071 int cmdIs3 = !EQ (Vmac_emulate_three_button_mouse, Qreverse);
9072 if (modifiers & cmdKey)
9073 result = cmdIs3 ? 2 : 1;
9074 else if (modifiers & optionKey)
9075 result = cmdIs3 ? 1 : 2;
9077 return result;
9080 #if TARGET_API_MAC_CARBON
9081 /***** Code to handle C-g testing *****/
9082 extern int quit_char;
9083 extern int make_ctrl_char P_ ((int));
9086 mac_quit_char_key_p (modifiers, key_code)
9087 UInt32 modifiers, key_code;
9089 UInt32 char_code;
9090 unsigned long some_state = 0;
9091 Ptr kchr_ptr = (Ptr) GetScriptManagerVariable (smKCHRCache);
9092 int c, emacs_modifiers;
9094 /* Mask off modifier keys that are mapped to some Emacs modifiers. */
9095 key_code |= (modifiers & ~(mac_mapped_modifiers (modifiers)));
9096 char_code = KeyTranslate (kchr_ptr, key_code, &some_state);
9097 if (char_code & ~0xff)
9098 return 0;
9100 emacs_modifiers = mac_to_emacs_modifiers (modifiers);
9101 if (emacs_modifiers & ctrl_modifier)
9102 c = make_ctrl_char (char_code);
9104 c |= (emacs_modifiers
9105 & (meta_modifier | alt_modifier
9106 | hyper_modifier | super_modifier));
9108 return c == quit_char;
9110 #endif
9112 #if USE_CARBON_EVENTS
9113 /* Obtains the event modifiers from the event ref and then calls
9114 mac_to_emacs_modifiers. */
9115 static int
9116 mac_event_to_emacs_modifiers (EventRef eventRef)
9118 UInt32 mods = 0;
9119 GetEventParameter (eventRef, kEventParamKeyModifiers, typeUInt32, NULL,
9120 sizeof (UInt32), NULL, &mods);
9121 if (!NILP (Vmac_emulate_three_button_mouse) &&
9122 GetEventClass(eventRef) == kEventClassMouse)
9124 mods &= ~(optionKey | cmdKey);
9126 return mac_to_emacs_modifiers (mods);
9129 /* Given an event ref, return the code to use for the mouse button
9130 code in the emacs input_event. */
9131 static int
9132 mac_get_mouse_btn (EventRef ref)
9134 EventMouseButton result = kEventMouseButtonPrimary;
9135 GetEventParameter (ref, kEventParamMouseButton, typeMouseButton, NULL,
9136 sizeof (EventMouseButton), NULL, &result);
9137 switch (result)
9139 case kEventMouseButtonPrimary:
9140 if (NILP (Vmac_emulate_three_button_mouse))
9141 return 0;
9142 else {
9143 UInt32 mods = 0;
9144 GetEventParameter (ref, kEventParamKeyModifiers, typeUInt32, NULL,
9145 sizeof (UInt32), NULL, &mods);
9146 return mac_get_emulated_btn(mods);
9148 case kEventMouseButtonSecondary:
9149 return mac_wheel_button_is_mouse_2 ? 2 : 1;
9150 case kEventMouseButtonTertiary:
9151 case 4: /* 4 is the number for the mouse wheel button */
9152 return mac_wheel_button_is_mouse_2 ? 1 : 2;
9153 default:
9154 return 0;
9158 /* Normally, ConvertEventRefToEventRecord will correctly handle all
9159 events. However the click of the mouse wheel is not converted to a
9160 mouseDown or mouseUp event. Likewise for dead key down events.
9161 This calls ConvertEventRef, but then checks to see if it is a mouse
9162 up/down, or a dead key down carbon event that has not been
9163 converted, and if so, converts it by hand (to be picked up in the
9164 XTread_socket loop). */
9165 static Boolean mac_convert_event_ref (EventRef eventRef, EventRecord *eventRec)
9167 OSStatus err;
9168 Boolean result = ConvertEventRefToEventRecord (eventRef, eventRec);
9170 if (result)
9171 return result;
9173 switch (GetEventClass (eventRef))
9175 case kEventClassMouse:
9176 switch (GetEventKind (eventRef))
9178 case kEventMouseDown:
9179 eventRec->what = mouseDown;
9180 result = 1;
9181 break;
9183 case kEventMouseUp:
9184 eventRec->what = mouseUp;
9185 result = 1;
9186 break;
9188 default:
9189 break;
9191 break;
9193 case kEventClassKeyboard:
9194 switch (GetEventKind (eventRef))
9196 case kEventRawKeyDown:
9198 unsigned char char_codes;
9199 UInt32 key_code;
9201 err = GetEventParameter (eventRef, kEventParamKeyMacCharCodes,
9202 typeChar, NULL, sizeof (char),
9203 NULL, &char_codes);
9204 if (err == noErr)
9205 err = GetEventParameter (eventRef, kEventParamKeyCode,
9206 typeUInt32, NULL, sizeof (UInt32),
9207 NULL, &key_code);
9208 if (err == noErr)
9210 eventRec->what = keyDown;
9211 eventRec->message = char_codes | ((key_code & 0xff) << 8);
9212 result = 1;
9215 break;
9217 default:
9218 break;
9220 break;
9222 default:
9223 break;
9226 if (result)
9228 /* Need where and when. */
9229 UInt32 mods = 0;
9231 GetEventParameter (eventRef, kEventParamMouseLocation, typeQDPoint,
9232 NULL, sizeof (Point), NULL, &eventRec->where);
9233 /* Use two step process because new event modifiers are 32-bit
9234 and old are 16-bit. Currently, only loss is NumLock & Fn. */
9235 GetEventParameter (eventRef, kEventParamKeyModifiers, typeUInt32,
9236 NULL, sizeof (UInt32), NULL, &mods);
9237 eventRec->modifiers = mods;
9239 eventRec->when = EventTimeToTicks (GetEventTime (eventRef));
9242 return result;
9245 #endif
9247 #ifdef MAC_OS8
9248 static void
9249 do_get_menus (void)
9251 Handle menubar_handle;
9252 MenuHandle menu_handle;
9254 menubar_handle = GetNewMBar (128);
9255 if(menubar_handle == NULL)
9256 abort ();
9257 SetMenuBar (menubar_handle);
9258 DrawMenuBar ();
9260 #if !TARGET_API_MAC_CARBON
9261 menu_handle = GetMenuHandle (M_APPLE);
9262 if(menu_handle != NULL)
9263 AppendResMenu (menu_handle,'DRVR');
9264 else
9265 abort ();
9266 #endif
9270 static void
9271 do_init_managers (void)
9273 #if !TARGET_API_MAC_CARBON
9274 InitGraf (&qd.thePort);
9275 InitFonts ();
9276 FlushEvents (everyEvent, 0);
9277 InitWindows ();
9278 InitMenus ();
9279 TEInit ();
9280 InitDialogs (NULL);
9281 #endif /* !TARGET_API_MAC_CARBON */
9282 InitCursor ();
9284 #if !TARGET_API_MAC_CARBON
9285 /* set up some extra stack space for use by emacs */
9286 SetApplLimit ((Ptr) ((long) GetApplLimit () - EXTRA_STACK_ALLOC));
9288 /* MaxApplZone must be called for AppleScript to execute more
9289 complicated scripts */
9290 MaxApplZone ();
9291 MoreMasters ();
9292 #endif /* !TARGET_API_MAC_CARBON */
9295 static void
9296 do_check_ram_size (void)
9298 SInt32 physical_ram_size, logical_ram_size;
9300 if (Gestalt (gestaltPhysicalRAMSize, &physical_ram_size) != noErr
9301 || Gestalt (gestaltLogicalRAMSize, &logical_ram_size) != noErr
9302 || physical_ram_size > (1 << VALBITS)
9303 || logical_ram_size > (1 << VALBITS))
9305 StopAlert (RAM_TOO_LARGE_ALERT_ID, NULL);
9306 exit (1);
9309 #endif /* MAC_OS8 */
9311 static void
9312 do_window_update (WindowPtr win)
9314 struct frame *f = mac_window_to_frame (win);
9316 BeginUpdate (win);
9318 /* The tooltip has been drawn already. Avoid the SET_FRAME_GARBAGED
9319 below. */
9320 if (win != tip_window)
9322 if (f->async_visible == 0)
9324 /* Update events may occur when a frame gets iconified. */
9325 #if 0
9326 f->async_visible = 1;
9327 f->async_iconified = 0;
9328 SET_FRAME_GARBAGED (f);
9329 #endif
9331 else
9333 Rect r;
9334 #if TARGET_API_MAC_CARBON
9335 RgnHandle region = NewRgn ();
9337 GetPortVisibleRegion (GetWindowPort (win), region);
9338 GetRegionBounds (region, &r);
9339 expose_frame (f, r.left, r.top, r.right - r.left, r.bottom - r.top);
9340 #if USE_CG_DRAWING
9341 mac_prepare_for_quickdraw (f);
9342 #endif
9343 UpdateControls (win, region);
9344 DisposeRgn (region);
9345 #else
9346 r = (*win->visRgn)->rgnBBox;
9347 expose_frame (f, r.left, r.top, r.right - r.left, r.bottom - r.top);
9348 UpdateControls (win, win->visRgn);
9349 #endif
9353 EndUpdate (win);
9356 static int
9357 is_emacs_window (WindowPtr win)
9359 Lisp_Object tail, frame;
9361 if (!win)
9362 return 0;
9364 FOR_EACH_FRAME (tail, frame)
9365 if (FRAME_MAC_P (XFRAME (frame)))
9366 if (FRAME_MAC_WINDOW (XFRAME (frame)) == win)
9367 return 1;
9369 return 0;
9372 #if USE_MAC_TSM
9373 static OSStatus
9374 mac_tsm_resume ()
9376 OSStatus err;
9377 ScriptLanguageRecord slrec, *slptr = NULL;
9379 err = ActivateTSMDocument (tsm_document_id);
9381 if (err == noErr)
9383 if (EQ (Vmac_ts_script_language_on_focus, Qt)
9384 && EQ (saved_ts_script_language_on_focus, Qt))
9385 slptr = &saved_ts_language;
9386 else if (CONSP (Vmac_ts_script_language_on_focus)
9387 && INTEGERP (XCAR (Vmac_ts_script_language_on_focus))
9388 && INTEGERP (XCDR (Vmac_ts_script_language_on_focus))
9389 && CONSP (saved_ts_script_language_on_focus)
9390 && EQ (XCAR (saved_ts_script_language_on_focus),
9391 XCAR (Vmac_ts_script_language_on_focus))
9392 && EQ (XCDR (saved_ts_script_language_on_focus),
9393 XCDR (Vmac_ts_script_language_on_focus)))
9395 slrec.fScript = XINT (XCAR (Vmac_ts_script_language_on_focus));
9396 slrec.fLanguage = XINT (XCDR (Vmac_ts_script_language_on_focus));
9397 slptr = &slrec;
9401 if (slptr)
9403 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
9404 err = SetDefaultInputMethodOfClass (saved_ts_component, slptr,
9405 kKeyboardInputMethodClass);
9406 #else
9407 err = SetDefaultInputMethod (saved_ts_component, slptr);
9408 #endif
9409 if (err == noErr)
9410 err = SetTextServiceLanguage (slptr);
9412 /* Seems to be needed on Mac OS X 10.2. */
9413 if (err == noErr)
9414 KeyScript (slptr->fScript | smKeyForceKeyScriptMask);
9417 return err;
9420 static OSStatus
9421 mac_tsm_suspend ()
9423 OSStatus err;
9424 ScriptLanguageRecord slrec, *slptr = NULL;
9426 saved_ts_script_language_on_focus = Vmac_ts_script_language_on_focus;
9428 if (EQ (Vmac_ts_script_language_on_focus, Qt))
9430 err = GetTextServiceLanguage (&saved_ts_language);
9431 if (err == noErr)
9432 slptr = &saved_ts_language;
9434 else if (CONSP (Vmac_ts_script_language_on_focus)
9435 && INTEGERP (XCAR (Vmac_ts_script_language_on_focus))
9436 && INTEGERP (XCDR (Vmac_ts_script_language_on_focus)))
9438 slrec.fScript = XINT (XCAR (Vmac_ts_script_language_on_focus));
9439 slrec.fLanguage = XINT (XCDR (Vmac_ts_script_language_on_focus));
9440 slptr = &slrec;
9443 if (slptr)
9445 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
9446 GetDefaultInputMethodOfClass (&saved_ts_component, slptr,
9447 kKeyboardInputMethodClass);
9448 #else
9449 GetDefaultInputMethod (&saved_ts_component, slptr);
9450 #endif
9453 err = DeactivateTSMDocument (tsm_document_id);
9455 return err;
9457 #endif
9459 #if !TARGET_API_MAC_CARBON
9460 void
9461 do_apple_menu (SInt16 menu_item)
9463 Str255 item_name;
9464 SInt16 da_driver_refnum;
9466 if (menu_item == I_ABOUT)
9467 NoteAlert (ABOUT_ALERT_ID, NULL);
9468 else
9470 GetMenuItemText (GetMenuHandle (M_APPLE), menu_item, item_name);
9471 da_driver_refnum = OpenDeskAcc (item_name);
9474 #endif /* !TARGET_API_MAC_CARBON */
9476 /* Handle drags in size box. Based on code contributed by Ben
9477 Mesander and IM - Window Manager A. */
9479 static void
9480 do_grow_window (w, e)
9481 WindowPtr w;
9482 const EventRecord *e;
9484 Rect limit_rect;
9485 int rows, columns, width, height;
9486 struct frame *f = mac_window_to_frame (w);
9487 XSizeHints *size_hints = FRAME_SIZE_HINTS (f);
9488 int min_width = MIN_DOC_SIZE, min_height = MIN_DOC_SIZE;
9489 #if TARGET_API_MAC_CARBON
9490 Rect new_rect;
9491 #else
9492 long grow_size;
9493 #endif
9495 if (size_hints->flags & PMinSize)
9497 min_width = size_hints->min_width;
9498 min_height = size_hints->min_height;
9500 SetRect (&limit_rect, min_width, min_height, MAX_DOC_SIZE, MAX_DOC_SIZE);
9502 #if TARGET_API_MAC_CARBON
9503 if (!ResizeWindow (w, e->where, &limit_rect, &new_rect))
9504 return;
9505 height = new_rect.bottom - new_rect.top;
9506 width = new_rect.right - new_rect.left;
9507 #else
9508 grow_size = GrowWindow (w, e->where, &limit_rect);
9509 /* see if it really changed size */
9510 if (grow_size == 0)
9511 return;
9512 height = HiWord (grow_size);
9513 width = LoWord (grow_size);
9514 #endif
9516 if (width != FRAME_PIXEL_WIDTH (f)
9517 || height != FRAME_PIXEL_HEIGHT (f))
9519 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, height);
9520 columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, width);
9522 x_set_window_size (f, 0, columns, rows);
9527 #if TARGET_API_MAC_CARBON
9528 static Point
9529 mac_get_ideal_size (f)
9530 struct frame *f;
9532 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
9533 WindowPtr w = FRAME_MAC_WINDOW (f);
9534 Point ideal_size;
9535 Rect standard_rect;
9536 int height, width, columns, rows;
9538 ideal_size.h = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, DEFAULT_NUM_COLS);
9539 ideal_size.v = dpyinfo->height;
9540 IsWindowInStandardState (w, &ideal_size, &standard_rect);
9541 /* Adjust the standard size according to character boundaries. */
9542 width = standard_rect.right - standard_rect.left;
9543 height = standard_rect.bottom - standard_rect.top;
9544 columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, width);
9545 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, height);
9546 ideal_size.h = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, columns);
9547 ideal_size.v = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
9549 return ideal_size;
9551 #endif
9553 /* Handle clicks in zoom box. Calculation of "standard state" based
9554 on code in IM - Window Manager A and code contributed by Ben
9555 Mesander. The standard state of an Emacs window is 80-characters
9556 wide (DEFAULT_NUM_COLS) and as tall as will fit on the screen. */
9558 static void
9559 do_zoom_window (WindowPtr w, int zoom_in_or_out)
9561 Rect zoom_rect, port_rect;
9562 int width, height;
9563 struct frame *f = mac_window_to_frame (w);
9564 #if TARGET_API_MAC_CARBON
9565 Point ideal_size = mac_get_ideal_size (f);
9567 GetWindowBounds (w, kWindowContentRgn, &port_rect);
9568 if (IsWindowInStandardState (w, &ideal_size, &zoom_rect)
9569 && port_rect.left == zoom_rect.left
9570 && port_rect.top == zoom_rect.top)
9571 zoom_in_or_out = inZoomIn;
9572 else
9573 zoom_in_or_out = inZoomOut;
9575 #ifdef MAC_OS8
9576 mac_clear_window (f);
9577 #endif
9578 ZoomWindowIdeal (w, zoom_in_or_out, &ideal_size);
9579 #else /* not TARGET_API_MAC_CARBON */
9580 GrafPtr save_port;
9581 Point top_left;
9582 int w_title_height, rows;
9583 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
9585 GetPort (&save_port);
9587 SetPortWindowPort (w);
9589 /* Clear window to avoid flicker. */
9590 EraseRect (&(w->portRect));
9591 if (zoom_in_or_out == inZoomOut)
9593 SetPt (&top_left, w->portRect.left, w->portRect.top);
9594 LocalToGlobal (&top_left);
9596 /* calculate height of window's title bar */
9597 w_title_height = top_left.v - 1
9598 - (**((WindowPeek) w)->strucRgn).rgnBBox.top + GetMBarHeight ();
9600 /* get maximum height of window into zoom_rect.bottom - zoom_rect.top */
9601 zoom_rect = qd.screenBits.bounds;
9602 zoom_rect.top += w_title_height;
9603 InsetRect (&zoom_rect, 8, 4); /* not too tight */
9605 zoom_rect.right = zoom_rect.left
9606 + FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, DEFAULT_NUM_COLS);
9608 /* Adjust the standard size according to character boundaries. */
9609 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, zoom_rect.bottom - zoom_rect.top);
9610 zoom_rect.bottom =
9611 zoom_rect.top + FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
9613 (**((WStateDataHandle) ((WindowPeek) w)->dataHandle)).stdState
9614 = zoom_rect;
9617 ZoomWindow (w, zoom_in_or_out, f == mac_focus_frame (dpyinfo));
9619 SetPort (save_port);
9620 #endif /* not TARGET_API_MAC_CARBON */
9622 #if !USE_CARBON_EVENTS
9623 /* retrieve window size and update application values */
9624 #if TARGET_API_MAC_CARBON
9625 GetWindowPortBounds (w, &port_rect);
9626 #else
9627 port_rect = w->portRect;
9628 #endif
9629 height = port_rect.bottom - port_rect.top;
9630 width = port_rect.right - port_rect.left;
9632 mac_handle_size_change (f, width, height);
9633 mac_handle_origin_change (f);
9634 #endif
9637 void
9638 mac_store_apple_event (class, id, desc)
9639 Lisp_Object class, id;
9640 const AEDesc *desc;
9642 struct input_event buf;
9644 EVENT_INIT (buf);
9646 buf.kind = MAC_APPLE_EVENT;
9647 buf.x = class;
9648 buf.y = id;
9649 XSETFRAME (buf.frame_or_window,
9650 mac_focus_frame (&one_mac_display_info));
9651 /* Now that Lisp object allocations are protected by BLOCK_INPUT, it
9652 is safe to use them during read_socket_hook. */
9653 buf.arg = mac_aedesc_to_lisp (desc);
9654 kbd_buffer_store_event (&buf);
9657 #if TARGET_API_MAC_CARBON
9658 static OSStatus
9659 mac_store_event_ref_as_apple_event (class, id, class_key, id_key,
9660 event, num_params, names, types)
9661 AEEventClass class;
9662 AEEventID id;
9663 Lisp_Object class_key, id_key;
9664 EventRef event;
9665 UInt32 num_params;
9666 const EventParamName *names;
9667 const EventParamType *types;
9669 OSStatus err = eventNotHandledErr;
9670 Lisp_Object binding;
9672 mac_find_apple_event_spec (class, id, &class_key, &id_key, &binding);
9673 if (!NILP (binding) && !EQ (binding, Qundefined))
9675 if (INTEGERP (binding))
9676 err = XINT (binding);
9677 else
9679 AppleEvent apple_event;
9680 err = create_apple_event_from_event_ref (event, num_params,
9681 names, types,
9682 &apple_event);
9683 if (err == noErr)
9685 mac_store_apple_event (class_key, id_key, &apple_event);
9686 AEDisposeDesc (&apple_event);
9687 mac_wakeup_from_rne ();
9692 return err;
9695 void
9696 mac_store_drag_event (window, mouse_pos, modifiers, desc)
9697 WindowRef window;
9698 Point mouse_pos;
9699 SInt16 modifiers;
9700 const AEDesc *desc;
9702 struct input_event buf;
9704 EVENT_INIT (buf);
9706 buf.kind = DRAG_N_DROP_EVENT;
9707 buf.modifiers = mac_to_emacs_modifiers (modifiers);
9708 buf.timestamp = TickCount () * (1000 / 60);
9709 XSETINT (buf.x, mouse_pos.h);
9710 XSETINT (buf.y, mouse_pos.v);
9711 XSETFRAME (buf.frame_or_window, mac_window_to_frame (window));
9712 buf.arg = mac_aedesc_to_lisp (desc);
9713 kbd_buffer_store_event (&buf);
9715 #endif
9717 #if USE_CARBON_EVENTS
9718 static pascal OSStatus
9719 mac_handle_command_event (next_handler, event, data)
9720 EventHandlerCallRef next_handler;
9721 EventRef event;
9722 void *data;
9724 OSStatus result, err;
9725 HICommand command;
9726 static const EventParamName names[] =
9727 {kEventParamDirectObject, kEventParamKeyModifiers};
9728 static const EventParamType types[] =
9729 {typeHICommand, typeUInt32};
9730 int num_params = sizeof (names) / sizeof (names[0]);
9732 result = CallNextEventHandler (next_handler, event);
9733 if (result != eventNotHandledErr)
9734 return result;
9736 err = GetEventParameter (event, kEventParamDirectObject, typeHICommand,
9737 NULL, sizeof (HICommand), NULL, &command);
9739 if (err != noErr || command.commandID == 0)
9740 return eventNotHandledErr;
9742 /* A HI command event is mapped to an Apple event whose event class
9743 symbol is `hi-command' and event ID is its command ID. */
9744 err = mac_store_event_ref_as_apple_event (0, command.commandID,
9745 Qhi_command, Qnil,
9746 event, num_params, names, types);
9747 return err == noErr ? noErr : eventNotHandledErr;
9750 static OSStatus
9751 init_command_handler ()
9753 static const EventTypeSpec specs[] =
9754 {{kEventClassCommand, kEventCommandProcess}};
9755 static EventHandlerUPP handle_command_eventUPP = NULL;
9757 if (handle_command_eventUPP == NULL)
9758 handle_command_eventUPP = NewEventHandlerUPP (mac_handle_command_event);
9759 return InstallApplicationEventHandler (handle_command_eventUPP,
9760 GetEventTypeCount (specs), specs,
9761 NULL, NULL);
9764 static pascal OSStatus
9765 mac_handle_window_event (next_handler, event, data)
9766 EventHandlerCallRef next_handler;
9767 EventRef event;
9768 void *data;
9770 WindowPtr wp;
9771 OSStatus result, err;
9772 struct frame *f;
9773 UInt32 attributes;
9774 XSizeHints *size_hints;
9776 err = GetEventParameter (event, kEventParamDirectObject, typeWindowRef,
9777 NULL, sizeof (WindowPtr), NULL, &wp);
9778 if (err != noErr)
9779 return eventNotHandledErr;
9781 f = mac_window_to_frame (wp);
9782 switch (GetEventKind (event))
9784 case kEventWindowUpdate:
9785 result = CallNextEventHandler (next_handler, event);
9786 if (result != eventNotHandledErr)
9787 return result;
9789 do_window_update (wp);
9790 return noErr;
9792 case kEventWindowGetIdealSize:
9793 result = CallNextEventHandler (next_handler, event);
9794 if (result != eventNotHandledErr)
9795 return result;
9798 Point ideal_size = mac_get_ideal_size (f);
9800 err = SetEventParameter (event, kEventParamDimensions,
9801 typeQDPoint, sizeof (Point), &ideal_size);
9802 if (err == noErr)
9803 return noErr;
9805 break;
9807 case kEventWindowBoundsChanging:
9808 result = CallNextEventHandler (next_handler, event);
9809 if (result != eventNotHandledErr)
9810 return result;
9812 err = GetEventParameter (event, kEventParamAttributes, typeUInt32,
9813 NULL, sizeof (UInt32), NULL, &attributes);
9814 if (err != noErr)
9815 break;
9817 size_hints = FRAME_SIZE_HINTS (f);
9818 if ((attributes & kWindowBoundsChangeUserResize)
9819 && ((size_hints->flags & (PResizeInc | PBaseSize | PMinSize))
9820 == (PResizeInc | PBaseSize | PMinSize)))
9822 Rect bounds;
9823 int width, height;
9825 err = GetEventParameter (event, kEventParamCurrentBounds,
9826 typeQDRectangle, NULL, sizeof (Rect),
9827 NULL, &bounds);
9828 if (err != noErr)
9829 break;
9831 width = bounds.right - bounds.left;
9832 height = bounds.bottom - bounds.top;
9834 if (width < size_hints->min_width)
9835 width = size_hints->min_width;
9836 else
9837 width = size_hints->base_width
9838 + (int) ((width - size_hints->base_width)
9839 / (float) size_hints->width_inc + .5)
9840 * size_hints->width_inc;
9842 if (height < size_hints->min_height)
9843 height = size_hints->min_height;
9844 else
9845 height = size_hints->base_height
9846 + (int) ((height - size_hints->base_height)
9847 / (float) size_hints->height_inc + .5)
9848 * size_hints->height_inc;
9850 bounds.right = bounds.left + width;
9851 bounds.bottom = bounds.top + height;
9852 SetEventParameter (event, kEventParamCurrentBounds,
9853 typeQDRectangle, sizeof (Rect), &bounds);
9854 return noErr;
9856 break;
9858 case kEventWindowBoundsChanged:
9859 err = GetEventParameter (event, kEventParamAttributes, typeUInt32,
9860 NULL, sizeof (UInt32), NULL, &attributes);
9861 if (err != noErr)
9862 break;
9864 if (attributes & kWindowBoundsChangeSizeChanged)
9866 Rect bounds;
9868 err = GetEventParameter (event, kEventParamCurrentBounds,
9869 typeQDRectangle, NULL, sizeof (Rect),
9870 NULL, &bounds);
9871 if (err == noErr)
9873 int width, height;
9875 width = bounds.right - bounds.left;
9876 height = bounds.bottom - bounds.top;
9877 mac_handle_size_change (f, width, height);
9881 if (attributes & kWindowBoundsChangeOriginChanged)
9882 mac_handle_origin_change (f);
9884 return noErr;
9886 case kEventWindowShown:
9887 case kEventWindowHidden:
9888 case kEventWindowExpanded:
9889 case kEventWindowCollapsed:
9890 result = CallNextEventHandler (next_handler, event);
9892 mac_handle_visibility_change (f);
9893 return noErr;
9895 break;
9897 case kEventWindowClose:
9898 result = CallNextEventHandler (next_handler, event);
9900 struct input_event buf;
9902 EVENT_INIT (buf);
9903 buf.kind = DELETE_WINDOW_EVENT;
9904 XSETFRAME (buf.frame_or_window, f);
9905 buf.arg = Qnil;
9906 kbd_buffer_store_event (&buf);
9908 return noErr;
9910 #ifdef MAC_OSX
9911 case kEventWindowToolbarSwitchMode:
9912 result = CallNextEventHandler (next_handler, event);
9914 static const EventParamName names[] = {kEventParamDirectObject,
9915 kEventParamWindowMouseLocation,
9916 kEventParamKeyModifiers,
9917 kEventParamMouseButton,
9918 kEventParamClickCount,
9919 kEventParamMouseChord};
9920 static const EventParamType types[] = {typeWindowRef,
9921 typeQDPoint,
9922 typeUInt32,
9923 typeMouseButton,
9924 typeUInt32,
9925 typeUInt32};
9926 int num_params = sizeof (names) / sizeof (names[0]);
9928 err = mac_store_event_ref_as_apple_event (0, 0,
9929 Qwindow,
9930 Qtoolbar_switch_mode,
9931 event, num_params,
9932 names, types);
9934 return err == noErr ? noErr : result;
9935 #endif
9937 #if USE_MAC_TSM
9938 case kEventWindowFocusAcquired:
9939 result = CallNextEventHandler (next_handler, event);
9940 err = mac_tsm_resume ();
9941 return err == noErr ? noErr : result;
9943 case kEventWindowFocusRelinquish:
9944 result = CallNextEventHandler (next_handler, event);
9945 err = mac_tsm_suspend ();
9946 return err == noErr ? noErr : result;
9947 #endif
9950 return eventNotHandledErr;
9953 static pascal OSStatus
9954 mac_handle_mouse_event (next_handler, event, data)
9955 EventHandlerCallRef next_handler;
9956 EventRef event;
9957 void *data;
9959 OSStatus result, err;
9961 switch (GetEventKind (event))
9963 case kEventMouseWheelMoved:
9965 WindowPtr wp;
9966 struct frame *f;
9967 EventMouseWheelAxis axis;
9968 SInt32 delta;
9969 Point point;
9971 result = CallNextEventHandler (next_handler, event);
9972 if (result != eventNotHandledErr || read_socket_inev == NULL)
9973 return result;
9975 err = GetEventParameter (event, kEventParamWindowRef, typeWindowRef,
9976 NULL, sizeof (WindowRef), NULL, &wp);
9977 if (err != noErr)
9978 break;
9980 f = mac_window_to_frame (wp);
9981 if (f != mac_focus_frame (&one_mac_display_info))
9982 break;
9984 err = GetEventParameter (event, kEventParamMouseWheelAxis,
9985 typeMouseWheelAxis, NULL,
9986 sizeof (EventMouseWheelAxis), NULL, &axis);
9987 if (err != noErr || axis != kEventMouseWheelAxisY)
9988 break;
9990 err = GetEventParameter (event, kEventParamMouseLocation,
9991 typeQDPoint, NULL, sizeof (Point),
9992 NULL, &point);
9993 if (err != noErr)
9994 break;
9996 SetPortWindowPort (wp);
9997 GlobalToLocal (&point);
9998 if (point.h < 0 || point.v < 0
9999 || EQ (window_from_coordinates (f, point.h, point.v, 0, 0, 0, 1),
10000 f->tool_bar_window))
10001 break;
10003 err = GetEventParameter (event, kEventParamMouseWheelDelta,
10004 typeSInt32, NULL, sizeof (SInt32),
10005 NULL, &delta);
10006 if (err != noErr)
10007 break;
10009 read_socket_inev->kind = WHEEL_EVENT;
10010 read_socket_inev->code = 0;
10011 read_socket_inev->modifiers =
10012 (mac_event_to_emacs_modifiers (event)
10013 | ((delta < 0) ? down_modifier : up_modifier));
10014 XSETINT (read_socket_inev->x, point.h);
10015 XSETINT (read_socket_inev->y, point.v);
10016 XSETFRAME (read_socket_inev->frame_or_window, f);
10018 return noErr;
10020 break;
10022 default:
10023 break;
10026 return eventNotHandledErr;
10029 #if USE_MAC_FONT_PANEL
10030 static pascal OSStatus
10031 mac_handle_font_event (next_handler, event, data)
10032 EventHandlerCallRef next_handler;
10033 EventRef event;
10034 void *data;
10036 OSStatus result, err;
10037 Lisp_Object id_key;
10038 int num_params;
10039 const EventParamName *names;
10040 const EventParamType *types;
10041 static const EventParamName names_sel[] = {kEventParamATSUFontID,
10042 kEventParamATSUFontSize,
10043 kEventParamFMFontFamily,
10044 kEventParamFMFontSize,
10045 kEventParamFontColor};
10046 static const EventParamType types_sel[] = {typeATSUFontID,
10047 typeATSUSize,
10048 typeFMFontFamily,
10049 typeFMFontSize,
10050 typeFontColor};
10052 result = CallNextEventHandler (next_handler, event);
10053 if (result != eventNotHandledErr)
10054 return result;
10056 switch (GetEventKind (event))
10058 case kEventFontPanelClosed:
10059 id_key = Qpanel_closed;
10060 num_params = 0;
10061 names = NULL;
10062 types = NULL;
10063 break;
10065 case kEventFontSelection:
10066 id_key = Qselection;
10067 num_params = sizeof (names_sel) / sizeof (names_sel[0]);
10068 names = names_sel;
10069 types = types_sel;
10070 break;
10073 err = mac_store_event_ref_as_apple_event (0, 0, Qfont, id_key,
10074 event, num_params,
10075 names, types);
10077 return err == noErr ? noErr : eventNotHandledErr;
10079 #endif
10081 #if USE_MAC_TSM
10082 static pascal OSStatus
10083 mac_handle_text_input_event (next_handler, event, data)
10084 EventHandlerCallRef next_handler;
10085 EventRef event;
10086 void *data;
10088 OSStatus result, err = noErr;
10089 Lisp_Object id_key = Qnil;
10090 int num_params;
10091 const EventParamName *names;
10092 const EventParamType *types;
10093 static UInt32 seqno_uaia = 0;
10094 static const EventParamName names_uaia[] =
10095 {kEventParamTextInputSendComponentInstance,
10096 kEventParamTextInputSendRefCon,
10097 kEventParamTextInputSendSLRec,
10098 kEventParamTextInputSendFixLen,
10099 kEventParamTextInputSendText,
10100 kEventParamTextInputSendUpdateRng,
10101 kEventParamTextInputSendHiliteRng,
10102 kEventParamTextInputSendClauseRng,
10103 kEventParamTextInputSendPinRng,
10104 kEventParamTextInputSendTextServiceEncoding,
10105 kEventParamTextInputSendTextServiceMacEncoding,
10106 EVENT_PARAM_TEXT_INPUT_SEQUENCE_NUMBER};
10107 static const EventParamType types_uaia[] =
10108 {typeComponentInstance,
10109 typeLongInteger,
10110 typeIntlWritingCode,
10111 typeLongInteger,
10112 #ifdef MAC_OSX
10113 typeUnicodeText,
10114 #else
10115 typeChar,
10116 #endif
10117 typeTextRangeArray,
10118 typeTextRangeArray,
10119 typeOffsetArray,
10120 typeTextRange,
10121 typeUInt32,
10122 typeUInt32,
10123 typeUInt32};
10124 static const EventParamName names_ufke[] =
10125 {kEventParamTextInputSendComponentInstance,
10126 kEventParamTextInputSendRefCon,
10127 kEventParamTextInputSendSLRec,
10128 kEventParamTextInputSendText};
10129 static const EventParamType types_ufke[] =
10130 {typeComponentInstance,
10131 typeLongInteger,
10132 typeIntlWritingCode,
10133 typeUnicodeText};
10135 result = CallNextEventHandler (next_handler, event);
10137 switch (GetEventKind (event))
10139 case kEventTextInputUpdateActiveInputArea:
10140 id_key = Qupdate_active_input_area;
10141 num_params = sizeof (names_uaia) / sizeof (names_uaia[0]);
10142 names = names_uaia;
10143 types = types_uaia;
10144 SetEventParameter (event, EVENT_PARAM_TEXT_INPUT_SEQUENCE_NUMBER,
10145 typeUInt32, sizeof (UInt32), &seqno_uaia);
10146 seqno_uaia++;
10147 break;
10149 case kEventTextInputUnicodeForKeyEvent:
10151 EventRef kbd_event;
10152 UInt32 actual_size, modifiers;
10154 err = GetEventParameter (event, kEventParamTextInputSendKeyboardEvent,
10155 typeEventRef, NULL, sizeof (EventRef), NULL,
10156 &kbd_event);
10157 if (err == noErr)
10158 err = GetEventParameter (kbd_event, kEventParamKeyModifiers,
10159 typeUInt32, NULL,
10160 sizeof (UInt32), NULL, &modifiers);
10161 if (err == noErr && mac_mapped_modifiers (modifiers))
10162 /* There're mapped modifier keys. Process it in
10163 XTread_socket. */
10164 return eventNotHandledErr;
10165 if (err == noErr)
10166 err = GetEventParameter (kbd_event, kEventParamKeyUnicodes,
10167 typeUnicodeText, NULL, 0, &actual_size,
10168 NULL);
10169 if (err == noErr && actual_size == sizeof (UniChar))
10171 UniChar code;
10173 err = GetEventParameter (kbd_event, kEventParamKeyUnicodes,
10174 typeUnicodeText, NULL,
10175 sizeof (UniChar), NULL, &code);
10176 if (err == noErr && code < 0x80)
10178 /* ASCII character. Process it in XTread_socket. */
10179 if (read_socket_inev && code >= 0x20 && code <= 0x7e)
10181 UInt32 key_code;
10183 err = GetEventParameter (kbd_event, kEventParamKeyCode,
10184 typeUInt32, NULL, sizeof (UInt32),
10185 NULL, &key_code);
10186 if (!(err == noErr && key_code <= 0x7f
10187 && keycode_to_xkeysym_table [key_code]))
10189 struct frame *f =
10190 mac_focus_frame (&one_mac_display_info);
10192 read_socket_inev->kind = ASCII_KEYSTROKE_EVENT;
10193 read_socket_inev->code = code;
10194 read_socket_inev->modifiers =
10195 mac_to_emacs_modifiers (modifiers);
10196 read_socket_inev->modifiers |=
10197 (extra_keyboard_modifiers
10198 & (meta_modifier | alt_modifier
10199 | hyper_modifier | super_modifier));
10200 XSETFRAME (read_socket_inev->frame_or_window, f);
10203 return eventNotHandledErr;
10207 /* Non-ASCII keystrokes without mapped modifiers are processed
10208 at the Lisp level. */
10209 id_key = Qunicode_for_key_event;
10210 num_params = sizeof (names_ufke) / sizeof (names_ufke[0]);
10211 names = names_ufke;
10212 types = types_ufke;
10213 break;
10215 case kEventTextInputOffsetToPos:
10217 struct frame *f;
10218 struct window *w;
10219 Point p;
10221 if (!OVERLAYP (Vmac_ts_active_input_overlay))
10222 return eventNotHandledErr;
10224 /* Strictly speaking, this is not always correct because
10225 previous events may change some states about display. */
10226 if (NILP (Foverlay_get (Vmac_ts_active_input_overlay, Qbefore_string)))
10228 /* Active input area is displayed in the echo area. */
10229 w = XWINDOW (echo_area_window);
10230 f = WINDOW_XFRAME (w);
10232 else
10234 /* Active input area is displayed around the current point. */
10235 f = SELECTED_FRAME ();
10236 w = XWINDOW (f->selected_window);
10239 p.h = (WINDOW_TO_FRAME_PIXEL_X (w, w->cursor.x)
10240 + WINDOW_LEFT_FRINGE_WIDTH (w));
10241 p.v = (WINDOW_TO_FRAME_PIXEL_Y (w, w->cursor.y)
10242 + FONT_BASE (FRAME_FONT (f)));
10243 SetPortWindowPort (FRAME_MAC_WINDOW (f));
10244 LocalToGlobal (&p);
10245 err = SetEventParameter (event, kEventParamTextInputReplyPoint,
10246 typeQDPoint, sizeof (typeQDPoint), &p);
10248 break;
10250 default:
10251 abort ();
10254 if (!NILP (id_key))
10255 err = mac_store_event_ref_as_apple_event (0, 0, Qtext_input, id_key,
10256 event, num_params,
10257 names, types);
10259 return err == noErr ? noErr : result;
10261 #endif
10263 #ifdef MAC_OSX
10264 OSStatus
10265 mac_store_service_event (event)
10266 EventRef event;
10268 OSStatus err;
10269 Lisp_Object id_key;
10270 int num_params;
10271 const EventParamName *names;
10272 const EventParamType *types;
10273 static const EventParamName names_pfm[] =
10274 {kEventParamServiceMessageName, kEventParamServiceUserData};
10275 static const EventParamType types_pfm[] =
10276 {typeCFStringRef, typeCFStringRef};
10278 switch (GetEventKind (event))
10280 case kEventServicePaste:
10281 id_key = Qpaste;
10282 num_params = 0;
10283 names = NULL;
10284 types = NULL;
10285 break;
10287 case kEventServicePerform:
10288 id_key = Qperform;
10289 num_params = sizeof (names_pfm) / sizeof (names_pfm[0]);
10290 names = names_pfm;
10291 types = types_pfm;
10292 break;
10294 default:
10295 abort ();
10298 err = mac_store_event_ref_as_apple_event (0, 0, Qservice, id_key,
10299 event, num_params,
10300 names, types);
10302 return err;
10304 #endif /* MAC_OSX */
10305 #endif /* USE_CARBON_EVENTS */
10308 OSStatus
10309 install_window_handler (window)
10310 WindowPtr window;
10312 OSStatus err = noErr;
10313 #if USE_CARBON_EVENTS
10314 static const EventTypeSpec specs_window[] =
10315 {{kEventClassWindow, kEventWindowUpdate},
10316 {kEventClassWindow, kEventWindowGetIdealSize},
10317 {kEventClassWindow, kEventWindowBoundsChanging},
10318 {kEventClassWindow, kEventWindowBoundsChanged},
10319 {kEventClassWindow, kEventWindowShown},
10320 {kEventClassWindow, kEventWindowHidden},
10321 {kEventClassWindow, kEventWindowExpanded},
10322 {kEventClassWindow, kEventWindowCollapsed},
10323 {kEventClassWindow, kEventWindowClose},
10324 #ifdef MAC_OSX
10325 {kEventClassWindow, kEventWindowToolbarSwitchMode},
10326 #endif
10327 #if USE_MAC_TSM
10328 {kEventClassWindow, kEventWindowFocusAcquired},
10329 {kEventClassWindow, kEventWindowFocusRelinquish},
10330 #endif
10332 static const EventTypeSpec specs_mouse[] =
10333 {{kEventClassMouse, kEventMouseWheelMoved}};
10334 static EventHandlerUPP handle_window_eventUPP = NULL;
10335 static EventHandlerUPP handle_mouse_eventUPP = NULL;
10336 #if USE_MAC_FONT_PANEL
10337 static const EventTypeSpec specs_font[] =
10338 {{kEventClassFont, kEventFontPanelClosed},
10339 {kEventClassFont, kEventFontSelection}};
10340 static EventHandlerUPP handle_font_eventUPP = NULL;
10341 #endif
10342 #if USE_MAC_TSM
10343 static const EventTypeSpec specs_text_input[] =
10344 {{kEventClassTextInput, kEventTextInputUpdateActiveInputArea},
10345 {kEventClassTextInput, kEventTextInputUnicodeForKeyEvent},
10346 {kEventClassTextInput, kEventTextInputOffsetToPos}};
10347 static EventHandlerUPP handle_text_input_eventUPP = NULL;
10348 #endif
10350 if (handle_window_eventUPP == NULL)
10351 handle_window_eventUPP = NewEventHandlerUPP (mac_handle_window_event);
10352 if (handle_mouse_eventUPP == NULL)
10353 handle_mouse_eventUPP = NewEventHandlerUPP (mac_handle_mouse_event);
10354 #if USE_MAC_FONT_PANEL
10355 if (handle_font_eventUPP == NULL)
10356 handle_font_eventUPP = NewEventHandlerUPP (mac_handle_font_event);
10357 #endif
10358 #if USE_MAC_TSM
10359 if (handle_text_input_eventUPP == NULL)
10360 handle_text_input_eventUPP =
10361 NewEventHandlerUPP (mac_handle_text_input_event);
10362 #endif
10363 err = InstallWindowEventHandler (window, handle_window_eventUPP,
10364 GetEventTypeCount (specs_window),
10365 specs_window, NULL, NULL);
10366 if (err == noErr)
10367 err = InstallWindowEventHandler (window, handle_mouse_eventUPP,
10368 GetEventTypeCount (specs_mouse),
10369 specs_mouse, NULL, NULL);
10370 #if USE_MAC_FONT_PANEL
10371 if (err == noErr)
10372 err = InstallWindowEventHandler (window, handle_font_eventUPP,
10373 GetEventTypeCount (specs_font),
10374 specs_font, NULL, NULL);
10375 #endif
10376 #if USE_MAC_TSM
10377 if (err == noErr)
10378 err = InstallWindowEventHandler (window, handle_text_input_eventUPP,
10379 GetEventTypeCount (specs_text_input),
10380 specs_text_input, window, NULL);
10381 #endif
10382 #endif
10383 if (err == noErr)
10384 err = install_drag_handler (window);
10385 if (err == noErr)
10386 err = install_menu_target_item_handler (window);
10388 return err;
10391 void
10392 remove_window_handler (window)
10393 WindowPtr window;
10395 remove_drag_handler (window);
10399 #if __profile__
10400 void
10401 profiler_exit_proc ()
10403 ProfilerDump ("\pEmacs.prof");
10404 ProfilerTerm ();
10406 #endif
10408 /* These few functions implement Emacs as a normal Mac application
10409 (almost): set up the heap and the Toolbox, handle necessary system
10410 events plus a few simple menu events. They also set up Emacs's
10411 access to functions defined in the rest of this file. Emacs uses
10412 function hooks to perform all its terminal I/O. A complete list of
10413 these functions appear in termhooks.h. For what they do, read the
10414 comments there and see also w32term.c and xterm.c. What's
10415 noticeably missing here is the event loop, which is normally
10416 present in most Mac application. After performing the necessary
10417 Mac initializations, main passes off control to emacs_main
10418 (corresponding to main in emacs.c). Emacs_main calls XTread_socket
10419 (defined further below) to read input. This is where
10420 WaitNextEvent/ReceiveNextEvent is called to process Mac events. */
10422 #ifdef MAC_OS8
10423 #undef main
10425 main (void)
10427 #if __profile__ /* is the profiler on? */
10428 if (ProfilerInit(collectDetailed, bestTimeBase, 5000, 200))
10429 exit(1);
10430 #endif
10432 #if __MWERKS__
10433 /* set creator and type for files created by MSL */
10434 _fcreator = MAC_EMACS_CREATOR_CODE;
10435 _ftype = 'TEXT';
10436 #endif
10438 do_init_managers ();
10440 do_get_menus ();
10442 #ifndef USE_LSB_TAG
10443 do_check_ram_size ();
10444 #endif
10446 init_emacs_passwd_dir ();
10448 init_environ ();
10450 init_coercion_handler ();
10452 initialize_applescript ();
10454 init_apple_event_handler ();
10457 char **argv;
10458 int argc = 0;
10460 /* set up argv array from STR# resource */
10461 get_string_list (&argv, ARGV_STRING_LIST_ID);
10462 while (argv[argc])
10463 argc++;
10465 /* free up AppleScript resources on exit */
10466 atexit (terminate_applescript);
10468 #if __profile__ /* is the profiler on? */
10469 atexit (profiler_exit_proc);
10470 #endif
10472 /* 3rd param "envp" never used in emacs_main */
10473 (void) emacs_main (argc, argv, 0);
10476 /* Never reached - real exit in Fkill_emacs */
10477 return 0;
10479 #endif
10481 #if !USE_CARBON_EVENTS
10482 static RgnHandle mouse_region = NULL;
10484 Boolean
10485 mac_wait_next_event (er, sleep_time, dequeue)
10486 EventRecord *er;
10487 UInt32 sleep_time;
10488 Boolean dequeue;
10490 static EventRecord er_buf = {nullEvent};
10491 UInt32 target_tick, current_tick;
10492 EventMask event_mask;
10494 if (mouse_region == NULL)
10495 mouse_region = NewRgn ();
10497 event_mask = everyEvent;
10498 if (!mac_ready_for_apple_events)
10499 event_mask -= highLevelEventMask;
10501 current_tick = TickCount ();
10502 target_tick = current_tick + sleep_time;
10504 if (er_buf.what == nullEvent)
10505 while (!WaitNextEvent (event_mask, &er_buf,
10506 target_tick - current_tick, mouse_region))
10508 current_tick = TickCount ();
10509 if (target_tick <= current_tick)
10510 return false;
10513 *er = er_buf;
10514 if (dequeue)
10515 er_buf.what = nullEvent;
10516 return true;
10518 #endif /* not USE_CARBON_EVENTS */
10520 #if TARGET_API_MAC_CARBON
10521 OSStatus
10522 mac_post_mouse_moved_event ()
10524 EventRef event = NULL;
10525 OSStatus err;
10527 err = CreateEvent (NULL, kEventClassMouse, kEventMouseMoved, 0,
10528 kEventAttributeNone, &event);
10529 if (err == noErr)
10531 Point mouse_pos;
10533 GetMouse (&mouse_pos);
10534 LocalToGlobal (&mouse_pos);
10535 err = SetEventParameter (event, kEventParamMouseLocation, typeQDPoint,
10536 sizeof (Point), &mouse_pos);
10538 if (err == noErr)
10540 UInt32 modifiers = GetCurrentKeyModifiers ();
10542 err = SetEventParameter (event, kEventParamKeyModifiers, typeUInt32,
10543 sizeof (UInt32), &modifiers);
10545 if (err == noErr)
10546 err = PostEventToQueue (GetCurrentEventQueue (), event,
10547 kEventPriorityStandard);
10548 if (event)
10549 ReleaseEvent (event);
10551 return err;
10554 static void
10555 mac_set_unicode_keystroke_event (code, buf)
10556 UniChar code;
10557 struct input_event *buf;
10559 int charset_id, c1, c2;
10561 if (code < 0x80)
10563 buf->kind = ASCII_KEYSTROKE_EVENT;
10564 buf->code = code;
10566 else if (code < 0x100)
10568 if (code < 0xA0)
10569 charset_id = CHARSET_8_BIT_CONTROL;
10570 else
10571 charset_id = charset_latin_iso8859_1;
10572 buf->kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
10573 buf->code = MAKE_CHAR (charset_id, code, 0);
10575 else
10577 if (code < 0x2500)
10578 charset_id = charset_mule_unicode_0100_24ff,
10579 code -= 0x100;
10580 else if (code < 0x33FF)
10581 charset_id = charset_mule_unicode_2500_33ff,
10582 code -= 0x2500;
10583 else if (code >= 0xE000)
10584 charset_id = charset_mule_unicode_e000_ffff,
10585 code -= 0xE000;
10586 c1 = (code / 96) + 32, c2 = (code % 96) + 32;
10587 buf->kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
10588 buf->code = MAKE_CHAR (charset_id, c1, c2);
10591 #endif
10593 /* Emacs calls this whenever it wants to read an input event from the
10594 user. */
10596 XTread_socket (sd, expected, hold_quit)
10597 int sd, expected;
10598 struct input_event *hold_quit;
10600 struct input_event inev;
10601 int count = 0;
10602 #if USE_CARBON_EVENTS
10603 EventRef eventRef;
10604 EventTargetRef toolbox_dispatcher;
10605 #endif
10606 EventRecord er;
10607 struct mac_display_info *dpyinfo = &one_mac_display_info;
10609 if (interrupt_input_blocked)
10611 interrupt_input_pending = 1;
10612 return -1;
10615 interrupt_input_pending = 0;
10616 BLOCK_INPUT;
10618 /* So people can tell when we have read the available input. */
10619 input_signal_count++;
10621 ++handling_signal;
10623 #if USE_CARBON_EVENTS
10624 toolbox_dispatcher = GetEventDispatcherTarget ();
10626 while (
10627 #if USE_CG_DRAWING
10628 mac_prepare_for_quickdraw (NULL),
10629 #endif
10630 !ReceiveNextEvent (0, NULL, kEventDurationNoWait,
10631 kEventRemoveFromQueue, &eventRef))
10632 #else /* !USE_CARBON_EVENTS */
10633 while (mac_wait_next_event (&er, 0, true))
10634 #endif /* !USE_CARBON_EVENTS */
10636 int do_help = 0;
10637 struct frame *f;
10638 unsigned long timestamp;
10640 EVENT_INIT (inev);
10641 inev.kind = NO_EVENT;
10642 inev.arg = Qnil;
10644 #if USE_CARBON_EVENTS
10645 timestamp = GetEventTime (eventRef) / kEventDurationMillisecond;
10646 #else
10647 timestamp = er.when * (1000 / 60); /* ticks to milliseconds */
10648 #endif
10650 #if USE_CARBON_EVENTS
10651 /* Handle new events */
10652 if (!mac_convert_event_ref (eventRef, &er))
10654 /* There used to be a handler for the kEventMouseWheelMoved
10655 event here. But as of Mac OS X 10.4, this kind of event
10656 is not directly posted to the main event queue by
10657 two-finger scrolling on the trackpad. Instead, some
10658 private event is posted and it is converted to a wheel
10659 event by the default handler for the application target.
10660 The converted one can be received by a Carbon event
10661 handler installed on a window target. */
10662 read_socket_inev = &inev;
10663 SendEventToEventTarget (eventRef, toolbox_dispatcher);
10664 read_socket_inev = NULL;
10666 else
10667 #endif /* USE_CARBON_EVENTS */
10668 switch (er.what)
10670 case mouseDown:
10671 case mouseUp:
10673 WindowPtr window_ptr;
10674 ControlPartCode part_code;
10675 int tool_bar_p = 0;
10677 #if USE_CARBON_EVENTS
10678 /* This is needed to send mouse events like aqua window
10679 buttons to the correct handler. */
10680 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
10681 != eventNotHandledErr)
10682 break;
10683 #endif
10684 last_mouse_glyph_frame = 0;
10686 if (dpyinfo->grabbed && last_mouse_frame
10687 && FRAME_LIVE_P (last_mouse_frame))
10689 window_ptr = FRAME_MAC_WINDOW (last_mouse_frame);
10690 part_code = inContent;
10692 else
10694 part_code = FindWindow (er.where, &window_ptr);
10695 if (tip_window && window_ptr == tip_window)
10697 HideWindow (tip_window);
10698 part_code = FindWindow (er.where, &window_ptr);
10702 if (er.what != mouseDown &&
10703 (part_code != inContent || dpyinfo->grabbed == 0))
10704 break;
10706 switch (part_code)
10708 case inMenuBar:
10709 f = mac_focus_frame (dpyinfo);
10710 saved_menu_event_location = er.where;
10711 inev.kind = MENU_BAR_ACTIVATE_EVENT;
10712 XSETFRAME (inev.frame_or_window, f);
10713 break;
10715 case inContent:
10716 if (
10717 #if TARGET_API_MAC_CARBON
10718 FrontNonFloatingWindow ()
10719 #else
10720 FrontWindow ()
10721 #endif
10722 != window_ptr
10723 || (mac_window_to_frame (window_ptr)
10724 != dpyinfo->x_focus_frame))
10725 SelectWindow (window_ptr);
10726 else
10728 ControlPartCode control_part_code;
10729 ControlHandle ch;
10730 Point mouse_loc = er.where;
10731 #ifdef MAC_OSX
10732 ControlKind control_kind;
10733 #endif
10735 f = mac_window_to_frame (window_ptr);
10736 /* convert to local coordinates of new window */
10737 SetPortWindowPort (window_ptr);
10739 GlobalToLocal (&mouse_loc);
10740 #if TARGET_API_MAC_CARBON
10741 ch = FindControlUnderMouse (mouse_loc, window_ptr,
10742 &control_part_code);
10743 #ifdef MAC_OSX
10744 if (ch)
10745 GetControlKind (ch, &control_kind);
10746 #endif
10747 #else
10748 control_part_code = FindControl (mouse_loc, window_ptr,
10749 &ch);
10750 #endif
10752 #if USE_CARBON_EVENTS
10753 inev.code = mac_get_mouse_btn (eventRef);
10754 inev.modifiers = mac_event_to_emacs_modifiers (eventRef);
10755 #else
10756 inev.code = mac_get_emulated_btn (er.modifiers);
10757 inev.modifiers = mac_to_emacs_modifiers (er.modifiers);
10758 #endif
10759 XSETINT (inev.x, mouse_loc.h);
10760 XSETINT (inev.y, mouse_loc.v);
10762 if ((dpyinfo->grabbed && tracked_scroll_bar)
10763 || (ch != 0
10764 #ifndef USE_TOOLKIT_SCROLL_BARS
10765 /* control_part_code becomes kControlNoPart if
10766 a progress indicator is clicked. */
10767 && control_part_code != kControlNoPart
10768 #else /* USE_TOOLKIT_SCROLL_BARS */
10769 #ifdef MAC_OSX
10770 && control_kind.kind == kControlKindScrollBar
10771 #endif /* MAC_OSX */
10772 #endif /* USE_TOOLKIT_SCROLL_BARS */
10775 struct scroll_bar *bar;
10777 if (dpyinfo->grabbed && tracked_scroll_bar)
10779 bar = tracked_scroll_bar;
10780 #ifndef USE_TOOLKIT_SCROLL_BARS
10781 control_part_code = kControlIndicatorPart;
10782 #endif
10784 else
10785 bar = (struct scroll_bar *) GetControlReference (ch);
10786 #ifdef USE_TOOLKIT_SCROLL_BARS
10787 /* Make the "Ctrl-Mouse-2 splits window" work
10788 for toolkit scroll bars. */
10789 if (inev.modifiers & ctrl_modifier)
10790 x_scroll_bar_handle_click (bar, control_part_code,
10791 &er, &inev);
10792 else if (er.what == mouseDown)
10793 x_scroll_bar_handle_press (bar, control_part_code,
10794 mouse_loc, &inev);
10795 else
10796 x_scroll_bar_handle_release (bar, &inev);
10797 #else /* not USE_TOOLKIT_SCROLL_BARS */
10798 x_scroll_bar_handle_click (bar, control_part_code,
10799 &er, &inev);
10800 if (er.what == mouseDown
10801 && control_part_code == kControlIndicatorPart)
10802 tracked_scroll_bar = bar;
10803 else
10804 tracked_scroll_bar = NULL;
10805 #endif /* not USE_TOOLKIT_SCROLL_BARS */
10807 else
10809 Lisp_Object window;
10810 int x = mouse_loc.h;
10811 int y = mouse_loc.v;
10813 window = window_from_coordinates (f, x, y, 0, 0, 0, 1);
10814 if (EQ (window, f->tool_bar_window))
10816 if (er.what == mouseDown)
10817 handle_tool_bar_click (f, x, y, 1, 0);
10818 else
10819 handle_tool_bar_click (f, x, y, 0,
10820 inev.modifiers);
10821 tool_bar_p = 1;
10823 else
10825 XSETFRAME (inev.frame_or_window, f);
10826 inev.kind = MOUSE_CLICK_EVENT;
10830 if (er.what == mouseDown)
10832 dpyinfo->grabbed |= (1 << inev.code);
10833 last_mouse_frame = f;
10835 if (!tool_bar_p)
10836 last_tool_bar_item = -1;
10838 else
10840 if ((dpyinfo->grabbed & (1 << inev.code)) == 0)
10841 /* If a button is released though it was not
10842 previously pressed, that would be because
10843 of multi-button emulation. */
10844 dpyinfo->grabbed = 0;
10845 else
10846 dpyinfo->grabbed &= ~(1 << inev.code);
10849 /* Ignore any mouse motion that happened before
10850 this event; any subsequent mouse-movement Emacs
10851 events should reflect only motion after the
10852 ButtonPress. */
10853 if (f != 0)
10854 f->mouse_moved = 0;
10856 #ifdef USE_TOOLKIT_SCROLL_BARS
10857 if (inev.kind == MOUSE_CLICK_EVENT
10858 || (inev.kind == SCROLL_BAR_CLICK_EVENT
10859 && (inev.modifiers & ctrl_modifier)))
10860 #endif
10861 switch (er.what)
10863 case mouseDown:
10864 inev.modifiers |= down_modifier;
10865 break;
10866 case mouseUp:
10867 inev.modifiers |= up_modifier;
10868 break;
10871 break;
10873 case inDrag:
10874 #if TARGET_API_MAC_CARBON
10875 case inProxyIcon:
10876 if (IsWindowPathSelectClick (window_ptr, &er))
10878 WindowPathSelect (window_ptr, NULL, NULL);
10879 break;
10881 if (part_code == inProxyIcon
10882 && (TrackWindowProxyDrag (window_ptr, er.where)
10883 != errUserWantsToDragWindow))
10884 break;
10885 DragWindow (window_ptr, er.where, NULL);
10886 #else /* not TARGET_API_MAC_CARBON */
10887 DragWindow (window_ptr, er.where, &qd.screenBits.bounds);
10888 #endif /* not TARGET_API_MAC_CARBON */
10889 /* Update the frame parameters. */
10890 #if !USE_CARBON_EVENTS
10892 struct frame *f = mac_window_to_frame (window_ptr);
10894 if (f && !f->async_iconified)
10895 mac_handle_origin_change (f);
10897 #endif
10898 break;
10900 case inGoAway:
10901 if (TrackGoAway (window_ptr, er.where))
10903 inev.kind = DELETE_WINDOW_EVENT;
10904 XSETFRAME (inev.frame_or_window,
10905 mac_window_to_frame (window_ptr));
10907 break;
10909 /* window resize handling added --ben */
10910 case inGrow:
10911 do_grow_window (window_ptr, &er);
10912 break;
10914 /* window zoom handling added --ben */
10915 case inZoomIn:
10916 case inZoomOut:
10917 if (TrackBox (window_ptr, er.where, part_code))
10918 do_zoom_window (window_ptr, part_code);
10919 break;
10921 default:
10922 break;
10925 break;
10927 case updateEvt:
10928 #if USE_CARBON_EVENTS
10929 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
10930 != eventNotHandledErr)
10931 break;
10932 #else
10933 do_window_update ((WindowPtr) er.message);
10934 #endif
10935 break;
10937 case osEvt:
10938 #if USE_CARBON_EVENTS
10939 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
10940 != eventNotHandledErr)
10941 break;
10942 #endif
10943 switch ((er.message >> 24) & 0x000000FF)
10945 case suspendResumeMessage:
10946 #if USE_MAC_TSM
10947 if (er.message & resumeFlag)
10948 mac_tsm_resume ();
10949 else
10950 mac_tsm_suspend ();
10951 #endif
10952 break;
10954 case mouseMovedMessage:
10955 #if !USE_CARBON_EVENTS
10956 SetRectRgn (mouse_region, er.where.h, er.where.v,
10957 er.where.h + 1, er.where.v + 1);
10958 #endif
10959 previous_help_echo_string = help_echo_string;
10960 help_echo_string = Qnil;
10962 if (dpyinfo->grabbed && last_mouse_frame
10963 && FRAME_LIVE_P (last_mouse_frame))
10964 f = last_mouse_frame;
10965 else
10966 f = dpyinfo->x_focus_frame;
10968 if (dpyinfo->mouse_face_hidden)
10970 dpyinfo->mouse_face_hidden = 0;
10971 clear_mouse_face (dpyinfo);
10974 if (f)
10976 WindowPtr wp = FRAME_MAC_WINDOW (f);
10977 Point mouse_pos = er.where;
10979 SetPortWindowPort (wp);
10981 GlobalToLocal (&mouse_pos);
10983 if (dpyinfo->grabbed && tracked_scroll_bar)
10984 #ifdef USE_TOOLKIT_SCROLL_BARS
10985 x_scroll_bar_handle_drag (wp, tracked_scroll_bar,
10986 mouse_pos, &inev);
10987 #else /* not USE_TOOLKIT_SCROLL_BARS */
10988 x_scroll_bar_note_movement (tracked_scroll_bar,
10989 mouse_pos.v
10990 - XINT (tracked_scroll_bar->top),
10991 er.when * (1000 / 60));
10992 #endif /* not USE_TOOLKIT_SCROLL_BARS */
10993 else
10995 /* Generate SELECT_WINDOW_EVENTs when needed. */
10996 if (!NILP (Vmouse_autoselect_window))
10998 Lisp_Object window;
11000 window = window_from_coordinates (f,
11001 mouse_pos.h,
11002 mouse_pos.v,
11003 0, 0, 0, 0);
11005 /* Window will be selected only when it is
11006 not selected now and last mouse movement
11007 event was not in it. Minibuffer window
11008 will be selected iff it is active. */
11009 if (WINDOWP (window)
11010 && !EQ (window, last_window)
11011 && !EQ (window, selected_window))
11013 inev.kind = SELECT_WINDOW_EVENT;
11014 inev.frame_or_window = window;
11017 last_window=window;
11019 if (!note_mouse_movement (f, &mouse_pos))
11020 help_echo_string = previous_help_echo_string;
11024 /* If the contents of the global variable
11025 help_echo_string has changed, generate a
11026 HELP_EVENT. */
11027 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
11028 do_help = 1;
11029 break;
11031 break;
11033 case activateEvt:
11035 WindowPtr window_ptr = (WindowPtr) er.message;
11037 #if USE_CARBON_EVENTS
11038 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
11039 != eventNotHandledErr)
11040 break;
11041 #endif
11042 if (window_ptr == tip_window)
11044 HideWindow (tip_window);
11045 break;
11048 if (!is_emacs_window (window_ptr))
11049 break;
11051 if ((er.modifiers & activeFlag) != 0)
11053 /* A window has been activated */
11054 Point mouse_loc = er.where;
11056 x_detect_focus_change (dpyinfo, &er, &inev);
11058 SetPortWindowPort (window_ptr);
11059 GlobalToLocal (&mouse_loc);
11060 /* Window-activated event counts as mouse movement,
11061 so update things that depend on mouse position. */
11062 note_mouse_movement (mac_window_to_frame (window_ptr),
11063 &mouse_loc);
11065 else
11067 /* A window has been deactivated */
11068 #ifdef USE_TOOLKIT_SCROLL_BARS
11069 if (dpyinfo->grabbed && tracked_scroll_bar)
11071 struct input_event event;
11073 EVENT_INIT (event);
11074 event.kind = NO_EVENT;
11075 x_scroll_bar_handle_release (tracked_scroll_bar, &event);
11076 if (event.kind != NO_EVENT)
11078 event.timestamp = timestamp;
11079 kbd_buffer_store_event_hold (&event, hold_quit);
11080 count++;
11083 #endif
11084 dpyinfo->grabbed = 0;
11086 x_detect_focus_change (dpyinfo, &er, &inev);
11088 f = mac_window_to_frame (window_ptr);
11089 if (f == dpyinfo->mouse_face_mouse_frame)
11091 /* If we move outside the frame, then we're
11092 certainly no longer on any text in the
11093 frame. */
11094 clear_mouse_face (dpyinfo);
11095 dpyinfo->mouse_face_mouse_frame = 0;
11098 /* Generate a nil HELP_EVENT to cancel a help-echo.
11099 Do it only if there's something to cancel.
11100 Otherwise, the startup message is cleared when the
11101 mouse leaves the frame. */
11102 if (any_help_event_p)
11103 do_help = -1;
11106 break;
11108 case keyDown:
11109 case keyUp:
11110 case autoKey:
11112 int keycode = (er.message & keyCodeMask) >> 8;
11113 static SInt16 last_key_script = -1;
11114 SInt16 current_key_script;
11115 UInt32 modifiers = er.modifiers, mapped_modifiers;
11117 #if USE_CARBON_EVENTS && defined (MAC_OSX)
11118 GetEventParameter (eventRef, kEventParamKeyModifiers,
11119 typeUInt32, NULL,
11120 sizeof (UInt32), NULL, &modifiers);
11121 #endif
11122 mapped_modifiers = mac_mapped_modifiers (modifiers);
11124 #if USE_CARBON_EVENTS && (defined (MAC_OSX) || USE_MAC_TSM)
11125 /* When using Carbon Events, we need to pass raw keyboard
11126 events to the TSM ourselves. If TSM handles it, it
11127 will pass back noErr, otherwise it will pass back
11128 "eventNotHandledErr" and we can process it
11129 normally. */
11130 if (!(mapped_modifiers
11131 & ~(mac_pass_command_to_system ? cmdKey : 0)
11132 & ~(mac_pass_control_to_system ? controlKey : 0)))
11134 OSStatus err;
11136 read_socket_inev = &inev;
11137 err = SendEventToEventTarget (eventRef, toolbox_dispatcher);
11138 read_socket_inev = NULL;
11139 if (err != eventNotHandledErr)
11140 break;
11142 #endif
11143 if (er.what == keyUp)
11144 break;
11146 ObscureCursor ();
11148 f = mac_focus_frame (dpyinfo);
11150 if (!dpyinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight)
11151 && !EQ (f->tool_bar_window, dpyinfo->mouse_face_window))
11153 clear_mouse_face (dpyinfo);
11154 dpyinfo->mouse_face_hidden = 1;
11157 current_key_script = GetScriptManagerVariable (smKeyScript);
11158 if (last_key_script != current_key_script)
11160 struct input_event event;
11162 EVENT_INIT (event);
11163 event.kind = LANGUAGE_CHANGE_EVENT;
11164 event.arg = Qnil;
11165 event.code = current_key_script;
11166 event.timestamp = timestamp;
11167 kbd_buffer_store_event (&event);
11168 count++;
11169 last_key_script = current_key_script;
11172 #if USE_MAC_TSM
11173 if (inev.kind != NO_EVENT)
11174 break;
11175 #endif
11177 #ifdef MAC_OSX
11178 if (mapped_modifiers & kEventKeyModifierFnMask
11179 && keycode <= 0x7f
11180 && fn_keycode_to_keycode_table[keycode])
11181 keycode = fn_keycode_to_keycode_table[keycode];
11182 #endif
11183 if (keycode <= 0x7f && keycode_to_xkeysym_table [keycode])
11185 inev.kind = NON_ASCII_KEYSTROKE_EVENT;
11186 inev.code = 0xff00 | keycode_to_xkeysym_table [keycode];
11187 #ifdef MAC_OSX
11188 if (modifiers & kEventKeyModifierFnMask
11189 && keycode <= 0x7f
11190 && fn_keycode_to_keycode_table[keycode] == keycode)
11191 modifiers &= ~kEventKeyModifierFnMask;
11192 #endif
11194 else if (mapped_modifiers)
11196 /* translate the keycode back to determine the
11197 original key */
11198 #ifdef MAC_OSX
11199 UCKeyboardLayout *uchr_ptr = NULL;
11200 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
11201 OSStatus err;
11202 KeyboardLayoutRef layout;
11204 err = KLGetCurrentKeyboardLayout (&layout);
11205 if (err == noErr)
11206 KLGetKeyboardLayoutProperty (layout, kKLuchrData,
11207 (const void **) &uchr_ptr);
11208 #else
11209 static SInt16 last_key_layout_id = 0;
11210 static Handle uchr_handle = (Handle)-1;
11211 SInt16 current_key_layout_id =
11212 GetScriptVariable (current_key_script, smScriptKeys);
11214 if (uchr_handle == (Handle)-1
11215 || last_key_layout_id != current_key_layout_id)
11217 uchr_handle = GetResource ('uchr', current_key_layout_id);
11218 last_key_layout_id = current_key_layout_id;
11220 if (uchr_handle)
11221 uchr_ptr = (UCKeyboardLayout *)*uchr_handle;
11222 #endif
11224 if (uchr_ptr)
11226 OSStatus status;
11227 UInt16 key_action = er.what - keyDown;
11228 UInt32 modifier_key_state =
11229 (modifiers & ~mapped_modifiers) >> 8;
11230 UInt32 keyboard_type = LMGetKbdType ();
11231 SInt32 dead_key_state = 0;
11232 UniChar code;
11233 UniCharCount actual_length;
11235 status = UCKeyTranslate (uchr_ptr,
11236 keycode, key_action,
11237 modifier_key_state,
11238 keyboard_type,
11239 kUCKeyTranslateNoDeadKeysMask,
11240 &dead_key_state,
11241 1, &actual_length, &code);
11242 if (status == noErr && actual_length == 1)
11243 mac_set_unicode_keystroke_event (code, &inev);
11245 #endif /* MAC_OSX */
11247 if (inev.kind == NO_EVENT)
11249 /* This code comes from Keyboard Resource,
11250 Appendix C of IM - Text. This is necessary
11251 since shift is ignored in KCHR table
11252 translation when option or command is pressed.
11253 It also does not translate correctly
11254 control-shift chars like C-% so mask off shift
11255 here also. */
11256 /* Mask off modifier keys that are mapped to some
11257 Emacs modifiers. */
11258 int new_modifiers = er.modifiers & ~mapped_modifiers;
11259 /* set high byte of keycode to modifier high byte*/
11260 int new_keycode = keycode | new_modifiers;
11261 Ptr kchr_ptr = (Ptr) GetScriptManagerVariable (smKCHRCache);
11262 unsigned long some_state = 0;
11263 UInt32 new_char_code;
11265 new_char_code = KeyTranslate (kchr_ptr, new_keycode,
11266 &some_state);
11267 if (new_char_code == 0)
11268 /* Seems like a dead key. Append up-stroke. */
11269 new_char_code = KeyTranslate (kchr_ptr,
11270 new_keycode | 0x80,
11271 &some_state);
11272 if (new_char_code)
11274 inev.kind = ASCII_KEYSTROKE_EVENT;
11275 inev.code = new_char_code & 0xff;
11280 if (inev.kind == NO_EVENT)
11282 inev.kind = ASCII_KEYSTROKE_EVENT;
11283 inev.code = er.message & charCodeMask;
11286 inev.modifiers = mac_to_emacs_modifiers (modifiers);
11287 inev.modifiers |= (extra_keyboard_modifiers
11288 & (meta_modifier | alt_modifier
11289 | hyper_modifier | super_modifier));
11290 XSETFRAME (inev.frame_or_window, f);
11292 #if TARGET_API_MAC_CARBON
11293 if (inev.kind == ASCII_KEYSTROKE_EVENT
11294 && inev.code >= 0x80 && inev.modifiers)
11296 OSStatus err;
11297 TextEncoding encoding = kTextEncodingMacRoman;
11298 TextToUnicodeInfo ttu_info;
11300 UpgradeScriptInfoToTextEncoding (current_key_script,
11301 kTextLanguageDontCare,
11302 kTextRegionDontCare,
11303 NULL, &encoding);
11304 err = CreateTextToUnicodeInfoByEncoding (encoding, &ttu_info);
11305 if (err == noErr)
11307 UniChar code;
11308 Str255 pstr;
11309 ByteCount unicode_len;
11311 pstr[0] = 1;
11312 pstr[1] = inev.code;
11313 err = ConvertFromPStringToUnicode (ttu_info, pstr,
11314 sizeof (UniChar),
11315 &unicode_len, &code);
11316 if (err == noErr && unicode_len == sizeof (UniChar))
11317 mac_set_unicode_keystroke_event (code, &inev);
11318 DisposeTextToUnicodeInfo (&ttu_info);
11321 #endif
11323 break;
11325 case kHighLevelEvent:
11326 AEProcessAppleEvent (&er);
11327 break;
11329 default:
11330 break;
11332 #if USE_CARBON_EVENTS
11333 ReleaseEvent (eventRef);
11334 #endif
11336 if (inev.kind != NO_EVENT)
11338 inev.timestamp = timestamp;
11339 kbd_buffer_store_event_hold (&inev, hold_quit);
11340 count++;
11343 if (do_help
11344 && !(hold_quit && hold_quit->kind != NO_EVENT))
11346 Lisp_Object frame;
11348 if (f)
11349 XSETFRAME (frame, f);
11350 else
11351 frame = Qnil;
11353 if (do_help > 0)
11355 any_help_event_p = 1;
11356 gen_help_event (help_echo_string, frame, help_echo_window,
11357 help_echo_object, help_echo_pos);
11359 else
11361 help_echo_string = Qnil;
11362 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
11364 count++;
11369 /* If the focus was just given to an autoraising frame,
11370 raise it now. */
11371 /* ??? This ought to be able to handle more than one such frame. */
11372 if (pending_autoraise_frame)
11374 x_raise_frame (pending_autoraise_frame);
11375 pending_autoraise_frame = 0;
11378 #if !USE_CARBON_EVENTS
11379 /* Check which frames are still visible. We do this here because
11380 there doesn't seem to be any direct notification from the Window
11381 Manager that the visibility of a window has changed (at least,
11382 not in all cases). */
11384 Lisp_Object tail, frame;
11386 FOR_EACH_FRAME (tail, frame)
11388 struct frame *f = XFRAME (frame);
11390 /* The tooltip has been drawn already. Avoid the
11391 SET_FRAME_GARBAGED in mac_handle_visibility_change. */
11392 if (EQ (frame, tip_frame))
11393 continue;
11395 if (FRAME_MAC_P (f))
11396 mac_handle_visibility_change (f);
11399 #endif
11401 --handling_signal;
11402 UNBLOCK_INPUT;
11403 return count;
11407 /* Need to override CodeWarrior's input function so no conversion is
11408 done on newlines Otherwise compiled functions in .elc files will be
11409 read incorrectly. Defined in ...:MSL C:MSL
11410 Common:Source:buffer_io.c. */
11411 #ifdef __MWERKS__
11412 void
11413 __convert_to_newlines (unsigned char * p, size_t * n)
11415 #pragma unused(p,n)
11418 void
11419 __convert_from_newlines (unsigned char * p, size_t * n)
11421 #pragma unused(p,n)
11423 #endif
11425 #ifdef MAC_OS8
11426 void
11427 make_mac_terminal_frame (struct frame *f)
11429 Lisp_Object frame;
11430 Rect r;
11432 XSETFRAME (frame, f);
11434 f->output_method = output_mac;
11435 f->output_data.mac = (struct mac_output *)
11436 xmalloc (sizeof (struct mac_output));
11437 bzero (f->output_data.mac, sizeof (struct mac_output));
11439 XSETFRAME (FRAME_KBOARD (f)->Vdefault_minibuffer_frame, f);
11441 FRAME_COLS (f) = 96;
11442 FRAME_LINES (f) = 4;
11444 FRAME_CAN_HAVE_SCROLL_BARS (f) = 1;
11445 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = vertical_scroll_bar_right;
11447 FRAME_DESIRED_CURSOR (f) = FILLED_BOX_CURSOR;
11449 f->output_data.mac->cursor_pixel = 0;
11450 f->output_data.mac->border_pixel = 0x00ff00;
11451 f->output_data.mac->mouse_pixel = 0xff00ff;
11452 f->output_data.mac->cursor_foreground_pixel = 0x0000ff;
11454 f->output_data.mac->text_cursor = kThemeIBeamCursor;
11455 f->output_data.mac->nontext_cursor = kThemeArrowCursor;
11456 f->output_data.mac->modeline_cursor = kThemeArrowCursor;
11457 f->output_data.mac->hand_cursor = kThemePointingHandCursor;
11458 f->output_data.mac->hourglass_cursor = kThemeWatchCursor;
11459 f->output_data.mac->horizontal_drag_cursor = kThemeResizeLeftRightCursor;
11461 FRAME_FONTSET (f) = -1;
11462 f->output_data.mac->explicit_parent = 0;
11463 f->left_pos = 8;
11464 f->top_pos = 32;
11465 f->border_width = 0;
11467 f->internal_border_width = 0;
11469 f->auto_raise = 1;
11470 f->auto_lower = 1;
11472 f->new_text_cols = 0;
11473 f->new_text_lines = 0;
11475 SetRect (&r, f->left_pos, f->top_pos,
11476 f->left_pos + FRAME_PIXEL_WIDTH (f),
11477 f->top_pos + FRAME_PIXEL_HEIGHT (f));
11479 BLOCK_INPUT;
11481 if (!(FRAME_MAC_WINDOW (f) =
11482 NewCWindow (NULL, &r, "\p", true, dBoxProc,
11483 (WindowPtr) -1, 1, (long) f->output_data.mac)))
11484 abort ();
11485 /* so that update events can find this mac_output struct */
11486 f->output_data.mac->mFP = f; /* point back to emacs frame */
11488 UNBLOCK_INPUT;
11490 x_make_gc (f);
11492 /* Need to be initialized for unshow_buffer in window.c. */
11493 selected_window = f->selected_window;
11495 Fmodify_frame_parameters (frame,
11496 Fcons (Fcons (Qfont,
11497 build_string ("-*-monaco-medium-r-*--*-90-*-*-*-*-mac-roman")), Qnil));
11498 Fmodify_frame_parameters (frame,
11499 Fcons (Fcons (Qforeground_color,
11500 build_string ("black")), Qnil));
11501 Fmodify_frame_parameters (frame,
11502 Fcons (Fcons (Qbackground_color,
11503 build_string ("white")), Qnil));
11505 #endif
11508 /***********************************************************************
11509 Initialization
11510 ***********************************************************************/
11512 int mac_initialized = 0;
11514 void
11515 mac_initialize_display_info ()
11517 struct mac_display_info *dpyinfo = &one_mac_display_info;
11519 bzero (dpyinfo, sizeof (*dpyinfo));
11521 #ifdef MAC_OSX
11522 dpyinfo->mac_id_name
11523 = (char *) xmalloc (SCHARS (Vinvocation_name)
11524 + SCHARS (Vsystem_name)
11525 + 2);
11526 sprintf (dpyinfo->mac_id_name, "%s@%s",
11527 SDATA (Vinvocation_name), SDATA (Vsystem_name));
11528 #else
11529 dpyinfo->mac_id_name = (char *) xmalloc (strlen ("Mac Display") + 1);
11530 strcpy (dpyinfo->mac_id_name, "Mac Display");
11531 #endif
11533 dpyinfo->reference_count = 0;
11534 dpyinfo->resx = 72.0;
11535 dpyinfo->resy = 72.0;
11536 #ifdef MAC_OSX
11537 /* HasDepth returns true if it is possible to have a 32 bit display,
11538 but this may not be what is actually used. Mac OSX can do better. */
11539 dpyinfo->color_p = CGDisplaySamplesPerPixel (kCGDirectMainDisplay) > 1;
11540 dpyinfo->n_planes = CGDisplayBitsPerPixel (kCGDirectMainDisplay);
11541 dpyinfo->height = CGDisplayPixelsHigh (kCGDirectMainDisplay);
11542 dpyinfo->width = CGDisplayPixelsWide (kCGDirectMainDisplay);
11543 #else
11545 GDHandle main_device_handle = LMGetMainDevice();
11547 dpyinfo->color_p = TestDeviceAttribute (main_device_handle, gdDevType);
11548 for (dpyinfo->n_planes = 32; dpyinfo->n_planes > 0; dpyinfo->n_planes >>= 1)
11549 if (HasDepth (main_device_handle, dpyinfo->n_planes,
11550 gdDevType, dpyinfo->color_p))
11551 break;
11552 dpyinfo->height = (**main_device_handle).gdRect.bottom;
11553 dpyinfo->width = (**main_device_handle).gdRect.right;
11555 #endif
11556 dpyinfo->grabbed = 0;
11557 dpyinfo->root_window = NULL;
11558 dpyinfo->image_cache = make_image_cache ();
11560 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
11561 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
11562 dpyinfo->mouse_face_face_id = DEFAULT_FACE_ID;
11563 dpyinfo->mouse_face_window = Qnil;
11564 dpyinfo->mouse_face_overlay = Qnil;
11565 dpyinfo->mouse_face_hidden = 0;
11569 static XrmDatabase
11570 mac_make_rdb (xrm_option)
11571 const char *xrm_option;
11573 XrmDatabase database;
11575 database = xrm_get_preference_database (NULL);
11576 if (xrm_option)
11577 xrm_merge_string_database (database, xrm_option);
11579 return database;
11582 struct mac_display_info *
11583 mac_term_init (display_name, xrm_option, resource_name)
11584 Lisp_Object display_name;
11585 char *xrm_option;
11586 char *resource_name;
11588 struct mac_display_info *dpyinfo;
11590 BLOCK_INPUT;
11592 if (!mac_initialized)
11594 mac_initialize ();
11595 mac_initialized = 1;
11598 if (x_display_list)
11599 error ("Sorry, this version can only handle one display");
11601 mac_initialize_display_info ();
11603 dpyinfo = &one_mac_display_info;
11605 dpyinfo->xrdb = mac_make_rdb (xrm_option);
11607 /* Put this display on the chain. */
11608 dpyinfo->next = x_display_list;
11609 x_display_list = dpyinfo;
11611 /* Put it on x_display_name_list. */
11612 x_display_name_list = Fcons (Fcons (display_name,
11613 Fcons (Qnil, dpyinfo->xrdb)),
11614 x_display_name_list);
11615 dpyinfo->name_list_element = XCAR (x_display_name_list);
11617 UNBLOCK_INPUT;
11619 return dpyinfo;
11621 /* Get rid of display DPYINFO, assuming all frames are already gone. */
11623 void
11624 x_delete_display (dpyinfo)
11625 struct mac_display_info *dpyinfo;
11627 int i;
11629 /* Discard this display from x_display_name_list and x_display_list.
11630 We can't use Fdelq because that can quit. */
11631 if (! NILP (x_display_name_list)
11632 && EQ (XCAR (x_display_name_list), dpyinfo->name_list_element))
11633 x_display_name_list = XCDR (x_display_name_list);
11634 else
11636 Lisp_Object tail;
11638 tail = x_display_name_list;
11639 while (CONSP (tail) && CONSP (XCDR (tail)))
11641 if (EQ (XCAR (XCDR (tail)), dpyinfo->name_list_element))
11643 XSETCDR (tail, XCDR (XCDR (tail)));
11644 break;
11646 tail = XCDR (tail);
11650 if (x_display_list == dpyinfo)
11651 x_display_list = dpyinfo->next;
11652 else
11654 struct x_display_info *tail;
11656 for (tail = x_display_list; tail; tail = tail->next)
11657 if (tail->next == dpyinfo)
11658 tail->next = tail->next->next;
11661 /* Free the font names in the font table. */
11662 for (i = 0; i < dpyinfo->n_fonts; i++)
11663 if (dpyinfo->font_table[i].name)
11665 if (dpyinfo->font_table[i].name != dpyinfo->font_table[i].full_name)
11666 xfree (dpyinfo->font_table[i].full_name);
11667 xfree (dpyinfo->font_table[i].name);
11670 if (dpyinfo->font_table)
11672 if (dpyinfo->font_table->font_encoder)
11673 xfree (dpyinfo->font_table->font_encoder);
11674 xfree (dpyinfo->font_table);
11676 if (dpyinfo->mac_id_name)
11677 xfree (dpyinfo->mac_id_name);
11679 if (x_display_list == 0)
11681 mac_clear_font_name_table ();
11682 bzero (dpyinfo, sizeof (*dpyinfo));
11687 static void
11688 init_menu_bar ()
11690 #ifdef MAC_OSX
11691 OSStatus err;
11692 MenuRef menu;
11693 MenuItemIndex menu_index;
11695 err = GetIndMenuItemWithCommandID (NULL, kHICommandQuit, 1,
11696 &menu, &menu_index);
11697 if (err == noErr)
11698 SetMenuItemCommandKey (menu, menu_index, false, 0);
11699 #if USE_CARBON_EVENTS
11700 EnableMenuCommand (NULL, kHICommandPreferences);
11701 err = GetIndMenuItemWithCommandID (NULL, kHICommandPreferences, 1,
11702 &menu, &menu_index);
11703 if (err == noErr)
11705 SetMenuItemCommandKey (menu, menu_index, false, 0);
11706 InsertMenuItemTextWithCFString (menu, NULL,
11707 0, kMenuItemAttrSeparator, 0);
11708 InsertMenuItemTextWithCFString (menu, CFSTR ("About Emacs"),
11709 0, 0, kHICommandAbout);
11711 #endif /* USE_CARBON_EVENTS */
11712 #else /* !MAC_OSX */
11713 #if USE_CARBON_EVENTS
11714 SetMenuItemCommandID (GetMenuHandle (M_APPLE), I_ABOUT, kHICommandAbout);
11715 #endif
11716 #endif
11719 #if USE_MAC_TSM
11720 static void
11721 init_tsm ()
11723 #ifdef MAC_OSX
11724 static InterfaceTypeList types = {kUnicodeDocument};
11725 #else
11726 static InterfaceTypeList types = {kTextService};
11727 #endif
11729 NewTSMDocument (sizeof (types) / sizeof (types[0]), types,
11730 &tsm_document_id, 0);
11732 #endif
11734 /* Set up use of X before we make the first connection. */
11736 extern frame_parm_handler mac_frame_parm_handlers[];
11738 static struct redisplay_interface x_redisplay_interface =
11740 mac_frame_parm_handlers,
11741 x_produce_glyphs,
11742 x_write_glyphs,
11743 x_insert_glyphs,
11744 x_clear_end_of_line,
11745 x_scroll_run,
11746 x_after_update_window_line,
11747 x_update_window_begin,
11748 x_update_window_end,
11749 x_cursor_to,
11750 x_flush,
11751 #if USE_CG_DRAWING
11752 mac_flush_display_optional,
11753 #else
11754 0, /* flush_display_optional */
11755 #endif
11756 x_clear_window_mouse_face,
11757 x_get_glyph_overhangs,
11758 x_fix_overlapping_area,
11759 x_draw_fringe_bitmap,
11760 #if USE_CG_DRAWING
11761 mac_define_fringe_bitmap,
11762 mac_destroy_fringe_bitmap,
11763 #else
11764 0, /* define_fringe_bitmap */
11765 0, /* destroy_fringe_bitmap */
11766 #endif
11767 mac_per_char_metric,
11768 mac_encode_char,
11769 mac_compute_glyph_string_overhangs,
11770 x_draw_glyph_string,
11771 mac_define_frame_cursor,
11772 mac_clear_frame_area,
11773 mac_draw_window_cursor,
11774 mac_draw_vertical_window_border,
11775 mac_shift_glyphs_for_insert
11778 void
11779 mac_initialize ()
11781 rif = &x_redisplay_interface;
11783 clear_frame_hook = x_clear_frame;
11784 ins_del_lines_hook = x_ins_del_lines;
11785 delete_glyphs_hook = x_delete_glyphs;
11786 ring_bell_hook = XTring_bell;
11787 reset_terminal_modes_hook = XTreset_terminal_modes;
11788 set_terminal_modes_hook = XTset_terminal_modes;
11789 update_begin_hook = x_update_begin;
11790 update_end_hook = x_update_end;
11791 set_terminal_window_hook = XTset_terminal_window;
11792 read_socket_hook = XTread_socket;
11793 frame_up_to_date_hook = XTframe_up_to_date;
11794 mouse_position_hook = XTmouse_position;
11795 frame_rehighlight_hook = XTframe_rehighlight;
11796 frame_raise_lower_hook = XTframe_raise_lower;
11798 set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
11799 condemn_scroll_bars_hook = XTcondemn_scroll_bars;
11800 redeem_scroll_bar_hook = XTredeem_scroll_bar;
11801 judge_scroll_bars_hook = XTjudge_scroll_bars;
11803 scroll_region_ok = 1; /* we'll scroll partial frames */
11804 char_ins_del_ok = 1;
11805 line_ins_del_ok = 1; /* we'll just blt 'em */
11806 fast_clear_end_of_line = 1; /* X does this well */
11807 memory_below_frame = 0; /* we don't remember what scrolls
11808 off the bottom */
11809 baud_rate = 19200;
11811 last_tool_bar_item = -1;
11812 any_help_event_p = 0;
11814 /* Try to use interrupt input; if we can't, then start polling. */
11815 Fset_input_mode (Qt, Qnil, Qt, Qnil);
11817 BLOCK_INPUT;
11819 #if TARGET_API_MAC_CARBON
11821 #if USE_CARBON_EVENTS
11822 #ifdef MAC_OSX
11823 init_service_handler ();
11824 #endif /* MAC_OSX */
11826 init_command_handler ();
11828 init_menu_bar ();
11830 #if USE_MAC_TSM
11831 init_tsm ();
11832 #endif
11833 #endif /* USE_CARBON_EVENTS */
11835 #ifdef MAC_OSX
11836 init_coercion_handler ();
11838 init_apple_event_handler ();
11840 if (!inhibit_window_system)
11842 static const ProcessSerialNumber psn = {0, kCurrentProcess};
11844 SetFrontProcess (&psn);
11846 #endif
11847 #endif
11849 #if USE_CG_DRAWING
11850 init_cg_color ();
11852 mac_init_fringe ();
11853 #endif
11855 UNBLOCK_INPUT;
11859 void
11860 syms_of_macterm ()
11862 #if 0
11863 staticpro (&x_error_message_string);
11864 x_error_message_string = Qnil;
11865 #endif
11867 Qcontrol = intern ("control"); staticpro (&Qcontrol);
11868 Qmeta = intern ("meta"); staticpro (&Qmeta);
11869 Qalt = intern ("alt"); staticpro (&Qalt);
11870 Qhyper = intern ("hyper"); staticpro (&Qhyper);
11871 Qsuper = intern ("super"); staticpro (&Qsuper);
11872 Qmodifier_value = intern ("modifier-value");
11873 staticpro (&Qmodifier_value);
11875 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
11876 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
11877 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
11878 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
11879 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
11881 #if USE_CARBON_EVENTS
11882 Qhi_command = intern ("hi-command"); staticpro (&Qhi_command);
11883 #ifdef MAC_OSX
11884 Qtoolbar_switch_mode = intern ("toolbar-switch-mode");
11885 staticpro (&Qtoolbar_switch_mode);
11886 #if USE_MAC_FONT_PANEL
11887 Qpanel_closed = intern ("panel-closed"); staticpro (&Qpanel_closed);
11888 Qselection = intern ("selection"); staticpro (&Qselection);
11889 #endif
11891 Qservice = intern ("service"); staticpro (&Qservice);
11892 Qpaste = intern ("paste"); staticpro (&Qpaste);
11893 Qperform = intern ("perform"); staticpro (&Qperform);
11894 #endif
11895 #if USE_MAC_TSM
11896 Qtext_input = intern ("text-input"); staticpro (&Qtext_input);
11897 Qupdate_active_input_area = intern ("update-active-input-area");
11898 staticpro (&Qupdate_active_input_area);
11899 Qunicode_for_key_event = intern ("unicode-for-key-event");
11900 staticpro (&Qunicode_for_key_event);
11901 #endif
11902 #endif
11904 #ifdef MAC_OSX
11905 Fprovide (intern ("mac-carbon"), Qnil);
11906 #endif
11908 staticpro (&Qreverse);
11909 Qreverse = intern ("reverse");
11911 staticpro (&x_display_name_list);
11912 x_display_name_list = Qnil;
11914 staticpro (&last_mouse_scroll_bar);
11915 last_mouse_scroll_bar = Qnil;
11917 staticpro (&fm_font_family_alist);
11918 fm_font_family_alist = Qnil;
11920 #if USE_ATSUI
11921 staticpro (&atsu_font_id_hash);
11922 atsu_font_id_hash = Qnil;
11924 staticpro (&fm_style_face_attributes_alist);
11925 fm_style_face_attributes_alist = Qnil;
11926 #endif
11928 #if USE_MAC_TSM
11929 staticpro (&saved_ts_script_language_on_focus);
11930 saved_ts_script_language_on_focus = Qnil;
11931 #endif
11933 /* We don't yet support this, but defining this here avoids whining
11934 from cus-start.el and other places, like "M-x set-variable". */
11935 DEFVAR_BOOL ("x-use-underline-position-properties",
11936 &x_use_underline_position_properties,
11937 doc: /* *Non-nil means make use of UNDERLINE_POSITION font properties.
11938 A value of nil means ignore them. If you encounter fonts with bogus
11939 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
11940 to 4.1, set this to nil.
11942 NOTE: Not supported on Mac yet. */);
11943 x_use_underline_position_properties = 0;
11945 DEFVAR_BOOL ("x-underline-at-descent-line",
11946 &x_underline_at_descent_line,
11947 doc: /* *Non-nil means to draw the underline at the same place as the descent line.
11948 A value of nil means to draw the underline according to the value of the
11949 variable `x-use-underline-position-properties', which is usually at the
11950 baseline level. The default value is nil. */);
11951 x_underline_at_descent_line = 0;
11953 DEFVAR_LISP ("x-toolkit-scroll-bars", &Vx_toolkit_scroll_bars,
11954 doc: /* If not nil, Emacs uses toolkit scroll bars. */);
11955 #ifdef USE_TOOLKIT_SCROLL_BARS
11956 Vx_toolkit_scroll_bars = Qt;
11957 #else
11958 Vx_toolkit_scroll_bars = Qnil;
11959 #endif
11961 staticpro (&last_mouse_motion_frame);
11962 last_mouse_motion_frame = Qnil;
11964 /* Variables to configure modifier key assignment. */
11966 DEFVAR_LISP ("mac-control-modifier", &Vmac_control_modifier,
11967 doc: /* *Modifier key assumed when the Mac control key is pressed.
11968 The value can be `control', `meta', `alt', `hyper', or `super' for the
11969 respective modifier. The default is `control'. */);
11970 Vmac_control_modifier = Qcontrol;
11972 DEFVAR_LISP ("mac-option-modifier", &Vmac_option_modifier,
11973 doc: /* *Modifier key assumed when the Mac alt/option key is pressed.
11974 The value can be `control', `meta', `alt', `hyper', or `super' for the
11975 respective modifier. If the value is nil then the key will act as the
11976 normal Mac control modifier, and the option key can be used to compose
11977 characters depending on the chosen Mac keyboard setting. */);
11978 Vmac_option_modifier = Qnil;
11980 DEFVAR_LISP ("mac-command-modifier", &Vmac_command_modifier,
11981 doc: /* *Modifier key assumed when the Mac command key is pressed.
11982 The value can be `control', `meta', `alt', `hyper', or `super' for the
11983 respective modifier. The default is `meta'. */);
11984 Vmac_command_modifier = Qmeta;
11986 DEFVAR_LISP ("mac-function-modifier", &Vmac_function_modifier,
11987 doc: /* *Modifier key assumed when the Mac function key is pressed.
11988 The value can be `control', `meta', `alt', `hyper', or `super' for the
11989 respective modifier. Note that remapping the function key may lead to
11990 unexpected results for some keys on non-US/GB keyboards. */);
11991 Vmac_function_modifier = Qnil;
11993 DEFVAR_LISP ("mac-emulate-three-button-mouse",
11994 &Vmac_emulate_three_button_mouse,
11995 doc: /* *Specify a way of three button mouse emulation.
11996 The value can be nil, t, or the symbol `reverse'.
11997 A value of nil means that no emulation should be done and the modifiers
11998 should be placed on the mouse-1 event.
11999 t means that when the option-key is held down while pressing the mouse
12000 button, the click will register as mouse-2 and while the command-key
12001 is held down, the click will register as mouse-3.
12002 The symbol `reverse' means that the option-key will register for
12003 mouse-3 and the command-key will register for mouse-2. */);
12004 Vmac_emulate_three_button_mouse = Qnil;
12006 #if USE_CARBON_EVENTS
12007 DEFVAR_BOOL ("mac-wheel-button-is-mouse-2", &mac_wheel_button_is_mouse_2,
12008 doc: /* *Non-nil if the wheel button is mouse-2 and the right click mouse-3.
12009 Otherwise, the right click will be treated as mouse-2 and the wheel
12010 button will be mouse-3. */);
12011 mac_wheel_button_is_mouse_2 = 1;
12013 DEFVAR_BOOL ("mac-pass-command-to-system", &mac_pass_command_to_system,
12014 doc: /* *Non-nil if command key presses are passed on to the Mac Toolbox. */);
12015 mac_pass_command_to_system = 1;
12017 DEFVAR_BOOL ("mac-pass-control-to-system", &mac_pass_control_to_system,
12018 doc: /* *Non-nil if control key presses are passed on to the Mac Toolbox. */);
12019 mac_pass_control_to_system = 1;
12021 #endif
12023 DEFVAR_BOOL ("mac-allow-anti-aliasing", &mac_use_core_graphics,
12024 doc: /* *If non-nil, allow anti-aliasing.
12025 The text will be rendered using Core Graphics text rendering which
12026 may anti-alias the text. */);
12027 #if USE_CG_DRAWING
12028 mac_use_core_graphics = 1;
12029 #else
12030 mac_use_core_graphics = 0;
12031 #endif
12033 /* Register an entry for `mac-roman' so that it can be used when
12034 creating the terminal frame on Mac OS 9 before loading
12035 term/mac-win.elc. */
12036 DEFVAR_LISP ("mac-charset-info-alist", &Vmac_charset_info_alist,
12037 doc: /* Alist of Emacs character sets vs text encodings and coding systems.
12038 Each entry should be of the form:
12040 (CHARSET-NAME TEXT-ENCODING CODING-SYSTEM)
12042 where CHARSET-NAME is a string used in font names to identify the
12043 charset, TEXT-ENCODING is a TextEncodingBase value in Mac, and
12044 CODING_SYSTEM is a coding system corresponding to TEXT-ENCODING. */);
12045 Vmac_charset_info_alist =
12046 Fcons (list3 (build_string ("mac-roman"),
12047 make_number (smRoman), Qnil), Qnil);
12049 #if USE_MAC_TSM
12050 DEFVAR_LISP ("mac-ts-active-input-overlay", &Vmac_ts_active_input_overlay,
12051 doc: /* Overlay used to display Mac TSM active input area. */);
12052 Vmac_ts_active_input_overlay = Qnil;
12054 DEFVAR_LISP ("mac-ts-script-language-on-focus", &Vmac_ts_script_language_on_focus,
12055 doc: /* *How to change Mac TSM script/language when a frame gets focus.
12056 If the value is t, the input script and language are restored to those
12057 used in the last focus frame. If the value is a pair of integers, the
12058 input script and language codes, which are defined in the Script
12059 Manager, are set to its car and cdr parts, respectively. Otherwise,
12060 Emacs doesn't set them and thus follows the system default behavior. */);
12061 Vmac_ts_script_language_on_focus = Qnil;
12062 #endif
12065 /* arch-tag: f2259165-4454-4c04-a029-a133c8af7b5b
12066 (do not change this comment) */