(Fprocess_send_eof): Abort if fail to open null device.
[emacs.git] / src / macterm.c
blobcc8e659515be635680babbd0845fabfe7104d107
1 /* Implementation of GUI terminal on the Mac OS.
2 Copyright (C) 2000, 2001, 2002, 2003, 2004,
3 2005, 2006 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, USA. */
22 /* Contributed by Andrew Choi (akochoi@mac.com). */
24 #include <config.h>
25 #include <signal.h>
27 #include <stdio.h>
29 #include "lisp.h"
30 #include "blockinput.h"
32 #include "macterm.h"
34 #ifndef MAC_OSX
35 #include <alloca.h>
36 #endif
38 #if TARGET_API_MAC_CARBON
39 /* USE_CARBON_EVENTS determines if the Carbon Event Manager is used to
40 obtain events from the event queue. If set to 0, WaitNextEvent is
41 used instead. */
42 #define USE_CARBON_EVENTS 1
43 #else /* not TARGET_API_MAC_CARBON */
44 #include <Quickdraw.h>
45 #include <ToolUtils.h>
46 #include <Sound.h>
47 #include <Events.h>
48 #include <Script.h>
49 #include <Resources.h>
50 #include <Fonts.h>
51 #include <TextUtils.h>
52 #include <LowMem.h>
53 #include <Controls.h>
54 #include <Windows.h>
55 #if defined (__MRC__) || (__MSL__ >= 0x6000)
56 #include <ControlDefinitions.h>
57 #endif
59 #if __profile__
60 #include <profiler.h>
61 #endif
62 #endif /* not TARGET_API_MAC_CARBON */
64 #include "systty.h"
65 #include "systime.h"
67 #include <ctype.h>
68 #include <errno.h>
69 #include <setjmp.h>
70 #include <sys/stat.h>
72 #include "charset.h"
73 #include "coding.h"
74 #include "frame.h"
75 #include "dispextern.h"
76 #include "fontset.h"
77 #include "termhooks.h"
78 #include "termopts.h"
79 #include "termchar.h"
80 #include "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 /* This is a chain of structures for all the X displays currently in
112 use. */
114 struct x_display_info *x_display_list;
116 /* This is a list of cons cells, each of the form (NAME
117 FONT-LIST-CACHE . RESOURCE-DATABASE), one for each element of
118 x_display_list and in the same order. NAME is the name of the
119 frame. FONT-LIST-CACHE records previous values returned by
120 x-list-fonts. RESOURCE-DATABASE preserves the X Resource Database
121 equivalent, which is implemented with a Lisp object, for the
122 display. */
124 Lisp_Object x_display_name_list;
126 /* This is display since Mac does not support multiple ones. */
127 struct mac_display_info one_mac_display_info;
129 /* Frame being updated by update_frame. This is declared in term.c.
130 This is set by update_begin and looked at by all the XT functions.
131 It is zero while not inside an update. In that case, the XT
132 functions assume that `selected_frame' is the frame to apply to. */
134 extern struct frame *updating_frame;
136 /* This is a frame waiting to be auto-raised, within XTread_socket. */
138 struct frame *pending_autoraise_frame;
140 /* Mouse movement.
142 Formerly, we used PointerMotionHintMask (in standard_event_mask)
143 so that we would have to call XQueryPointer after each MotionNotify
144 event to ask for another such event. However, this made mouse tracking
145 slow, and there was a bug that made it eventually stop.
147 Simply asking for MotionNotify all the time seems to work better.
149 In order to avoid asking for motion events and then throwing most
150 of them away or busy-polling the server for mouse positions, we ask
151 the server for pointer motion hints. This means that we get only
152 one event per group of mouse movements. "Groups" are delimited by
153 other kinds of events (focus changes and button clicks, for
154 example), or by XQueryPointer calls; when one of these happens, we
155 get another MotionNotify event the next time the mouse moves. This
156 is at least as efficient as getting motion events when mouse
157 tracking is on, and I suspect only negligibly worse when tracking
158 is off. */
160 /* Where the mouse was last time we reported a mouse event. */
162 static Rect last_mouse_glyph;
163 static FRAME_PTR last_mouse_glyph_frame;
165 /* The scroll bar in which the last X motion event occurred.
167 If the last X motion event occurred in a scroll bar, we set this so
168 XTmouse_position can know whether to report a scroll bar motion or
169 an ordinary motion.
171 If the last X motion event didn't occur in a scroll bar, we set
172 this to Qnil, to tell XTmouse_position to return an ordinary motion
173 event. */
175 static Lisp_Object last_mouse_scroll_bar;
177 /* This is a hack. We would really prefer that XTmouse_position would
178 return the time associated with the position it returns, but there
179 doesn't seem to be any way to wrest the time-stamp from the server
180 along with the position query. So, we just keep track of the time
181 of the last movement we received, and return that in hopes that
182 it's somewhat accurate. */
184 static Time last_mouse_movement_time;
186 struct scroll_bar *tracked_scroll_bar = NULL;
188 /* Incremented by XTread_socket whenever it really tries to read
189 events. */
191 #ifdef __STDC__
192 static int volatile input_signal_count;
193 #else
194 static int input_signal_count;
195 #endif
197 extern Lisp_Object Vsystem_name;
199 /* A mask of extra modifier bits to put into every keyboard char. */
201 extern EMACS_INT extra_keyboard_modifiers;
203 /* The keysyms to use for the various modifiers. */
205 static Lisp_Object Qalt, Qhyper, Qsuper, Qcontrol, Qmeta, Qmodifier_value;
207 extern int inhibit_window_system;
209 #if __MRC__ && !TARGET_API_MAC_CARBON
210 QDGlobals qd; /* QuickDraw global information structure. */
211 #endif
213 #define mac_window_to_frame(wp) (((mac_output *) GetWRefCon (wp))->mFP)
215 struct mac_display_info *mac_display_info_for_display (Display *);
216 static void x_update_window_end P_ ((struct window *, int, int));
217 int x_catch_errors P_ ((Display *));
218 void x_uncatch_errors P_ ((Display *, int));
219 void x_lower_frame P_ ((struct frame *));
220 void x_scroll_bar_clear P_ ((struct frame *));
221 int x_had_errors_p P_ ((Display *));
222 void x_wm_set_size_hint P_ ((struct frame *, long, int));
223 void x_raise_frame P_ ((struct frame *));
224 void x_set_window_size P_ ((struct frame *, int, int, int));
225 void x_wm_set_window_state P_ ((struct frame *, int));
226 void x_wm_set_icon_pixmap P_ ((struct frame *, int));
227 void mac_initialize P_ ((void));
228 static void x_font_min_bounds P_ ((XFontStruct *, int *, int *));
229 static int x_compute_min_glyph_bounds P_ ((struct frame *));
230 static void x_update_end P_ ((struct frame *));
231 static void XTframe_up_to_date P_ ((struct frame *));
232 static void XTset_terminal_modes P_ ((void));
233 static void XTreset_terminal_modes P_ ((void));
234 static void x_clear_frame P_ ((void));
235 static void frame_highlight P_ ((struct frame *));
236 static void frame_unhighlight P_ ((struct frame *));
237 static void x_new_focus_frame P_ ((struct x_display_info *, struct frame *));
238 static void mac_focus_changed P_ ((int, struct mac_display_info *,
239 struct frame *, struct input_event *));
240 static void x_detect_focus_change P_ ((struct mac_display_info *,
241 EventRecord *, struct input_event *));
242 static void XTframe_rehighlight P_ ((struct frame *));
243 static void x_frame_rehighlight P_ ((struct x_display_info *));
244 static void x_draw_hollow_cursor P_ ((struct window *, struct glyph_row *));
245 static void x_draw_bar_cursor P_ ((struct window *, struct glyph_row *, int,
246 enum text_cursor_kinds));
248 static void x_clip_to_row P_ ((struct window *, struct glyph_row *, int, GC));
249 static void x_flush P_ ((struct frame *f));
250 static void x_update_begin P_ ((struct frame *));
251 static void x_update_window_begin P_ ((struct window *));
252 static void x_after_update_window_line P_ ((struct glyph_row *));
253 static void x_scroll_bar_report_motion P_ ((struct frame **, Lisp_Object *,
254 enum scroll_bar_part *,
255 Lisp_Object *, Lisp_Object *,
256 unsigned long *));
258 static int is_emacs_window P_ ((WindowPtr));
259 static XCharStruct *mac_per_char_metric P_ ((XFontStruct *, XChar2b *, int));
260 static void XSetFont P_ ((Display *, GC, XFontStruct *));
262 /* Defined in macmenu.h. */
263 extern void menubar_selection_callback (FRAME_PTR, int);
265 #define GC_FORE_COLOR(gc) (&(gc)->fore_color)
266 #define GC_BACK_COLOR(gc) (&(gc)->back_color)
267 #define GC_FONT(gc) ((gc)->xgcv.font)
268 #define FRAME_NORMAL_GC(f) ((f)->output_data.mac->normal_gc)
269 #define CG_SET_FILL_COLOR(context, color) \
270 CGContextSetRGBFillColor (context, \
271 RED_FROM_ULONG (color) / 255.0f, \
272 GREEN_FROM_ULONG (color) / 255.0f, \
273 BLUE_FROM_ULONG (color) / 255.0f, 1.0f)
274 #define CG_SET_STROKE_COLOR(context, color) \
275 CGContextSetRGBStrokeColor (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
280 #define FRAME_CG_CONTEXT(f) ((f)->output_data.mac->cg_context)
282 /* Fringe bitmaps. */
284 static int max_fringe_bmp = 0;
285 static CGImageRef *fringe_bmp = 0;
287 static CGContextRef
288 mac_begin_cg_clip (f, gc)
289 struct frame *f;
290 GC gc;
292 CGContextRef context = FRAME_CG_CONTEXT (f);
294 if (!context)
296 QDBeginCGContext (GetWindowPort (FRAME_MAC_WINDOW (f)), &context);
297 FRAME_CG_CONTEXT (f) = context;
300 CGContextSaveGState (context);
301 CGContextTranslateCTM (context, 0, FRAME_PIXEL_HEIGHT (f));
302 CGContextScaleCTM (context, 1, -1);
303 if (gc && gc->n_clip_rects)
304 CGContextClipToRects (context, gc->clip_rects, gc->n_clip_rects);
306 return context;
309 static void
310 mac_end_cg_clip (f)
311 struct frame *f;
313 CGContextRestoreGState (FRAME_CG_CONTEXT (f));
316 void
317 mac_prepare_for_quickdraw (f)
318 struct frame *f;
320 if (f == NULL)
322 Lisp_Object rest, frame;
323 FOR_EACH_FRAME (rest, frame)
324 if (FRAME_MAC_P (XFRAME (frame)))
325 mac_prepare_for_quickdraw (XFRAME (frame));
327 else
329 CGContextRef context = FRAME_CG_CONTEXT (f);
331 if (context)
333 CGContextSynchronize (context);
334 QDEndCGContext (GetWindowPort (FRAME_MAC_WINDOW (f)),
335 &FRAME_CG_CONTEXT (f));
339 #endif
341 static RgnHandle saved_port_clip_region = NULL;
343 static void
344 mac_begin_clip (gc)
345 GC gc;
347 static RgnHandle new_region = NULL;
349 if (saved_port_clip_region == NULL)
350 saved_port_clip_region = NewRgn ();
351 if (new_region == NULL)
352 new_region = NewRgn ();
354 if (gc->n_clip_rects)
356 GetClip (saved_port_clip_region);
357 SectRgn (saved_port_clip_region, gc->clip_region, new_region);
358 SetClip (new_region);
362 static void
363 mac_end_clip (gc)
364 GC gc;
366 if (gc->n_clip_rects)
367 SetClip (saved_port_clip_region);
371 /* X display function emulation */
373 void
374 XFreePixmap (display, pixmap)
375 Display *display; /* not used */
376 Pixmap pixmap;
378 DisposeGWorld (pixmap);
382 /* Mac version of XDrawLine. */
384 static void
385 mac_draw_line (f, gc, x1, y1, x2, y2)
386 struct frame *f;
387 GC gc;
388 int x1, y1, x2, y2;
390 #if USE_CG_DRAWING
391 CGContextRef context;
393 context = mac_begin_cg_clip (f, gc);
394 CG_SET_STROKE_COLOR (context, gc->xgcv.foreground);
395 CGContextBeginPath (context);
396 CGContextMoveToPoint (context, x1 + 0.5f, y1 + 0.5f);
397 CGContextAddLineToPoint (context, x2 + 0.5f, y2 + 0.5f);
398 CGContextClosePath (context);
399 CGContextStrokePath (context);
400 mac_end_cg_clip (f);
401 #else
402 SetPortWindowPort (FRAME_MAC_WINDOW (f));
404 RGBForeColor (GC_FORE_COLOR (gc));
406 mac_begin_clip (gc);
407 MoveTo (x1, y1);
408 LineTo (x2, y2);
409 mac_end_clip (gc);
410 #endif
413 void
414 mac_draw_line_to_pixmap (display, p, gc, x1, y1, x2, y2)
415 Display *display;
416 Pixmap p;
417 GC gc;
418 int x1, y1, x2, y2;
420 CGrafPtr old_port;
421 GDHandle old_gdh;
423 GetGWorld (&old_port, &old_gdh);
424 SetGWorld (p, NULL);
426 RGBForeColor (GC_FORE_COLOR (gc));
428 LockPixels (GetGWorldPixMap (p));
429 MoveTo (x1, y1);
430 LineTo (x2, y2);
431 UnlockPixels (GetGWorldPixMap (p));
433 SetGWorld (old_port, old_gdh);
437 static void
438 mac_erase_rectangle (f, gc, x, y, width, height)
439 struct frame *f;
440 GC gc;
441 int x, y;
442 unsigned int width, height;
444 #if USE_CG_DRAWING
445 CGContextRef context;
447 context = mac_begin_cg_clip (f, gc);
448 CG_SET_FILL_COLOR (context, gc->xgcv.background);
449 CGContextFillRect (context, CGRectMake (x, y, width, height));
450 mac_end_cg_clip (f);
451 #else
452 Rect r;
454 SetPortWindowPort (FRAME_MAC_WINDOW (f));
456 RGBBackColor (GC_BACK_COLOR (gc));
457 SetRect (&r, x, y, x + width, y + height);
459 mac_begin_clip (gc);
460 EraseRect (&r);
461 mac_end_clip (gc);
463 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
464 #endif
468 /* Mac version of XClearArea. */
470 void
471 mac_clear_area (f, x, y, width, height)
472 struct frame *f;
473 int x, y;
474 unsigned int width, height;
476 mac_erase_rectangle (f, FRAME_NORMAL_GC (f), x, y, width, height);
479 /* Mac version of XClearWindow. */
481 static void
482 mac_clear_window (f)
483 struct frame *f;
485 #if USE_CG_DRAWING
486 CGContextRef context;
487 GC gc = FRAME_NORMAL_GC (f);
489 context = mac_begin_cg_clip (f, NULL);
490 CG_SET_FILL_COLOR (context, gc->xgcv.background);
491 CGContextFillRect (context, CGRectMake (0, 0, FRAME_PIXEL_WIDTH (f),
492 FRAME_PIXEL_HEIGHT (f)));
493 mac_end_cg_clip (f);
494 #else
495 SetPortWindowPort (FRAME_MAC_WINDOW (f));
497 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
499 #if TARGET_API_MAC_CARBON
501 Rect r;
503 GetWindowPortBounds (FRAME_MAC_WINDOW (f), &r);
504 EraseRect (&r);
506 #else /* not TARGET_API_MAC_CARBON */
507 EraseRect (&(FRAME_MAC_WINDOW (f)->portRect));
508 #endif /* not TARGET_API_MAC_CARBON */
509 #endif
513 /* Mac replacement for XCopyArea. */
515 #if USE_CG_DRAWING
516 static void
517 mac_draw_cg_image (image, f, gc, src_x, src_y, width, height,
518 dest_x, dest_y, overlay_p)
519 CGImageRef image;
520 struct frame *f;
521 GC gc;
522 int src_x, src_y;
523 unsigned int width, height;
524 int dest_x, dest_y, overlay_p;
526 CGContextRef context;
527 float port_height = FRAME_PIXEL_HEIGHT (f);
528 CGRect dest_rect = CGRectMake (dest_x, dest_y, width, height);
530 context = mac_begin_cg_clip (f, gc);
531 if (!overlay_p)
533 CG_SET_FILL_COLOR (context, gc->xgcv.background);
534 CGContextFillRect (context, dest_rect);
536 CGContextClipToRect (context, dest_rect);
537 CGContextScaleCTM (context, 1, -1);
538 CGContextTranslateCTM (context, 0, -port_height);
539 if (CGImageIsMask (image))
540 CG_SET_FILL_COLOR (context, gc->xgcv.foreground);
541 CGContextDrawImage (context,
542 CGRectMake (dest_x - src_x,
543 port_height - (dest_y - src_y
544 + CGImageGetHeight (image)),
545 CGImageGetWidth (image),
546 CGImageGetHeight (image)),
547 image);
548 mac_end_cg_clip (f);
551 #else /* !USE_CG_DRAWING */
553 static void
554 mac_draw_bitmap (f, gc, x, y, width, height, bits, overlay_p)
555 struct frame *f;
556 GC gc;
557 int x, y, width, height;
558 unsigned short *bits;
559 int overlay_p;
561 BitMap bitmap;
562 Rect r;
564 bitmap.rowBytes = sizeof(unsigned short);
565 bitmap.baseAddr = (char *)bits;
566 SetRect (&(bitmap.bounds), 0, 0, width, height);
568 SetPortWindowPort (FRAME_MAC_WINDOW (f));
570 RGBForeColor (GC_FORE_COLOR (gc));
571 RGBBackColor (GC_BACK_COLOR (gc));
572 SetRect (&r, x, y, x + width, y + height);
574 mac_begin_clip (gc);
575 #if TARGET_API_MAC_CARBON
577 CGrafPtr port;
579 GetPort (&port);
580 LockPortBits (port);
581 CopyBits (&bitmap, GetPortBitMapForCopyBits (port),
582 &(bitmap.bounds), &r, overlay_p ? srcOr : srcCopy, 0);
583 UnlockPortBits (port);
585 #else /* not TARGET_API_MAC_CARBON */
586 CopyBits (&bitmap, &(FRAME_MAC_WINDOW (f)->portBits), &(bitmap.bounds), &r,
587 overlay_p ? srcOr : srcCopy, 0);
588 #endif /* not TARGET_API_MAC_CARBON */
589 mac_end_clip (gc);
591 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
593 #endif /* !USE_CG_DRAWING */
596 /* Mac replacement for XCreateBitmapFromBitmapData. */
598 static void
599 mac_create_bitmap_from_bitmap_data (bitmap, bits, w, h)
600 BitMap *bitmap;
601 char *bits;
602 int w, h;
604 static unsigned char swap_nibble[16]
605 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
606 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
607 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
608 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
609 int i, j, w1;
610 char *p;
612 w1 = (w + 7) / 8; /* nb of 8bits elt in X bitmap */
613 bitmap->rowBytes = ((w + 15) / 16) * 2; /* nb of 16bits elt in Mac bitmap */
614 bitmap->baseAddr = xmalloc (bitmap->rowBytes * h);
615 bzero (bitmap->baseAddr, bitmap->rowBytes * h);
616 for (i = 0; i < h; i++)
618 p = bitmap->baseAddr + i * bitmap->rowBytes;
619 for (j = 0; j < w1; j++)
621 /* Bitswap XBM bytes to match how Mac does things. */
622 unsigned char c = *bits++;
623 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
624 | (swap_nibble[(c>>4) & 0xf]));;
628 SetRect (&(bitmap->bounds), 0, 0, w, h);
632 static void
633 mac_free_bitmap (bitmap)
634 BitMap *bitmap;
636 xfree (bitmap->baseAddr);
640 Pixmap
641 XCreatePixmap (display, w, width, height, depth)
642 Display *display; /* not used */
643 WindowPtr w;
644 unsigned int width, height;
645 unsigned int depth;
647 Pixmap pixmap;
648 Rect r;
649 QDErr err;
651 SetPortWindowPort (w);
653 SetRect (&r, 0, 0, width, height);
654 #if !defined (WORDS_BIG_ENDIAN) && USE_CG_DRAWING
655 if (depth == 1)
656 #endif
657 err = NewGWorld (&pixmap, depth, &r, NULL, NULL, 0);
658 #if !defined (WORDS_BIG_ENDIAN) && USE_CG_DRAWING
659 else
660 /* CreateCGImageFromPixMaps requires ARGB format. */
661 err = QTNewGWorld (&pixmap, k32ARGBPixelFormat, &r, NULL, NULL, 0);
662 #endif
663 if (err != noErr)
664 return NULL;
665 return pixmap;
669 Pixmap
670 XCreatePixmapFromBitmapData (display, w, data, width, height, fg, bg, depth)
671 Display *display; /* not used */
672 WindowPtr w;
673 char *data;
674 unsigned int width, height;
675 unsigned long fg, bg;
676 unsigned int depth;
678 Pixmap pixmap;
679 BitMap bitmap;
680 CGrafPtr old_port;
681 GDHandle old_gdh;
682 static GC gc = NULL; /* not reentrant */
684 if (gc == NULL)
685 gc = XCreateGC (display, w, 0, NULL);
687 pixmap = XCreatePixmap (display, w, width, height, depth);
688 if (pixmap == NULL)
689 return NULL;
691 GetGWorld (&old_port, &old_gdh);
692 SetGWorld (pixmap, NULL);
693 mac_create_bitmap_from_bitmap_data (&bitmap, data, width, height);
694 XSetForeground (display, gc, fg);
695 XSetBackground (display, gc, bg);
696 RGBForeColor (GC_FORE_COLOR (gc));
697 RGBBackColor (GC_BACK_COLOR (gc));
698 LockPixels (GetGWorldPixMap (pixmap));
699 #if TARGET_API_MAC_CARBON
700 CopyBits (&bitmap, GetPortBitMapForCopyBits (pixmap),
701 &bitmap.bounds, &bitmap.bounds, srcCopy, 0);
702 #else /* not TARGET_API_MAC_CARBON */
703 CopyBits (&bitmap, &(((GrafPtr)pixmap)->portBits),
704 &bitmap.bounds, &bitmap.bounds, srcCopy, 0);
705 #endif /* not TARGET_API_MAC_CARBON */
706 UnlockPixels (GetGWorldPixMap (pixmap));
707 SetGWorld (old_port, old_gdh);
708 mac_free_bitmap (&bitmap);
710 return pixmap;
714 /* Mac replacement for XFillRectangle. */
716 static void
717 mac_fill_rectangle (f, gc, x, y, width, height)
718 struct frame *f;
719 GC gc;
720 int x, y;
721 unsigned int width, height;
723 #if USE_CG_DRAWING
724 CGContextRef context;
726 context = mac_begin_cg_clip (f, gc);
727 CG_SET_FILL_COLOR (context, gc->xgcv.foreground);
728 CGContextFillRect (context, CGRectMake (x, y, width, height));
729 mac_end_cg_clip (f);
730 #else
731 Rect r;
733 SetPortWindowPort (FRAME_MAC_WINDOW (f));
735 RGBForeColor (GC_FORE_COLOR (gc));
736 SetRect (&r, x, y, x + width, y + height);
738 mac_begin_clip (gc);
739 PaintRect (&r); /* using foreground color of gc */
740 mac_end_clip (gc);
741 #endif
745 /* Mac replacement for XDrawRectangle: dest is a window. */
747 static void
748 mac_draw_rectangle (f, gc, x, y, width, height)
749 struct frame *f;
750 GC gc;
751 int x, y;
752 unsigned int width, height;
754 #if USE_CG_DRAWING
755 CGContextRef context;
757 context = mac_begin_cg_clip (f, gc);
758 CG_SET_STROKE_COLOR (context, gc->xgcv.foreground);
759 CGContextStrokeRect (context,
760 CGRectMake (x + 0.5f, y + 0.5f, width, height));
761 mac_end_cg_clip (f);
762 #else
763 Rect r;
765 SetPortWindowPort (FRAME_MAC_WINDOW (f));
767 RGBForeColor (GC_FORE_COLOR (gc));
768 SetRect (&r, x, y, x + width + 1, y + height + 1);
770 mac_begin_clip (gc);
771 FrameRect (&r); /* using foreground color of gc */
772 mac_end_clip (gc);
773 #endif
777 #if USE_ATSUI
778 static OSStatus
779 atsu_get_text_layout_with_text_ptr (text, text_length, style, text_layout)
780 ConstUniCharArrayPtr text;
781 UniCharCount text_length;
782 ATSUStyle style;
783 ATSUTextLayout *text_layout;
785 OSStatus err;
786 static ATSUTextLayout saved_text_layout = NULL; /* not reentrant */
788 if (saved_text_layout == NULL)
790 UniCharCount lengths[] = {kATSUToTextEnd};
791 ATSUAttributeTag tags[] = {kATSULineLayoutOptionsTag};
792 ByteCount sizes[] = {sizeof (ATSLineLayoutOptions)};
793 static ATSLineLayoutOptions line_layout =
794 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
795 kATSLineDisableAllLayoutOperations | kATSLineUseDeviceMetrics
796 | kATSLineUseQDRendering
797 #else
798 kATSLineIsDisplayOnly | kATSLineFractDisable
799 #endif
801 ATSUAttributeValuePtr values[] = {&line_layout};
803 err = ATSUCreateTextLayoutWithTextPtr (text,
804 kATSUFromTextBeginning,
805 kATSUToTextEnd,
806 text_length,
807 1, lengths, &style,
808 &saved_text_layout);
809 if (err == noErr)
810 err = ATSUSetLayoutControls (saved_text_layout,
811 sizeof (tags) / sizeof (tags[0]),
812 tags, sizes, values);
813 /* XXX: Should we do this? */
814 if (err == noErr)
815 err = ATSUSetTransientFontMatching (saved_text_layout, true);
817 else
819 err = ATSUSetRunStyle (saved_text_layout, style,
820 kATSUFromTextBeginning, kATSUToTextEnd);
821 if (err == noErr)
822 err = ATSUSetTextPointerLocation (saved_text_layout, text,
823 kATSUFromTextBeginning,
824 kATSUToTextEnd,
825 text_length);
828 if (err == noErr)
829 *text_layout = saved_text_layout;
830 return err;
832 #endif
835 static void
836 mac_invert_rectangle (f, x, y, width, height)
837 struct frame *f;
838 int x, y;
839 unsigned int width, height;
841 Rect r;
843 #if USE_CG_DRAWING
844 mac_prepare_for_quickdraw (f);
845 #endif
846 SetPortWindowPort (FRAME_MAC_WINDOW (f));
848 SetRect (&r, x, y, x + width, y + height);
850 InvertRect (&r);
854 static void
855 mac_draw_string_common (f, gc, x, y, buf, nchars, bg_width, bytes_per_char)
856 struct frame *f;
857 GC gc;
858 int x, y;
859 char *buf;
860 int nchars, bg_width, bytes_per_char;
862 SetPortWindowPort (FRAME_MAC_WINDOW (f));
864 #if USE_ATSUI
865 if (GC_FONT (gc)->mac_style)
867 OSErr err;
868 ATSUTextLayout text_layout;
870 xassert (bytes_per_char == 2);
872 #ifndef WORDS_BIG_ENDIAN
874 int i;
875 UniChar *text = (UniChar *)buf;
877 for (i = 0; i < nchars; i++)
878 text[i] = EndianU16_BtoN (text[i]);
880 #endif
881 err = atsu_get_text_layout_with_text_ptr ((ConstUniCharArrayPtr)buf,
882 nchars,
883 GC_FONT (gc)->mac_style,
884 &text_layout);
885 if (err != noErr)
886 return;
887 #ifdef MAC_OSX
888 if (!mac_use_core_graphics)
890 #endif
891 #if USE_CG_DRAWING
892 mac_prepare_for_quickdraw (f);
893 #endif
894 mac_begin_clip (gc);
895 RGBForeColor (GC_FORE_COLOR (gc));
896 if (bg_width)
898 Rect r;
900 SetRect (&r, x, y - FONT_BASE (GC_FONT (gc)),
901 x + bg_width, y + FONT_DESCENT (GC_FONT (gc)));
902 RGBBackColor (GC_BACK_COLOR (gc));
903 EraseRect (&r);
904 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
906 MoveTo (x, y);
907 ATSUDrawText (text_layout,
908 kATSUFromTextBeginning, kATSUToTextEnd,
909 kATSUUseGrafPortPenLoc, kATSUUseGrafPortPenLoc);
910 mac_end_clip (gc);
911 #ifdef MAC_OSX
913 else
915 CGrafPtr port;
916 CGContextRef context;
917 float port_height = FRAME_PIXEL_HEIGHT (f);
918 ATSUAttributeTag tags[] = {kATSUCGContextTag};
919 ByteCount sizes[] = {sizeof (CGContextRef)};
920 ATSUAttributeValuePtr values[] = {&context};
922 #if USE_CG_DRAWING
923 context = mac_begin_cg_clip (f, gc);
924 #else
925 GetPort (&port);
926 QDBeginCGContext (port, &context);
927 if (gc->n_clip_rects || bg_width)
929 CGContextTranslateCTM (context, 0, port_height);
930 CGContextScaleCTM (context, 1, -1);
931 if (gc->n_clip_rects)
932 CGContextClipToRects (context, gc->clip_rects,
933 gc->n_clip_rects);
934 #endif
935 if (bg_width)
937 CG_SET_FILL_COLOR (context, gc->xgcv.background);
938 CGContextFillRect
939 (context,
940 CGRectMake (x, y - FONT_BASE (GC_FONT (gc)),
941 bg_width, FONT_HEIGHT (GC_FONT (gc))));
943 CGContextScaleCTM (context, 1, -1);
944 CGContextTranslateCTM (context, 0, -port_height);
945 #if !USE_CG_DRAWING
947 #endif
948 CG_SET_FILL_COLOR (context, gc->xgcv.foreground);
949 err = ATSUSetLayoutControls (text_layout,
950 sizeof (tags) / sizeof (tags[0]),
951 tags, sizes, values);
952 if (err == noErr)
953 ATSUDrawText (text_layout,
954 kATSUFromTextBeginning, kATSUToTextEnd,
955 Long2Fix (x), Long2Fix (port_height - y));
956 #if USE_CG_DRAWING
957 mac_end_cg_clip (f);
958 context = NULL;
959 #else
960 CGContextSynchronize (context);
961 QDEndCGContext (port, &context);
962 #endif
963 #if 0
964 /* This doesn't work on Mac OS X 10.1. */
965 ATSUClearLayoutControls (text_layout,
966 sizeof (tags) / sizeof (tags[0]), tags);
967 #else
968 ATSUSetLayoutControls (text_layout,
969 sizeof (tags) / sizeof (tags[0]),
970 tags, sizes, values);
971 #endif
973 #endif /* MAC_OSX */
975 else
976 #endif /* USE_ATSUI */
978 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
979 UInt32 savedFlags;
981 if (mac_use_core_graphics)
982 savedFlags = SwapQDTextFlags (kQDUseCGTextRendering);
983 #endif
984 #if USE_CG_DRAWING
985 mac_prepare_for_quickdraw (f);
986 #endif
987 mac_begin_clip (gc);
988 RGBForeColor (GC_FORE_COLOR (gc));
989 #ifdef MAC_OS8
990 if (bg_width)
992 RGBBackColor (GC_BACK_COLOR (gc));
993 TextMode (srcCopy);
995 else
996 TextMode (srcOr);
997 #else
998 /* We prefer not to use srcCopy text transfer mode on Mac OS X
999 because:
1000 - Screen is double-buffered. (In srcCopy mode, a text is
1001 drawn into an offscreen graphics world first. So
1002 performance gain cannot be expected.)
1003 - It lowers rendering quality.
1004 - Some fonts leave garbage on cursor movement. */
1005 if (bg_width)
1007 Rect r;
1009 RGBBackColor (GC_BACK_COLOR (gc));
1010 SetRect (&r, x, y - FONT_BASE (GC_FONT (gc)),
1011 x + bg_width, y + FONT_DESCENT (GC_FONT (gc)));
1012 EraseRect (&r);
1014 TextMode (srcOr);
1015 #endif
1016 TextFont (GC_FONT (gc)->mac_fontnum);
1017 TextSize (GC_FONT (gc)->mac_fontsize);
1018 TextFace (GC_FONT (gc)->mac_fontface);
1019 MoveTo (x, y);
1020 DrawText (buf, 0, nchars * bytes_per_char);
1021 if (bg_width)
1022 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
1023 mac_end_clip (gc);
1025 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
1026 if (mac_use_core_graphics)
1027 SwapQDTextFlags(savedFlags);
1028 #endif
1033 /* Mac replacement for XDrawString. */
1035 static void
1036 mac_draw_string (f, gc, x, y, buf, nchars)
1037 struct frame *f;
1038 GC gc;
1039 int x, y;
1040 char *buf;
1041 int nchars;
1043 mac_draw_string_common (f, gc, x, y, buf, nchars, 0, 1);
1047 /* Mac replacement for XDrawString16. */
1049 static void
1050 mac_draw_string_16 (f, gc, x, y, buf, nchars)
1051 struct frame *f;
1052 GC gc;
1053 int x, y;
1054 XChar2b *buf;
1055 int nchars;
1057 mac_draw_string_common (f, gc, x, y, (char *) buf, nchars, 0, 2);
1061 /* Mac replacement for XDrawImageString. */
1063 static void
1064 mac_draw_image_string (f, gc, x, y, buf, nchars, bg_width)
1065 struct frame *f;
1066 GC gc;
1067 int x, y;
1068 char *buf;
1069 int nchars, bg_width;
1071 mac_draw_string_common (f, gc, x, y, buf, nchars, bg_width, 1);
1075 /* Mac replacement for XDrawString16. */
1077 static void
1078 mac_draw_image_string_16 (f, gc, x, y, buf, nchars, bg_width)
1079 struct frame *f;
1080 GC gc;
1081 int x, y;
1082 XChar2b *buf;
1083 int nchars, bg_width;
1085 mac_draw_string_common (f, gc, x, y, (char *) buf, nchars, bg_width, 2);
1089 /* Mac replacement for XQueryTextExtents, but takes a character. If
1090 STYLE is NULL, measurement is done by QuickDraw Text routines for
1091 the font of the current graphics port. If CG_GLYPH is not NULL,
1092 *CG_GLYPH is set to the glyph ID or 0 if it cannot be obtained. */
1094 static OSErr
1095 mac_query_char_extents (style, c,
1096 font_ascent_return, font_descent_return,
1097 overall_return, cg_glyph)
1098 #if USE_ATSUI
1099 ATSUStyle style;
1100 #else
1101 void *style;
1102 #endif
1103 int c;
1104 int *font_ascent_return, *font_descent_return;
1105 XCharStruct *overall_return;
1106 #if USE_CG_TEXT_DRAWING
1107 CGGlyph *cg_glyph;
1108 #else
1109 void *cg_glyph;
1110 #endif
1112 OSErr err = noErr;
1113 int width;
1114 Rect char_bounds;
1116 #if USE_ATSUI
1117 if (style)
1119 ATSUTextLayout text_layout;
1120 UniChar ch = c;
1122 err = atsu_get_text_layout_with_text_ptr (&ch, 1, style, &text_layout);
1123 if (err == noErr)
1125 ATSTrapezoid glyph_bounds;
1127 err = ATSUGetGlyphBounds (text_layout, 0, 0,
1128 kATSUFromTextBeginning, kATSUToTextEnd,
1129 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
1130 kATSUseFractionalOrigins,
1131 #else
1132 kATSUseDeviceOrigins,
1133 #endif
1134 1, &glyph_bounds, NULL);
1135 if (err == noErr)
1137 xassert (glyph_bounds.lowerRight.x - glyph_bounds.lowerLeft.x
1138 == glyph_bounds.upperRight.x - glyph_bounds.upperLeft.x);
1140 width = Fix2Long (glyph_bounds.upperRight.x
1141 - glyph_bounds.upperLeft.x);
1142 if (font_ascent_return)
1143 *font_ascent_return = -Fix2Long (glyph_bounds.upperLeft.y);
1144 if (font_descent_return)
1145 *font_descent_return = Fix2Long (glyph_bounds.lowerLeft.y);
1148 if (err == noErr && overall_return)
1150 err = ATSUMeasureTextImage (text_layout,
1151 kATSUFromTextBeginning, kATSUToTextEnd,
1152 0, 0, &char_bounds);
1153 if (err == noErr)
1154 STORE_XCHARSTRUCT (*overall_return, width, char_bounds);
1155 #if USE_CG_TEXT_DRAWING
1156 if (err == noErr && cg_glyph)
1158 OSErr err1;
1159 ATSUGlyphInfoArray glyph_info_array;
1160 ByteCount count = sizeof (ATSUGlyphInfoArray);
1162 err1 = ATSUMatchFontsToText (text_layout, kATSUFromTextBeginning,
1163 kATSUToTextEnd, NULL, NULL, NULL);
1164 if (err1 == noErr)
1165 err1 = ATSUGetGlyphInfo (text_layout, kATSUFromTextBeginning,
1166 kATSUToTextEnd, &count,
1167 &glyph_info_array);
1168 if (err1 == noErr)
1170 xassert (glyph_info_array.glyphs[0].glyphID);
1171 *cg_glyph = glyph_info_array.glyphs[0].glyphID;
1173 else
1174 *cg_glyph = 0;
1176 #endif
1179 else
1180 #endif
1182 if (font_ascent_return || font_descent_return)
1184 FontInfo font_info;
1186 GetFontInfo (&font_info);
1187 if (font_ascent_return)
1188 *font_ascent_return = font_info.ascent;
1189 if (font_descent_return)
1190 *font_descent_return = font_info.descent;
1192 if (overall_return)
1194 char ch = c;
1196 width = CharWidth (ch);
1197 QDTextBounds (1, &ch, &char_bounds);
1198 STORE_XCHARSTRUCT (*overall_return, width, char_bounds);
1202 return err;
1206 /* Mac replacement for XTextExtents16. Only sets horizontal metrics. */
1208 static int
1209 mac_text_extents_16 (font_struct, string, nchars, overall_return)
1210 XFontStruct *font_struct;
1211 XChar2b *string;
1212 int nchars;
1213 XCharStruct *overall_return;
1215 int i;
1216 short width = 0, lbearing = 0, rbearing = 0;
1217 XCharStruct *pcm;
1219 for (i = 0; i < nchars; i++)
1221 pcm = mac_per_char_metric (font_struct, string, 0);
1222 if (pcm == NULL)
1223 width += FONT_WIDTH (font_struct);
1224 else
1226 lbearing = min (lbearing, width + pcm->lbearing);
1227 rbearing = max (rbearing, width + pcm->rbearing);
1228 width += pcm->width;
1230 string++;
1233 overall_return->lbearing = lbearing;
1234 overall_return->rbearing = rbearing;
1235 overall_return->width = width;
1237 /* What's the meaning of the return value of XTextExtents16? */
1241 #if USE_CG_TEXT_DRAWING
1242 static int cg_text_anti_aliasing_threshold = 8;
1244 static void
1245 init_cg_text_anti_aliasing_threshold ()
1247 int threshold;
1248 Boolean valid_p;
1250 threshold =
1251 CFPreferencesGetAppIntegerValue (CFSTR ("AppleAntiAliasingThreshold"),
1252 kCFPreferencesCurrentApplication,
1253 &valid_p);
1254 if (valid_p)
1255 cg_text_anti_aliasing_threshold = threshold;
1258 static int
1259 mac_draw_image_string_cg (f, gc, x, y, buf, nchars, bg_width)
1260 struct frame *f;
1261 GC gc;
1262 int x, y;
1263 XChar2b *buf;
1264 int nchars, bg_width;
1266 CGrafPtr port;
1267 float port_height, gx, gy;
1268 int i;
1269 CGContextRef context;
1270 CGGlyph *glyphs;
1271 CGSize *advances;
1273 if (!mac_use_core_graphics || GC_FONT (gc)->cg_font == NULL)
1274 return 0;
1276 port = GetWindowPort (FRAME_MAC_WINDOW (f));
1277 port_height = FRAME_PIXEL_HEIGHT (f);
1278 gx = x;
1279 gy = port_height - y;
1280 glyphs = (CGGlyph *)buf;
1281 advances = alloca (sizeof (CGSize) * nchars);
1282 if (advances == NULL)
1283 return 0;
1284 for (i = 0; i < nchars; i++)
1286 XCharStruct *pcm = mac_per_char_metric (GC_FONT (gc), buf, 0);
1288 advances[i].width = pcm->width;
1289 advances[i].height = 0;
1290 glyphs[i] = GC_FONT (gc)->cg_glyphs[buf->byte2];
1291 buf++;
1294 #if USE_CG_DRAWING
1295 context = mac_begin_cg_clip (f, gc);
1296 #else
1297 QDBeginCGContext (port, &context);
1298 if (gc->n_clip_rects || bg_width)
1300 CGContextTranslateCTM (context, 0, port_height);
1301 CGContextScaleCTM (context, 1, -1);
1302 if (gc->n_clip_rects)
1303 CGContextClipToRects (context, gc->clip_rects, gc->n_clip_rects);
1304 #endif
1305 if (bg_width)
1307 CG_SET_FILL_COLOR (context, gc->xgcv.background);
1308 CGContextFillRect
1309 (context,
1310 CGRectMake (gx, y - FONT_BASE (GC_FONT (gc)),
1311 bg_width, FONT_HEIGHT (GC_FONT (gc))));
1313 CGContextScaleCTM (context, 1, -1);
1314 CGContextTranslateCTM (context, 0, -port_height);
1315 #if !USE_CG_DRAWING
1317 #endif
1318 CG_SET_FILL_COLOR (context, gc->xgcv.foreground);
1319 CGContextSetFont (context, GC_FONT (gc)->cg_font);
1320 CGContextSetFontSize (context, GC_FONT (gc)->mac_fontsize);
1321 if (GC_FONT (gc)->mac_fontsize <= cg_text_anti_aliasing_threshold)
1322 CGContextSetShouldAntialias (context, false);
1323 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1030
1324 CGContextSetTextPosition (context, gx, gy);
1325 CGContextShowGlyphsWithAdvances (context, glyphs, advances, nchars);
1326 #else
1327 for (i = 0; i < nchars; i++)
1329 CGContextShowGlyphsAtPoint (context, gx, gy, glyphs + i, 1);
1330 gx += advances[i].width;
1332 #endif
1333 #if USE_CG_DRAWING
1334 mac_end_cg_clip (f);
1335 #else
1336 CGContextSynchronize (context);
1337 QDEndCGContext (port, &context);
1338 #endif
1340 return 1;
1342 #endif
1345 #if !USE_CG_DRAWING
1346 /* Mac replacement for XCopyArea: dest must be window. */
1348 static void
1349 mac_copy_area (src, f, gc, src_x, src_y, width, height, dest_x, dest_y)
1350 Pixmap src;
1351 struct frame *f;
1352 GC gc;
1353 int src_x, src_y;
1354 unsigned int width, height;
1355 int dest_x, dest_y;
1357 Rect src_r, dest_r;
1359 SetPortWindowPort (FRAME_MAC_WINDOW (f));
1361 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
1362 SetRect (&dest_r, dest_x, dest_y, dest_x + width, dest_y + height);
1364 ForeColor (blackColor);
1365 BackColor (whiteColor);
1367 mac_begin_clip (gc);
1368 LockPixels (GetGWorldPixMap (src));
1369 #if TARGET_API_MAC_CARBON
1371 CGrafPtr port;
1373 GetPort (&port);
1374 LockPortBits (port);
1375 CopyBits (GetPortBitMapForCopyBits (src),
1376 GetPortBitMapForCopyBits (port),
1377 &src_r, &dest_r, srcCopy, 0);
1378 UnlockPortBits (port);
1380 #else /* not TARGET_API_MAC_CARBON */
1381 CopyBits (&(((GrafPtr)src)->portBits), &(FRAME_MAC_WINDOW (f)->portBits),
1382 &src_r, &dest_r, srcCopy, 0);
1383 #endif /* not TARGET_API_MAC_CARBON */
1384 UnlockPixels (GetGWorldPixMap (src));
1385 mac_end_clip (gc);
1387 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
1391 static void
1392 mac_copy_area_with_mask (src, mask, f, gc, src_x, src_y,
1393 width, height, dest_x, dest_y)
1394 Pixmap src, mask;
1395 struct frame *f;
1396 GC gc;
1397 int src_x, src_y;
1398 unsigned int width, height;
1399 int dest_x, dest_y;
1401 Rect src_r, dest_r;
1403 SetPortWindowPort (FRAME_MAC_WINDOW (f));
1405 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
1406 SetRect (&dest_r, dest_x, dest_y, dest_x + width, dest_y + height);
1408 ForeColor (blackColor);
1409 BackColor (whiteColor);
1411 mac_begin_clip (gc);
1412 LockPixels (GetGWorldPixMap (src));
1413 LockPixels (GetGWorldPixMap (mask));
1414 #if TARGET_API_MAC_CARBON
1416 CGrafPtr port;
1418 GetPort (&port);
1419 LockPortBits (port);
1420 CopyMask (GetPortBitMapForCopyBits (src), GetPortBitMapForCopyBits (mask),
1421 GetPortBitMapForCopyBits (port),
1422 &src_r, &src_r, &dest_r);
1423 UnlockPortBits (port);
1425 #else /* not TARGET_API_MAC_CARBON */
1426 CopyMask (&(((GrafPtr)src)->portBits), &(((GrafPtr)mask)->portBits),
1427 &(FRAME_MAC_WINDOW (f)->portBits), &src_r, &src_r, &dest_r);
1428 #endif /* not TARGET_API_MAC_CARBON */
1429 UnlockPixels (GetGWorldPixMap (mask));
1430 UnlockPixels (GetGWorldPixMap (src));
1431 mac_end_clip (gc);
1433 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
1435 #endif /* !USE_CG_DRAWING */
1438 /* Mac replacement for XCopyArea: used only for scrolling. */
1440 static void
1441 mac_scroll_area (f, gc, src_x, src_y, width, height, dest_x, dest_y)
1442 struct frame *f;
1443 GC gc;
1444 int src_x, src_y;
1445 unsigned int width, height;
1446 int dest_x, dest_y;
1448 #if TARGET_API_MAC_CARBON
1449 Rect src_r;
1450 RgnHandle dummy = NewRgn (); /* For avoiding update events. */
1452 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
1453 #if USE_CG_DRAWING
1454 mac_prepare_for_quickdraw (f);
1455 #endif
1456 ScrollWindowRect (FRAME_MAC_WINDOW (f),
1457 &src_r, dest_x - src_x, dest_y - src_y,
1458 kScrollWindowNoOptions, dummy);
1459 DisposeRgn (dummy);
1460 #else /* not TARGET_API_MAC_CARBON */
1461 Rect src_r, dest_r;
1462 WindowPtr w = FRAME_MAC_WINDOW (f);
1464 SetPort (w);
1466 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
1467 SetRect (&dest_r, dest_x, dest_y, dest_x + width, dest_y + height);
1469 /* In Color QuickDraw, set ForeColor and BackColor as follows to avoid
1470 color mapping in CopyBits. Otherwise, it will be slow. */
1471 ForeColor (blackColor);
1472 BackColor (whiteColor);
1473 mac_begin_clip (gc);
1474 CopyBits (&(w->portBits), &(w->portBits), &src_r, &dest_r, srcCopy, 0);
1475 mac_end_clip (gc);
1477 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
1478 #endif /* not TARGET_API_MAC_CARBON */
1482 /* Mac replacement for XChangeGC. */
1484 static void
1485 XChangeGC (display, gc, mask, xgcv)
1486 Display *display;
1487 GC gc;
1488 unsigned long mask;
1489 XGCValues *xgcv;
1491 if (mask & GCForeground)
1492 XSetForeground (display, gc, xgcv->foreground);
1493 if (mask & GCBackground)
1494 XSetBackground (display, gc, xgcv->background);
1495 if (mask & GCFont)
1496 XSetFont (display, gc, xgcv->font);
1500 /* Mac replacement for XCreateGC. */
1503 XCreateGC (display, window, mask, xgcv)
1504 Display *display;
1505 Window window;
1506 unsigned long mask;
1507 XGCValues *xgcv;
1509 GC gc = xmalloc (sizeof (*gc));
1511 if (gc)
1513 bzero (gc, sizeof (*gc));
1514 XChangeGC (display, gc, mask, xgcv);
1517 return gc;
1521 /* Used in xfaces.c. */
1523 void
1524 XFreeGC (display, gc)
1525 Display *display;
1526 GC gc;
1528 if (gc->clip_region)
1529 DisposeRgn (gc->clip_region);
1530 xfree (gc);
1534 /* Mac replacement for XGetGCValues. */
1536 static void
1537 XGetGCValues (display, gc, mask, xgcv)
1538 Display *display;
1539 GC gc;
1540 unsigned long mask;
1541 XGCValues *xgcv;
1543 if (mask & GCForeground)
1544 xgcv->foreground = gc->xgcv.foreground;
1545 if (mask & GCBackground)
1546 xgcv->background = gc->xgcv.background;
1547 if (mask & GCFont)
1548 xgcv->font = gc->xgcv.font;
1552 /* Mac replacement for XSetForeground. */
1554 void
1555 XSetForeground (display, gc, color)
1556 Display *display;
1557 GC gc;
1558 unsigned long color;
1560 if (gc->xgcv.foreground != color)
1562 gc->xgcv.foreground = color;
1563 gc->fore_color.red = RED16_FROM_ULONG (color);
1564 gc->fore_color.green = GREEN16_FROM_ULONG (color);
1565 gc->fore_color.blue = BLUE16_FROM_ULONG (color);
1570 /* Mac replacement for XSetBackground. */
1572 void
1573 XSetBackground (display, gc, color)
1574 Display *display;
1575 GC gc;
1576 unsigned long color;
1578 if (gc->xgcv.background != color)
1580 gc->xgcv.background = color;
1581 gc->back_color.red = RED16_FROM_ULONG (color);
1582 gc->back_color.green = GREEN16_FROM_ULONG (color);
1583 gc->back_color.blue = BLUE16_FROM_ULONG (color);
1588 /* Mac replacement for XSetFont. */
1590 static void
1591 XSetFont (display, gc, font)
1592 Display *display;
1593 GC gc;
1594 XFontStruct *font;
1596 gc->xgcv.font = font;
1600 /* Mac replacement for XSetClipRectangles. */
1602 static void
1603 mac_set_clip_rectangles (display, gc, rectangles, n)
1604 Display *display;
1605 GC gc;
1606 Rect *rectangles;
1607 int n;
1609 int i;
1611 xassert (n >= 0 && n <= MAX_CLIP_RECTS);
1613 gc->n_clip_rects = n;
1614 if (n > 0)
1616 if (gc->clip_region == NULL)
1617 gc->clip_region = NewRgn ();
1618 RectRgn (gc->clip_region, rectangles);
1619 if (n > 1)
1621 RgnHandle region = NewRgn ();
1623 for (i = 1; i < n; i++)
1625 RectRgn (region, rectangles + i);
1626 UnionRgn (gc->clip_region, region, gc->clip_region);
1628 DisposeRgn (region);
1631 #if defined (MAC_OSX) && USE_ATSUI
1632 for (i = 0; i < n; i++)
1634 Rect *rect = rectangles + i;
1636 gc->clip_rects[i] = CGRectMake (rect->left, rect->top,
1637 rect->right - rect->left,
1638 rect->bottom - rect->top);
1640 #endif
1644 /* Mac replacement for XSetClipMask. */
1646 static INLINE void
1647 mac_reset_clip_rectangles (display, gc)
1648 Display *display;
1649 GC gc;
1651 gc->n_clip_rects = 0;
1655 /* Mac replacement for XSetWindowBackground. */
1657 void
1658 XSetWindowBackground (display, w, color)
1659 Display *display;
1660 WindowPtr w;
1661 unsigned long color;
1663 #if !TARGET_API_MAC_CARBON
1664 AuxWinHandle aw_handle;
1665 CTabHandle ctab_handle;
1666 ColorSpecPtr ct_table;
1667 short ct_size;
1668 #endif
1669 RGBColor bg_color;
1671 bg_color.red = RED16_FROM_ULONG (color);
1672 bg_color.green = GREEN16_FROM_ULONG (color);
1673 bg_color.blue = BLUE16_FROM_ULONG (color);
1675 #if TARGET_API_MAC_CARBON
1676 SetWindowContentColor (w, &bg_color);
1677 #else
1678 if (GetAuxWin (w, &aw_handle))
1680 ctab_handle = (*aw_handle)->awCTable;
1681 HandToHand ((Handle *) &ctab_handle);
1682 ct_table = (*ctab_handle)->ctTable;
1683 ct_size = (*ctab_handle)->ctSize;
1684 while (ct_size > -1)
1686 if (ct_table->value == 0)
1688 ct_table->rgb = bg_color;
1689 CTabChanged (ctab_handle);
1690 SetWinColor (w, (WCTabHandle) ctab_handle);
1692 ct_size--;
1695 #endif
1698 /* Flush display of frame F, or of all frames if F is null. */
1700 static void
1701 x_flush (f)
1702 struct frame *f;
1704 #if TARGET_API_MAC_CARBON
1705 BLOCK_INPUT;
1706 #if USE_CG_DRAWING
1707 mac_prepare_for_quickdraw (f);
1708 #endif
1709 if (f)
1710 QDFlushPortBuffer (GetWindowPort (FRAME_MAC_WINDOW (f)), NULL);
1711 else
1712 QDFlushPortBuffer (GetQDGlobalsThePort (), NULL);
1713 UNBLOCK_INPUT;
1714 #endif
1718 /* Remove calls to XFlush by defining XFlush to an empty replacement.
1719 Calls to XFlush should be unnecessary because the X output buffer
1720 is flushed automatically as needed by calls to XPending,
1721 XNextEvent, or XWindowEvent according to the XFlush man page.
1722 XTread_socket calls XPending. Removing XFlush improves
1723 performance. */
1725 #define XFlush(DISPLAY) (void) 0
1728 /* Return the struct mac_display_info corresponding to DPY. There's
1729 only one. */
1731 struct mac_display_info *
1732 mac_display_info_for_display (dpy)
1733 Display *dpy;
1735 return &one_mac_display_info;
1740 /***********************************************************************
1741 Starting and ending an update
1742 ***********************************************************************/
1744 /* Start an update of frame F. This function is installed as a hook
1745 for update_begin, i.e. it is called when update_begin is called.
1746 This function is called prior to calls to x_update_window_begin for
1747 each window being updated. */
1749 static void
1750 x_update_begin (f)
1751 struct frame *f;
1753 #if TARGET_API_MAC_CARBON
1754 /* During update of a frame, availability of input events is
1755 periodically checked with ReceiveNextEvent if
1756 redisplay-dont-pause is nil. That normally flushes window buffer
1757 changes for every check, and thus screen update looks waving even
1758 if no input is available. So we disable screen updates during
1759 update of a frame. */
1760 BLOCK_INPUT;
1761 DisableScreenUpdates ();
1762 UNBLOCK_INPUT;
1763 #endif
1767 /* Start update of window W. Set the global variable updated_window
1768 to the window being updated and set output_cursor to the cursor
1769 position of W. */
1771 static void
1772 x_update_window_begin (w)
1773 struct window *w;
1775 struct frame *f = XFRAME (WINDOW_FRAME (w));
1776 struct mac_display_info *display_info = FRAME_MAC_DISPLAY_INFO (f);
1778 updated_window = w;
1779 set_output_cursor (&w->cursor);
1781 BLOCK_INPUT;
1783 if (f == display_info->mouse_face_mouse_frame)
1785 /* Don't do highlighting for mouse motion during the update. */
1786 display_info->mouse_face_defer = 1;
1788 /* If F needs to be redrawn, simply forget about any prior mouse
1789 highlighting. */
1790 if (FRAME_GARBAGED_P (f))
1791 display_info->mouse_face_window = Qnil;
1793 #if 0 /* Rows in a current matrix containing glyphs in mouse-face have
1794 their mouse_face_p flag set, which means that they are always
1795 unequal to rows in a desired matrix which never have that
1796 flag set. So, rows containing mouse-face glyphs are never
1797 scrolled, and we don't have to switch the mouse highlight off
1798 here to prevent it from being scrolled. */
1800 /* Can we tell that this update does not affect the window
1801 where the mouse highlight is? If so, no need to turn off.
1802 Likewise, don't do anything if the frame is garbaged;
1803 in that case, the frame's current matrix that we would use
1804 is all wrong, and we will redisplay that line anyway. */
1805 if (!NILP (display_info->mouse_face_window)
1806 && w == XWINDOW (display_info->mouse_face_window))
1808 int i;
1810 for (i = 0; i < w->desired_matrix->nrows; ++i)
1811 if (MATRIX_ROW_ENABLED_P (w->desired_matrix, i))
1812 break;
1814 if (i < w->desired_matrix->nrows)
1815 clear_mouse_face (display_info);
1817 #endif /* 0 */
1820 UNBLOCK_INPUT;
1824 /* Draw a vertical window border from (x,y0) to (x,y1) */
1826 static void
1827 mac_draw_vertical_window_border (w, x, y0, y1)
1828 struct window *w;
1829 int x, y0, y1;
1831 struct frame *f = XFRAME (WINDOW_FRAME (w));
1832 struct face *face;
1834 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
1835 if (face)
1836 XSetForeground (FRAME_MAC_DISPLAY (f), f->output_data.mac->normal_gc,
1837 face->foreground);
1839 mac_draw_line (f, f->output_data.mac->normal_gc, x, y0, x, y1);
1842 /* End update of window W (which is equal to updated_window).
1844 Draw vertical borders between horizontally adjacent windows, and
1845 display W's cursor if CURSOR_ON_P is non-zero.
1847 MOUSE_FACE_OVERWRITTEN_P non-zero means that some row containing
1848 glyphs in mouse-face were overwritten. In that case we have to
1849 make sure that the mouse-highlight is properly redrawn.
1851 W may be a menu bar pseudo-window in case we don't have X toolkit
1852 support. Such windows don't have a cursor, so don't display it
1853 here. */
1855 static void
1856 x_update_window_end (w, cursor_on_p, mouse_face_overwritten_p)
1857 struct window *w;
1858 int cursor_on_p, mouse_face_overwritten_p;
1860 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (XFRAME (w->frame));
1862 if (!w->pseudo_window_p)
1864 BLOCK_INPUT;
1866 if (cursor_on_p)
1867 display_and_set_cursor (w, 1, output_cursor.hpos,
1868 output_cursor.vpos,
1869 output_cursor.x, output_cursor.y);
1871 if (draw_window_fringes (w, 1))
1872 x_draw_vertical_border (w);
1874 UNBLOCK_INPUT;
1877 /* If a row with mouse-face was overwritten, arrange for
1878 XTframe_up_to_date to redisplay the mouse highlight. */
1879 if (mouse_face_overwritten_p)
1881 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
1882 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
1883 dpyinfo->mouse_face_window = Qnil;
1886 updated_window = NULL;
1890 /* End update of frame F. This function is installed as a hook in
1891 update_end. */
1893 static void
1894 x_update_end (f)
1895 struct frame *f;
1897 /* Mouse highlight may be displayed again. */
1898 FRAME_MAC_DISPLAY_INFO (f)->mouse_face_defer = 0;
1900 BLOCK_INPUT;
1901 #if TARGET_API_MAC_CARBON
1902 EnableScreenUpdates ();
1903 #endif
1904 XFlush (FRAME_MAC_DISPLAY (f));
1905 UNBLOCK_INPUT;
1909 /* This function is called from various places in xdisp.c whenever a
1910 complete update has been performed. The global variable
1911 updated_window is not available here. */
1913 static void
1914 XTframe_up_to_date (f)
1915 struct frame *f;
1917 if (FRAME_MAC_P (f))
1919 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
1921 if (dpyinfo->mouse_face_deferred_gc
1922 || f == dpyinfo->mouse_face_mouse_frame)
1924 BLOCK_INPUT;
1925 if (dpyinfo->mouse_face_mouse_frame)
1926 note_mouse_highlight (dpyinfo->mouse_face_mouse_frame,
1927 dpyinfo->mouse_face_mouse_x,
1928 dpyinfo->mouse_face_mouse_y);
1929 dpyinfo->mouse_face_deferred_gc = 0;
1930 UNBLOCK_INPUT;
1936 /* Draw truncation mark bitmaps, continuation mark bitmaps, overlay
1937 arrow bitmaps, or clear the fringes if no bitmaps are required
1938 before DESIRED_ROW is made current. The window being updated is
1939 found in updated_window. This function is called from
1940 update_window_line only if it is known that there are differences
1941 between bitmaps to be drawn between current row and DESIRED_ROW. */
1943 static void
1944 x_after_update_window_line (desired_row)
1945 struct glyph_row *desired_row;
1947 struct window *w = updated_window;
1948 struct frame *f;
1949 int width, height;
1951 xassert (w);
1953 if (!desired_row->mode_line_p && !w->pseudo_window_p)
1954 desired_row->redraw_fringe_bitmaps_p = 1;
1956 /* When a window has disappeared, make sure that no rest of
1957 full-width rows stays visible in the internal border. Could
1958 check here if updated_window is the leftmost/rightmost window,
1959 but I guess it's not worth doing since vertically split windows
1960 are almost never used, internal border is rarely set, and the
1961 overhead is very small. */
1962 if (windows_or_buffers_changed
1963 && desired_row->full_width_p
1964 && (f = XFRAME (w->frame),
1965 width = FRAME_INTERNAL_BORDER_WIDTH (f),
1966 width != 0)
1967 && (height = desired_row->visible_height,
1968 height > 0))
1970 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
1972 /* Internal border is drawn below the tool bar. */
1973 if (WINDOWP (f->tool_bar_window)
1974 && w == XWINDOW (f->tool_bar_window))
1975 y -= width;
1977 BLOCK_INPUT;
1978 mac_clear_area (f, 0, y, width, height);
1979 mac_clear_area (f, FRAME_PIXEL_WIDTH (f) - width, y, width, height);
1980 UNBLOCK_INPUT;
1985 /* Draw the bitmap WHICH in one of the left or right fringes of
1986 window W. ROW is the glyph row for which to display the bitmap; it
1987 determines the vertical position at which the bitmap has to be
1988 drawn. */
1990 static void
1991 x_draw_fringe_bitmap (w, row, p)
1992 struct window *w;
1993 struct glyph_row *row;
1994 struct draw_fringe_bitmap_params *p;
1996 struct frame *f = XFRAME (WINDOW_FRAME (w));
1997 Display *display = FRAME_MAC_DISPLAY (f);
1998 struct face *face = p->face;
1999 int rowY;
2001 /* Must clip because of partially visible lines. */
2002 rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
2003 if (p->y < rowY)
2005 /* Adjust position of "bottom aligned" bitmap on partially
2006 visible last row. */
2007 int oldY = row->y;
2008 int oldVH = row->visible_height;
2009 row->visible_height = p->h;
2010 row->y -= rowY - p->y;
2011 x_clip_to_row (w, row, -1, face->gc);
2012 row->y = oldY;
2013 row->visible_height = oldVH;
2015 else
2016 x_clip_to_row (w, row, -1, face->gc);
2018 if (p->bx >= 0 && !p->overlay_p)
2020 #if 0 /* MAC_TODO: stipple */
2021 /* In case the same realized face is used for fringes and
2022 for something displayed in the text (e.g. face `region' on
2023 mono-displays, the fill style may have been changed to
2024 FillSolid in x_draw_glyph_string_background. */
2025 if (face->stipple)
2026 XSetFillStyle (FRAME_X_DISPLAY (f), face->gc, FillOpaqueStippled);
2027 else
2028 XSetForeground (FRAME_X_DISPLAY (f), face->gc, face->background);
2029 #endif
2031 mac_erase_rectangle (f, face->gc, p->bx, p->by, p->nx, p->ny);
2033 #if 0 /* MAC_TODO: stipple */
2034 if (!face->stipple)
2035 XSetForeground (FRAME_X_DISPLAY (f), face->gc, face->foreground);
2036 #endif
2039 if (p->which
2040 #if USE_CG_DRAWING
2041 && p->which < max_fringe_bmp
2042 #endif
2045 XGCValues gcv;
2047 XGetGCValues (display, face->gc, GCForeground, &gcv);
2048 XSetForeground (display, face->gc,
2049 (p->cursor_p
2050 ? (p->overlay_p ? face->background
2051 : f->output_data.mac->cursor_pixel)
2052 : face->foreground));
2053 #if USE_CG_DRAWING
2054 mac_draw_cg_image (fringe_bmp[p->which], f, face->gc, 0, p->dh,
2055 p->wd, p->h, p->x, p->y, p->overlay_p);
2056 #else
2057 mac_draw_bitmap (f, face->gc, p->x, p->y,
2058 p->wd, p->h, p->bits + p->dh, p->overlay_p);
2059 #endif
2060 XSetForeground (display, face->gc, gcv.foreground);
2063 mac_reset_clip_rectangles (display, face->gc);
2066 #if USE_CG_DRAWING
2067 static void
2068 mac_define_fringe_bitmap (which, bits, h, wd)
2069 int which;
2070 unsigned short *bits;
2071 int h, wd;
2073 int i;
2074 CGDataProviderRef provider;
2076 if (which >= max_fringe_bmp)
2078 i = max_fringe_bmp;
2079 max_fringe_bmp = which + 20;
2080 fringe_bmp = (CGImageRef *) xrealloc (fringe_bmp, max_fringe_bmp * sizeof (CGImageRef));
2081 while (i < max_fringe_bmp)
2082 fringe_bmp[i++] = 0;
2085 for (i = 0; i < h; i++)
2086 bits[i] = ~bits[i];
2087 provider = CGDataProviderCreateWithData (NULL, bits,
2088 sizeof (unsigned short) * h, NULL);
2089 if (provider)
2091 fringe_bmp[which] = CGImageMaskCreate (wd, h, 1, 1,
2092 sizeof (unsigned short),
2093 provider, NULL, 0);
2094 CGDataProviderRelease (provider);
2098 static void
2099 mac_destroy_fringe_bitmap (which)
2100 int which;
2102 if (which >= max_fringe_bmp)
2103 return;
2105 if (fringe_bmp[which])
2106 CGImageRelease (fringe_bmp[which]);
2107 fringe_bmp[which] = 0;
2109 #endif
2112 /* This is called when starting Emacs and when restarting after
2113 suspend. When starting Emacs, no window is mapped. And nothing
2114 must be done to Emacs's own window if it is suspended (though that
2115 rarely happens). */
2117 static void
2118 XTset_terminal_modes ()
2122 /* This is called when exiting or suspending Emacs. Exiting will make
2123 the windows go away, and suspending requires no action. */
2125 static void
2126 XTreset_terminal_modes ()
2132 /***********************************************************************
2133 Display Iterator
2134 ***********************************************************************/
2136 /* Function prototypes of this page. */
2138 static XCharStruct *x_per_char_metric P_ ((XFontStruct *, XChar2b *));
2139 static int mac_encode_char P_ ((int, XChar2b *, struct font_info *, int *));
2142 /* Get metrics of character CHAR2B in FONT. Value is null if CHAR2B
2143 is not contained in the font. */
2145 static INLINE XCharStruct *
2146 x_per_char_metric (font, char2b)
2147 XFontStruct *font;
2148 XChar2b *char2b;
2150 /* The result metric information. */
2151 XCharStruct *pcm = NULL;
2153 xassert (font && char2b);
2155 #if USE_ATSUI
2156 if (font->mac_style)
2158 XCharStructRow **row = font->bounds.rows + char2b->byte1;
2160 if (*row == NULL)
2162 *row = xmalloc (sizeof (XCharStructRow));
2163 if (*row)
2164 bzero (*row, sizeof (XCharStructRow));
2166 if (*row)
2168 pcm = (*row)->per_char + char2b->byte2;
2169 if (!XCHARSTRUCTROW_CHAR_VALID_P (*row, char2b->byte2))
2171 BLOCK_INPUT;
2172 mac_query_char_extents (font->mac_style,
2173 (char2b->byte1 << 8) + char2b->byte2,
2174 NULL, NULL, pcm, NULL);
2175 UNBLOCK_INPUT;
2176 XCHARSTRUCTROW_SET_CHAR_VALID (*row, char2b->byte2);
2180 else
2182 #endif
2183 if (font->bounds.per_char != NULL)
2185 if (font->min_byte1 == 0 && font->max_byte1 == 0)
2187 /* min_char_or_byte2 specifies the linear character index
2188 corresponding to the first element of the per_char array,
2189 max_char_or_byte2 is the index of the last character. A
2190 character with non-zero CHAR2B->byte1 is not in the font.
2191 A character with byte2 less than min_char_or_byte2 or
2192 greater max_char_or_byte2 is not in the font. */
2193 if (char2b->byte1 == 0
2194 && char2b->byte2 >= font->min_char_or_byte2
2195 && char2b->byte2 <= font->max_char_or_byte2)
2196 pcm = font->bounds.per_char
2197 + (char2b->byte2 - font->min_char_or_byte2);
2199 else
2201 /* If either min_byte1 or max_byte1 are nonzero, both
2202 min_char_or_byte2 and max_char_or_byte2 are less than
2203 256, and the 2-byte character index values corresponding
2204 to the per_char array element N (counting from 0) are:
2206 byte1 = N/D + min_byte1
2207 byte2 = N\D + min_char_or_byte2
2209 where:
2211 D = max_char_or_byte2 - min_char_or_byte2 + 1
2212 / = integer division
2213 \ = integer modulus */
2214 if (char2b->byte1 >= font->min_byte1
2215 && char2b->byte1 <= font->max_byte1
2216 && char2b->byte2 >= font->min_char_or_byte2
2217 && char2b->byte2 <= font->max_char_or_byte2)
2219 pcm = (font->bounds.per_char
2220 + ((font->max_char_or_byte2 - font->min_char_or_byte2 + 1)
2221 * (char2b->byte1 - font->min_byte1))
2222 + (char2b->byte2 - font->min_char_or_byte2));
2226 else
2228 /* If the per_char pointer is null, all glyphs between the first
2229 and last character indexes inclusive have the same
2230 information, as given by both min_bounds and max_bounds. */
2231 if (char2b->byte2 >= font->min_char_or_byte2
2232 && char2b->byte2 <= font->max_char_or_byte2)
2233 pcm = &font->max_bounds;
2235 #if USE_ATSUI
2237 #endif
2239 return ((pcm == NULL
2240 || (pcm->width == 0 && (pcm->rbearing - pcm->lbearing) == 0))
2241 ? NULL : pcm);
2244 /* RIF:
2247 static XCharStruct *
2248 mac_per_char_metric (font, char2b, font_type)
2249 XFontStruct *font;
2250 XChar2b *char2b;
2251 int font_type;
2253 return x_per_char_metric (font, char2b);
2256 /* RIF:
2257 Encode CHAR2B using encoding information from FONT_INFO. CHAR2B is
2258 the two-byte form of C. Encoding is returned in *CHAR2B. */
2260 static int
2261 mac_encode_char (c, char2b, font_info, two_byte_p)
2262 int c;
2263 XChar2b *char2b;
2264 struct font_info *font_info;
2265 int *two_byte_p;
2267 int charset = CHAR_CHARSET (c);
2268 XFontStruct *font = font_info->font;
2270 /* FONT_INFO may define a scheme by which to encode byte1 and byte2.
2271 This may be either a program in a special encoder language or a
2272 fixed encoding. */
2273 if (font_info->font_encoder)
2275 /* It's a program. */
2276 struct ccl_program *ccl = font_info->font_encoder;
2278 check_ccl_update (ccl);
2279 if (CHARSET_DIMENSION (charset) == 1)
2281 ccl->reg[0] = charset;
2282 ccl->reg[1] = char2b->byte2;
2283 ccl->reg[2] = -1;
2285 else
2287 ccl->reg[0] = charset;
2288 ccl->reg[1] = char2b->byte1;
2289 ccl->reg[2] = char2b->byte2;
2292 ccl_driver (ccl, NULL, NULL, 0, 0, NULL);
2294 /* We assume that MSBs are appropriately set/reset by CCL
2295 program. */
2296 if (font->max_byte1 == 0) /* 1-byte font */
2297 char2b->byte1 = 0, char2b->byte2 = ccl->reg[1];
2298 else
2299 char2b->byte1 = ccl->reg[1], char2b->byte2 = ccl->reg[2];
2301 else if (font_info->encoding[charset])
2303 /* Fixed encoding scheme. See fontset.h for the meaning of the
2304 encoding numbers. */
2305 int enc = font_info->encoding[charset];
2307 if ((enc == 1 || enc == 2)
2308 && CHARSET_DIMENSION (charset) == 2)
2309 char2b->byte1 |= 0x80;
2311 if (enc == 1 || enc == 3)
2312 char2b->byte2 |= 0x80;
2314 if (enc == 4)
2316 int sjis1, sjis2;
2318 ENCODE_SJIS (char2b->byte1, char2b->byte2, sjis1, sjis2);
2319 char2b->byte1 = sjis1;
2320 char2b->byte2 = sjis2;
2324 if (two_byte_p)
2325 *two_byte_p = ((XFontStruct *) (font_info->font))->max_byte1 > 0;
2327 return FONT_TYPE_UNKNOWN;
2332 /***********************************************************************
2333 Glyph display
2334 ***********************************************************************/
2338 static void x_set_glyph_string_clipping P_ ((struct glyph_string *));
2339 static void x_set_glyph_string_gc P_ ((struct glyph_string *));
2340 static void x_draw_glyph_string_background P_ ((struct glyph_string *,
2341 int));
2342 static void x_draw_glyph_string_foreground P_ ((struct glyph_string *));
2343 static void x_draw_composite_glyph_string_foreground P_ ((struct glyph_string *));
2344 static void x_draw_glyph_string_box P_ ((struct glyph_string *));
2345 static void x_draw_glyph_string P_ ((struct glyph_string *));
2346 static void mac_compute_glyph_string_overhangs P_ ((struct glyph_string *));
2347 static void x_set_cursor_gc P_ ((struct glyph_string *));
2348 static void x_set_mode_line_face_gc P_ ((struct glyph_string *));
2349 static void x_set_mouse_face_gc P_ ((struct glyph_string *));
2350 /*static int x_alloc_lighter_color P_ ((struct frame *, Display *, Colormap,
2351 unsigned long *, double, int));*/
2352 static void x_setup_relief_color P_ ((struct frame *, struct relief *,
2353 double, int, unsigned long));
2354 static void x_setup_relief_colors P_ ((struct glyph_string *));
2355 static void x_draw_image_glyph_string P_ ((struct glyph_string *));
2356 static void x_draw_image_relief P_ ((struct glyph_string *));
2357 static void x_draw_image_foreground P_ ((struct glyph_string *));
2358 static void x_clear_glyph_string_rect P_ ((struct glyph_string *, int,
2359 int, int, int));
2360 static void x_draw_relief_rect P_ ((struct frame *, int, int, int, int,
2361 int, int, int, int, int, int,
2362 Rect *));
2363 static void x_draw_box_rect P_ ((struct glyph_string *, int, int, int, int,
2364 int, int, int, Rect *));
2366 #if GLYPH_DEBUG
2367 static void x_check_font P_ ((struct frame *, XFontStruct *));
2368 #endif
2371 /* Set S->gc to a suitable GC for drawing glyph string S in cursor
2372 face. */
2374 static void
2375 x_set_cursor_gc (s)
2376 struct glyph_string *s;
2378 if (s->font == FRAME_FONT (s->f)
2379 && s->face->background == FRAME_BACKGROUND_PIXEL (s->f)
2380 && s->face->foreground == FRAME_FOREGROUND_PIXEL (s->f)
2381 && !s->cmp)
2382 s->gc = s->f->output_data.mac->cursor_gc;
2383 else
2385 /* Cursor on non-default face: must merge. */
2386 XGCValues xgcv;
2387 unsigned long mask;
2389 xgcv.background = s->f->output_data.mac->cursor_pixel;
2390 xgcv.foreground = s->face->background;
2392 /* If the glyph would be invisible, try a different foreground. */
2393 if (xgcv.foreground == xgcv.background)
2394 xgcv.foreground = s->face->foreground;
2395 if (xgcv.foreground == xgcv.background)
2396 xgcv.foreground = s->f->output_data.mac->cursor_foreground_pixel;
2397 if (xgcv.foreground == xgcv.background)
2398 xgcv.foreground = s->face->foreground;
2400 /* Make sure the cursor is distinct from text in this face. */
2401 if (xgcv.background == s->face->background
2402 && xgcv.foreground == s->face->foreground)
2404 xgcv.background = s->face->foreground;
2405 xgcv.foreground = s->face->background;
2408 IF_DEBUG (x_check_font (s->f, s->font));
2409 xgcv.font = s->font;
2410 mask = GCForeground | GCBackground | GCFont;
2412 if (FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc)
2413 XChangeGC (s->display, FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc,
2414 mask, &xgcv);
2415 else
2416 FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc
2417 = XCreateGC (s->display, s->window, mask, &xgcv);
2419 s->gc = FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc;
2424 /* Set up S->gc of glyph string S for drawing text in mouse face. */
2426 static void
2427 x_set_mouse_face_gc (s)
2428 struct glyph_string *s;
2430 int face_id;
2431 struct face *face;
2433 /* What face has to be used last for the mouse face? */
2434 face_id = FRAME_X_DISPLAY_INFO (s->f)->mouse_face_face_id;
2435 face = FACE_FROM_ID (s->f, face_id);
2436 if (face == NULL)
2437 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2439 if (s->first_glyph->type == CHAR_GLYPH)
2440 face_id = FACE_FOR_CHAR (s->f, face, s->first_glyph->u.ch);
2441 else
2442 face_id = FACE_FOR_CHAR (s->f, face, 0);
2443 s->face = FACE_FROM_ID (s->f, face_id);
2444 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
2446 /* If font in this face is same as S->font, use it. */
2447 if (s->font == s->face->font)
2448 s->gc = s->face->gc;
2449 else
2451 /* Otherwise construct scratch_cursor_gc with values from FACE
2452 but font FONT. */
2453 XGCValues xgcv;
2454 unsigned long mask;
2456 xgcv.background = s->face->background;
2457 xgcv.foreground = s->face->foreground;
2458 IF_DEBUG (x_check_font (s->f, s->font));
2459 xgcv.font = s->font;
2460 mask = GCForeground | GCBackground | GCFont;
2462 if (FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc)
2463 XChangeGC (s->display, FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc,
2464 mask, &xgcv);
2465 else
2466 FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc
2467 = XCreateGC (s->display, s->window, mask, &xgcv);
2469 s->gc = FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc;
2472 xassert (s->gc != 0);
2476 /* Set S->gc of glyph string S to a GC suitable for drawing a mode line.
2477 Faces to use in the mode line have already been computed when the
2478 matrix was built, so there isn't much to do, here. */
2480 static INLINE void
2481 x_set_mode_line_face_gc (s)
2482 struct glyph_string *s;
2484 s->gc = s->face->gc;
2488 /* Set S->gc of glyph string S for drawing that glyph string. Set
2489 S->stippled_p to a non-zero value if the face of S has a stipple
2490 pattern. */
2492 static INLINE void
2493 x_set_glyph_string_gc (s)
2494 struct glyph_string *s;
2496 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
2498 if (s->hl == DRAW_NORMAL_TEXT)
2500 s->gc = s->face->gc;
2501 s->stippled_p = s->face->stipple != 0;
2503 else if (s->hl == DRAW_INVERSE_VIDEO)
2505 x_set_mode_line_face_gc (s);
2506 s->stippled_p = s->face->stipple != 0;
2508 else if (s->hl == DRAW_CURSOR)
2510 x_set_cursor_gc (s);
2511 s->stippled_p = 0;
2513 else if (s->hl == DRAW_MOUSE_FACE)
2515 x_set_mouse_face_gc (s);
2516 s->stippled_p = s->face->stipple != 0;
2518 else if (s->hl == DRAW_IMAGE_RAISED
2519 || s->hl == DRAW_IMAGE_SUNKEN)
2521 s->gc = s->face->gc;
2522 s->stippled_p = s->face->stipple != 0;
2524 else
2526 s->gc = s->face->gc;
2527 s->stippled_p = s->face->stipple != 0;
2530 /* GC must have been set. */
2531 xassert (s->gc != 0);
2535 /* Set clipping for output of glyph string S. S may be part of a mode
2536 line or menu if we don't have X toolkit support. */
2538 static INLINE void
2539 x_set_glyph_string_clipping (s)
2540 struct glyph_string *s;
2542 Rect rects[MAX_CLIP_RECTS];
2543 int n;
2545 n = get_glyph_string_clip_rects (s, rects, MAX_CLIP_RECTS);
2546 mac_set_clip_rectangles (s->display, s->gc, rects, n);
2550 /* RIF:
2551 Compute left and right overhang of glyph string S. If S is a glyph
2552 string for a composition, assume overhangs don't exist. */
2554 static void
2555 mac_compute_glyph_string_overhangs (s)
2556 struct glyph_string *s;
2558 if (!(s->cmp == NULL
2559 && s->first_glyph->type == CHAR_GLYPH))
2560 return;
2562 if (!s->two_byte_p
2563 #if USE_ATSUI
2564 || s->font->mac_style
2565 #endif
2568 XCharStruct cs;
2570 mac_text_extents_16 (s->font, s->char2b, s->nchars, &cs);
2571 s->right_overhang = cs.rbearing > cs.width ? cs.rbearing - cs.width : 0;
2572 s->left_overhang = cs.lbearing < 0 ? -cs.lbearing : 0;
2574 else
2576 Rect r;
2577 MacFontStruct *font = s->font;
2579 TextFont (font->mac_fontnum);
2580 TextSize (font->mac_fontsize);
2581 TextFace (font->mac_fontface);
2583 QDTextBounds (s->nchars * 2, (char *)s->char2b, &r);
2585 s->right_overhang = r.right > s->width ? r.right - s->width : 0;
2586 s->left_overhang = r.left < 0 ? -r.left : 0;
2591 /* Fill rectangle X, Y, W, H with background color of glyph string S. */
2593 static INLINE void
2594 x_clear_glyph_string_rect (s, x, y, w, h)
2595 struct glyph_string *s;
2596 int x, y, w, h;
2598 mac_erase_rectangle (s->f, s->gc, x, y, w, h);
2602 /* Draw the background of glyph_string S. If S->background_filled_p
2603 is non-zero don't draw it. FORCE_P non-zero means draw the
2604 background even if it wouldn't be drawn normally. This is used
2605 when a string preceding S draws into the background of S, or S
2606 contains the first component of a composition. */
2608 static void
2609 x_draw_glyph_string_background (s, force_p)
2610 struct glyph_string *s;
2611 int force_p;
2613 /* Nothing to do if background has already been drawn or if it
2614 shouldn't be drawn in the first place. */
2615 if (!s->background_filled_p)
2617 int box_line_width = max (s->face->box_line_width, 0);
2619 #if 0 /* MAC_TODO: stipple */
2620 if (s->stippled_p)
2622 /* Fill background with a stipple pattern. */
2623 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2624 XFillRectangle (s->display, s->window, s->gc, s->x,
2625 s->y + box_line_width,
2626 s->background_width,
2627 s->height - 2 * box_line_width);
2628 XSetFillStyle (s->display, s->gc, FillSolid);
2629 s->background_filled_p = 1;
2631 else
2632 #endif
2633 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2634 || s->font_not_found_p
2635 || s->extends_to_end_of_line_p
2636 || force_p)
2638 x_clear_glyph_string_rect (s, s->x, s->y + box_line_width,
2639 s->background_width,
2640 s->height - 2 * box_line_width);
2641 s->background_filled_p = 1;
2647 /* Draw the foreground of glyph string S. */
2649 static void
2650 x_draw_glyph_string_foreground (s)
2651 struct glyph_string *s;
2653 int i, x, bg_width;
2655 /* If first glyph of S has a left box line, start drawing the text
2656 of S to the right of that box line. */
2657 if (s->face->box != FACE_NO_BOX
2658 && s->first_glyph->left_box_line_p)
2659 x = s->x + abs (s->face->box_line_width);
2660 else
2661 x = s->x;
2663 /* Draw characters of S as rectangles if S's font could not be
2664 loaded. */
2665 if (s->font_not_found_p)
2667 for (i = 0; i < s->nchars; ++i)
2669 struct glyph *g = s->first_glyph + i;
2670 mac_draw_rectangle (s->f, s->gc, x, s->y,
2671 g->pixel_width - 1, s->height - 1);
2672 x += g->pixel_width;
2675 else
2677 char *char1b = (char *) s->char2b;
2678 int boff = s->font_info->baseline_offset;
2680 if (s->font_info->vertical_centering)
2681 boff = VCENTER_BASELINE_OFFSET (s->font, s->f) - boff;
2683 /* If we can use 8-bit functions, condense S->char2b. */
2684 if (!s->two_byte_p
2685 #if USE_ATSUI
2686 && GC_FONT (s->gc)->mac_style == NULL
2687 #endif
2689 for (i = 0; i < s->nchars; ++i)
2690 char1b[i] = s->char2b[i].byte2;
2692 /* Draw text with XDrawString if background has already been
2693 filled. Otherwise, use XDrawImageString. (Note that
2694 XDrawImageString is usually faster than XDrawString.) Always
2695 use XDrawImageString when drawing the cursor so that there is
2696 no chance that characters under a box cursor are invisible. */
2697 if (s->for_overlaps
2698 || (s->background_filled_p && s->hl != DRAW_CURSOR))
2699 bg_width = 0; /* Corresponds to XDrawString. */
2700 else
2701 bg_width = s->background_width; /* Corresponds to XDrawImageString. */
2703 if (s->two_byte_p
2704 #if USE_ATSUI
2705 || GC_FONT (s->gc)->mac_style
2706 #endif
2708 #if USE_CG_TEXT_DRAWING
2709 if (!s->two_byte_p
2710 && mac_draw_image_string_cg (s->f, s->gc, x, s->ybase - boff,
2711 s->char2b, s->nchars, bg_width))
2713 else
2714 #endif
2715 mac_draw_image_string_16 (s->f, s->gc, x, s->ybase - boff,
2716 s->char2b, s->nchars, bg_width);
2717 else
2718 mac_draw_image_string (s->f, s->gc, x, s->ybase - boff,
2719 char1b, s->nchars, bg_width);
2723 /* Draw the foreground of composite glyph string S. */
2725 static void
2726 x_draw_composite_glyph_string_foreground (s)
2727 struct glyph_string *s;
2729 int i, x;
2731 /* If first glyph of S has a left box line, start drawing the text
2732 of S to the right of that box line. */
2733 if (s->face->box != FACE_NO_BOX
2734 && s->first_glyph->left_box_line_p)
2735 x = s->x + abs (s->face->box_line_width);
2736 else
2737 x = s->x;
2739 /* S is a glyph string for a composition. S->gidx is the index of
2740 the first character drawn for glyphs of this composition.
2741 S->gidx == 0 means we are drawing the very first character of
2742 this composition. */
2744 /* Draw a rectangle for the composition if the font for the very
2745 first character of the composition could not be loaded. */
2746 if (s->font_not_found_p)
2748 if (s->gidx == 0)
2749 mac_draw_rectangle (s->f, s->gc, x, s->y,
2750 s->width - 1, s->height - 1);
2752 else
2754 for (i = 0; i < s->nchars; i++, ++s->gidx)
2755 mac_draw_string_16 (s->f, s->gc,
2756 x + s->cmp->offsets[s->gidx * 2],
2757 s->ybase - s->cmp->offsets[s->gidx * 2 + 1],
2758 s->char2b + i, 1);
2763 #ifdef USE_X_TOOLKIT
2765 static struct frame *x_frame_of_widget P_ ((Widget));
2768 /* Return the frame on which widget WIDGET is used.. Abort if frame
2769 cannot be determined. */
2771 static struct frame *
2772 x_frame_of_widget (widget)
2773 Widget widget;
2775 struct x_display_info *dpyinfo;
2776 Lisp_Object tail;
2777 struct frame *f;
2779 dpyinfo = x_display_info_for_display (XtDisplay (widget));
2781 /* Find the top-level shell of the widget. Note that this function
2782 can be called when the widget is not yet realized, so XtWindow
2783 (widget) == 0. That's the reason we can't simply use
2784 x_any_window_to_frame. */
2785 while (!XtIsTopLevelShell (widget))
2786 widget = XtParent (widget);
2788 /* Look for a frame with that top-level widget. Allocate the color
2789 on that frame to get the right gamma correction value. */
2790 for (tail = Vframe_list; GC_CONSP (tail); tail = XCDR (tail))
2791 if (GC_FRAMEP (XCAR (tail))
2792 && (f = XFRAME (XCAR (tail)),
2793 (f->output_data.nothing != 1
2794 && FRAME_X_DISPLAY_INFO (f) == dpyinfo))
2795 && f->output_data.x->widget == widget)
2796 return f;
2798 abort ();
2802 /* Allocate the color COLOR->pixel on the screen and display of
2803 widget WIDGET in colormap CMAP. If an exact match cannot be
2804 allocated, try the nearest color available. Value is non-zero
2805 if successful. This is called from lwlib. */
2808 x_alloc_nearest_color_for_widget (widget, cmap, color)
2809 Widget widget;
2810 Colormap cmap;
2811 XColor *color;
2813 struct frame *f = x_frame_of_widget (widget);
2814 return x_alloc_nearest_color (f, cmap, color);
2818 #endif /* USE_X_TOOLKIT */
2820 #if 0 /* MAC_TODO */
2822 /* Allocate the color COLOR->pixel on SCREEN of DISPLAY, colormap
2823 CMAP. If an exact match can't be allocated, try the nearest color
2824 available. Value is non-zero if successful. Set *COLOR to the
2825 color allocated. */
2828 x_alloc_nearest_color (f, cmap, color)
2829 struct frame *f;
2830 Colormap cmap;
2831 XColor *color;
2833 Display *display = FRAME_X_DISPLAY (f);
2834 Screen *screen = FRAME_X_SCREEN (f);
2835 int rc;
2837 gamma_correct (f, color);
2838 rc = XAllocColor (display, cmap, color);
2839 if (rc == 0)
2841 /* If we got to this point, the colormap is full, so we're going
2842 to try to get the next closest color. The algorithm used is
2843 a least-squares matching, which is what X uses for closest
2844 color matching with StaticColor visuals. */
2845 int nearest, i;
2846 unsigned long nearest_delta = ~0;
2847 int ncells = XDisplayCells (display, XScreenNumberOfScreen (screen));
2848 XColor *cells = (XColor *) alloca (ncells * sizeof *cells);
2850 for (i = 0; i < ncells; ++i)
2851 cells[i].pixel = i;
2852 XQueryColors (display, cmap, cells, ncells);
2854 for (nearest = i = 0; i < ncells; ++i)
2856 long dred = (color->red >> 8) - (cells[i].red >> 8);
2857 long dgreen = (color->green >> 8) - (cells[i].green >> 8);
2858 long dblue = (color->blue >> 8) - (cells[i].blue >> 8);
2859 unsigned long delta = dred * dred + dgreen * dgreen + dblue * dblue;
2861 if (delta < nearest_delta)
2863 nearest = i;
2864 nearest_delta = delta;
2868 color->red = cells[nearest].red;
2869 color->green = cells[nearest].green;
2870 color->blue = cells[nearest].blue;
2871 rc = XAllocColor (display, cmap, color);
2874 #ifdef DEBUG_X_COLORS
2875 if (rc)
2876 register_color (color->pixel);
2877 #endif /* DEBUG_X_COLORS */
2879 return rc;
2883 /* Allocate color PIXEL on frame F. PIXEL must already be allocated.
2884 It's necessary to do this instead of just using PIXEL directly to
2885 get color reference counts right. */
2887 unsigned long
2888 x_copy_color (f, pixel)
2889 struct frame *f;
2890 unsigned long pixel;
2892 XColor color;
2894 color.pixel = pixel;
2895 BLOCK_INPUT;
2896 XQueryColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
2897 XAllocColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
2898 UNBLOCK_INPUT;
2899 #ifdef DEBUG_X_COLORS
2900 register_color (pixel);
2901 #endif
2902 return color.pixel;
2906 /* Allocate color PIXEL on display DPY. PIXEL must already be allocated.
2907 It's necessary to do this instead of just using PIXEL directly to
2908 get color reference counts right. */
2910 unsigned long
2911 x_copy_dpy_color (dpy, cmap, pixel)
2912 Display *dpy;
2913 Colormap cmap;
2914 unsigned long pixel;
2916 XColor color;
2918 color.pixel = pixel;
2919 BLOCK_INPUT;
2920 XQueryColor (dpy, cmap, &color);
2921 XAllocColor (dpy, cmap, &color);
2922 UNBLOCK_INPUT;
2923 #ifdef DEBUG_X_COLORS
2924 register_color (pixel);
2925 #endif
2926 return color.pixel;
2929 #endif /* MAC_TODO */
2932 /* Brightness beyond which a color won't have its highlight brightness
2933 boosted.
2935 Nominally, highlight colors for `3d' faces are calculated by
2936 brightening an object's color by a constant scale factor, but this
2937 doesn't yield good results for dark colors, so for colors who's
2938 brightness is less than this value (on a scale of 0-255) have to
2939 use an additional additive factor.
2941 The value here is set so that the default menu-bar/mode-line color
2942 (grey75) will not have its highlights changed at all. */
2943 #define HIGHLIGHT_COLOR_DARK_BOOST_LIMIT 187
2946 /* Allocate a color which is lighter or darker than *COLOR by FACTOR
2947 or DELTA. Try a color with RGB values multiplied by FACTOR first.
2948 If this produces the same color as COLOR, try a color where all RGB
2949 values have DELTA added. Return the allocated color in *COLOR.
2950 DISPLAY is the X display, CMAP is the colormap to operate on.
2951 Value is non-zero if successful. */
2953 static int
2954 mac_alloc_lighter_color (f, color, factor, delta)
2955 struct frame *f;
2956 unsigned long *color;
2957 double factor;
2958 int delta;
2960 unsigned long new;
2961 long bright;
2963 /* On Mac, RGB values are 0-255, not 0-65535, so scale delta. */
2964 delta /= 256;
2966 /* Change RGB values by specified FACTOR. Avoid overflow! */
2967 xassert (factor >= 0);
2968 new = RGB_TO_ULONG (min (0xff, (int) (factor * RED_FROM_ULONG (*color))),
2969 min (0xff, (int) (factor * GREEN_FROM_ULONG (*color))),
2970 min (0xff, (int) (factor * BLUE_FROM_ULONG (*color))));
2972 /* Calculate brightness of COLOR. */
2973 bright = (2 * RED_FROM_ULONG (*color) + 3 * GREEN_FROM_ULONG (*color)
2974 + BLUE_FROM_ULONG (*color)) / 6;
2976 /* We only boost colors that are darker than
2977 HIGHLIGHT_COLOR_DARK_BOOST_LIMIT. */
2978 if (bright < HIGHLIGHT_COLOR_DARK_BOOST_LIMIT)
2979 /* Make an additive adjustment to NEW, because it's dark enough so
2980 that scaling by FACTOR alone isn't enough. */
2982 /* How far below the limit this color is (0 - 1, 1 being darker). */
2983 double dimness = 1 - (double)bright / HIGHLIGHT_COLOR_DARK_BOOST_LIMIT;
2984 /* The additive adjustment. */
2985 int min_delta = delta * dimness * factor / 2;
2987 if (factor < 1)
2988 new = RGB_TO_ULONG (max (0, min (0xff, (int) (RED_FROM_ULONG (*color)) - min_delta)),
2989 max (0, min (0xff, (int) (GREEN_FROM_ULONG (*color)) - min_delta)),
2990 max (0, min (0xff, (int) (BLUE_FROM_ULONG (*color)) - min_delta)));
2991 else
2992 new = RGB_TO_ULONG (max (0, min (0xff, (int) (min_delta + RED_FROM_ULONG (*color)))),
2993 max (0, min (0xff, (int) (min_delta + GREEN_FROM_ULONG (*color)))),
2994 max (0, min (0xff, (int) (min_delta + BLUE_FROM_ULONG (*color)))));
2997 if (new == *color)
2998 new = RGB_TO_ULONG (max (0, min (0xff, (int) (delta + RED_FROM_ULONG (*color)))),
2999 max (0, min (0xff, (int) (delta + GREEN_FROM_ULONG (*color)))),
3000 max (0, min (0xff, (int) (delta + BLUE_FROM_ULONG (*color)))));
3002 /* MAC_TODO: Map to palette and retry with delta if same? */
3003 /* MAC_TODO: Free colors (if using palette)? */
3005 if (new == *color)
3006 return 0;
3008 *color = new;
3010 return 1;
3014 /* Set up the foreground color for drawing relief lines of glyph
3015 string S. RELIEF is a pointer to a struct relief containing the GC
3016 with which lines will be drawn. Use a color that is FACTOR or
3017 DELTA lighter or darker than the relief's background which is found
3018 in S->f->output_data.x->relief_background. If such a color cannot
3019 be allocated, use DEFAULT_PIXEL, instead. */
3021 static void
3022 x_setup_relief_color (f, relief, factor, delta, default_pixel)
3023 struct frame *f;
3024 struct relief *relief;
3025 double factor;
3026 int delta;
3027 unsigned long default_pixel;
3029 XGCValues xgcv;
3030 struct mac_output *di = f->output_data.mac;
3031 unsigned long mask = GCForeground;
3032 unsigned long pixel;
3033 unsigned long background = di->relief_background;
3034 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
3036 /* MAC_TODO: Free colors (if using palette)? */
3038 /* Allocate new color. */
3039 xgcv.foreground = default_pixel;
3040 pixel = background;
3041 if (dpyinfo->n_planes != 1
3042 && mac_alloc_lighter_color (f, &pixel, factor, delta))
3044 relief->allocated_p = 1;
3045 xgcv.foreground = relief->pixel = pixel;
3048 if (relief->gc == 0)
3050 #if 0 /* MAC_TODO: stipple */
3051 xgcv.stipple = dpyinfo->gray;
3052 mask |= GCStipple;
3053 #endif
3054 relief->gc = XCreateGC (NULL, FRAME_MAC_WINDOW (f), mask, &xgcv);
3056 else
3057 XChangeGC (NULL, relief->gc, mask, &xgcv);
3061 /* Set up colors for the relief lines around glyph string S. */
3063 static void
3064 x_setup_relief_colors (s)
3065 struct glyph_string *s;
3067 struct mac_output *di = s->f->output_data.mac;
3068 unsigned long color;
3070 if (s->face->use_box_color_for_shadows_p)
3071 color = s->face->box_color;
3072 else if (s->first_glyph->type == IMAGE_GLYPH
3073 && s->img->pixmap
3074 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
3075 color = IMAGE_BACKGROUND (s->img, s->f, 0);
3076 else
3078 XGCValues xgcv;
3080 /* Get the background color of the face. */
3081 XGetGCValues (s->display, s->gc, GCBackground, &xgcv);
3082 color = xgcv.background;
3085 if (di->white_relief.gc == 0
3086 || color != di->relief_background)
3088 di->relief_background = color;
3089 x_setup_relief_color (s->f, &di->white_relief, 1.2, 0x8000,
3090 WHITE_PIX_DEFAULT (s->f));
3091 x_setup_relief_color (s->f, &di->black_relief, 0.6, 0x4000,
3092 BLACK_PIX_DEFAULT (s->f));
3097 /* Draw a relief on frame F inside the rectangle given by LEFT_X,
3098 TOP_Y, RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the relief
3099 to draw, it must be >= 0. RAISED_P non-zero means draw a raised
3100 relief. LEFT_P non-zero means draw a relief on the left side of
3101 the rectangle. RIGHT_P non-zero means draw a relief on the right
3102 side of the rectangle. CLIP_RECT is the clipping rectangle to use
3103 when drawing. */
3105 static void
3106 x_draw_relief_rect (f, left_x, top_y, right_x, bottom_y, width,
3107 raised_p, top_p, bot_p, left_p, right_p, clip_rect)
3108 struct frame *f;
3109 int left_x, top_y, right_x, bottom_y, width;
3110 int top_p, bot_p, left_p, right_p, raised_p;
3111 Rect *clip_rect;
3113 Display *dpy = FRAME_MAC_DISPLAY (f);
3114 int i;
3115 GC gc;
3117 if (raised_p)
3118 gc = f->output_data.mac->white_relief.gc;
3119 else
3120 gc = f->output_data.mac->black_relief.gc;
3121 mac_set_clip_rectangles (dpy, gc, clip_rect, 1);
3123 /* Top. */
3124 if (top_p)
3125 for (i = 0; i < width; ++i)
3126 mac_draw_line (f, gc,
3127 left_x + i * left_p, top_y + i,
3128 right_x - i * right_p, top_y + i);
3130 /* Left. */
3131 if (left_p)
3132 for (i = 0; i < width; ++i)
3133 mac_draw_line (f, gc,
3134 left_x + i, top_y + i, left_x + i, bottom_y - i);
3136 mac_reset_clip_rectangles (dpy, gc);
3137 if (raised_p)
3138 gc = f->output_data.mac->black_relief.gc;
3139 else
3140 gc = f->output_data.mac->white_relief.gc;
3141 mac_set_clip_rectangles (dpy, gc, clip_rect, 1);
3143 /* Bottom. */
3144 if (bot_p)
3145 for (i = 0; i < width; ++i)
3146 mac_draw_line (f, gc,
3147 left_x + i * left_p, bottom_y - i,
3148 right_x - i * right_p, bottom_y - i);
3150 /* Right. */
3151 if (right_p)
3152 for (i = 0; i < width; ++i)
3153 mac_draw_line (f, gc,
3154 right_x - i, top_y + i + 1, right_x - i, bottom_y - i - 1);
3156 mac_reset_clip_rectangles (dpy, gc);
3160 /* Draw a box on frame F inside the rectangle given by LEFT_X, TOP_Y,
3161 RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the lines to
3162 draw, it must be >= 0. LEFT_P non-zero means draw a line on the
3163 left side of the rectangle. RIGHT_P non-zero means draw a line
3164 on the right side of the rectangle. CLIP_RECT is the clipping
3165 rectangle to use when drawing. */
3167 static void
3168 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
3169 left_p, right_p, clip_rect)
3170 struct glyph_string *s;
3171 int left_x, top_y, right_x, bottom_y, width, left_p, right_p;
3172 Rect *clip_rect;
3174 XGCValues xgcv;
3176 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3177 XSetForeground (s->display, s->gc, s->face->box_color);
3178 mac_set_clip_rectangles (s->display, s->gc, clip_rect, 1);
3180 /* Top. */
3181 mac_fill_rectangle (s->f, s->gc, left_x, top_y,
3182 right_x - left_x + 1, width);
3184 /* Left. */
3185 if (left_p)
3186 mac_fill_rectangle (s->f, s->gc, left_x, top_y,
3187 width, bottom_y - top_y + 1);
3189 /* Bottom. */
3190 mac_fill_rectangle (s->f, s->gc, left_x, bottom_y - width + 1,
3191 right_x - left_x + 1, width);
3193 /* Right. */
3194 if (right_p)
3195 mac_fill_rectangle (s->f, s->gc, right_x - width + 1,
3196 top_y, width, bottom_y - top_y + 1);
3198 XSetForeground (s->display, s->gc, xgcv.foreground);
3199 mac_reset_clip_rectangles (s->display, s->gc);
3203 /* Draw a box around glyph string S. */
3205 static void
3206 x_draw_glyph_string_box (s)
3207 struct glyph_string *s;
3209 int width, left_x, right_x, top_y, bottom_y, last_x, raised_p;
3210 int left_p, right_p;
3211 struct glyph *last_glyph;
3212 Rect clip_rect;
3214 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
3215 ? WINDOW_RIGHT_EDGE_X (s->w)
3216 : window_box_right (s->w, s->area));
3218 /* The glyph that may have a right box line. */
3219 last_glyph = (s->cmp || s->img
3220 ? s->first_glyph
3221 : s->first_glyph + s->nchars - 1);
3223 width = abs (s->face->box_line_width);
3224 raised_p = s->face->box == FACE_RAISED_BOX;
3225 left_x = s->x;
3226 right_x = (s->row->full_width_p && s->extends_to_end_of_line_p
3227 ? last_x - 1
3228 : min (last_x, s->x + s->background_width) - 1);
3229 top_y = s->y;
3230 bottom_y = top_y + s->height - 1;
3232 left_p = (s->first_glyph->left_box_line_p
3233 || (s->hl == DRAW_MOUSE_FACE
3234 && (s->prev == NULL
3235 || s->prev->hl != s->hl)));
3236 right_p = (last_glyph->right_box_line_p
3237 || (s->hl == DRAW_MOUSE_FACE
3238 && (s->next == NULL
3239 || s->next->hl != s->hl)));
3241 get_glyph_string_clip_rect (s, &clip_rect);
3243 if (s->face->box == FACE_SIMPLE_BOX)
3244 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
3245 left_p, right_p, &clip_rect);
3246 else
3248 x_setup_relief_colors (s);
3249 x_draw_relief_rect (s->f, left_x, top_y, right_x, bottom_y,
3250 width, raised_p, 1, 1, left_p, right_p, &clip_rect);
3255 /* Draw foreground of image glyph string S. */
3257 static void
3258 x_draw_image_foreground (s)
3259 struct glyph_string *s;
3261 int x = s->x;
3262 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3264 /* If first glyph of S has a left box line, start drawing it to the
3265 right of that line. */
3266 if (s->face->box != FACE_NO_BOX
3267 && s->first_glyph->left_box_line_p
3268 && s->slice.x == 0)
3269 x += abs (s->face->box_line_width);
3271 /* If there is a margin around the image, adjust x- and y-position
3272 by that margin. */
3273 if (s->slice.x == 0)
3274 x += s->img->hmargin;
3275 if (s->slice.y == 0)
3276 y += s->img->vmargin;
3278 if (s->img->pixmap)
3280 x_set_glyph_string_clipping (s);
3282 #if USE_CG_DRAWING
3283 mac_draw_cg_image (s->img->data.ptr_val,
3284 s->f, s->gc, s->slice.x, s->slice.y,
3285 s->slice.width, s->slice.height, x, y, 1);
3286 #endif
3287 if (s->img->mask)
3288 #if !USE_CG_DRAWING
3289 mac_copy_area_with_mask (s->img->pixmap, s->img->mask,
3290 s->f, s->gc, s->slice.x, s->slice.y,
3291 s->slice.width, s->slice.height, x, y);
3292 #else
3294 #endif
3295 else
3297 #if !USE_CG_DRAWING
3298 mac_copy_area (s->img->pixmap,
3299 s->f, s->gc, s->slice.x, s->slice.y,
3300 s->slice.width, s->slice.height, x, y);
3301 #endif
3303 /* When the image has a mask, we can expect that at
3304 least part of a mouse highlight or a block cursor will
3305 be visible. If the image doesn't have a mask, make
3306 a block cursor visible by drawing a rectangle around
3307 the image. I believe it's looking better if we do
3308 nothing here for mouse-face. */
3309 if (s->hl == DRAW_CURSOR)
3311 int r = s->img->relief;
3312 if (r < 0) r = -r;
3313 mac_draw_rectangle (s->f, s->gc, x - r, y - r,
3314 s->slice.width + r*2 - 1,
3315 s->slice.height + r*2 - 1);
3319 else
3320 /* Draw a rectangle if image could not be loaded. */
3321 mac_draw_rectangle (s->f, s->gc, x, y,
3322 s->slice.width - 1, s->slice.height - 1);
3326 /* Draw a relief around the image glyph string S. */
3328 static void
3329 x_draw_image_relief (s)
3330 struct glyph_string *s;
3332 int x0, y0, x1, y1, thick, raised_p;
3333 Rect r;
3334 int x = s->x;
3335 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3337 /* If first glyph of S has a left box line, start drawing it to the
3338 right of that line. */
3339 if (s->face->box != FACE_NO_BOX
3340 && s->first_glyph->left_box_line_p
3341 && s->slice.x == 0)
3342 x += abs (s->face->box_line_width);
3344 /* If there is a margin around the image, adjust x- and y-position
3345 by that margin. */
3346 if (s->slice.x == 0)
3347 x += s->img->hmargin;
3348 if (s->slice.y == 0)
3349 y += s->img->vmargin;
3351 if (s->hl == DRAW_IMAGE_SUNKEN
3352 || s->hl == DRAW_IMAGE_RAISED)
3354 thick = tool_bar_button_relief >= 0 ? tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3355 raised_p = s->hl == DRAW_IMAGE_RAISED;
3357 else
3359 thick = abs (s->img->relief);
3360 raised_p = s->img->relief > 0;
3363 x0 = x - thick;
3364 y0 = y - thick;
3365 x1 = x + s->slice.width + thick - 1;
3366 y1 = y + s->slice.height + thick - 1;
3368 x_setup_relief_colors (s);
3369 get_glyph_string_clip_rect (s, &r);
3370 x_draw_relief_rect (s->f, x0, y0, x1, y1, thick, raised_p,
3371 s->slice.y == 0,
3372 s->slice.y + s->slice.height == s->img->height,
3373 s->slice.x == 0,
3374 s->slice.x + s->slice.width == s->img->width,
3375 &r);
3379 /* Draw part of the background of glyph string S. X, Y, W, and H
3380 give the rectangle to draw. */
3382 static void
3383 x_draw_glyph_string_bg_rect (s, x, y, w, h)
3384 struct glyph_string *s;
3385 int x, y, w, h;
3387 #if 0 /* MAC_TODO: stipple */
3388 if (s->stippled_p)
3390 /* Fill background with a stipple pattern. */
3391 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
3392 XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
3393 XSetFillStyle (s->display, s->gc, FillSolid);
3395 else
3396 #endif /* MAC_TODO */
3397 x_clear_glyph_string_rect (s, x, y, w, h);
3401 /* Draw image glyph string S.
3403 s->y
3404 s->x +-------------------------
3405 | s->face->box
3407 | +-------------------------
3408 | | s->img->margin
3410 | | +-------------------
3411 | | | the image
3415 static void
3416 x_draw_image_glyph_string (s)
3417 struct glyph_string *s;
3419 int x, y;
3420 int box_line_hwidth = abs (s->face->box_line_width);
3421 int box_line_vwidth = max (s->face->box_line_width, 0);
3422 int height;
3424 height = s->height - 2 * box_line_vwidth;
3427 /* Fill background with face under the image. Do it only if row is
3428 taller than image or if image has a clip mask to reduce
3429 flickering. */
3430 s->stippled_p = s->face->stipple != 0;
3431 if (height > s->slice.height
3432 || s->img->hmargin
3433 || s->img->vmargin
3434 || s->img->mask
3435 || s->img->pixmap == 0
3436 || s->width != s->background_width)
3438 x = s->x;
3439 if (s->first_glyph->left_box_line_p
3440 && s->slice.x == 0)
3441 x += box_line_hwidth;
3443 y = s->y;
3444 if (s->slice.y == 0)
3445 y += box_line_vwidth;
3447 x_draw_glyph_string_bg_rect (s, x, y, s->background_width, height);
3449 s->background_filled_p = 1;
3452 /* Draw the foreground. */
3453 x_draw_image_foreground (s);
3455 /* If we must draw a relief around the image, do it. */
3456 if (s->img->relief
3457 || s->hl == DRAW_IMAGE_RAISED
3458 || s->hl == DRAW_IMAGE_SUNKEN)
3459 x_draw_image_relief (s);
3463 /* Draw stretch glyph string S. */
3465 static void
3466 x_draw_stretch_glyph_string (s)
3467 struct glyph_string *s;
3469 xassert (s->first_glyph->type == STRETCH_GLYPH);
3470 s->stippled_p = s->face->stipple != 0;
3472 if (s->hl == DRAW_CURSOR
3473 && !x_stretch_cursor_p)
3475 /* If `x-stretch-block-cursor' is nil, don't draw a block cursor
3476 as wide as the stretch glyph. */
3477 int width = min (FRAME_COLUMN_WIDTH (s->f), s->background_width);
3479 /* Draw cursor. */
3480 x_draw_glyph_string_bg_rect (s, s->x, s->y, width, s->height);
3482 /* Clear rest using the GC of the original non-cursor face. */
3483 if (width < s->background_width)
3485 int x = s->x + width, y = s->y;
3486 int w = s->background_width - width, h = s->height;
3487 Rect r;
3488 GC gc;
3490 if (s->row->mouse_face_p
3491 && cursor_in_mouse_face_p (s->w))
3493 x_set_mouse_face_gc (s);
3494 gc = s->gc;
3496 else
3497 gc = s->face->gc;
3499 get_glyph_string_clip_rect (s, &r);
3500 mac_set_clip_rectangles (s->display, gc, &r, 1);
3502 #if 0 /* MAC_TODO: stipple */
3503 if (s->face->stipple)
3505 /* Fill background with a stipple pattern. */
3506 XSetFillStyle (s->display, gc, FillOpaqueStippled);
3507 XFillRectangle (s->display, s->window, gc, x, y, w, h);
3508 XSetFillStyle (s->display, gc, FillSolid);
3510 else
3511 #endif /* MAC_TODO */
3512 mac_erase_rectangle (s->f, gc, x, y, w, h);
3515 else if (!s->background_filled_p)
3516 x_draw_glyph_string_bg_rect (s, s->x, s->y, s->background_width,
3517 s->height);
3519 s->background_filled_p = 1;
3523 /* Draw glyph string S. */
3525 static void
3526 x_draw_glyph_string (s)
3527 struct glyph_string *s;
3529 int relief_drawn_p = 0;
3531 /* If S draws into the background of its successor that does not
3532 draw a cursor, draw the background of the successor first so that
3533 S can draw into it. This makes S->next use XDrawString instead
3534 of XDrawImageString. */
3535 if (s->next && s->right_overhang && !s->for_overlaps
3536 && s->next->hl != DRAW_CURSOR)
3538 xassert (s->next->img == NULL);
3539 x_set_glyph_string_gc (s->next);
3540 x_set_glyph_string_clipping (s->next);
3541 x_draw_glyph_string_background (s->next, 1);
3544 /* Set up S->gc, set clipping and draw S. */
3545 x_set_glyph_string_gc (s);
3547 /* Draw relief (if any) in advance for char/composition so that the
3548 glyph string can be drawn over it. */
3549 if (!s->for_overlaps
3550 && s->face->box != FACE_NO_BOX
3551 && (s->first_glyph->type == CHAR_GLYPH
3552 || s->first_glyph->type == COMPOSITE_GLYPH))
3555 x_set_glyph_string_clipping (s);
3556 x_draw_glyph_string_background (s, 1);
3557 x_draw_glyph_string_box (s);
3558 x_set_glyph_string_clipping (s);
3559 relief_drawn_p = 1;
3561 else
3562 x_set_glyph_string_clipping (s);
3564 switch (s->first_glyph->type)
3566 case IMAGE_GLYPH:
3567 x_draw_image_glyph_string (s);
3568 break;
3570 case STRETCH_GLYPH:
3571 x_draw_stretch_glyph_string (s);
3572 break;
3574 case CHAR_GLYPH:
3575 if (s->for_overlaps)
3576 s->background_filled_p = 1;
3577 else
3578 x_draw_glyph_string_background (s, 0);
3579 x_draw_glyph_string_foreground (s);
3580 break;
3582 case COMPOSITE_GLYPH:
3583 if (s->for_overlaps || s->gidx > 0)
3584 s->background_filled_p = 1;
3585 else
3586 x_draw_glyph_string_background (s, 1);
3587 x_draw_composite_glyph_string_foreground (s);
3588 break;
3590 default:
3591 abort ();
3594 if (!s->for_overlaps)
3596 /* Draw underline. */
3597 if (s->face->underline_p)
3599 unsigned long h = 1;
3600 unsigned long dy = s->height - h;
3602 if (s->face->underline_defaulted_p)
3603 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3604 s->width, h);
3605 else
3607 XGCValues xgcv;
3608 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3609 XSetForeground (s->display, s->gc, s->face->underline_color);
3610 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3611 s->width, h);
3612 XSetForeground (s->display, s->gc, xgcv.foreground);
3616 /* Draw overline. */
3617 if (s->face->overline_p)
3619 unsigned long dy = 0, h = 1;
3621 if (s->face->overline_color_defaulted_p)
3622 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3623 s->width, h);
3624 else
3626 XGCValues xgcv;
3627 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3628 XSetForeground (s->display, s->gc, s->face->overline_color);
3629 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3630 s->width, h);
3631 XSetForeground (s->display, s->gc, xgcv.foreground);
3635 /* Draw strike-through. */
3636 if (s->face->strike_through_p)
3638 unsigned long h = 1;
3639 unsigned long dy = (s->height - h) / 2;
3641 if (s->face->strike_through_color_defaulted_p)
3642 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3643 s->width, h);
3644 else
3646 XGCValues xgcv;
3647 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3648 XSetForeground (s->display, s->gc, s->face->strike_through_color);
3649 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3650 s->width, h);
3651 XSetForeground (s->display, s->gc, xgcv.foreground);
3655 /* Draw relief if not yet drawn. */
3656 if (!relief_drawn_p && s->face->box != FACE_NO_BOX)
3657 x_draw_glyph_string_box (s);
3660 /* Reset clipping. */
3661 mac_reset_clip_rectangles (s->display, s->gc);
3664 /* Shift display to make room for inserted glyphs. */
3666 void
3667 mac_shift_glyphs_for_insert (f, x, y, width, height, shift_by)
3668 struct frame *f;
3669 int x, y, width, height, shift_by;
3671 mac_scroll_area (f, f->output_data.mac->normal_gc,
3672 x, y, width, height,
3673 x + shift_by, y);
3676 /* Delete N glyphs at the nominal cursor position. Not implemented
3677 for X frames. */
3679 static void
3680 x_delete_glyphs (n)
3681 register int n;
3683 abort ();
3687 /* Clear entire frame. If updating_frame is non-null, clear that
3688 frame. Otherwise clear the selected frame. */
3690 static void
3691 x_clear_frame ()
3693 struct frame *f;
3695 if (updating_frame)
3696 f = updating_frame;
3697 else
3698 f = SELECTED_FRAME ();
3700 /* Clearing the frame will erase any cursor, so mark them all as no
3701 longer visible. */
3702 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
3703 output_cursor.hpos = output_cursor.vpos = 0;
3704 output_cursor.x = -1;
3706 /* We don't set the output cursor here because there will always
3707 follow an explicit cursor_to. */
3708 BLOCK_INPUT;
3709 mac_clear_window (f);
3711 /* We have to clear the scroll bars, too. If we have changed
3712 colors or something like that, then they should be notified. */
3713 x_scroll_bar_clear (f);
3715 XFlush (FRAME_MAC_DISPLAY (f));
3716 UNBLOCK_INPUT;
3721 /* Invert the middle quarter of the frame for .15 sec. */
3723 /* We use the select system call to do the waiting, so we have to make
3724 sure it's available. If it isn't, we just won't do visual bells. */
3726 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
3729 /* Subtract the `struct timeval' values X and Y, storing the result in
3730 *RESULT. Return 1 if the difference is negative, otherwise 0. */
3732 static int
3733 timeval_subtract (result, x, y)
3734 struct timeval *result, x, y;
3736 /* Perform the carry for the later subtraction by updating y. This
3737 is safer because on some systems the tv_sec member is unsigned. */
3738 if (x.tv_usec < y.tv_usec)
3740 int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
3741 y.tv_usec -= 1000000 * nsec;
3742 y.tv_sec += nsec;
3745 if (x.tv_usec - y.tv_usec > 1000000)
3747 int nsec = (y.tv_usec - x.tv_usec) / 1000000;
3748 y.tv_usec += 1000000 * nsec;
3749 y.tv_sec -= nsec;
3752 /* Compute the time remaining to wait. tv_usec is certainly
3753 positive. */
3754 result->tv_sec = x.tv_sec - y.tv_sec;
3755 result->tv_usec = x.tv_usec - y.tv_usec;
3757 /* Return indication of whether the result should be considered
3758 negative. */
3759 return x.tv_sec < y.tv_sec;
3762 void
3763 XTflash (f)
3764 struct frame *f;
3766 /* Get the height not including a menu bar widget. */
3767 int height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, FRAME_LINES (f));
3768 /* Height of each line to flash. */
3769 int flash_height = FRAME_LINE_HEIGHT (f);
3770 /* These will be the left and right margins of the rectangles. */
3771 int flash_left = FRAME_INTERNAL_BORDER_WIDTH (f);
3772 int flash_right = FRAME_PIXEL_WIDTH (f) - FRAME_INTERNAL_BORDER_WIDTH (f);
3774 int width;
3776 /* Don't flash the area between a scroll bar and the frame
3777 edge it is next to. */
3778 switch (FRAME_VERTICAL_SCROLL_BAR_TYPE (f))
3780 case vertical_scroll_bar_left:
3781 flash_left += VERTICAL_SCROLL_BAR_WIDTH_TRIM;
3782 break;
3784 case vertical_scroll_bar_right:
3785 flash_right -= VERTICAL_SCROLL_BAR_WIDTH_TRIM;
3786 break;
3788 default:
3789 break;
3792 width = flash_right - flash_left;
3794 BLOCK_INPUT;
3796 /* If window is tall, flash top and bottom line. */
3797 if (height > 3 * FRAME_LINE_HEIGHT (f))
3799 mac_invert_rectangle (f, flash_left,
3800 (FRAME_INTERNAL_BORDER_WIDTH (f)
3801 + FRAME_TOOL_BAR_LINES (f) * FRAME_LINE_HEIGHT (f)),
3802 width, flash_height);
3803 mac_invert_rectangle (f, flash_left,
3804 (height - flash_height
3805 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3806 width, flash_height);
3808 else
3809 /* If it is short, flash it all. */
3810 mac_invert_rectangle (f, flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3811 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3813 x_flush (f);
3816 struct timeval wakeup;
3818 EMACS_GET_TIME (wakeup);
3820 /* Compute time to wait until, propagating carry from usecs. */
3821 wakeup.tv_usec += 150000;
3822 wakeup.tv_sec += (wakeup.tv_usec / 1000000);
3823 wakeup.tv_usec %= 1000000;
3825 /* Keep waiting until past the time wakeup or any input gets
3826 available. */
3827 while (! detect_input_pending ())
3829 struct timeval current;
3830 struct timeval timeout;
3832 EMACS_GET_TIME (current);
3834 /* Break if result would be negative. */
3835 if (timeval_subtract (&current, wakeup, current))
3836 break;
3838 /* How long `select' should wait. */
3839 timeout.tv_sec = 0;
3840 timeout.tv_usec = 10000;
3842 /* Try to wait that long--but we might wake up sooner. */
3843 select (0, NULL, NULL, NULL, &timeout);
3847 /* If window is tall, flash top and bottom line. */
3848 if (height > 3 * FRAME_LINE_HEIGHT (f))
3850 mac_invert_rectangle (f, flash_left,
3851 (FRAME_INTERNAL_BORDER_WIDTH (f)
3852 + FRAME_TOOL_BAR_LINES (f) * FRAME_LINE_HEIGHT (f)),
3853 width, flash_height);
3854 mac_invert_rectangle (f, flash_left,
3855 (height - flash_height
3856 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3857 width, flash_height);
3859 else
3860 /* If it is short, flash it all. */
3861 mac_invert_rectangle (f, flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3862 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3864 x_flush (f);
3866 UNBLOCK_INPUT;
3869 #endif /* defined (HAVE_TIMEVAL) && defined (HAVE_SELECT) */
3872 /* Make audible bell. */
3874 void
3875 XTring_bell ()
3877 struct frame *f = SELECTED_FRAME ();
3879 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
3880 if (visible_bell)
3881 XTflash (f);
3882 else
3883 #endif
3885 BLOCK_INPUT;
3886 SysBeep (1);
3887 XFlush (FRAME_MAC_DISPLAY (f));
3888 UNBLOCK_INPUT;
3893 /* Specify how many text lines, from the top of the window,
3894 should be affected by insert-lines and delete-lines operations.
3895 This, and those operations, are used only within an update
3896 that is bounded by calls to x_update_begin and x_update_end. */
3898 static void
3899 XTset_terminal_window (n)
3900 register int n;
3902 /* This function intentionally left blank. */
3907 /***********************************************************************
3908 Line Dance
3909 ***********************************************************************/
3911 /* Perform an insert-lines or delete-lines operation, inserting N
3912 lines or deleting -N lines at vertical position VPOS. */
3914 static void
3915 x_ins_del_lines (vpos, n)
3916 int vpos, n;
3918 abort ();
3922 /* Scroll part of the display as described by RUN. */
3924 static void
3925 x_scroll_run (w, run)
3926 struct window *w;
3927 struct run *run;
3929 struct frame *f = XFRAME (w->frame);
3930 int x, y, width, height, from_y, to_y, bottom_y;
3932 /* Get frame-relative bounding box of the text display area of W,
3933 without mode lines. Include in this box the left and right
3934 fringe of W. */
3935 window_box (w, -1, &x, &y, &width, &height);
3937 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
3938 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
3939 bottom_y = y + height;
3941 if (to_y < from_y)
3943 /* Scrolling up. Make sure we don't copy part of the mode
3944 line at the bottom. */
3945 if (from_y + run->height > bottom_y)
3946 height = bottom_y - from_y;
3947 else
3948 height = run->height;
3950 else
3952 /* Scolling down. Make sure we don't copy over the mode line.
3953 at the bottom. */
3954 if (to_y + run->height > bottom_y)
3955 height = bottom_y - to_y;
3956 else
3957 height = run->height;
3960 BLOCK_INPUT;
3962 /* Cursor off. Will be switched on again in x_update_window_end. */
3963 updated_window = w;
3964 x_clear_cursor (w);
3966 mac_scroll_area (f, f->output_data.mac->normal_gc,
3967 x, from_y,
3968 width, height,
3969 x, to_y);
3971 UNBLOCK_INPUT;
3976 /***********************************************************************
3977 Exposure Events
3978 ***********************************************************************/
3981 static void
3982 frame_highlight (f)
3983 struct frame *f;
3985 OSErr err;
3986 ControlRef root_control;
3988 BLOCK_INPUT;
3989 err = GetRootControl (FRAME_MAC_WINDOW (f), &root_control);
3990 if (err == noErr)
3991 ActivateControl (root_control);
3992 UNBLOCK_INPUT;
3993 x_update_cursor (f, 1);
3996 static void
3997 frame_unhighlight (f)
3998 struct frame *f;
4000 OSErr err;
4001 ControlRef root_control;
4003 BLOCK_INPUT;
4004 err = GetRootControl (FRAME_MAC_WINDOW (f), &root_control);
4005 if (err == noErr)
4006 DeactivateControl (root_control);
4007 UNBLOCK_INPUT;
4008 x_update_cursor (f, 1);
4011 /* The focus has changed. Update the frames as necessary to reflect
4012 the new situation. Note that we can't change the selected frame
4013 here, because the Lisp code we are interrupting might become confused.
4014 Each event gets marked with the frame in which it occurred, so the
4015 Lisp code can tell when the switch took place by examining the events. */
4017 static void
4018 x_new_focus_frame (dpyinfo, frame)
4019 struct x_display_info *dpyinfo;
4020 struct frame *frame;
4022 struct frame *old_focus = dpyinfo->x_focus_frame;
4024 if (frame != dpyinfo->x_focus_frame)
4026 /* Set this before calling other routines, so that they see
4027 the correct value of x_focus_frame. */
4028 dpyinfo->x_focus_frame = frame;
4030 if (old_focus && old_focus->auto_lower)
4031 x_lower_frame (old_focus);
4033 #if 0
4034 selected_frame = frame;
4035 XSETFRAME (XWINDOW (selected_frame->selected_window)->frame,
4036 selected_frame);
4037 Fselect_window (selected_frame->selected_window, Qnil);
4038 choose_minibuf_frame ();
4039 #endif /* ! 0 */
4041 if (dpyinfo->x_focus_frame && dpyinfo->x_focus_frame->auto_raise)
4042 pending_autoraise_frame = dpyinfo->x_focus_frame;
4043 else
4044 pending_autoraise_frame = 0;
4047 x_frame_rehighlight (dpyinfo);
4050 /* Handle FocusIn and FocusOut state changes for FRAME.
4051 If FRAME has focus and there exists more than one frame, puts
4052 a FOCUS_IN_EVENT into *BUFP. */
4054 static void
4055 mac_focus_changed (type, dpyinfo, frame, bufp)
4056 int type;
4057 struct mac_display_info *dpyinfo;
4058 struct frame *frame;
4059 struct input_event *bufp;
4061 if (type == activeFlag)
4063 if (dpyinfo->x_focus_event_frame != frame)
4065 x_new_focus_frame (dpyinfo, frame);
4066 dpyinfo->x_focus_event_frame = frame;
4068 /* Don't stop displaying the initial startup message
4069 for a switch-frame event we don't need. */
4070 if (GC_NILP (Vterminal_frame)
4071 && GC_CONSP (Vframe_list)
4072 && !GC_NILP (XCDR (Vframe_list)))
4074 bufp->kind = FOCUS_IN_EVENT;
4075 XSETFRAME (bufp->frame_or_window, frame);
4079 else
4081 if (dpyinfo->x_focus_event_frame == frame)
4083 dpyinfo->x_focus_event_frame = 0;
4084 x_new_focus_frame (dpyinfo, 0);
4089 /* The focus may have changed. Figure out if it is a real focus change,
4090 by checking both FocusIn/Out and Enter/LeaveNotify events.
4092 Returns FOCUS_IN_EVENT event in *BUFP. */
4094 static void
4095 x_detect_focus_change (dpyinfo, event, bufp)
4096 struct mac_display_info *dpyinfo;
4097 EventRecord *event;
4098 struct input_event *bufp;
4100 struct frame *frame;
4102 frame = mac_window_to_frame ((WindowPtr) event->message);
4103 if (! frame)
4104 return;
4106 /* On Mac, this is only called from focus events, so no switch needed. */
4107 mac_focus_changed ((event->modifiers & activeFlag),
4108 dpyinfo, frame, bufp);
4112 /* Handle an event saying the mouse has moved out of an Emacs frame. */
4114 void
4115 x_mouse_leave (dpyinfo)
4116 struct x_display_info *dpyinfo;
4118 x_new_focus_frame (dpyinfo, dpyinfo->x_focus_event_frame);
4121 /* The focus has changed, or we have redirected a frame's focus to
4122 another frame (this happens when a frame uses a surrogate
4123 mini-buffer frame). Shift the highlight as appropriate.
4125 The FRAME argument doesn't necessarily have anything to do with which
4126 frame is being highlighted or un-highlighted; we only use it to find
4127 the appropriate X display info. */
4129 static void
4130 XTframe_rehighlight (frame)
4131 struct frame *frame;
4133 x_frame_rehighlight (FRAME_X_DISPLAY_INFO (frame));
4136 static void
4137 x_frame_rehighlight (dpyinfo)
4138 struct x_display_info *dpyinfo;
4140 struct frame *old_highlight = dpyinfo->x_highlight_frame;
4142 if (dpyinfo->x_focus_frame)
4144 dpyinfo->x_highlight_frame
4145 = ((GC_FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame)))
4146 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
4147 : dpyinfo->x_focus_frame);
4148 if (! FRAME_LIVE_P (dpyinfo->x_highlight_frame))
4150 FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
4151 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
4154 else
4155 dpyinfo->x_highlight_frame = 0;
4157 if (dpyinfo->x_highlight_frame != old_highlight)
4159 if (old_highlight)
4160 frame_unhighlight (old_highlight);
4161 if (dpyinfo->x_highlight_frame)
4162 frame_highlight (dpyinfo->x_highlight_frame);
4168 /* Convert a keysym to its name. */
4170 char *
4171 x_get_keysym_name (keysym)
4172 int keysym;
4174 char *value;
4176 BLOCK_INPUT;
4177 #if 0
4178 value = XKeysymToString (keysym);
4179 #else
4180 value = 0;
4181 #endif
4182 UNBLOCK_INPUT;
4184 return value;
4189 /* Function to report a mouse movement to the mainstream Emacs code.
4190 The input handler calls this.
4192 We have received a mouse movement event, which is given in *event.
4193 If the mouse is over a different glyph than it was last time, tell
4194 the mainstream emacs code by setting mouse_moved. If not, ask for
4195 another motion event, so we can check again the next time it moves. */
4197 static Point last_mouse_motion_position;
4198 static Lisp_Object last_mouse_motion_frame;
4200 static int
4201 note_mouse_movement (frame, pos)
4202 FRAME_PTR frame;
4203 Point *pos;
4205 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (frame);
4206 #if TARGET_API_MAC_CARBON
4207 Rect r;
4208 #endif
4210 last_mouse_movement_time = TickCount () * (1000 / 60); /* to milliseconds */
4211 last_mouse_motion_position = *pos;
4212 XSETFRAME (last_mouse_motion_frame, frame);
4214 #if TARGET_API_MAC_CARBON
4215 if (!PtInRect (*pos, GetWindowPortBounds (FRAME_MAC_WINDOW (frame), &r)))
4216 #else
4217 if (!PtInRect (*pos, &FRAME_MAC_WINDOW (frame)->portRect))
4218 #endif
4220 if (frame == dpyinfo->mouse_face_mouse_frame)
4221 /* This case corresponds to LeaveNotify in X11. */
4223 /* If we move outside the frame, then we're certainly no
4224 longer on any text in the frame. */
4225 clear_mouse_face (dpyinfo);
4226 dpyinfo->mouse_face_mouse_frame = 0;
4227 if (!dpyinfo->grabbed)
4228 rif->define_frame_cursor (frame,
4229 frame->output_data.mac->nontext_cursor);
4231 return 1;
4233 /* Has the mouse moved off the glyph it was on at the last sighting? */
4234 if (frame != last_mouse_glyph_frame
4235 || !PtInRect (*pos, &last_mouse_glyph))
4237 frame->mouse_moved = 1;
4238 last_mouse_scroll_bar = Qnil;
4239 note_mouse_highlight (frame, pos->h, pos->v);
4240 /* Remember which glyph we're now on. */
4241 remember_mouse_glyph (frame, pos->h, pos->v, &last_mouse_glyph);
4242 last_mouse_glyph_frame = frame;
4243 return 1;
4246 return 0;
4250 /************************************************************************
4251 Mouse Face
4252 ************************************************************************/
4254 /* MAC TODO: This should be called from somewhere (or removed) ++KFS */
4256 static void
4257 redo_mouse_highlight ()
4259 if (!NILP (last_mouse_motion_frame)
4260 && FRAME_LIVE_P (XFRAME (last_mouse_motion_frame)))
4261 note_mouse_highlight (XFRAME (last_mouse_motion_frame),
4262 last_mouse_motion_position.h,
4263 last_mouse_motion_position.v);
4267 static struct frame *
4268 mac_focus_frame (dpyinfo)
4269 struct mac_display_info *dpyinfo;
4271 if (dpyinfo->x_focus_frame)
4272 return dpyinfo->x_focus_frame;
4273 else
4274 /* Mac version may get events, such as a menu bar click, even when
4275 all the frames are invisible. In this case, we regard the
4276 event came to the selected frame. */
4277 return SELECTED_FRAME ();
4281 /* Return the current position of the mouse.
4282 *FP should be a frame which indicates which display to ask about.
4284 If the mouse movement started in a scroll bar, set *FP, *BAR_WINDOW,
4285 and *PART to the frame, window, and scroll bar part that the mouse
4286 is over. Set *X and *Y to the portion and whole of the mouse's
4287 position on the scroll bar.
4289 If the mouse movement started elsewhere, set *FP to the frame the
4290 mouse is on, *BAR_WINDOW to nil, and *X and *Y to the character cell
4291 the mouse is over.
4293 Set *TIME to the server time-stamp for the time at which the mouse
4294 was at this position.
4296 Don't store anything if we don't have a valid set of values to report.
4298 This clears the mouse_moved flag, so we can wait for the next mouse
4299 movement. */
4301 static void
4302 XTmouse_position (fp, insist, bar_window, part, x, y, time)
4303 FRAME_PTR *fp;
4304 int insist;
4305 Lisp_Object *bar_window;
4306 enum scroll_bar_part *part;
4307 Lisp_Object *x, *y;
4308 unsigned long *time;
4310 FRAME_PTR f1;
4312 BLOCK_INPUT;
4314 if (! NILP (last_mouse_scroll_bar) && insist == 0)
4315 x_scroll_bar_report_motion (fp, bar_window, part, x, y, time);
4316 else
4318 Lisp_Object frame, tail;
4320 /* Clear the mouse-moved flag for every frame on this display. */
4321 FOR_EACH_FRAME (tail, frame)
4322 XFRAME (frame)->mouse_moved = 0;
4324 last_mouse_scroll_bar = Qnil;
4326 if (FRAME_MAC_DISPLAY_INFO (*fp)->grabbed && last_mouse_frame
4327 && FRAME_LIVE_P (last_mouse_frame))
4328 f1 = last_mouse_frame;
4329 else
4330 f1 = mac_focus_frame (FRAME_MAC_DISPLAY_INFO (*fp));
4332 if (f1)
4334 /* Ok, we found a frame. Store all the values.
4335 last_mouse_glyph is a rectangle used to reduce the
4336 generation of mouse events. To not miss any motion
4337 events, we must divide the frame into rectangles of the
4338 size of the smallest character that could be displayed
4339 on it, i.e. into the same rectangles that matrices on
4340 the frame are divided into. */
4341 Point mouse_pos;
4343 SetPortWindowPort (FRAME_MAC_WINDOW (f1));
4344 GetMouse (&mouse_pos);
4345 remember_mouse_glyph (f1, mouse_pos.h, mouse_pos.v,
4346 &last_mouse_glyph);
4347 last_mouse_glyph_frame = f1;
4349 *bar_window = Qnil;
4350 *part = 0;
4351 *fp = f1;
4352 XSETINT (*x, mouse_pos.h);
4353 XSETINT (*y, mouse_pos.v);
4354 *time = last_mouse_movement_time;
4358 UNBLOCK_INPUT;
4362 /************************************************************************
4363 Toolkit scroll bars
4364 ************************************************************************/
4366 #ifdef USE_TOOLKIT_SCROLL_BARS
4368 static pascal void scroll_bar_timer_callback P_ ((EventLoopTimerRef, void *));
4369 static OSStatus install_scroll_bar_timer P_ ((void));
4370 static OSStatus set_scroll_bar_timer P_ ((EventTimerInterval));
4371 static int control_part_code_to_scroll_bar_part P_ ((ControlPartCode));
4372 static void construct_scroll_bar_click P_ ((struct scroll_bar *, int,
4373 struct input_event *));
4374 static OSStatus get_control_part_bounds P_ ((ControlHandle, ControlPartCode,
4375 Rect *));
4376 static void x_scroll_bar_handle_press P_ ((struct scroll_bar *,
4377 ControlPartCode,
4378 struct input_event *));
4379 static void x_scroll_bar_handle_release P_ ((struct scroll_bar *,
4380 struct input_event *));
4381 static void x_scroll_bar_handle_drag P_ ((WindowPtr, struct scroll_bar *,
4382 Point, struct input_event *));
4383 static void x_set_toolkit_scroll_bar_thumb P_ ((struct scroll_bar *,
4384 int, int, int));
4386 /* Last scroll bar part sent in x_scroll_bar_handle_*. */
4388 static int last_scroll_bar_part;
4390 static EventLoopTimerRef scroll_bar_timer;
4392 static int scroll_bar_timer_event_posted_p;
4394 #define SCROLL_BAR_FIRST_DELAY 0.5
4395 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
4397 static pascal void
4398 scroll_bar_timer_callback (timer, data)
4399 EventLoopTimerRef timer;
4400 void *data;
4402 EventRef event = NULL;
4403 OSErr err;
4405 err = CreateEvent (NULL, kEventClassMouse, kEventMouseMoved, 0,
4406 kEventAttributeNone, &event);
4407 if (err == noErr)
4409 Point mouse_pos;
4411 GetMouse (&mouse_pos);
4412 LocalToGlobal (&mouse_pos);
4413 err = SetEventParameter (event, kEventParamMouseLocation, typeQDPoint,
4414 sizeof (Point), &mouse_pos);
4416 if (err == noErr)
4418 UInt32 modifiers = GetCurrentKeyModifiers ();
4420 err = SetEventParameter (event, kEventParamKeyModifiers, typeUInt32,
4421 sizeof (UInt32), &modifiers);
4423 if (err == noErr)
4424 err = PostEventToQueue (GetCurrentEventQueue (), event,
4425 kEventPriorityStandard);
4426 if (err == noErr)
4427 scroll_bar_timer_event_posted_p = 1;
4429 if (event)
4430 ReleaseEvent (event);
4433 static OSStatus
4434 install_scroll_bar_timer ()
4436 static EventLoopTimerUPP scroll_bar_timer_callbackUPP = NULL;
4438 if (scroll_bar_timer_callbackUPP == NULL)
4439 scroll_bar_timer_callbackUPP =
4440 NewEventLoopTimerUPP (scroll_bar_timer_callback);
4442 if (scroll_bar_timer == NULL)
4443 /* Mac OS X and CarbonLib 1.5 and later allow us to specify
4444 kEventDurationForever as delays. */
4445 return
4446 InstallEventLoopTimer (GetCurrentEventLoop (),
4447 kEventDurationForever, kEventDurationForever,
4448 scroll_bar_timer_callbackUPP, NULL,
4449 &scroll_bar_timer);
4452 static OSStatus
4453 set_scroll_bar_timer (delay)
4454 EventTimerInterval delay;
4456 if (scroll_bar_timer == NULL)
4457 install_scroll_bar_timer ();
4459 scroll_bar_timer_event_posted_p = 0;
4461 return SetEventLoopTimerNextFireTime (scroll_bar_timer, delay);
4464 static int
4465 control_part_code_to_scroll_bar_part (part_code)
4466 ControlPartCode part_code;
4468 switch (part_code)
4470 case kControlUpButtonPart: return scroll_bar_up_arrow;
4471 case kControlDownButtonPart: return scroll_bar_down_arrow;
4472 case kControlPageUpPart: return scroll_bar_above_handle;
4473 case kControlPageDownPart: return scroll_bar_below_handle;
4474 case kControlIndicatorPart: return scroll_bar_handle;
4477 return -1;
4480 static void
4481 construct_scroll_bar_click (bar, part, bufp)
4482 struct scroll_bar *bar;
4483 int part;
4484 struct input_event *bufp;
4486 bufp->kind = SCROLL_BAR_CLICK_EVENT;
4487 bufp->frame_or_window = bar->window;
4488 bufp->arg = Qnil;
4489 bufp->part = part;
4490 bufp->code = 0;
4491 XSETINT (bufp->x, 0);
4492 XSETINT (bufp->y, 0);
4493 bufp->modifiers = 0;
4496 static OSStatus
4497 get_control_part_bounds (ch, part_code, rect)
4498 ControlHandle ch;
4499 ControlPartCode part_code;
4500 Rect *rect;
4502 RgnHandle region = NewRgn ();
4503 OSStatus err;
4505 err = GetControlRegion (ch, part_code, region);
4506 if (err == noErr)
4507 GetRegionBounds (region, rect);
4508 DisposeRgn (region);
4510 return err;
4513 static void
4514 x_scroll_bar_handle_press (bar, part_code, bufp)
4515 struct scroll_bar *bar;
4516 ControlPartCode part_code;
4517 struct input_event *bufp;
4519 int part = control_part_code_to_scroll_bar_part (part_code);
4521 if (part < 0)
4522 return;
4524 if (part != scroll_bar_handle)
4526 construct_scroll_bar_click (bar, part, bufp);
4527 HiliteControl (SCROLL_BAR_CONTROL_HANDLE (bar), part_code);
4528 set_scroll_bar_timer (SCROLL_BAR_FIRST_DELAY);
4531 last_scroll_bar_part = part;
4532 bar->dragging = Qnil;
4533 tracked_scroll_bar = bar;
4536 static void
4537 x_scroll_bar_handle_release (bar, bufp)
4538 struct scroll_bar *bar;
4539 struct input_event *bufp;
4541 if (last_scroll_bar_part != scroll_bar_handle
4542 || !GC_NILP (bar->dragging))
4543 construct_scroll_bar_click (bar, scroll_bar_end_scroll, bufp);
4545 HiliteControl (SCROLL_BAR_CONTROL_HANDLE (bar), 0);
4546 set_scroll_bar_timer (kEventDurationForever);
4548 last_scroll_bar_part = -1;
4549 bar->dragging = Qnil;
4550 tracked_scroll_bar = NULL;
4553 static void
4554 x_scroll_bar_handle_drag (win, bar, mouse_pos, bufp)
4555 WindowPtr win;
4556 struct scroll_bar *bar;
4557 Point mouse_pos;
4558 struct input_event *bufp;
4560 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4562 if (last_scroll_bar_part == scroll_bar_handle)
4564 int top, top_range;
4565 Rect r;
4567 get_control_part_bounds (SCROLL_BAR_CONTROL_HANDLE (bar),
4568 kControlIndicatorPart, &r);
4570 if (GC_NILP (bar->dragging))
4571 XSETINT (bar->dragging, mouse_pos.v - r.top);
4573 top = mouse_pos.v - XINT (bar->dragging) - XINT (bar->track_top);
4574 top_range = (XINT (bar->track_height) - (r.bottom - r.top)) *
4575 (1.0 + (float) GetControlViewSize (ch) / GetControl32BitMaximum (ch))
4576 + .5;
4578 if (top < 0)
4579 top = 0;
4580 if (top > top_range)
4581 top = top_range;
4583 construct_scroll_bar_click (bar, scroll_bar_handle, bufp);
4584 XSETINT (bufp->x, top);
4585 XSETINT (bufp->y, top_range);
4587 else
4589 ControlPartCode part_code;
4590 int unhilite_p = 0, part;
4592 if (ch != FindControlUnderMouse (mouse_pos, win, &part_code))
4593 unhilite_p = 1;
4594 else
4596 part = control_part_code_to_scroll_bar_part (part_code);
4598 switch (last_scroll_bar_part)
4600 case scroll_bar_above_handle:
4601 case scroll_bar_below_handle:
4602 if (part != scroll_bar_above_handle
4603 && part != scroll_bar_below_handle)
4604 unhilite_p = 1;
4605 break;
4607 case scroll_bar_up_arrow:
4608 case scroll_bar_down_arrow:
4609 if (part != scroll_bar_up_arrow
4610 && part != scroll_bar_down_arrow)
4611 unhilite_p = 1;
4612 break;
4616 if (unhilite_p)
4617 HiliteControl (SCROLL_BAR_CONTROL_HANDLE (bar), 0);
4618 else if (part != last_scroll_bar_part
4619 || scroll_bar_timer_event_posted_p)
4621 construct_scroll_bar_click (bar, part, bufp);
4622 last_scroll_bar_part = part;
4623 HiliteControl (SCROLL_BAR_CONTROL_HANDLE (bar), part_code);
4624 set_scroll_bar_timer (SCROLL_BAR_CONTINUOUS_DELAY);
4629 /* Set the thumb size and position of scroll bar BAR. We are currently
4630 displaying PORTION out of a whole WHOLE, and our position POSITION. */
4632 static void
4633 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole)
4634 struct scroll_bar *bar;
4635 int portion, position, whole;
4637 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4638 int value, viewsize, maximum;
4640 if (XINT (bar->track_height) == 0)
4641 return;
4643 if (whole == 0)
4644 value = 0, viewsize = 1, maximum = 0;
4645 else
4647 value = position;
4648 viewsize = portion;
4649 maximum = max (0, whole - portion);
4652 BLOCK_INPUT;
4654 if (GetControlViewSize (ch) != viewsize
4655 || GetControl32BitValue (ch) != value
4656 || GetControl32BitMaximum (ch) != maximum)
4658 /* Temporarily hide the scroll bar to avoid multiple redraws. */
4659 SetControlVisibility (ch, false, false);
4661 SetControl32BitMaximum (ch, maximum);
4662 SetControl32BitValue (ch, value);
4663 SetControlViewSize (ch, viewsize);
4665 SetControlVisibility (ch, true, true);
4668 UNBLOCK_INPUT;
4671 #endif /* USE_TOOLKIT_SCROLL_BARS */
4675 /************************************************************************
4676 Scroll bars, general
4677 ************************************************************************/
4679 /* Create a scroll bar and return the scroll bar vector for it. W is
4680 the Emacs window on which to create the scroll bar. TOP, LEFT,
4681 WIDTH and HEIGHT are the pixel coordinates and dimensions of the
4682 scroll bar. */
4684 static struct scroll_bar *
4685 x_scroll_bar_create (w, top, left, width, height, disp_top, disp_height)
4686 struct window *w;
4687 int top, left, width, height, disp_top, disp_height;
4689 struct frame *f = XFRAME (w->frame);
4690 struct scroll_bar *bar
4691 = XSCROLL_BAR (Fmake_vector (make_number (SCROLL_BAR_VEC_SIZE), Qnil));
4692 Rect r;
4693 ControlHandle ch;
4695 BLOCK_INPUT;
4697 r.left = left;
4698 r.top = disp_top;
4699 r.right = left + width;
4700 r.bottom = disp_top + disp_height;
4702 #if USE_CG_DRAWING
4703 mac_prepare_for_quickdraw (f);
4704 #endif
4705 #if TARGET_API_MAC_CARBON
4706 ch = NewControl (FRAME_MAC_WINDOW (f), &r, "\p",
4707 #if USE_TOOLKIT_SCROLL_BARS
4708 false,
4709 #else
4710 width < disp_height,
4711 #endif
4712 0, 0, 0, kControlScrollBarProc, (long) bar);
4713 #else
4714 ch = NewControl (FRAME_MAC_WINDOW (f), &r, "\p", width < disp_height,
4715 0, 0, 0, scrollBarProc, (long) bar);
4716 #endif
4717 SET_SCROLL_BAR_CONTROL_HANDLE (bar, ch);
4719 XSETWINDOW (bar->window, w);
4720 XSETINT (bar->top, top);
4721 XSETINT (bar->left, left);
4722 XSETINT (bar->width, width);
4723 XSETINT (bar->height, height);
4724 XSETINT (bar->start, 0);
4725 XSETINT (bar->end, 0);
4726 bar->dragging = Qnil;
4727 #ifdef USE_TOOLKIT_SCROLL_BARS
4728 bar->track_top = Qnil;
4729 bar->track_height = Qnil;
4730 #endif
4732 /* Add bar to its frame's list of scroll bars. */
4733 bar->next = FRAME_SCROLL_BARS (f);
4734 bar->prev = Qnil;
4735 XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
4736 if (!NILP (bar->next))
4737 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
4739 UNBLOCK_INPUT;
4740 return bar;
4744 /* Draw BAR's handle in the proper position.
4746 If the handle is already drawn from START to END, don't bother
4747 redrawing it, unless REBUILD is non-zero; in that case, always
4748 redraw it. (REBUILD is handy for drawing the handle after expose
4749 events.)
4751 Normally, we want to constrain the start and end of the handle to
4752 fit inside its rectangle, but if the user is dragging the scroll
4753 bar handle, we want to let them drag it down all the way, so that
4754 the bar's top is as far down as it goes; otherwise, there's no way
4755 to move to the very end of the buffer. */
4757 #ifndef USE_TOOLKIT_SCROLL_BARS
4759 static void
4760 x_scroll_bar_set_handle (bar, start, end, rebuild)
4761 struct scroll_bar *bar;
4762 int start, end;
4763 int rebuild;
4765 int dragging = ! NILP (bar->dragging);
4766 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4767 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4768 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, XINT (bar->height));
4769 int length = end - start;
4771 /* If the display is already accurate, do nothing. */
4772 if (! rebuild
4773 && start == XINT (bar->start)
4774 && end == XINT (bar->end))
4775 return;
4777 BLOCK_INPUT;
4779 /* Make sure the values are reasonable, and try to preserve the
4780 distance between start and end. */
4781 if (start < 0)
4782 start = 0;
4783 else if (start > top_range)
4784 start = top_range;
4785 end = start + length;
4787 if (end < start)
4788 end = start;
4789 else if (end > top_range && ! dragging)
4790 end = top_range;
4792 /* Store the adjusted setting in the scroll bar. */
4793 XSETINT (bar->start, start);
4794 XSETINT (bar->end, end);
4796 /* Clip the end position, just for display. */
4797 if (end > top_range)
4798 end = top_range;
4800 /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels below
4801 top positions, to make sure the handle is always at least that
4802 many pixels tall. */
4803 end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
4805 SetControlMinimum (ch, 0);
4806 /* Don't inadvertently activate deactivated scroll bars */
4807 if (GetControlMaximum (ch) != -1)
4808 SetControlMaximum (ch, top_range + VERTICAL_SCROLL_BAR_MIN_HANDLE
4809 - (end - start));
4810 SetControlValue (ch, start);
4811 #if TARGET_API_MAC_CARBON
4812 SetControlViewSize (ch, end - start);
4813 #endif
4815 UNBLOCK_INPUT;
4818 #endif /* !USE_TOOLKIT_SCROLL_BARS */
4820 /* Destroy scroll bar BAR, and set its Emacs window's scroll bar to
4821 nil. */
4823 static void
4824 x_scroll_bar_remove (bar)
4825 struct scroll_bar *bar;
4827 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4829 BLOCK_INPUT;
4831 #if USE_CG_DRAWING
4832 mac_prepare_for_quickdraw (f);
4833 #endif
4834 /* Destroy the Mac scroll bar control */
4835 DisposeControl (SCROLL_BAR_CONTROL_HANDLE (bar));
4837 /* Disassociate this scroll bar from its window. */
4838 XWINDOW (bar->window)->vertical_scroll_bar = Qnil;
4840 UNBLOCK_INPUT;
4844 /* Set the handle of the vertical scroll bar for WINDOW to indicate
4845 that we are displaying PORTION characters out of a total of WHOLE
4846 characters, starting at POSITION. If WINDOW has no scroll bar,
4847 create one. */
4849 static void
4850 XTset_vertical_scroll_bar (w, portion, whole, position)
4851 struct window *w;
4852 int portion, whole, position;
4854 struct frame *f = XFRAME (w->frame);
4855 struct scroll_bar *bar;
4856 int top, height, left, sb_left, width, sb_width, disp_top, disp_height;
4857 int window_y, window_height;
4859 /* Get window dimensions. */
4860 window_box (w, -1, 0, &window_y, 0, &window_height);
4861 top = window_y;
4862 width = WINDOW_CONFIG_SCROLL_BAR_COLS (w) * FRAME_COLUMN_WIDTH (f);
4863 height = window_height;
4865 /* Compute the left edge of the scroll bar area. */
4866 left = WINDOW_SCROLL_BAR_AREA_X (w);
4868 /* Compute the width of the scroll bar which might be less than
4869 the width of the area reserved for the scroll bar. */
4870 if (WINDOW_CONFIG_SCROLL_BAR_WIDTH (w) > 0)
4871 sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
4872 else
4873 sb_width = width;
4875 /* Compute the left edge of the scroll bar. */
4876 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
4877 sb_left = left;
4878 else
4879 sb_left = left + width - sb_width;
4881 /* Adjustments according to Inside Macintosh to make it look nice */
4882 disp_top = top;
4883 disp_height = height;
4884 #ifdef MAC_OS8
4885 if (disp_top == 0)
4887 disp_top = -1;
4888 disp_height++;
4890 else if (disp_top == FRAME_PIXEL_HEIGHT (f) - 16)
4892 disp_top++;
4893 disp_height--;
4896 if (sb_left + sb_width == FRAME_PIXEL_WIDTH (f))
4897 sb_left++;
4898 #endif
4900 /* Does the scroll bar exist yet? */
4901 if (NILP (w->vertical_scroll_bar))
4903 BLOCK_INPUT;
4904 mac_clear_area (f, left, top, width, height);
4905 UNBLOCK_INPUT;
4906 bar = x_scroll_bar_create (w, top, sb_left, sb_width, height, disp_top,
4907 disp_height);
4908 XSETVECTOR (w->vertical_scroll_bar, bar);
4910 else
4912 /* It may just need to be moved and resized. */
4913 ControlHandle ch;
4915 bar = XSCROLL_BAR (w->vertical_scroll_bar);
4916 ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4918 BLOCK_INPUT;
4920 /* If already correctly positioned, do nothing. */
4921 if (!(XINT (bar->left) == sb_left
4922 && XINT (bar->top) == top
4923 && XINT (bar->width) == sb_width
4924 && XINT (bar->height) == height))
4926 /* Since toolkit scroll bars are smaller than the space reserved
4927 for them on the frame, we have to clear "under" them. */
4928 mac_clear_area (f, left, top, width, height);
4930 #if USE_CG_DRAWING
4931 mac_prepare_for_quickdraw (f);
4932 #endif
4933 HideControl (ch);
4934 MoveControl (ch, sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM, disp_top);
4935 SizeControl (ch, sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
4936 disp_height);
4937 #ifndef USE_TOOLKIT_SCROLL_BARS
4938 if (sb_width < disp_height)
4939 ShowControl (ch);
4940 #endif
4942 /* Remember new settings. */
4943 XSETINT (bar->left, sb_left);
4944 XSETINT (bar->top, top);
4945 XSETINT (bar->width, sb_width);
4946 XSETINT (bar->height, height);
4947 #ifdef USE_TOOLKIT_SCROLL_BARS
4948 bar->track_top = Qnil;
4949 bar->track_height = Qnil;
4950 #endif
4953 UNBLOCK_INPUT;
4956 #ifdef USE_TOOLKIT_SCROLL_BARS
4957 if (NILP (bar->track_top))
4959 if (sb_width >= disp_height)
4961 XSETINT (bar->track_top, 0);
4962 XSETINT (bar->track_height, 0);
4964 else
4966 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4967 Rect r0, r1;
4969 BLOCK_INPUT;
4971 SetControl32BitMinimum (ch, 0);
4972 SetControl32BitMaximum (ch, 1);
4973 SetControlViewSize (ch, 1);
4975 /* Move the scroll bar thumb to the top. */
4976 SetControl32BitValue (ch, 0);
4977 get_control_part_bounds (ch, kControlIndicatorPart, &r0);
4979 /* Move the scroll bar thumb to the bottom. */
4980 SetControl32BitValue (ch, 1);
4981 get_control_part_bounds (ch, kControlIndicatorPart, &r1);
4983 UnionRect (&r0, &r1, &r0);
4984 XSETINT (bar->track_top, r0.top);
4985 XSETINT (bar->track_height, r0.bottom - r0.top);
4987 /* Don't show the scroll bar if its height is not enough to
4988 display the scroll bar thumb. */
4989 if (r0.bottom - r0.top > 0)
4990 ShowControl (ch);
4992 UNBLOCK_INPUT;
4996 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
4997 #else /* not USE_TOOLKIT_SCROLL_BARS */
4998 /* Set the scroll bar's current state, unless we're currently being
4999 dragged. */
5000 if (NILP (bar->dragging))
5002 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, height);
5004 if (whole == 0)
5005 x_scroll_bar_set_handle (bar, 0, top_range, 0);
5006 else
5008 int start = ((double) position * top_range) / whole;
5009 int end = ((double) (position + portion) * top_range) / whole;
5010 x_scroll_bar_set_handle (bar, start, end, 0);
5013 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5017 /* The following three hooks are used when we're doing a thorough
5018 redisplay of the frame. We don't explicitly know which scroll bars
5019 are going to be deleted, because keeping track of when windows go
5020 away is a real pain - "Can you say set-window-configuration, boys
5021 and girls?" Instead, we just assert at the beginning of redisplay
5022 that *all* scroll bars are to be removed, and then save a scroll bar
5023 from the fiery pit when we actually redisplay its window. */
5025 /* Arrange for all scroll bars on FRAME to be removed at the next call
5026 to `*judge_scroll_bars_hook'. A scroll bar may be spared if
5027 `*redeem_scroll_bar_hook' is applied to its window before the judgment. */
5029 static void
5030 XTcondemn_scroll_bars (frame)
5031 FRAME_PTR frame;
5033 /* Transfer all the scroll bars to FRAME_CONDEMNED_SCROLL_BARS. */
5034 while (! NILP (FRAME_SCROLL_BARS (frame)))
5036 Lisp_Object bar;
5037 bar = FRAME_SCROLL_BARS (frame);
5038 FRAME_SCROLL_BARS (frame) = XSCROLL_BAR (bar)->next;
5039 XSCROLL_BAR (bar)->next = FRAME_CONDEMNED_SCROLL_BARS (frame);
5040 XSCROLL_BAR (bar)->prev = Qnil;
5041 if (! NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
5042 XSCROLL_BAR (FRAME_CONDEMNED_SCROLL_BARS (frame))->prev = bar;
5043 FRAME_CONDEMNED_SCROLL_BARS (frame) = bar;
5048 /* Un-mark WINDOW's scroll bar for deletion in this judgment cycle.
5049 Note that WINDOW isn't necessarily condemned at all. */
5051 static void
5052 XTredeem_scroll_bar (window)
5053 struct window *window;
5055 struct scroll_bar *bar;
5056 struct frame *f;
5058 /* We can't redeem this window's scroll bar if it doesn't have one. */
5059 if (NILP (window->vertical_scroll_bar))
5060 abort ();
5062 bar = XSCROLL_BAR (window->vertical_scroll_bar);
5064 /* Unlink it from the condemned list. */
5065 f = XFRAME (WINDOW_FRAME (window));
5066 if (NILP (bar->prev))
5068 /* If the prev pointer is nil, it must be the first in one of
5069 the lists. */
5070 if (EQ (FRAME_SCROLL_BARS (f), window->vertical_scroll_bar))
5071 /* It's not condemned. Everything's fine. */
5072 return;
5073 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
5074 window->vertical_scroll_bar))
5075 FRAME_CONDEMNED_SCROLL_BARS (f) = bar->next;
5076 else
5077 /* If its prev pointer is nil, it must be at the front of
5078 one or the other! */
5079 abort ();
5081 else
5082 XSCROLL_BAR (bar->prev)->next = bar->next;
5084 if (! NILP (bar->next))
5085 XSCROLL_BAR (bar->next)->prev = bar->prev;
5087 bar->next = FRAME_SCROLL_BARS (f);
5088 bar->prev = Qnil;
5089 XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
5090 if (! NILP (bar->next))
5091 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
5094 /* Remove all scroll bars on FRAME that haven't been saved since the
5095 last call to `*condemn_scroll_bars_hook'. */
5097 static void
5098 XTjudge_scroll_bars (f)
5099 FRAME_PTR f;
5101 Lisp_Object bar, next;
5103 bar = FRAME_CONDEMNED_SCROLL_BARS (f);
5105 /* Clear out the condemned list now so we won't try to process any
5106 more events on the hapless scroll bars. */
5107 FRAME_CONDEMNED_SCROLL_BARS (f) = Qnil;
5109 for (; ! NILP (bar); bar = next)
5111 struct scroll_bar *b = XSCROLL_BAR (bar);
5113 x_scroll_bar_remove (b);
5115 next = b->next;
5116 b->next = b->prev = Qnil;
5119 /* Now there should be no references to the condemned scroll bars,
5120 and they should get garbage-collected. */
5124 /* Handle a mouse click on the scroll bar BAR. If *EMACS_EVENT's kind
5125 is set to something other than NO_EVENT, it is enqueued.
5127 This may be called from a signal handler, so we have to ignore GC
5128 mark bits. */
5130 static void
5131 x_scroll_bar_handle_click (bar, part_code, er, bufp)
5132 struct scroll_bar *bar;
5133 ControlPartCode part_code;
5134 EventRecord *er;
5135 struct input_event *bufp;
5137 int win_y, top_range;
5139 if (! GC_WINDOWP (bar->window))
5140 abort ();
5142 bufp->kind = SCROLL_BAR_CLICK_EVENT;
5143 bufp->frame_or_window = bar->window;
5144 bufp->arg = Qnil;
5146 bar->dragging = Qnil;
5148 switch (part_code)
5150 case kControlUpButtonPart:
5151 bufp->part = scroll_bar_up_arrow;
5152 break;
5153 case kControlDownButtonPart:
5154 bufp->part = scroll_bar_down_arrow;
5155 break;
5156 case kControlPageUpPart:
5157 bufp->part = scroll_bar_above_handle;
5158 break;
5159 case kControlPageDownPart:
5160 bufp->part = scroll_bar_below_handle;
5161 break;
5162 #if TARGET_API_MAC_CARBON
5163 default:
5164 #else
5165 case kControlIndicatorPart:
5166 #endif
5167 if (er->what == mouseDown)
5168 bar->dragging = make_number (0);
5169 XSETVECTOR (last_mouse_scroll_bar, bar);
5170 bufp->part = scroll_bar_handle;
5171 break;
5174 win_y = XINT (bufp->y) - XINT (bar->top);
5175 top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (0/*dummy*/, XINT (bar->height));
5177 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
5179 win_y -= 24;
5181 if (! NILP (bar->dragging))
5182 win_y -= XINT (bar->dragging);
5184 if (win_y < 0)
5185 win_y = 0;
5186 if (win_y > top_range)
5187 win_y = top_range;
5189 XSETINT (bufp->x, win_y);
5190 XSETINT (bufp->y, top_range);
5193 #ifndef USE_TOOLKIT_SCROLL_BARS
5195 /* Handle some mouse motion while someone is dragging the scroll bar.
5197 This may be called from a signal handler, so we have to ignore GC
5198 mark bits. */
5200 static void
5201 x_scroll_bar_note_movement (bar, y_pos, t)
5202 struct scroll_bar *bar;
5203 int y_pos;
5204 Time t;
5206 FRAME_PTR f = XFRAME (XWINDOW (bar->window)->frame);
5208 last_mouse_movement_time = t;
5210 f->mouse_moved = 1;
5211 XSETVECTOR (last_mouse_scroll_bar, bar);
5213 /* If we're dragging the bar, display it. */
5214 if (! GC_NILP (bar->dragging))
5216 /* Where should the handle be now? */
5217 int new_start = y_pos - 24;
5219 if (new_start != XINT (bar->start))
5221 int new_end = new_start + (XINT (bar->end) - XINT (bar->start));
5223 x_scroll_bar_set_handle (bar, new_start, new_end, 0);
5228 #endif /* !USE_TOOLKIT_SCROLL_BARS */
5230 /* Return information to the user about the current position of the mouse
5231 on the scroll bar. */
5233 static void
5234 x_scroll_bar_report_motion (fp, bar_window, part, x, y, time)
5235 FRAME_PTR *fp;
5236 Lisp_Object *bar_window;
5237 enum scroll_bar_part *part;
5238 Lisp_Object *x, *y;
5239 unsigned long *time;
5241 struct scroll_bar *bar = XSCROLL_BAR (last_mouse_scroll_bar);
5242 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
5243 #if TARGET_API_MAC_CARBON
5244 WindowPtr wp = GetControlOwner (ch);
5245 #else
5246 WindowPtr wp = (*ch)->contrlOwner;
5247 #endif
5248 Point mouse_pos;
5249 struct frame *f = mac_window_to_frame (wp);
5250 int win_y, top_range;
5252 SetPortWindowPort (wp);
5254 GetMouse (&mouse_pos);
5256 win_y = mouse_pos.v - XINT (bar->top);
5257 top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, XINT (bar->height));
5259 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
5261 win_y -= 24;
5263 if (! NILP (bar->dragging))
5264 win_y -= XINT (bar->dragging);
5266 if (win_y < 0)
5267 win_y = 0;
5268 if (win_y > top_range)
5269 win_y = top_range;
5271 *fp = f;
5272 *bar_window = bar->window;
5274 if (! NILP (bar->dragging))
5275 *part = scroll_bar_handle;
5276 else if (win_y < XINT (bar->start))
5277 *part = scroll_bar_above_handle;
5278 else if (win_y < XINT (bar->end) + VERTICAL_SCROLL_BAR_MIN_HANDLE)
5279 *part = scroll_bar_handle;
5280 else
5281 *part = scroll_bar_below_handle;
5283 XSETINT (*x, win_y);
5284 XSETINT (*y, top_range);
5286 f->mouse_moved = 0;
5287 last_mouse_scroll_bar = Qnil;
5289 *time = last_mouse_movement_time;
5293 /* The screen has been cleared so we may have changed foreground or
5294 background colors, and the scroll bars may need to be redrawn.
5295 Clear out the scroll bars, and ask for expose events, so we can
5296 redraw them. */
5298 void
5299 x_scroll_bar_clear (f)
5300 FRAME_PTR f;
5302 XTcondemn_scroll_bars (f);
5303 XTjudge_scroll_bars (f);
5307 /***********************************************************************
5308 Text Cursor
5309 ***********************************************************************/
5311 /* Set clipping for output in glyph row ROW. W is the window in which
5312 we operate. GC is the graphics context to set clipping in.
5314 ROW may be a text row or, e.g., a mode line. Text rows must be
5315 clipped to the interior of the window dedicated to text display,
5316 mode lines must be clipped to the whole window. */
5318 static void
5319 x_clip_to_row (w, row, area, gc)
5320 struct window *w;
5321 struct glyph_row *row;
5322 int area;
5323 GC gc;
5325 struct frame *f = XFRAME (WINDOW_FRAME (w));
5326 Rect clip_rect;
5327 int window_x, window_y, window_width;
5329 window_box (w, area, &window_x, &window_y, &window_width, 0);
5331 clip_rect.left = window_x;
5332 clip_rect.top = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
5333 clip_rect.top = max (clip_rect.top, window_y);
5334 clip_rect.right = clip_rect.left + window_width;
5335 clip_rect.bottom = clip_rect.top + row->visible_height;
5337 mac_set_clip_rectangles (FRAME_MAC_DISPLAY (f), gc, &clip_rect, 1);
5341 /* Draw a hollow box cursor on window W in glyph row ROW. */
5343 static void
5344 x_draw_hollow_cursor (w, row)
5345 struct window *w;
5346 struct glyph_row *row;
5348 struct frame *f = XFRAME (WINDOW_FRAME (w));
5349 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
5350 Display *dpy = FRAME_MAC_DISPLAY (f);
5351 int x, y, wd, h;
5352 XGCValues xgcv;
5353 struct glyph *cursor_glyph;
5354 GC gc;
5356 /* Get the glyph the cursor is on. If we can't tell because
5357 the current matrix is invalid or such, give up. */
5358 cursor_glyph = get_phys_cursor_glyph (w);
5359 if (cursor_glyph == NULL)
5360 return;
5362 /* Compute frame-relative coordinates for phys cursor. */
5363 x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
5364 y = get_phys_cursor_geometry (w, row, cursor_glyph, &h);
5365 wd = w->phys_cursor_width;
5367 /* The foreground of cursor_gc is typically the same as the normal
5368 background color, which can cause the cursor box to be invisible. */
5369 xgcv.foreground = f->output_data.mac->cursor_pixel;
5370 if (dpyinfo->scratch_cursor_gc)
5371 XChangeGC (dpy, dpyinfo->scratch_cursor_gc, GCForeground, &xgcv);
5372 else
5373 dpyinfo->scratch_cursor_gc = XCreateGC (dpy, FRAME_MAC_WINDOW (f),
5374 GCForeground, &xgcv);
5375 gc = dpyinfo->scratch_cursor_gc;
5377 /* Set clipping, draw the rectangle, and reset clipping again. */
5378 x_clip_to_row (w, row, TEXT_AREA, gc);
5379 mac_draw_rectangle (f, gc, x, y, wd, h - 1);
5380 mac_reset_clip_rectangles (dpy, gc);
5384 /* Draw a bar cursor on window W in glyph row ROW.
5386 Implementation note: One would like to draw a bar cursor with an
5387 angle equal to the one given by the font property XA_ITALIC_ANGLE.
5388 Unfortunately, I didn't find a font yet that has this property set.
5389 --gerd. */
5391 static void
5392 x_draw_bar_cursor (w, row, width, kind)
5393 struct window *w;
5394 struct glyph_row *row;
5395 int width;
5396 enum text_cursor_kinds kind;
5398 struct frame *f = XFRAME (w->frame);
5399 struct glyph *cursor_glyph;
5401 /* If cursor is out of bounds, don't draw garbage. This can happen
5402 in mini-buffer windows when switching between echo area glyphs
5403 and mini-buffer. */
5404 cursor_glyph = get_phys_cursor_glyph (w);
5405 if (cursor_glyph == NULL)
5406 return;
5408 /* If on an image, draw like a normal cursor. That's usually better
5409 visible than drawing a bar, esp. if the image is large so that
5410 the bar might not be in the window. */
5411 if (cursor_glyph->type == IMAGE_GLYPH)
5413 struct glyph_row *row;
5414 row = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos);
5415 draw_phys_cursor_glyph (w, row, DRAW_CURSOR);
5417 else
5419 Display *dpy = FRAME_MAC_DISPLAY (f);
5420 Window window = FRAME_MAC_WINDOW (f);
5421 GC gc = FRAME_MAC_DISPLAY_INFO (f)->scratch_cursor_gc;
5422 unsigned long mask = GCForeground | GCBackground;
5423 struct face *face = FACE_FROM_ID (f, cursor_glyph->face_id);
5424 XGCValues xgcv;
5426 /* If the glyph's background equals the color we normally draw
5427 the bar cursor in, the bar cursor in its normal color is
5428 invisible. Use the glyph's foreground color instead in this
5429 case, on the assumption that the glyph's colors are chosen so
5430 that the glyph is legible. */
5431 if (face->background == f->output_data.mac->cursor_pixel)
5432 xgcv.background = xgcv.foreground = face->foreground;
5433 else
5434 xgcv.background = xgcv.foreground = f->output_data.mac->cursor_pixel;
5436 if (gc)
5437 XChangeGC (dpy, gc, mask, &xgcv);
5438 else
5440 gc = XCreateGC (dpy, window, mask, &xgcv);
5441 FRAME_MAC_DISPLAY_INFO (f)->scratch_cursor_gc = gc;
5444 if (width < 0)
5445 width = FRAME_CURSOR_WIDTH (f);
5446 width = min (cursor_glyph->pixel_width, width);
5448 w->phys_cursor_width = width;
5449 x_clip_to_row (w, row, TEXT_AREA, gc);
5451 if (kind == BAR_CURSOR)
5452 mac_fill_rectangle (f, gc,
5453 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x),
5454 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
5455 width, row->height);
5456 else
5457 mac_fill_rectangle (f, gc,
5458 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x),
5459 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y +
5460 row->height - width),
5461 cursor_glyph->pixel_width,
5462 width);
5464 mac_reset_clip_rectangles (dpy, gc);
5469 /* RIF: Define cursor CURSOR on frame F. */
5471 static void
5472 mac_define_frame_cursor (f, cursor)
5473 struct frame *f;
5474 Cursor cursor;
5476 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
5478 if (dpyinfo->x_focus_frame == f)
5479 SetThemeCursor (cursor);
5483 /* RIF: Clear area on frame F. */
5485 static void
5486 mac_clear_frame_area (f, x, y, width, height)
5487 struct frame *f;
5488 int x, y, width, height;
5490 mac_clear_area (f, x, y, width, height);
5494 /* RIF: Draw cursor on window W. */
5496 static void
5497 mac_draw_window_cursor (w, glyph_row, x, y, cursor_type, cursor_width, on_p, active_p)
5498 struct window *w;
5499 struct glyph_row *glyph_row;
5500 int x, y;
5501 int cursor_type, cursor_width;
5502 int on_p, active_p;
5504 if (on_p)
5506 w->phys_cursor_type = cursor_type;
5507 w->phys_cursor_on_p = 1;
5509 if (glyph_row->exact_window_width_line_p
5510 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
5512 glyph_row->cursor_in_fringe_p = 1;
5513 draw_fringe_bitmap (w, glyph_row, 0);
5515 else
5516 switch (cursor_type)
5518 case HOLLOW_BOX_CURSOR:
5519 x_draw_hollow_cursor (w, glyph_row);
5520 break;
5522 case FILLED_BOX_CURSOR:
5523 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
5524 break;
5526 case BAR_CURSOR:
5527 x_draw_bar_cursor (w, glyph_row, cursor_width, BAR_CURSOR);
5528 break;
5530 case HBAR_CURSOR:
5531 x_draw_bar_cursor (w, glyph_row, cursor_width, HBAR_CURSOR);
5532 break;
5534 case NO_CURSOR:
5535 w->phys_cursor_width = 0;
5536 break;
5538 default:
5539 abort ();
5545 /* Icons. */
5547 #if 0 /* MAC_TODO: no icon support yet. */
5549 x_bitmap_icon (f, icon)
5550 struct frame *f;
5551 Lisp_Object icon;
5553 HANDLE hicon;
5555 if (FRAME_W32_WINDOW (f) == 0)
5556 return 1;
5558 if (NILP (icon))
5559 hicon = LoadIcon (hinst, EMACS_CLASS);
5560 else if (STRINGP (icon))
5561 hicon = LoadImage (NULL, (LPCTSTR) SDATA (icon), IMAGE_ICON, 0, 0,
5562 LR_DEFAULTSIZE | LR_LOADFROMFILE);
5563 else if (SYMBOLP (icon))
5565 LPCTSTR name;
5567 if (EQ (icon, intern ("application")))
5568 name = (LPCTSTR) IDI_APPLICATION;
5569 else if (EQ (icon, intern ("hand")))
5570 name = (LPCTSTR) IDI_HAND;
5571 else if (EQ (icon, intern ("question")))
5572 name = (LPCTSTR) IDI_QUESTION;
5573 else if (EQ (icon, intern ("exclamation")))
5574 name = (LPCTSTR) IDI_EXCLAMATION;
5575 else if (EQ (icon, intern ("asterisk")))
5576 name = (LPCTSTR) IDI_ASTERISK;
5577 else if (EQ (icon, intern ("winlogo")))
5578 name = (LPCTSTR) IDI_WINLOGO;
5579 else
5580 return 1;
5582 hicon = LoadIcon (NULL, name);
5584 else
5585 return 1;
5587 if (hicon == NULL)
5588 return 1;
5590 PostMessage (FRAME_W32_WINDOW (f), WM_SETICON, (WPARAM) ICON_BIG,
5591 (LPARAM) hicon);
5593 return 0;
5595 #endif /* MAC_TODO */
5597 /************************************************************************
5598 Handling X errors
5599 ************************************************************************/
5601 /* Display Error Handling functions not used on W32. Listing them here
5602 helps diff stay in step when comparing w32term.c with xterm.c.
5604 x_error_catcher (display, error)
5605 x_catch_errors (dpy)
5606 x_catch_errors_unwind (old_val)
5607 x_check_errors (dpy, format)
5608 x_had_errors_p (dpy)
5609 x_clear_errors (dpy)
5610 x_uncatch_errors (dpy, count)
5611 x_trace_wire ()
5612 x_connection_signal (signalnum)
5613 x_connection_closed (dpy, error_message)
5614 x_error_quitter (display, error)
5615 x_error_handler (display, error)
5616 x_io_error_quitter (display)
5621 /* Changing the font of the frame. */
5623 /* Give frame F the font named FONTNAME as its default font, and
5624 return the full name of that font. FONTNAME may be a wildcard
5625 pattern; in that case, we choose some font that fits the pattern.
5626 The return value shows which font we chose. */
5628 Lisp_Object
5629 x_new_font (f, fontname)
5630 struct frame *f;
5631 register char *fontname;
5633 struct font_info *fontp
5634 = FS_LOAD_FONT (f, 0, fontname, -1);
5636 if (!fontp)
5637 return Qnil;
5639 FRAME_FONT (f) = (XFontStruct *) (fontp->font);
5640 FRAME_BASELINE_OFFSET (f) = fontp->baseline_offset;
5641 FRAME_FONTSET (f) = -1;
5643 FRAME_COLUMN_WIDTH (f) = fontp->average_width;
5644 FRAME_SPACE_WIDTH (f) = fontp->space_width;
5645 FRAME_LINE_HEIGHT (f) = FONT_HEIGHT (FRAME_FONT (f));
5647 compute_fringe_widths (f, 1);
5649 /* Compute the scroll bar width in character columns. */
5650 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
5652 int wid = FRAME_COLUMN_WIDTH (f);
5653 FRAME_CONFIG_SCROLL_BAR_COLS (f)
5654 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid-1) / wid;
5656 else
5658 int wid = FRAME_COLUMN_WIDTH (f);
5659 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
5662 /* Now make the frame display the given font. */
5663 if (FRAME_MAC_WINDOW (f) != 0)
5665 XSetFont (FRAME_MAC_DISPLAY (f), f->output_data.mac->normal_gc,
5666 FRAME_FONT (f));
5667 XSetFont (FRAME_MAC_DISPLAY (f), f->output_data.mac->reverse_gc,
5668 FRAME_FONT (f));
5669 XSetFont (FRAME_MAC_DISPLAY (f), f->output_data.mac->cursor_gc,
5670 FRAME_FONT (f));
5672 /* Don't change the size of a tip frame; there's no point in
5673 doing it because it's done in Fx_show_tip, and it leads to
5674 problems because the tip frame has no widget. */
5675 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
5676 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
5679 return build_string (fontp->full_name);
5682 /* Give frame F the fontset named FONTSETNAME as its default font, and
5683 return the full name of that fontset. FONTSETNAME may be a wildcard
5684 pattern; in that case, we choose some fontset that fits the pattern.
5685 The return value shows which fontset we chose. */
5687 Lisp_Object
5688 x_new_fontset (f, fontsetname)
5689 struct frame *f;
5690 char *fontsetname;
5692 int fontset = fs_query_fontset (build_string (fontsetname), 0);
5693 Lisp_Object result;
5695 if (fontset < 0)
5696 return Qnil;
5698 if (FRAME_FONTSET (f) == fontset)
5699 /* This fontset is already set in frame F. There's nothing more
5700 to do. */
5701 return fontset_name (fontset);
5703 result = x_new_font (f, (SDATA (fontset_ascii (fontset))));
5705 if (!STRINGP (result))
5706 /* Can't load ASCII font. */
5707 return Qnil;
5709 /* Since x_new_font doesn't update any fontset information, do it now. */
5710 FRAME_FONTSET (f) = fontset;
5712 return build_string (fontsetname);
5716 /***********************************************************************
5717 TODO: W32 Input Methods
5718 ***********************************************************************/
5719 /* Listing missing functions from xterm.c helps diff stay in step.
5721 xim_destroy_callback (xim, client_data, call_data)
5722 xim_open_dpy (dpyinfo, resource_name)
5723 struct xim_inst_t
5724 xim_instantiate_callback (display, client_data, call_data)
5725 xim_initialize (dpyinfo, resource_name)
5726 xim_close_dpy (dpyinfo)
5731 void
5732 mac_get_window_bounds (f, inner, outer)
5733 struct frame *f;
5734 Rect *inner, *outer;
5736 #if TARGET_API_MAC_CARBON
5737 GetWindowBounds (FRAME_MAC_WINDOW (f), kWindowContentRgn, inner);
5738 GetWindowBounds (FRAME_MAC_WINDOW (f), kWindowStructureRgn, outer);
5739 #else /* not TARGET_API_MAC_CARBON */
5740 RgnHandle region = NewRgn ();
5742 GetWindowRegion (FRAME_MAC_WINDOW (f), kWindowContentRgn, region);
5743 *inner = (*region)->rgnBBox;
5744 GetWindowRegion (FRAME_MAC_WINDOW (f), kWindowStructureRgn, region);
5745 *outer = (*region)->rgnBBox;
5746 DisposeRgn (region);
5747 #endif /* not TARGET_API_MAC_CARBON */
5752 /* Calculate the absolute position in frame F
5753 from its current recorded position values and gravity. */
5755 void
5756 x_calc_absolute_position (f)
5757 struct frame *f;
5759 int width_diff = 0, height_diff = 0;
5760 int flags = f->size_hint_flags;
5761 Rect inner, outer;
5763 /* We have nothing to do if the current position
5764 is already for the top-left corner. */
5765 if (! ((flags & XNegative) || (flags & YNegative)))
5766 return;
5768 /* Find the offsets of the outside upper-left corner of
5769 the inner window, with respect to the outer window. */
5770 mac_get_window_bounds (f, &inner, &outer);
5772 width_diff = (outer.right - outer.left) - (inner.right - inner.left);
5773 height_diff = (outer.bottom - outer.top) - (inner.bottom - inner.top);
5775 /* Treat negative positions as relative to the leftmost bottommost
5776 position that fits on the screen. */
5777 if (flags & XNegative)
5778 f->left_pos = (FRAME_MAC_DISPLAY_INFO (f)->width
5779 - width_diff
5780 - FRAME_PIXEL_WIDTH (f)
5781 + f->left_pos);
5783 if (flags & YNegative)
5784 f->top_pos = (FRAME_MAC_DISPLAY_INFO (f)->height
5785 - height_diff
5786 - FRAME_PIXEL_HEIGHT (f)
5787 + f->top_pos);
5789 /* The left_pos and top_pos
5790 are now relative to the top and left screen edges,
5791 so the flags should correspond. */
5792 f->size_hint_flags &= ~ (XNegative | YNegative);
5795 /* CHANGE_GRAVITY is 1 when calling from Fset_frame_position,
5796 to really change the position, and 0 when calling from
5797 x_make_frame_visible (in that case, XOFF and YOFF are the current
5798 position values). It is -1 when calling from x_set_frame_parameters,
5799 which means, do adjust for borders but don't change the gravity. */
5801 void
5802 x_set_offset (f, xoff, yoff, change_gravity)
5803 struct frame *f;
5804 register int xoff, yoff;
5805 int change_gravity;
5807 if (change_gravity > 0)
5809 f->top_pos = yoff;
5810 f->left_pos = xoff;
5811 f->size_hint_flags &= ~ (XNegative | YNegative);
5812 if (xoff < 0)
5813 f->size_hint_flags |= XNegative;
5814 if (yoff < 0)
5815 f->size_hint_flags |= YNegative;
5816 f->win_gravity = NorthWestGravity;
5818 x_calc_absolute_position (f);
5820 BLOCK_INPUT;
5821 x_wm_set_size_hint (f, (long) 0, 0);
5823 #if TARGET_API_MAC_CARBON
5824 MoveWindowStructure (FRAME_MAC_WINDOW (f), f->left_pos, f->top_pos);
5825 /* If the title bar is completely outside the screen, adjust the
5826 position. */
5827 ConstrainWindowToScreen (FRAME_MAC_WINDOW (f), kWindowTitleBarRgn,
5828 kWindowConstrainMoveRegardlessOfFit
5829 | kWindowConstrainAllowPartial, NULL, NULL);
5830 x_real_positions (f, &f->left_pos, &f->top_pos);
5831 #else
5833 Rect inner, outer, screen_rect, dummy;
5834 RgnHandle region = NewRgn ();
5836 mac_get_window_bounds (f, &inner, &outer);
5837 f->x_pixels_diff = inner.left - outer.left;
5838 f->y_pixels_diff = inner.top - outer.top;
5839 MoveWindow (FRAME_MAC_WINDOW (f), f->left_pos + f->x_pixels_diff,
5840 f->top_pos + f->y_pixels_diff, false);
5842 /* If the title bar is completely outside the screen, adjust the
5843 position. The variable `outer' holds the title bar rectangle.
5844 The variable `inner' holds slightly smaller one than `outer',
5845 so that the calculation of overlapping may not become too
5846 strict. */
5847 GetWindowRegion (FRAME_MAC_WINDOW (f), kWindowTitleBarRgn, region);
5848 outer = (*region)->rgnBBox;
5849 DisposeRgn (region);
5850 inner = outer;
5851 InsetRect (&inner, 8, 8);
5852 screen_rect = qd.screenBits.bounds;
5853 screen_rect.top += GetMBarHeight ();
5855 if (!SectRect (&inner, &screen_rect, &dummy))
5857 if (inner.right <= screen_rect.left)
5858 f->left_pos = screen_rect.left;
5859 else if (inner.left >= screen_rect.right)
5860 f->left_pos = screen_rect.right - (outer.right - outer.left);
5862 if (inner.bottom <= screen_rect.top)
5863 f->top_pos = screen_rect.top;
5864 else if (inner.top >= screen_rect.bottom)
5865 f->top_pos = screen_rect.bottom - (outer.bottom - outer.top);
5867 MoveWindow (FRAME_MAC_WINDOW (f), f->left_pos + f->x_pixels_diff,
5868 f->top_pos + f->y_pixels_diff, false);
5871 #endif
5873 UNBLOCK_INPUT;
5876 /* Call this to change the size of frame F's x-window.
5877 If CHANGE_GRAVITY is 1, we change to top-left-corner window gravity
5878 for this size change and subsequent size changes.
5879 Otherwise we leave the window gravity unchanged. */
5881 void
5882 x_set_window_size (f, change_gravity, cols, rows)
5883 struct frame *f;
5884 int change_gravity;
5885 int cols, rows;
5887 int pixelwidth, pixelheight;
5889 BLOCK_INPUT;
5891 check_frame_size (f, &rows, &cols);
5892 f->scroll_bar_actual_width
5893 = FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f);
5895 compute_fringe_widths (f, 0);
5897 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols);
5898 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
5900 f->win_gravity = NorthWestGravity;
5901 x_wm_set_size_hint (f, (long) 0, 0);
5903 SizeWindow (FRAME_MAC_WINDOW (f), pixelwidth, pixelheight, 0);
5904 #if TARGET_API_MAC_CARBON
5905 if (f->output_data.mac->hourglass_control)
5907 #if USE_CG_DRAWING
5908 mac_prepare_for_quickdraw (f);
5909 #endif
5910 MoveControl (f->output_data.mac->hourglass_control,
5911 pixelwidth - HOURGLASS_WIDTH, 0);
5913 #endif
5915 /* Now, strictly speaking, we can't be sure that this is accurate,
5916 but the window manager will get around to dealing with the size
5917 change request eventually, and we'll hear how it went when the
5918 ConfigureNotify event gets here.
5920 We could just not bother storing any of this information here,
5921 and let the ConfigureNotify event set everything up, but that
5922 might be kind of confusing to the Lisp code, since size changes
5923 wouldn't be reported in the frame parameters until some random
5924 point in the future when the ConfigureNotify event arrives.
5926 We pass 1 for DELAY since we can't run Lisp code inside of
5927 a BLOCK_INPUT. */
5928 change_frame_size (f, rows, cols, 0, 1, 0);
5929 FRAME_PIXEL_WIDTH (f) = pixelwidth;
5930 FRAME_PIXEL_HEIGHT (f) = pixelheight;
5932 /* We've set {FRAME,PIXEL}_{WIDTH,HEIGHT} to the values we hope to
5933 receive in the ConfigureNotify event; if we get what we asked
5934 for, then the event won't cause the screen to become garbaged, so
5935 we have to make sure to do it here. */
5936 SET_FRAME_GARBAGED (f);
5938 XFlush (FRAME_X_DISPLAY (f));
5940 /* If cursor was outside the new size, mark it as off. */
5941 mark_window_cursors_off (XWINDOW (f->root_window));
5943 /* Clear out any recollection of where the mouse highlighting was,
5944 since it might be in a place that's outside the new frame size.
5945 Actually checking whether it is outside is a pain in the neck,
5946 so don't try--just let the highlighting be done afresh with new size. */
5947 cancel_mouse_face (f);
5949 UNBLOCK_INPUT;
5952 /* Mouse warping. */
5954 void x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y);
5956 void
5957 x_set_mouse_position (f, x, y)
5958 struct frame *f;
5959 int x, y;
5961 int pix_x, pix_y;
5963 pix_x = FRAME_COL_TO_PIXEL_X (f, x) + FRAME_COLUMN_WIDTH (f) / 2;
5964 pix_y = FRAME_LINE_TO_PIXEL_Y (f, y) + FRAME_LINE_HEIGHT (f) / 2;
5966 if (pix_x < 0) pix_x = 0;
5967 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
5969 if (pix_y < 0) pix_y = 0;
5970 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
5972 x_set_mouse_pixel_position (f, pix_x, pix_y);
5975 void
5976 x_set_mouse_pixel_position (f, pix_x, pix_y)
5977 struct frame *f;
5978 int pix_x, pix_y;
5980 #if 0 /* MAC_TODO: CursorDeviceMoveTo is non-Carbon */
5981 BLOCK_INPUT;
5983 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
5984 0, 0, 0, 0, pix_x, pix_y);
5985 UNBLOCK_INPUT;
5986 #endif
5989 /* focus shifting, raising and lowering. */
5991 void
5992 x_focus_on_frame (f)
5993 struct frame *f;
5995 #if 0 /* This proves to be unpleasant. */
5996 x_raise_frame (f);
5997 #endif
5998 #if 0
5999 /* I don't think that the ICCCM allows programs to do things like this
6000 without the interaction of the window manager. Whatever you end up
6001 doing with this code, do it to x_unfocus_frame too. */
6002 XSetInputFocus (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
6003 RevertToPointerRoot, CurrentTime);
6004 #endif /* ! 0 */
6007 void
6008 x_unfocus_frame (f)
6009 struct frame *f;
6013 /* Raise frame F. */
6015 void
6016 x_raise_frame (f)
6017 struct frame *f;
6019 if (f->async_visible)
6021 BLOCK_INPUT;
6022 BringToFront (FRAME_MAC_WINDOW (f));
6023 UNBLOCK_INPUT;
6027 /* Lower frame F. */
6029 void
6030 x_lower_frame (f)
6031 struct frame *f;
6033 if (f->async_visible)
6035 BLOCK_INPUT;
6036 SendBehind (FRAME_MAC_WINDOW (f), NULL);
6037 UNBLOCK_INPUT;
6041 static void
6042 XTframe_raise_lower (f, raise_flag)
6043 FRAME_PTR f;
6044 int raise_flag;
6046 if (raise_flag)
6047 x_raise_frame (f);
6048 else
6049 x_lower_frame (f);
6052 /* Change of visibility. */
6054 static void
6055 mac_handle_visibility_change (f)
6056 struct frame *f;
6058 WindowPtr wp = FRAME_MAC_WINDOW (f);
6059 int visible = 0, iconified = 0;
6060 struct input_event buf;
6062 if (IsWindowVisible (wp))
6064 if (IsWindowCollapsed (wp))
6065 iconified = 1;
6066 else
6067 visible = 1;
6070 if (!f->async_visible && visible)
6072 if (f->iconified)
6074 /* wait_reading_process_output will notice this and update
6075 the frame's display structures. If we were made
6076 invisible, we should not set garbaged, because that stops
6077 redrawing on Update events. */
6078 SET_FRAME_GARBAGED (f);
6080 EVENT_INIT (buf);
6081 buf.kind = DEICONIFY_EVENT;
6082 XSETFRAME (buf.frame_or_window, f);
6083 kbd_buffer_store_event (&buf);
6085 else if (! NILP (Vframe_list) && ! NILP (XCDR (Vframe_list)))
6086 /* Force a redisplay sooner or later to update the
6087 frame titles in case this is the second frame. */
6088 record_asynch_buffer_change ();
6090 else if (f->async_visible && !visible)
6091 if (iconified)
6093 EVENT_INIT (buf);
6094 buf.kind = ICONIFY_EVENT;
6095 XSETFRAME (buf.frame_or_window, f);
6096 kbd_buffer_store_event (&buf);
6099 f->async_visible = visible;
6100 f->async_iconified = iconified;
6103 /* This tries to wait until the frame is really visible.
6104 However, if the window manager asks the user where to position
6105 the frame, this will return before the user finishes doing that.
6106 The frame will not actually be visible at that time,
6107 but it will become visible later when the window manager
6108 finishes with it. */
6110 void
6111 x_make_frame_visible (f)
6112 struct frame *f;
6114 BLOCK_INPUT;
6116 if (! FRAME_VISIBLE_P (f))
6118 /* We test FRAME_GARBAGED_P here to make sure we don't
6119 call x_set_offset a second time
6120 if we get to x_make_frame_visible a second time
6121 before the window gets really visible. */
6122 if (! FRAME_ICONIFIED_P (f)
6123 && ! f->output_data.mac->asked_for_visible)
6125 #if TARGET_API_MAC_CARBON
6126 if (!(FRAME_SIZE_HINTS (f)->flags & (USPosition | PPosition)))
6128 struct frame *sf = SELECTED_FRAME ();
6129 if (!FRAME_MAC_P (sf))
6130 RepositionWindow (FRAME_MAC_WINDOW (f), NULL,
6131 kWindowCenterOnMainScreen);
6132 else
6133 RepositionWindow (FRAME_MAC_WINDOW (f),
6134 FRAME_MAC_WINDOW (sf),
6135 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
6136 kWindowCascadeStartAtParentWindowScreen
6137 #else
6138 kWindowCascadeOnParentWindowScreen
6139 #endif
6141 x_real_positions (f, &f->left_pos, &f->top_pos);
6143 else
6144 #endif
6145 x_set_offset (f, f->left_pos, f->top_pos, 0);
6148 f->output_data.mac->asked_for_visible = 1;
6150 CollapseWindow (FRAME_MAC_WINDOW (f), false);
6151 ShowWindow (FRAME_MAC_WINDOW (f));
6154 XFlush (FRAME_MAC_DISPLAY (f));
6156 /* Synchronize to ensure Emacs knows the frame is visible
6157 before we do anything else. We do this loop with input not blocked
6158 so that incoming events are handled. */
6160 Lisp_Object frame;
6161 int count;
6163 /* This must come after we set COUNT. */
6164 UNBLOCK_INPUT;
6166 XSETFRAME (frame, f);
6168 /* Wait until the frame is visible. Process X events until a
6169 MapNotify event has been seen, or until we think we won't get a
6170 MapNotify at all.. */
6171 for (count = input_signal_count + 10;
6172 input_signal_count < count && !FRAME_VISIBLE_P (f);)
6174 /* Force processing of queued events. */
6175 x_sync (f);
6177 /* Machines that do polling rather than SIGIO have been
6178 observed to go into a busy-wait here. So we'll fake an
6179 alarm signal to let the handler know that there's something
6180 to be read. We used to raise a real alarm, but it seems
6181 that the handler isn't always enabled here. This is
6182 probably a bug. */
6183 if (input_polling_used ())
6185 /* It could be confusing if a real alarm arrives while
6186 processing the fake one. Turn it off and let the
6187 handler reset it. */
6188 extern void poll_for_input_1 P_ ((void));
6189 int old_poll_suppress_count = poll_suppress_count;
6190 poll_suppress_count = 1;
6191 poll_for_input_1 ();
6192 poll_suppress_count = old_poll_suppress_count;
6195 /* See if a MapNotify event has been processed. */
6196 FRAME_SAMPLE_VISIBILITY (f);
6201 /* Change from mapped state to withdrawn state. */
6203 /* Make the frame visible (mapped and not iconified). */
6205 void
6206 x_make_frame_invisible (f)
6207 struct frame *f;
6209 /* A deactivate event does not occur when the last visible frame is
6210 made invisible. So if we clear the highlight here, it will not
6211 be rehighlighted when it is made visible. */
6212 #if 0
6213 /* Don't keep the highlight on an invisible frame. */
6214 if (FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame == f)
6215 FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame = 0;
6216 #endif
6218 BLOCK_INPUT;
6220 /* Before unmapping the window, update the WM_SIZE_HINTS property to claim
6221 that the current position of the window is user-specified, rather than
6222 program-specified, so that when the window is mapped again, it will be
6223 placed at the same location, without forcing the user to position it
6224 by hand again (they have already done that once for this window.) */
6225 x_wm_set_size_hint (f, (long) 0, 1);
6227 HideWindow (FRAME_MAC_WINDOW (f));
6229 UNBLOCK_INPUT;
6231 #if !USE_CARBON_EVENTS
6232 mac_handle_visibility_change (f);
6233 #endif
6236 /* Change window state from mapped to iconified. */
6238 void
6239 x_iconify_frame (f)
6240 struct frame *f;
6242 OSErr err;
6244 /* A deactivate event does not occur when the last visible frame is
6245 iconified. So if we clear the highlight here, it will not be
6246 rehighlighted when it is deiconified. */
6247 #if 0
6248 /* Don't keep the highlight on an invisible frame. */
6249 if (FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame == f)
6250 FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame = 0;
6251 #endif
6253 if (f->async_iconified)
6254 return;
6256 BLOCK_INPUT;
6258 FRAME_SAMPLE_VISIBILITY (f);
6260 if (! FRAME_VISIBLE_P (f))
6261 ShowWindow (FRAME_MAC_WINDOW (f));
6263 err = CollapseWindow (FRAME_MAC_WINDOW (f), true);
6265 UNBLOCK_INPUT;
6267 if (err != noErr)
6268 error ("Can't notify window manager of iconification");
6270 #if !USE_CARBON_EVENTS
6271 mac_handle_visibility_change (f);
6272 #endif
6276 /* Free X resources of frame F. */
6278 void
6279 x_free_frame_resources (f)
6280 struct frame *f;
6282 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
6283 WindowPtr wp = FRAME_MAC_WINDOW (f);
6285 BLOCK_INPUT;
6287 if (wp != tip_window)
6288 remove_window_handler (wp);
6290 DisposeWindow (wp);
6291 if (wp == tip_window)
6292 /* Neither WaitNextEvent nor ReceiveNextEvent receives `window
6293 closed' event. So we reset tip_window here. */
6294 tip_window = NULL;
6296 free_frame_menubar (f);
6298 if (FRAME_FACE_CACHE (f))
6299 free_frame_faces (f);
6301 x_free_gcs (f);
6303 if (FRAME_SIZE_HINTS (f))
6304 xfree (FRAME_SIZE_HINTS (f));
6306 xfree (f->output_data.mac);
6307 f->output_data.mac = NULL;
6309 if (f == dpyinfo->x_focus_frame)
6310 dpyinfo->x_focus_frame = 0;
6311 if (f == dpyinfo->x_focus_event_frame)
6312 dpyinfo->x_focus_event_frame = 0;
6313 if (f == dpyinfo->x_highlight_frame)
6314 dpyinfo->x_highlight_frame = 0;
6316 if (f == dpyinfo->mouse_face_mouse_frame)
6318 dpyinfo->mouse_face_beg_row
6319 = dpyinfo->mouse_face_beg_col = -1;
6320 dpyinfo->mouse_face_end_row
6321 = dpyinfo->mouse_face_end_col = -1;
6322 dpyinfo->mouse_face_window = Qnil;
6323 dpyinfo->mouse_face_deferred_gc = 0;
6324 dpyinfo->mouse_face_mouse_frame = 0;
6327 UNBLOCK_INPUT;
6331 /* Destroy the X window of frame F. */
6333 void
6334 x_destroy_window (f)
6335 struct frame *f;
6337 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
6339 x_free_frame_resources (f);
6341 dpyinfo->reference_count--;
6345 /* Setting window manager hints. */
6347 /* Set the normal size hints for the window manager, for frame F.
6348 FLAGS is the flags word to use--or 0 meaning preserve the flags
6349 that the window now has.
6350 If USER_POSITION is nonzero, we set the USPosition
6351 flag (this is useful when FLAGS is 0). */
6352 void
6353 x_wm_set_size_hint (f, flags, user_position)
6354 struct frame *f;
6355 long flags;
6356 int user_position;
6358 int base_width, base_height, width_inc, height_inc;
6359 int min_rows = 0, min_cols = 0;
6360 XSizeHints *size_hints;
6362 base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
6363 base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
6364 width_inc = FRAME_COLUMN_WIDTH (f);
6365 height_inc = FRAME_LINE_HEIGHT (f);
6367 check_frame_size (f, &min_rows, &min_cols);
6369 size_hints = FRAME_SIZE_HINTS (f);
6370 if (size_hints == NULL)
6372 size_hints = FRAME_SIZE_HINTS (f) = xmalloc (sizeof (XSizeHints));
6373 bzero (size_hints, sizeof (XSizeHints));
6376 size_hints->flags |= PResizeInc | PMinSize | PBaseSize ;
6377 size_hints->width_inc = width_inc;
6378 size_hints->height_inc = height_inc;
6379 size_hints->min_width = base_width + min_cols * width_inc;
6380 size_hints->min_height = base_height + min_rows * height_inc;
6381 size_hints->base_width = base_width;
6382 size_hints->base_height = base_height;
6384 if (flags)
6385 size_hints->flags = flags;
6386 else if (user_position)
6388 size_hints->flags &= ~ PPosition;
6389 size_hints->flags |= USPosition;
6393 #if 0 /* MAC_TODO: hide application instead of iconify? */
6394 /* Used for IconicState or NormalState */
6396 void
6397 x_wm_set_window_state (f, state)
6398 struct frame *f;
6399 int state;
6401 #ifdef USE_X_TOOLKIT
6402 Arg al[1];
6404 XtSetArg (al[0], XtNinitialState, state);
6405 XtSetValues (f->output_data.x->widget, al, 1);
6406 #else /* not USE_X_TOOLKIT */
6407 Window window = FRAME_X_WINDOW (f);
6409 f->output_data.x->wm_hints.flags |= StateHint;
6410 f->output_data.x->wm_hints.initial_state = state;
6412 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
6413 #endif /* not USE_X_TOOLKIT */
6416 void
6417 x_wm_set_icon_pixmap (f, pixmap_id)
6418 struct frame *f;
6419 int pixmap_id;
6421 Pixmap icon_pixmap;
6423 #ifndef USE_X_TOOLKIT
6424 Window window = FRAME_X_WINDOW (f);
6425 #endif
6427 if (pixmap_id > 0)
6429 icon_pixmap = x_bitmap_pixmap (f, pixmap_id);
6430 f->output_data.x->wm_hints.icon_pixmap = icon_pixmap;
6432 else
6434 /* It seems there is no way to turn off use of an icon pixmap.
6435 The following line does it, only if no icon has yet been created,
6436 for some window managers. But with mwm it crashes.
6437 Some people say it should clear the IconPixmapHint bit in this case,
6438 but that doesn't work, and the X consortium said it isn't the
6439 right thing at all. Since there is no way to win,
6440 best to explicitly give up. */
6441 #if 0
6442 f->output_data.x->wm_hints.icon_pixmap = None;
6443 #else
6444 return;
6445 #endif
6448 #ifdef USE_X_TOOLKIT /* same as in x_wm_set_window_state. */
6451 Arg al[1];
6452 XtSetArg (al[0], XtNiconPixmap, icon_pixmap);
6453 XtSetValues (f->output_data.x->widget, al, 1);
6456 #else /* not USE_X_TOOLKIT */
6458 f->output_data.x->wm_hints.flags |= IconPixmapHint;
6459 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
6461 #endif /* not USE_X_TOOLKIT */
6464 #endif /* MAC_TODO */
6466 void
6467 x_wm_set_icon_position (f, icon_x, icon_y)
6468 struct frame *f;
6469 int icon_x, icon_y;
6471 #if 0 /* MAC_TODO: no icons on Mac */
6472 #ifdef USE_X_TOOLKIT
6473 Window window = XtWindow (f->output_data.x->widget);
6474 #else
6475 Window window = FRAME_X_WINDOW (f);
6476 #endif
6478 f->output_data.x->wm_hints.flags |= IconPositionHint;
6479 f->output_data.x->wm_hints.icon_x = icon_x;
6480 f->output_data.x->wm_hints.icon_y = icon_y;
6482 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
6483 #endif /* MAC_TODO */
6487 /***********************************************************************
6488 XLFD Pattern Match
6489 ***********************************************************************/
6491 /* An XLFD pattern is divided into blocks delimited by '*'. This
6492 structure holds information for each block. */
6493 struct xlfdpat_block
6495 /* Length of the pattern string in this block. Non-zero except for
6496 the first and the last blocks. */
6497 int len;
6499 /* Pattern string except the last character in this block. The last
6500 character is replaced with NUL in order to use it as a
6501 sentinel. */
6502 unsigned char *pattern;
6504 /* Last character of the pattern string. Must not be '?'. */
6505 unsigned char last_char;
6507 /* One of the tables for the Boyer-Moore string search. It
6508 specifies the number of positions to proceed for each character
6509 with which the match fails. */
6510 int skip[256];
6512 /* The skip value for the last character in the above `skip' is
6513 assigned to `infinity' in order to simplify a loop condition.
6514 The original value is saved here. */
6515 int last_char_skip;
6518 struct xlfdpat
6520 /* Normalized pattern string. "Normalized" means that capital
6521 letters are lowered, blocks are not empty except the first and
6522 the last ones, and trailing '?'s in a block that is not the last
6523 one are moved to the next one. The last character in each block
6524 is replaced with NUL. */
6525 unsigned char *buf;
6527 /* Number of characters except '*'s and trailing '?'s in the
6528 normalized pattern string. */
6529 int nchars;
6531 /* Number of trailing '?'s in the normalized pattern string. */
6532 int trailing_anychars;
6534 /* Number of blocks and information for each block. The latter is
6535 NULL if the pattern is exact (no '*' or '?' in it). */
6536 int nblocks;
6537 struct xlfdpat_block *blocks;
6540 static void
6541 xlfdpat_destroy (pat)
6542 struct xlfdpat *pat;
6544 if (pat)
6546 if (pat->buf)
6548 if (pat->blocks)
6549 xfree (pat->blocks);
6550 xfree (pat->buf);
6552 xfree (pat);
6556 static struct xlfdpat *
6557 xlfdpat_create (pattern)
6558 char *pattern;
6560 struct xlfdpat *pat;
6561 int nblocks, i, skip;
6562 unsigned char last_char, *p, *q, *anychar_head;
6563 struct xlfdpat_block *blk;
6565 pat = xmalloc (sizeof (struct xlfdpat));
6566 if (pat == NULL)
6567 goto error;
6569 pat->buf = xmalloc (strlen (pattern) + 1);
6570 if (pat->buf == NULL)
6571 goto error;
6573 /* Normalize the pattern string and store it to `pat->buf'. */
6574 nblocks = 0;
6575 anychar_head = NULL;
6576 q = pat->buf;
6577 last_char = '\0';
6578 for (p = pattern; *p; p++)
6580 unsigned char c = *p;
6582 if (c == '*')
6583 if (last_char == '*')
6584 /* ...a** -> ...a* */
6585 continue;
6586 else
6588 if (last_char == '?')
6590 if (anychar_head > pat->buf && *(anychar_head - 1) == '*')
6591 /* ...*??* -> ...*?? */
6592 continue;
6593 else
6594 /* ...a??* -> ...a*?? */
6596 *anychar_head++ = '*';
6597 c = '?';
6600 nblocks++;
6602 else if (c == '?')
6604 if (last_char != '?')
6605 anychar_head = q;
6607 else
6608 /* On Mac OS X 10.3, tolower also converts non-ASCII
6609 characters for some locales. */
6610 if (isascii (c))
6611 c = tolower (c);
6613 *q++ = last_char = c;
6615 *q = '\0';
6616 nblocks++;
6617 pat->nblocks = nblocks;
6618 if (last_char != '?')
6619 pat->trailing_anychars = 0;
6620 else
6622 pat->trailing_anychars = q - anychar_head;
6623 q = anychar_head;
6625 pat->nchars = q - pat->buf - (nblocks - 1);
6627 if (anychar_head == NULL && nblocks == 1)
6629 /* The pattern is exact. */
6630 pat->blocks = NULL;
6631 return pat;
6634 pat->blocks = xmalloc (sizeof (struct xlfdpat_block) * nblocks);
6635 if (pat->blocks == NULL)
6636 goto error;
6638 /* Divide the normalized pattern into blocks. */
6639 p = pat->buf;
6640 for (blk = pat->blocks; blk < pat->blocks + nblocks - 1; blk++)
6642 blk->pattern = p;
6643 while (*p != '*')
6644 p++;
6645 blk->len = p - blk->pattern;
6646 p++;
6648 blk->pattern = p;
6649 blk->len = q - blk->pattern;
6651 /* Setup a table for the Boyer-Moore string search. */
6652 for (blk = pat->blocks; blk < pat->blocks + nblocks; blk++)
6653 if (blk->len != 0)
6655 blk->last_char = blk->pattern[blk->len - 1];
6656 blk->pattern[blk->len - 1] = '\0';
6658 for (skip = 1; skip < blk->len; skip++)
6659 if (blk->pattern[blk->len - skip - 1] == '?')
6660 break;
6662 for (i = 0; i < 256; i++)
6663 blk->skip[i] = skip;
6665 p = blk->pattern + (blk->len - skip);
6666 while (--skip > 0)
6667 blk->skip[*p++] = skip;
6669 blk->last_char_skip = blk->skip[blk->last_char];
6672 return pat;
6674 error:
6675 xlfdpat_destroy (pat);
6676 return NULL;
6679 static INLINE int
6680 xlfdpat_exact_p (pat)
6681 struct xlfdpat *pat;
6683 return pat->blocks == NULL;
6686 /* Return the first string in STRING + 0, ..., STRING + START_MAX such
6687 that the pattern in *BLK matches with its prefix. Return NULL
6688 there is no such strings. STRING must be lowered in advance. */
6690 static char *
6691 xlfdpat_block_match_1 (blk, string, start_max)
6692 struct xlfdpat_block *blk;
6693 unsigned char *string;
6694 int start_max;
6696 int start, infinity;
6697 unsigned char *p, *s;
6699 xassert (blk->len > 0);
6700 xassert (start_max + blk->len <= strlen (string));
6701 xassert (blk->last_char != '?');
6703 /* See the comments in the function `boyer_moore' (search.c) for the
6704 use of `infinity'. */
6705 infinity = start_max + blk->len + 1;
6706 blk->skip[blk->last_char] = infinity;
6708 start = 0;
6711 /* Check the last character of the pattern. */
6712 s = string + blk->len - 1;
6715 start += blk->skip[*(s + start)];
6717 while (start <= start_max);
6719 if (start < infinity)
6720 /* Couldn't find the last character. */
6721 return NULL;
6723 /* No less than `infinity' means we could find the last
6724 character at `s[start - infinity]'. */
6725 start -= infinity;
6727 /* Check the remaining characters. We prefer making no-'?'
6728 cases faster because the use of '?' is really rare. */
6729 p = blk->pattern;
6730 s = string + start;
6733 while (*p++ == *s++)
6736 while (*(p - 1) == '?');
6738 if (*(p - 1) == '\0')
6739 /* Matched. */
6740 return string + start;
6742 /* Didn't match. */
6743 start += blk->last_char_skip;
6745 while (start <= start_max);
6747 return NULL;
6750 #define xlfdpat_block_match(b, s, m) \
6751 ((b)->len == 1 ? memchr ((s), (b)->last_char, (m) + 1) \
6752 : xlfdpat_block_match_1 (b, s, m))
6754 /* Check if XLFD pattern PAT, which is generated by `xfldpat_create',
6755 matches with STRING. STRING must be lowered in advance. */
6757 static int
6758 xlfdpat_match (pat, string)
6759 struct xlfdpat *pat;
6760 unsigned char *string;
6762 int str_len, nblocks, i, start_max;
6763 struct xlfdpat_block *blk;
6764 unsigned char *s;
6766 xassert (pat->nblocks > 0);
6768 if (xlfdpat_exact_p (pat))
6769 return strcmp (pat->buf, string) == 0;
6771 /* The number of the characters in the string must not be smaller
6772 than that in the pattern. */
6773 str_len = strlen (string);
6774 if (str_len < pat->nchars + pat->trailing_anychars)
6775 return 0;
6777 /* Chop off the trailing '?'s. */
6778 str_len -= pat->trailing_anychars;
6780 /* The last block. When it is non-empty, it must match at the end
6781 of the string. */
6782 nblocks = pat->nblocks;
6783 blk = pat->blocks + (nblocks - 1);
6784 if (nblocks == 1)
6785 /* The last block is also the first one. */
6786 return (str_len == blk->len
6787 && (blk->len == 0 || xlfdpat_block_match (blk, string, 0)));
6788 else if (blk->len != 0)
6789 if (!xlfdpat_block_match (blk, string + (str_len - blk->len), 0))
6790 return 0;
6792 /* The first block. When it is non-empty, it must match at the
6793 beginning of the string. */
6794 blk = pat->blocks;
6795 if (blk->len != 0)
6797 s = xlfdpat_block_match (blk, string, 0);
6798 if (s == NULL)
6799 return 0;
6800 string = s + blk->len;
6803 /* The rest of the blocks. */
6804 start_max = str_len - pat->nchars;
6805 for (i = 1, blk++; i < nblocks - 1; i++, blk++)
6807 s = xlfdpat_block_match (blk, string, start_max);
6808 if (s == NULL)
6809 return 0;
6810 start_max -= s - string;
6811 string = s + blk->len;
6814 return 1;
6818 /***********************************************************************
6819 Fonts
6820 ***********************************************************************/
6822 /* Return a pointer to struct font_info of font FONT_IDX of frame F. */
6824 struct font_info *
6825 x_get_font_info (f, font_idx)
6826 FRAME_PTR f;
6827 int font_idx;
6829 return (FRAME_MAC_FONT_TABLE (f) + font_idx);
6832 /* the global font name table */
6833 static char **font_name_table = NULL;
6834 static int font_name_table_size = 0;
6835 static int font_name_count = 0;
6837 /* Alist linking font family names to Font Manager font family
6838 references (which can also be used as QuickDraw font IDs). We use
6839 an alist because hash tables are not ready when the terminal frame
6840 for Mac OS Classic is created. */
6841 static Lisp_Object fm_font_family_alist;
6842 #if USE_ATSUI
6843 /* Hash table linking font family names to ATSU font IDs. */
6844 static Lisp_Object atsu_font_id_hash;
6845 #endif
6847 /* Alist linking character set strings to Mac text encoding and Emacs
6848 coding system. */
6849 static Lisp_Object Vmac_charset_info_alist;
6851 static Lisp_Object
6852 create_text_encoding_info_alist ()
6854 Lisp_Object result = Qnil, rest;
6856 for (rest = Vmac_charset_info_alist; CONSP (rest); rest = XCDR (rest))
6858 Lisp_Object charset_info = XCAR (rest);
6859 Lisp_Object charset, coding_system, text_encoding;
6860 Lisp_Object existing_info;
6862 if (!(CONSP (charset_info)
6863 && STRINGP (charset = XCAR (charset_info))
6864 && CONSP (XCDR (charset_info))
6865 && INTEGERP (text_encoding = XCAR (XCDR (charset_info)))
6866 && CONSP (XCDR (XCDR (charset_info)))
6867 && SYMBOLP (coding_system = XCAR (XCDR (XCDR (charset_info))))))
6868 continue;
6870 existing_info = assq_no_quit (text_encoding, result);
6871 if (NILP (existing_info))
6872 result = Fcons (list3 (text_encoding, coding_system, charset),
6873 result);
6874 else
6875 if (NILP (Fmember (charset, XCDR (XCDR (existing_info)))))
6876 XSETCDR (XCDR (existing_info),
6877 Fcons (charset, XCDR (XCDR (existing_info))));
6880 return result;
6884 static void
6885 decode_mac_font_name (name, size, coding_system)
6886 char *name;
6887 int size;
6888 Lisp_Object coding_system;
6890 struct coding_system coding;
6891 char *buf, *p;
6893 if (!NILP (coding_system) && !NILP (Fcoding_system_p (coding_system)))
6895 for (p = name; *p; p++)
6896 if (!isascii (*p) || iscntrl (*p))
6897 break;
6899 if (*p)
6901 setup_coding_system (coding_system, &coding);
6902 coding.src_multibyte = 0;
6903 coding.dst_multibyte = 1;
6904 coding.mode |= CODING_MODE_LAST_BLOCK;
6905 coding.composing = COMPOSITION_DISABLED;
6906 buf = (char *) alloca (size);
6908 decode_coding (&coding, name, buf, strlen (name), size - 1);
6909 bcopy (buf, name, coding.produced);
6910 name[coding.produced] = '\0';
6914 /* If there's just one occurrence of '-' in the family name, it is
6915 replaced with '_'. (More than one occurrence of '-' means a
6916 "FOUNDRY-FAMILY-CHARSET"-style name.) */
6917 p = strchr (name, '-');
6918 if (p && strchr (p + 1, '-') == NULL)
6919 *p = '_';
6921 for (p = name; *p; p++)
6922 /* On Mac OS X 10.3, tolower also converts non-ASCII characters
6923 for some locales. */
6924 if (isascii (*p))
6925 *p = tolower (*p);
6929 static char *
6930 mac_to_x_fontname (name, size, style, charset)
6931 char *name;
6932 int size;
6933 Style style;
6934 char *charset;
6936 Str31 foundry, cs;
6937 Str255 family;
6938 char xf[256], *result;
6939 unsigned char *p;
6941 if (sscanf (name, "%31[^-]-%255[^-]-%31s", foundry, family, cs) == 3)
6942 charset = cs;
6943 else
6945 strcpy(foundry, "Apple");
6946 strcpy(family, name);
6949 sprintf (xf, "%s-%c-normal--%d-%d-%d-%d-m-%d-%s",
6950 style & bold ? "bold" : "medium", style & italic ? 'i' : 'r',
6951 size, size * 10, size ? 72 : 0, size ? 72 : 0, size * 10, charset);
6953 result = xmalloc (strlen (foundry) + strlen (family) + strlen (xf) + 3 + 1);
6954 sprintf (result, "-%s-%s-%s", foundry, family, xf);
6955 for (p = result; *p; p++)
6956 /* On Mac OS X 10.3, tolower also converts non-ASCII characters
6957 for some locales. */
6958 if (isascii (*p))
6959 *p = tolower (*p);
6960 return result;
6964 /* Parse fully-specified and instantiated X11 font spec XF, and store
6965 the results to FAMILY, *SIZE, *STYLE, and CHARSET. Return 1 if the
6966 parsing succeeded, and 0 otherwise. For FAMILY and CHARSET, the
6967 caller must allocate at least 256 and 32 bytes respectively. For
6968 ordinary Mac fonts, the value stored to FAMILY should just be their
6969 names, like "monaco", "Taipei", etc. Fonts converted from the GNU
6970 intlfonts collection contain their charset designation in their
6971 names, like "ETL-Fixed-iso8859-1", "ETL-Fixed-koi8-r", etc. Both
6972 types of font names are handled accordingly. */
6974 const int kDefaultFontSize = 12;
6976 static int
6977 parse_x_font_name (xf, family, size, style, charset)
6978 char *xf, *family;
6979 int *size;
6980 Style *style;
6981 char *charset;
6983 Str31 foundry, weight;
6984 int point_size, avgwidth;
6985 char slant[2], *p;
6987 if (sscanf (xf, "-%31[^-]-%255[^-]-%31[^-]-%1[^-]-%*[^-]-%*[^-]-%d-%d-%*[^-]-%*[^-]-%*c-%d-%31s",
6988 foundry, family, weight, slant, size,
6989 &point_size, &avgwidth, charset) != 8
6990 && sscanf (xf, "-%31[^-]-%255[^-]-%31[^-]-%1[^-]-%*[^-]--%d-%d-%*[^-]-%*[^-]-%*c-%d-%31s",
6991 foundry, family, weight, slant, size,
6992 &point_size, &avgwidth, charset) != 8)
6993 return 0;
6995 if (*size == 0)
6997 if (point_size > 0)
6998 *size = point_size / 10;
6999 else if (avgwidth > 0)
7000 *size = avgwidth / 10;
7002 if (*size == 0)
7003 *size = kDefaultFontSize;
7005 *style = normal;
7006 if (strcmp (weight, "bold") == 0)
7007 *style |= bold;
7008 if (*slant == 'i')
7009 *style |= italic;
7011 if (NILP (Fassoc (build_string (charset), Vmac_charset_info_alist)))
7013 int foundry_len = strlen (foundry), family_len = strlen (family);
7015 if (foundry_len + family_len + strlen (charset) + 2 < sizeof (Str255))
7017 /* Like sprintf (family, "%s-%s-%s", foundry, family, charset),
7018 but take overlap into account. */
7019 memmove (family + foundry_len + 1, family, family_len);
7020 memcpy (family, foundry, foundry_len);
7021 family[foundry_len] = '-';
7022 family[foundry_len + 1 + family_len] = '-';
7023 strcpy (family + foundry_len + 1 + family_len + 1, charset);
7025 else
7026 return 0;
7029 for (p = family; *p; p++)
7030 /* On Mac OS X 10.3, tolower also converts non-ASCII characters
7031 for some locales. */
7032 if (isascii (*p))
7033 *p = tolower (*p);
7035 return 1;
7039 static void
7040 add_font_name_table_entry (char *font_name)
7042 if (font_name_table_size == 0)
7044 font_name_table_size = 256;
7045 font_name_table = (char **)
7046 xmalloc (font_name_table_size * sizeof (char *));
7048 else if (font_name_count + 1 >= font_name_table_size)
7050 font_name_table_size *= 2;
7051 font_name_table = (char **)
7052 xrealloc (font_name_table,
7053 font_name_table_size * sizeof (char *));
7056 font_name_table[font_name_count++] = font_name;
7059 /* Sets up the table font_name_table to contain the list of all fonts
7060 in the system the first time the table is used so that the Resource
7061 Manager need not be accessed every time this information is
7062 needed. */
7064 static void
7065 init_font_name_table ()
7067 #if TARGET_API_MAC_CARBON
7068 FMFontFamilyIterator ffi;
7069 FMFontFamilyInstanceIterator ffii;
7070 FMFontFamily ff;
7071 Lisp_Object text_encoding_info_alist;
7072 struct gcpro gcpro1;
7074 text_encoding_info_alist = create_text_encoding_info_alist ();
7076 #if USE_ATSUI
7077 #if USE_CG_TEXT_DRAWING
7078 init_cg_text_anti_aliasing_threshold ();
7079 #endif
7080 if (!NILP (assq_no_quit (make_number (kTextEncodingMacUnicode),
7081 text_encoding_info_alist)))
7083 OSErr err;
7084 ItemCount nfonts, i;
7085 ATSUFontID *font_ids = NULL;
7086 Ptr name, prev_name = NULL;
7087 ByteCount name_len;
7089 atsu_font_id_hash =
7090 make_hash_table (Qequal, make_number (DEFAULT_HASH_SIZE),
7091 make_float (DEFAULT_REHASH_SIZE),
7092 make_float (DEFAULT_REHASH_THRESHOLD),
7093 Qnil, Qnil, Qnil);;
7094 err = ATSUFontCount (&nfonts);
7095 if (err == noErr)
7096 font_ids = xmalloc (sizeof (ATSUFontID) * nfonts);
7097 if (font_ids)
7098 err = ATSUGetFontIDs (font_ids, nfonts, NULL);
7099 if (err == noErr)
7100 for (i = 0; i < nfonts; i++)
7102 err = ATSUFindFontName (font_ids[i], kFontFamilyName,
7103 kFontMacintoshPlatform, kFontNoScript,
7104 kFontNoLanguage, 0, NULL, &name_len, NULL);
7105 if (err != noErr)
7106 continue;
7107 name = xmalloc (name_len + 1);
7108 if (name == NULL)
7109 continue;
7110 name[name_len] = '\0';
7111 err = ATSUFindFontName (font_ids[i], kFontFamilyName,
7112 kFontMacintoshPlatform, kFontNoScript,
7113 kFontNoLanguage, name_len, name,
7114 NULL, NULL);
7115 if (err == noErr)
7116 decode_mac_font_name (name, name_len + 1, Qnil);
7117 if (err == noErr
7118 && *name != '.'
7119 && (prev_name == NULL
7120 || strcmp (name, prev_name) != 0))
7122 static char *cs = "iso10646-1";
7124 add_font_name_table_entry (mac_to_x_fontname (name, 0,
7125 normal, cs));
7126 add_font_name_table_entry (mac_to_x_fontname (name, 0,
7127 italic, cs));
7128 add_font_name_table_entry (mac_to_x_fontname (name, 0,
7129 bold, cs));
7130 add_font_name_table_entry (mac_to_x_fontname (name, 0,
7131 italic | bold, cs));
7132 Fputhash (make_unibyte_string (name, name_len),
7133 long_to_cons (font_ids[i]), atsu_font_id_hash);
7134 xfree (prev_name);
7135 prev_name = name;
7137 else
7138 xfree (name);
7140 if (prev_name)
7141 xfree (prev_name);
7142 if (font_ids)
7143 xfree (font_ids);
7145 #endif
7147 /* Create a dummy instance iterator here to avoid creating and
7148 destroying it in the loop. */
7149 if (FMCreateFontFamilyInstanceIterator (0, &ffii) != noErr)
7150 return;
7151 /* Create an iterator to enumerate the font families. */
7152 if (FMCreateFontFamilyIterator (NULL, NULL, kFMDefaultOptions, &ffi)
7153 != noErr)
7155 FMDisposeFontFamilyInstanceIterator (&ffii);
7156 return;
7159 GCPRO1 (text_encoding_info_alist);
7161 while (FMGetNextFontFamily (&ffi, &ff) == noErr)
7163 Str255 name;
7164 FMFont font;
7165 FMFontStyle style;
7166 FMFontSize size;
7167 TextEncoding encoding;
7168 TextEncodingBase sc;
7169 Lisp_Object text_encoding_info;
7171 if (FMGetFontFamilyName (ff, name) != noErr)
7172 break;
7173 p2cstr (name);
7174 if (*name == '.')
7175 continue;
7177 if (FMGetFontFamilyTextEncoding (ff, &encoding) != noErr)
7178 break;
7179 sc = GetTextEncodingBase (encoding);
7180 text_encoding_info = assq_no_quit (make_number (sc),
7181 text_encoding_info_alist);
7182 if (NILP (text_encoding_info))
7183 text_encoding_info = assq_no_quit (make_number (kTextEncodingMacRoman),
7184 text_encoding_info_alist);
7185 decode_mac_font_name (name, sizeof (name),
7186 XCAR (XCDR (text_encoding_info)));
7187 fm_font_family_alist = Fcons (Fcons (build_string (name),
7188 make_number (ff)),
7189 fm_font_family_alist);
7191 /* Point the instance iterator at the current font family. */
7192 if (FMResetFontFamilyInstanceIterator (ff, &ffii) != noErr)
7193 break;
7195 while (FMGetNextFontFamilyInstance (&ffii, &font, &style, &size)
7196 == noErr)
7198 Lisp_Object rest = XCDR (XCDR (text_encoding_info));
7200 if (size > 0 || style == normal)
7201 for (; !NILP (rest); rest = XCDR (rest))
7203 char *cs = SDATA (XCAR (rest));
7205 if (size == 0)
7207 add_font_name_table_entry (mac_to_x_fontname (name, size,
7208 style, cs));
7209 add_font_name_table_entry (mac_to_x_fontname (name, size,
7210 italic, cs));
7211 add_font_name_table_entry (mac_to_x_fontname (name, size,
7212 bold, cs));
7213 add_font_name_table_entry (mac_to_x_fontname (name, size,
7214 italic | bold,
7215 cs));
7217 else
7219 add_font_name_table_entry (mac_to_x_fontname (name, size,
7220 style, cs));
7226 UNGCPRO;
7228 /* Dispose of the iterators. */
7229 FMDisposeFontFamilyIterator (&ffi);
7230 FMDisposeFontFamilyInstanceIterator (&ffii);
7231 #else /* !TARGET_API_MAC_CARBON */
7232 GrafPtr port;
7233 SInt16 fontnum, old_fontnum;
7234 int num_mac_fonts = CountResources('FOND');
7235 int i, j;
7236 Handle font_handle, font_handle_2;
7237 short id, scriptcode;
7238 ResType type;
7239 Str255 name;
7240 struct FontAssoc *fat;
7241 struct AsscEntry *assc_entry;
7242 Lisp_Object text_encoding_info_alist, text_encoding_info;
7243 struct gcpro gcpro1;
7245 GetPort (&port); /* save the current font number used */
7246 old_fontnum = port->txFont;
7248 text_encoding_info_alist = create_text_encoding_info_alist ();
7250 GCPRO1 (text_encoding_info_alist);
7252 for (i = 1; i <= num_mac_fonts; i++) /* get all available fonts */
7254 font_handle = GetIndResource ('FOND', i);
7255 if (!font_handle)
7256 continue;
7258 GetResInfo (font_handle, &id, &type, name);
7259 GetFNum (name, &fontnum);
7260 p2cstr (name);
7261 if (fontnum == 0)
7262 continue;
7264 TextFont (fontnum);
7265 scriptcode = FontToScript (fontnum);
7266 text_encoding_info = assq_no_quit (make_number (scriptcode),
7267 text_encoding_info_alist);
7268 if (NILP (text_encoding_info))
7269 text_encoding_info = assq_no_quit (make_number (smRoman),
7270 text_encoding_info_alist);
7271 decode_mac_font_name (name, sizeof (name),
7272 XCAR (XCDR (text_encoding_info)));
7273 fm_font_family_alist = Fcons (Fcons (build_string (name),
7274 make_number (fontnum)),
7275 fm_font_family_alist);
7278 HLock (font_handle);
7280 if (GetResourceSizeOnDisk (font_handle)
7281 >= sizeof (struct FamRec))
7283 fat = (struct FontAssoc *) (*font_handle
7284 + sizeof (struct FamRec));
7285 assc_entry
7286 = (struct AsscEntry *) (*font_handle
7287 + sizeof (struct FamRec)
7288 + sizeof (struct FontAssoc));
7290 for (j = 0; j <= fat->numAssoc; j++, assc_entry++)
7292 Lisp_Object rest = XCDR (XCDR (text_encoding_info));
7294 for (; !NILP (rest); rest = XCDR (rest))
7296 char *cs = SDATA (XCAR (rest));
7298 add_font_name_table_entry (mac_to_x_fontname (name,
7299 assc_entry->fontSize,
7300 assc_entry->fontStyle,
7301 cs));
7306 HUnlock (font_handle);
7307 font_handle_2 = GetNextFOND (font_handle);
7308 ReleaseResource (font_handle);
7309 font_handle = font_handle_2;
7311 while (ResError () == noErr && font_handle);
7314 UNGCPRO;
7316 TextFont (old_fontnum);
7317 #endif /* !TARGET_API_MAC_CARBON */
7321 void
7322 mac_clear_font_name_table ()
7324 int i;
7326 for (i = 0; i < font_name_count; i++)
7327 xfree (font_name_table[i]);
7328 xfree (font_name_table);
7329 font_name_table = NULL;
7330 font_name_table_size = font_name_count = 0;
7331 fm_font_family_alist = Qnil;
7335 enum xlfd_scalable_field_index
7337 XLFD_SCL_PIXEL_SIZE,
7338 XLFD_SCL_POINT_SIZE,
7339 XLFD_SCL_AVGWIDTH,
7340 XLFD_SCL_LAST
7343 static int xlfd_scalable_fields[] =
7345 6, /* PIXEL_SIZE */
7346 7, /* POINT_SIZE */
7347 11, /* AVGWIDTH */
7351 static Lisp_Object
7352 mac_do_list_fonts (pattern, maxnames)
7353 char *pattern;
7354 int maxnames;
7356 int i, n_fonts = 0;
7357 Lisp_Object font_list = Qnil;
7358 struct xlfdpat *pat;
7359 char *scaled, *ptr;
7360 int scl_val[XLFD_SCL_LAST], *field, *val;
7361 int exact;
7363 if (font_name_table == NULL) /* Initialize when first used. */
7364 init_font_name_table ();
7366 for (i = 0; i < XLFD_SCL_LAST; i++)
7367 scl_val[i] = -1;
7369 /* If the pattern contains 14 dashes and one of PIXEL_SIZE,
7370 POINT_SIZE, and AVGWIDTH fields is explicitly specified, scalable
7371 fonts are scaled according to the specified size. */
7372 ptr = pattern;
7373 i = 0;
7374 field = xlfd_scalable_fields;
7375 val = scl_val;
7376 if (*ptr == '-')
7379 ptr++;
7380 if (i == *field)
7382 if ('0' <= *ptr && *ptr <= '9')
7384 *val = *ptr++ - '0';
7385 while ('0' <= *ptr && *ptr <= '9' && *val < 10000)
7386 *val = *val * 10 + *ptr++ - '0';
7387 if (*ptr != '-')
7388 *val = -1;
7390 field++;
7391 val++;
7393 ptr = strchr (ptr, '-');
7394 i++;
7396 while (ptr && i < 14);
7398 if (i == 14 && ptr == NULL)
7400 if (scl_val[XLFD_SCL_PIXEL_SIZE] < 0)
7401 scl_val[XLFD_SCL_PIXEL_SIZE] =
7402 (scl_val[XLFD_SCL_POINT_SIZE] > 0 ? scl_val[XLFD_SCL_POINT_SIZE] / 10
7403 : (scl_val[XLFD_SCL_AVGWIDTH] > 0 ? scl_val[XLFD_SCL_AVGWIDTH] / 10
7404 : -1));
7405 if (scl_val[XLFD_SCL_POINT_SIZE] < 0)
7406 scl_val[XLFD_SCL_POINT_SIZE] =
7407 (scl_val[XLFD_SCL_PIXEL_SIZE] > 0 ? scl_val[XLFD_SCL_PIXEL_SIZE] * 10
7408 : (scl_val[XLFD_SCL_AVGWIDTH] > 0 ? scl_val[XLFD_SCL_AVGWIDTH]
7409 : -1));
7410 if (scl_val[XLFD_SCL_AVGWIDTH] < 0)
7411 scl_val[XLFD_SCL_AVGWIDTH] =
7412 (scl_val[XLFD_SCL_PIXEL_SIZE] > 0 ? scl_val[XLFD_SCL_PIXEL_SIZE] * 10
7413 : (scl_val[XLFD_SCL_POINT_SIZE] > 0 ? scl_val[XLFD_SCL_POINT_SIZE]
7414 : -1));
7416 else
7417 scl_val[XLFD_SCL_PIXEL_SIZE] = -1;
7419 pat = xlfdpat_create (pattern);
7420 if (pat == NULL)
7421 return Qnil;
7423 exact = xlfdpat_exact_p (pat);
7425 for (i = 0; i < font_name_count; i++)
7427 if (xlfdpat_match (pat, font_name_table[i]))
7429 font_list = Fcons (build_string (font_name_table[i]), font_list);
7430 if (exact || (maxnames > 0 && ++n_fonts >= maxnames))
7431 break;
7433 else if (scl_val[XLFD_SCL_PIXEL_SIZE] > 0
7434 && (ptr = strstr (font_name_table[i], "-0-0-0-0-m-0-")))
7436 int former_len = ptr - font_name_table[i];
7438 scaled = xmalloc (strlen (font_name_table[i]) + 20 + 1);
7439 if (scaled == NULL)
7440 continue;
7441 memcpy (scaled, font_name_table[i], former_len);
7442 sprintf (scaled + former_len,
7443 "-%d-%d-72-72-m-%d-%s",
7444 scl_val[XLFD_SCL_PIXEL_SIZE],
7445 scl_val[XLFD_SCL_POINT_SIZE],
7446 scl_val[XLFD_SCL_AVGWIDTH],
7447 ptr + sizeof ("-0-0-0-0-m-0-") - 1);
7449 if (xlfdpat_match (pat, scaled))
7451 font_list = Fcons (build_string (scaled), font_list);
7452 xfree (scaled);
7453 if (exact || (maxnames > 0 && ++n_fonts >= maxnames))
7454 break;
7456 else
7457 xfree (scaled);
7461 xlfdpat_destroy (pat);
7463 return font_list;
7466 /* Return a list of names of available fonts matching PATTERN on frame F.
7468 Frame F null means we have not yet created any frame on Mac, and
7469 consult the first display in x_display_list. MAXNAMES sets a limit
7470 on how many fonts to match. */
7472 Lisp_Object
7473 x_list_fonts (f, pattern, size, maxnames)
7474 struct frame *f;
7475 Lisp_Object pattern;
7476 int size, maxnames;
7478 Lisp_Object list = Qnil, patterns, tem, key;
7479 struct mac_display_info *dpyinfo
7480 = f ? FRAME_MAC_DISPLAY_INFO (f) : x_display_list;
7482 xassert (size <= 0);
7484 patterns = Fassoc (pattern, Valternate_fontname_alist);
7485 if (NILP (patterns))
7486 patterns = Fcons (pattern, Qnil);
7488 for (; CONSP (patterns); patterns = XCDR (patterns))
7490 pattern = XCAR (patterns);
7492 if (!STRINGP (pattern))
7493 continue;
7495 tem = XCAR (XCDR (dpyinfo->name_list_element));
7496 key = Fcons (pattern, make_number (maxnames));
7498 list = Fassoc (key, tem);
7499 if (!NILP (list))
7501 list = Fcdr_safe (list);
7502 /* We have a cashed list. Don't have to get the list again. */
7503 goto label_cached;
7506 BLOCK_INPUT;
7507 list = mac_do_list_fonts (SDATA (pattern), maxnames);
7508 UNBLOCK_INPUT;
7510 /* MAC_TODO: add code for matching outline fonts here */
7512 /* Now store the result in the cache. */
7513 XSETCAR (XCDR (dpyinfo->name_list_element),
7514 Fcons (Fcons (key, list),
7515 XCAR (XCDR (dpyinfo->name_list_element))));
7517 label_cached:
7518 if (NILP (list)) continue; /* Try the remaining alternatives. */
7521 return list;
7525 #if GLYPH_DEBUG
7527 /* Check that FONT is valid on frame F. It is if it can be found in F's
7528 font table. */
7530 static void
7531 x_check_font (f, font)
7532 struct frame *f;
7533 XFontStruct *font;
7535 int i;
7536 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
7538 xassert (font != NULL);
7540 for (i = 0; i < dpyinfo->n_fonts; i++)
7541 if (dpyinfo->font_table[i].name
7542 && font == dpyinfo->font_table[i].font)
7543 break;
7545 xassert (i < dpyinfo->n_fonts);
7548 #endif /* GLYPH_DEBUG != 0 */
7550 /* Set *W to the minimum width, *H to the minimum font height of FONT.
7551 Note: There are (broken) X fonts out there with invalid XFontStruct
7552 min_bounds contents. For example, handa@etl.go.jp reports that
7553 "-adobe-courier-medium-r-normal--*-180-*-*-m-*-iso8859-1" fonts
7554 have font->min_bounds.width == 0. */
7556 static INLINE void
7557 x_font_min_bounds (font, w, h)
7558 MacFontStruct *font;
7559 int *w, *h;
7561 *h = FONT_HEIGHT (font);
7562 *w = font->min_bounds.width;
7566 /* Compute the smallest character width and smallest font height over
7567 all fonts available on frame F. Set the members smallest_char_width
7568 and smallest_font_height in F's x_display_info structure to
7569 the values computed. Value is non-zero if smallest_font_height or
7570 smallest_char_width become smaller than they were before. */
7572 static int
7573 x_compute_min_glyph_bounds (f)
7574 struct frame *f;
7576 int i;
7577 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
7578 MacFontStruct *font;
7579 int old_width = dpyinfo->smallest_char_width;
7580 int old_height = dpyinfo->smallest_font_height;
7582 dpyinfo->smallest_font_height = 100000;
7583 dpyinfo->smallest_char_width = 100000;
7585 for (i = 0; i < dpyinfo->n_fonts; ++i)
7586 if (dpyinfo->font_table[i].name)
7588 struct font_info *fontp = dpyinfo->font_table + i;
7589 int w, h;
7591 font = (MacFontStruct *) fontp->font;
7592 xassert (font != (MacFontStruct *) ~0);
7593 x_font_min_bounds (font, &w, &h);
7595 dpyinfo->smallest_font_height = min (dpyinfo->smallest_font_height, h);
7596 dpyinfo->smallest_char_width = min (dpyinfo->smallest_char_width, w);
7599 xassert (dpyinfo->smallest_char_width > 0
7600 && dpyinfo->smallest_font_height > 0);
7602 return (dpyinfo->n_fonts == 1
7603 || dpyinfo->smallest_char_width < old_width
7604 || dpyinfo->smallest_font_height < old_height);
7608 /* Determine whether given string is a fully-specified XLFD: all 14
7609 fields are present, none is '*'. */
7611 static int
7612 is_fully_specified_xlfd (char *p)
7614 int i;
7615 char *q;
7617 if (*p != '-')
7618 return 0;
7620 for (i = 0; i < 13; i++)
7622 q = strchr (p + 1, '-');
7623 if (q == NULL)
7624 return 0;
7625 if (q - p == 2 && *(p + 1) == '*')
7626 return 0;
7627 p = q;
7630 if (strchr (p + 1, '-') != NULL)
7631 return 0;
7633 if (*(p + 1) == '*' && *(p + 2) == '\0')
7634 return 0;
7636 return 1;
7640 /* XLoadQueryFont creates and returns an internal representation for a
7641 font in a MacFontStruct struct. There is really no concept
7642 corresponding to "loading" a font on the Mac. But we check its
7643 existence and find the font number and all other information for it
7644 and store them in the returned MacFontStruct. */
7646 static MacFontStruct *
7647 XLoadQueryFont (Display *dpy, char *fontname)
7649 int size;
7650 char *name;
7651 Str255 family;
7652 Str31 charset;
7653 SInt16 fontnum;
7654 #if USE_ATSUI
7655 static ATSUFontID font_id;
7656 ATSUStyle mac_style = NULL;
7657 #endif
7658 Style fontface;
7659 #if TARGET_API_MAC_CARBON
7660 TextEncoding encoding;
7661 int scriptcode;
7662 #else
7663 short scriptcode;
7664 #endif
7665 MacFontStruct *font;
7666 XCharStruct *space_bounds = NULL, *pcm;
7668 if (is_fully_specified_xlfd (fontname))
7669 name = fontname;
7670 else
7672 Lisp_Object matched_fonts;
7674 matched_fonts = mac_do_list_fonts (fontname, 1);
7675 if (NILP (matched_fonts))
7676 return NULL;
7677 name = SDATA (XCAR (matched_fonts));
7680 if (parse_x_font_name (name, family, &size, &fontface, charset) == 0)
7681 return NULL;
7683 #if USE_ATSUI
7684 if (strcmp (charset, "iso10646-1") == 0) /* XXX */
7686 OSErr err;
7687 ATSUAttributeTag tags[] = {kATSUFontTag, kATSUSizeTag,
7688 kATSUQDBoldfaceTag, kATSUQDItalicTag};
7689 ByteCount sizes[] = {sizeof (ATSUFontID), sizeof (Fixed),
7690 sizeof (Boolean), sizeof (Boolean)};
7691 static Fixed size_fixed;
7692 static Boolean bold_p, italic_p;
7693 ATSUAttributeValuePtr values[] = {&font_id, &size_fixed,
7694 &bold_p, &italic_p};
7695 ATSUFontFeatureType types[] = {kAllTypographicFeaturesType,
7696 kDiacriticsType};
7697 ATSUFontFeatureSelector selectors[] = {kAllTypeFeaturesOffSelector,
7698 kDecomposeDiacriticsSelector};
7699 Lisp_Object font_id_cons;
7701 font_id_cons = Fgethash (make_unibyte_string (family, strlen (family)),
7702 atsu_font_id_hash, Qnil);
7703 if (NILP (font_id_cons))
7704 return NULL;
7705 font_id = cons_to_long (font_id_cons);
7706 size_fixed = Long2Fix (size);
7707 bold_p = (fontface & bold) != 0;
7708 italic_p = (fontface & italic) != 0;
7709 err = ATSUCreateStyle (&mac_style);
7710 if (err != noErr)
7711 return NULL;
7712 err = ATSUSetFontFeatures (mac_style, sizeof (types) / sizeof (types[0]),
7713 types, selectors);
7714 if (err != noErr)
7715 return NULL;
7716 err = ATSUSetAttributes (mac_style, sizeof (tags) / sizeof (tags[0]),
7717 tags, sizes, values);
7718 fontnum = -1;
7719 scriptcode = kTextEncodingMacUnicode;
7721 else
7722 #endif
7724 Lisp_Object tmp = Fassoc (build_string (family), fm_font_family_alist);
7726 if (NILP (tmp))
7727 return NULL;
7728 fontnum = XINT (XCDR (tmp));
7729 #if TARGET_API_MAC_CARBON
7730 if (FMGetFontFamilyTextEncoding (fontnum, &encoding) != noErr)
7731 return NULL;
7732 scriptcode = GetTextEncodingBase (encoding);
7733 #else
7734 scriptcode = FontToScript (fontnum);
7735 #endif
7738 font = (MacFontStruct *) xmalloc (sizeof (struct MacFontStruct));
7740 font->mac_fontnum = fontnum;
7741 font->mac_fontsize = size;
7742 font->mac_fontface = fontface;
7743 font->mac_scriptcode = scriptcode;
7744 #if USE_ATSUI
7745 font->mac_style = mac_style;
7746 #if USE_CG_TEXT_DRAWING
7747 font->cg_font = NULL;
7748 font->cg_glyphs = NULL;
7749 #endif
7750 #endif
7752 /* Apple Japanese (SJIS) font is listed as both
7753 "*-jisx0208.1983-sjis" (Japanese script) and "*-jisx0201.1976-0"
7754 (Roman script) in init_font_name_table (). The latter should be
7755 treated as a one-byte font. */
7756 if (scriptcode == smJapanese && strcmp (charset, "jisx0201.1976-0") == 0)
7757 font->mac_scriptcode = smRoman;
7759 font->full_name = mac_to_x_fontname (family, size, fontface, charset);
7761 #if USE_ATSUI
7762 if (font->mac_style)
7764 OSErr err;
7765 UniChar c;
7767 font->min_byte1 = 0;
7768 font->max_byte1 = 0xff;
7769 font->min_char_or_byte2 = 0;
7770 font->max_char_or_byte2 = 0xff;
7772 font->bounds.rows = xmalloc (sizeof (XCharStructRow *) * 0x100);
7773 if (font->bounds.rows == NULL)
7775 mac_unload_font (&one_mac_display_info, font);
7776 return NULL;
7778 bzero (font->bounds.rows, sizeof (XCharStructRow *) * 0x100);
7779 font->bounds.rows[0] = xmalloc (sizeof (XCharStructRow));
7780 if (font->bounds.rows[0] == NULL)
7782 mac_unload_font (&one_mac_display_info, font);
7783 return NULL;
7785 bzero (font->bounds.rows[0], sizeof (XCharStructRow));
7787 #if USE_CG_TEXT_DRAWING
7789 FMFontFamily font_family;
7790 FMFontStyle style;
7791 ATSFontRef ats_font;
7793 err = FMGetFontFamilyInstanceFromFont (font_id, &font_family, &style);
7794 if (err == noErr)
7795 err = FMGetFontFromFontFamilyInstance (font_family, fontface,
7796 &font_id, &style);
7797 /* Use CG text drawing if italic/bold is not synthesized. */
7798 if (err == noErr && style == fontface)
7800 ats_font = FMGetATSFontRefFromFont (font_id);
7801 font->cg_font = CGFontCreateWithPlatformFont (&ats_font);
7805 if (font->cg_font)
7806 font->cg_glyphs = xmalloc (sizeof (CGGlyph) * 0x100);
7807 if (font->cg_glyphs)
7808 bzero (font->cg_glyphs, sizeof (CGGlyph) * 0x100);
7809 #endif
7810 space_bounds = font->bounds.rows[0]->per_char + 0x20;
7811 err = mac_query_char_extents (font->mac_style, 0x20,
7812 &font->ascent, &font->descent,
7813 space_bounds,
7814 #if USE_CG_TEXT_DRAWING
7815 (font->cg_glyphs ? font->cg_glyphs + 0x20
7816 : NULL)
7817 #else
7818 NULL
7819 #endif
7821 if (err != noErr)
7823 mac_unload_font (&one_mac_display_info, font);
7824 return NULL;
7826 XCHARSTRUCTROW_SET_CHAR_VALID (font->bounds.rows[0], 0x20);
7828 pcm = font->bounds.rows[0]->per_char;
7829 for (c = 0x21; c <= 0xff; c++)
7831 if (c == 0xad)
7832 /* Soft hyphen is not supported in ATSUI. */
7833 continue;
7834 else if (c == 0x7f)
7836 c = 0x9f;
7837 continue;
7840 mac_query_char_extents (font->mac_style, c, NULL, NULL, pcm + c,
7841 #if USE_CG_TEXT_DRAWING
7842 (font->cg_glyphs ? font->cg_glyphs + c
7843 : NULL)
7844 #else
7845 NULL
7846 #endif
7848 XCHARSTRUCTROW_SET_CHAR_VALID (font->bounds.rows[0], c);
7850 #if USE_CG_TEXT_DRAWING
7851 if (font->cg_glyphs && font->cg_glyphs[c] == 0)
7853 /* Don't use CG text drawing if font substitution occurs in
7854 ASCII or Latin-1 characters. */
7855 CGFontRelease (font->cg_font);
7856 font->cg_font = NULL;
7857 xfree (font->cg_glyphs);
7858 font->cg_glyphs = NULL;
7860 #endif
7863 else
7864 #endif
7866 GrafPtr port;
7867 SInt16 old_fontnum, old_fontsize;
7868 Style old_fontface;
7869 FontInfo the_fontinfo;
7870 int is_two_byte_font;
7872 /* Save the current font number used. */
7873 GetPort (&port);
7874 #if TARGET_API_MAC_CARBON
7875 old_fontnum = GetPortTextFont (port);
7876 old_fontsize = GetPortTextSize (port);
7877 old_fontface = GetPortTextFace (port);
7878 #else
7879 old_fontnum = port->txFont;
7880 old_fontsize = port->txSize;
7881 old_fontface = port->txFace;
7882 #endif
7884 TextFont (fontnum);
7885 TextSize (size);
7886 TextFace (fontface);
7888 GetFontInfo (&the_fontinfo);
7890 font->ascent = the_fontinfo.ascent;
7891 font->descent = the_fontinfo.descent;
7893 is_two_byte_font = (font->mac_scriptcode == smJapanese
7894 || font->mac_scriptcode == smTradChinese
7895 || font->mac_scriptcode == smSimpChinese
7896 || font->mac_scriptcode == smKorean);
7898 if (is_two_byte_font)
7900 int char_width;
7902 font->min_byte1 = 0xa1;
7903 font->max_byte1 = 0xfe;
7904 font->min_char_or_byte2 = 0xa1;
7905 font->max_char_or_byte2 = 0xfe;
7907 /* Use the width of an "ideographic space" of that font
7908 because the_fontinfo.widMax returns the wrong width for
7909 some fonts. */
7910 switch (font->mac_scriptcode)
7912 case smJapanese:
7913 font->min_byte1 = 0x81;
7914 font->max_byte1 = 0xfc;
7915 font->min_char_or_byte2 = 0x40;
7916 font->max_char_or_byte2 = 0xfc;
7917 char_width = StringWidth("\p\x81\x40");
7918 break;
7919 case smTradChinese:
7920 font->min_char_or_byte2 = 0x40;
7921 char_width = StringWidth("\p\xa1\x40");
7922 break;
7923 case smSimpChinese:
7924 char_width = StringWidth("\p\xa1\xa1");
7925 break;
7926 case smKorean:
7927 char_width = StringWidth("\p\xa1\xa1");
7928 break;
7931 font->bounds.per_char = NULL;
7933 if (fontface & italic)
7934 font->max_bounds.rbearing = char_width + 1;
7935 else
7936 font->max_bounds.rbearing = char_width;
7937 font->max_bounds.lbearing = 0;
7938 font->max_bounds.width = char_width;
7939 font->max_bounds.ascent = the_fontinfo.ascent;
7940 font->max_bounds.descent = the_fontinfo.descent;
7942 font->min_bounds = font->max_bounds;
7944 else
7946 int c;
7948 font->min_byte1 = font->max_byte1 = 0;
7949 font->min_char_or_byte2 = 0x20;
7950 font->max_char_or_byte2 = 0xff;
7952 font->bounds.per_char =
7953 xmalloc (sizeof (XCharStruct) * (0xff - 0x20 + 1));
7954 if (font->bounds.per_char == NULL)
7956 mac_unload_font (&one_mac_display_info, font);
7957 return NULL;
7959 bzero (font->bounds.per_char,
7960 sizeof (XCharStruct) * (0xff - 0x20 + 1));
7962 space_bounds = font->bounds.per_char;
7963 mac_query_char_extents (NULL, 0x20, &font->ascent, &font->descent,
7964 space_bounds, NULL);
7966 for (c = 0x21, pcm = space_bounds + 1; c <= 0xff; c++, pcm++)
7967 mac_query_char_extents (NULL, c, NULL, NULL, pcm, NULL);
7970 /* Restore previous font number, size and face. */
7971 TextFont (old_fontnum);
7972 TextSize (old_fontsize);
7973 TextFace (old_fontface);
7976 if (space_bounds)
7978 int c;
7980 font->min_bounds = font->max_bounds = *space_bounds;
7981 for (c = 0x21, pcm = space_bounds + 1; c <= 0x7f; c++, pcm++)
7982 if (pcm->width > 0)
7984 font->min_bounds.lbearing = min (font->min_bounds.lbearing,
7985 pcm->lbearing);
7986 font->min_bounds.rbearing = min (font->min_bounds.rbearing,
7987 pcm->rbearing);
7988 font->min_bounds.width = min (font->min_bounds.width,
7989 pcm->width);
7990 font->min_bounds.ascent = min (font->min_bounds.ascent,
7991 pcm->ascent);
7993 font->max_bounds.lbearing = max (font->max_bounds.lbearing,
7994 pcm->lbearing);
7995 font->max_bounds.rbearing = max (font->max_bounds.rbearing,
7996 pcm->rbearing);
7997 font->max_bounds.width = max (font->max_bounds.width,
7998 pcm->width);
7999 font->max_bounds.ascent = max (font->max_bounds.ascent,
8000 pcm->ascent);
8002 if (
8003 #if USE_ATSUI
8004 font->mac_style == NULL &&
8005 #endif
8006 font->max_bounds.width == font->min_bounds.width
8007 && font->min_bounds.lbearing >= 0
8008 && font->max_bounds.rbearing <= font->max_bounds.width)
8010 /* Fixed width and no overhangs. */
8011 xfree (font->bounds.per_char);
8012 font->bounds.per_char = NULL;
8016 #if !defined (MAC_OS8) || USE_ATSUI
8017 /* AppKit and WebKit do some adjustment to the heights of Courier,
8018 Helvetica, and Times. This only works on the environments where
8019 srcCopy text transfer mode is never used. */
8020 if (
8021 #ifdef MAC_OS8 /* implies USE_ATSUI */
8022 font->mac_style &&
8023 #endif
8024 (strcmp (family, "courier") == 0 || strcmp (family, "helvetica") == 0
8025 || strcmp (family, "times") == 0))
8026 font->ascent += (font->ascent + font->descent) * .15 + 0.5;
8027 #endif
8029 return font;
8033 void
8034 mac_unload_font (dpyinfo, font)
8035 struct mac_display_info *dpyinfo;
8036 XFontStruct *font;
8038 xfree (font->full_name);
8039 #if USE_ATSUI
8040 if (font->mac_style)
8042 int i;
8044 for (i = font->min_byte1; i <= font->max_byte1; i++)
8045 if (font->bounds.rows[i])
8046 xfree (font->bounds.rows[i]);
8047 xfree (font->bounds.rows);
8048 ATSUDisposeStyle (font->mac_style);
8050 else
8051 #endif
8052 if (font->bounds.per_char)
8053 xfree (font->bounds.per_char);
8054 #if USE_CG_TEXT_DRAWING
8055 if (font->cg_font)
8056 CGFontRelease (font->cg_font);
8057 if (font->cg_glyphs)
8058 xfree (font->cg_glyphs);
8059 #endif
8060 xfree (font);
8064 /* Load font named FONTNAME of the size SIZE for frame F, and return a
8065 pointer to the structure font_info while allocating it dynamically.
8066 If SIZE is 0, load any size of font.
8067 If loading is failed, return NULL. */
8069 struct font_info *
8070 x_load_font (f, fontname, size)
8071 struct frame *f;
8072 register char *fontname;
8073 int size;
8075 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
8076 Lisp_Object font_names;
8078 /* Get a list of all the fonts that match this name. Once we
8079 have a list of matching fonts, we compare them against the fonts
8080 we already have by comparing names. */
8081 font_names = x_list_fonts (f, build_string (fontname), size, 1);
8083 if (!NILP (font_names))
8085 Lisp_Object tail;
8086 int i;
8088 for (i = 0; i < dpyinfo->n_fonts; i++)
8089 for (tail = font_names; CONSP (tail); tail = XCDR (tail))
8090 if (dpyinfo->font_table[i].name
8091 && (!strcmp (dpyinfo->font_table[i].name,
8092 SDATA (XCAR (tail)))
8093 || !strcmp (dpyinfo->font_table[i].full_name,
8094 SDATA (XCAR (tail)))))
8095 return (dpyinfo->font_table + i);
8097 else
8098 return NULL;
8100 /* Load the font and add it to the table. */
8102 struct MacFontStruct *font;
8103 struct font_info *fontp;
8104 int i;
8106 fontname = (char *) SDATA (XCAR (font_names));
8108 BLOCK_INPUT;
8109 font = (MacFontStruct *) XLoadQueryFont (FRAME_MAC_DISPLAY (f), fontname);
8110 UNBLOCK_INPUT;
8111 if (!font)
8112 return NULL;
8114 /* Find a free slot in the font table. */
8115 for (i = 0; i < dpyinfo->n_fonts; ++i)
8116 if (dpyinfo->font_table[i].name == NULL)
8117 break;
8119 /* If no free slot found, maybe enlarge the font table. */
8120 if (i == dpyinfo->n_fonts
8121 && dpyinfo->n_fonts == dpyinfo->font_table_size)
8123 int sz;
8124 dpyinfo->font_table_size = max (16, 2 * dpyinfo->font_table_size);
8125 sz = dpyinfo->font_table_size * sizeof *dpyinfo->font_table;
8126 dpyinfo->font_table
8127 = (struct font_info *) xrealloc (dpyinfo->font_table, sz);
8130 fontp = dpyinfo->font_table + i;
8131 if (i == dpyinfo->n_fonts)
8132 ++dpyinfo->n_fonts;
8134 /* Now fill in the slots of *FONTP. */
8135 BLOCK_INPUT;
8136 bzero (fontp, sizeof (*fontp));
8137 fontp->font = font;
8138 fontp->font_idx = i;
8139 fontp->name = (char *) xmalloc (strlen (fontname) + 1);
8140 bcopy (fontname, fontp->name, strlen (fontname) + 1);
8142 if (font->min_bounds.width == font->max_bounds.width)
8144 /* Fixed width font. */
8145 fontp->average_width = fontp->space_width = font->min_bounds.width;
8147 else
8149 XChar2b char2b;
8150 XCharStruct *pcm;
8152 char2b.byte1 = 0x00, char2b.byte2 = 0x20;
8153 pcm = mac_per_char_metric (font, &char2b, 0);
8154 if (pcm)
8155 fontp->space_width = pcm->width;
8156 else
8157 fontp->space_width = FONT_WIDTH (font);
8159 if (pcm)
8161 int width = pcm->width;
8162 for (char2b.byte2 = 33; char2b.byte2 <= 126; char2b.byte2++)
8163 if ((pcm = mac_per_char_metric (font, &char2b, 0)) != NULL)
8164 width += pcm->width;
8165 fontp->average_width = width / 95;
8167 else
8168 fontp->average_width = FONT_WIDTH (font);
8171 fontp->full_name = (char *) xmalloc (strlen (font->full_name) + 1);
8172 bcopy (font->full_name, fontp->full_name, strlen (font->full_name) + 1);
8174 fontp->size = font->max_bounds.width;
8175 fontp->height = FONT_HEIGHT (font);
8177 /* For some font, ascent and descent in max_bounds field is
8178 larger than the above value. */
8179 int max_height = font->max_bounds.ascent + font->max_bounds.descent;
8180 if (max_height > fontp->height)
8181 fontp->height = max_height;
8184 /* The slot `encoding' specifies how to map a character
8185 code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
8186 the font code-points (0:0x20..0x7F, 1:0xA0..0xFF), or
8187 (0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF,
8188 2:0xA020..0xFF7F). For the moment, we don't know which charset
8189 uses this font. So, we set information in fontp->encoding[1]
8190 which is never used by any charset. If mapping can't be
8191 decided, set FONT_ENCODING_NOT_DECIDED. */
8192 if (font->mac_scriptcode == smJapanese)
8193 fontp->encoding[1] = 4;
8194 else
8196 fontp->encoding[1]
8197 = (font->max_byte1 == 0
8198 /* 1-byte font */
8199 ? (font->min_char_or_byte2 < 0x80
8200 ? (font->max_char_or_byte2 < 0x80
8201 ? 0 /* 0x20..0x7F */
8202 : FONT_ENCODING_NOT_DECIDED) /* 0x20..0xFF */
8203 : 1) /* 0xA0..0xFF */
8204 /* 2-byte font */
8205 : (font->min_byte1 < 0x80
8206 ? (font->max_byte1 < 0x80
8207 ? (font->min_char_or_byte2 < 0x80
8208 ? (font->max_char_or_byte2 < 0x80
8209 ? 0 /* 0x2020..0x7F7F */
8210 : FONT_ENCODING_NOT_DECIDED) /* 0x2020..0x7FFF */
8211 : 3) /* 0x20A0..0x7FFF */
8212 : FONT_ENCODING_NOT_DECIDED) /* 0x20??..0xA0?? */
8213 : (font->min_char_or_byte2 < 0x80
8214 ? (font->max_char_or_byte2 < 0x80
8215 ? 2 /* 0xA020..0xFF7F */
8216 : FONT_ENCODING_NOT_DECIDED) /* 0xA020..0xFFFF */
8217 : 1))); /* 0xA0A0..0xFFFF */
8220 #if 0 /* MAC_TODO: fill these out with more reasonably values */
8221 fontp->baseline_offset
8222 = (XGetFontProperty (font, dpyinfo->Xatom_MULE_BASELINE_OFFSET, &value)
8223 ? (long) value : 0);
8224 fontp->relative_compose
8225 = (XGetFontProperty (font, dpyinfo->Xatom_MULE_RELATIVE_COMPOSE, &value)
8226 ? (long) value : 0);
8227 fontp->default_ascent
8228 = (XGetFontProperty (font, dpyinfo->Xatom_MULE_DEFAULT_ASCENT, &value)
8229 ? (long) value : 0);
8230 #else
8231 fontp->baseline_offset = 0;
8232 fontp->relative_compose = 0;
8233 fontp->default_ascent = 0;
8234 #endif
8236 /* Set global flag fonts_changed_p to non-zero if the font loaded
8237 has a character with a smaller width than any other character
8238 before, or if the font loaded has a smaller height than any
8239 other font loaded before. If this happens, it will make a
8240 glyph matrix reallocation necessary. */
8241 fonts_changed_p |= x_compute_min_glyph_bounds (f);
8242 UNBLOCK_INPUT;
8243 return fontp;
8248 /* Return a pointer to struct font_info of a font named FONTNAME for
8249 frame F. If no such font is loaded, return NULL. */
8251 struct font_info *
8252 x_query_font (f, fontname)
8253 struct frame *f;
8254 register char *fontname;
8256 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
8257 int i;
8259 for (i = 0; i < dpyinfo->n_fonts; i++)
8260 if (dpyinfo->font_table[i].name
8261 && (!strcmp (dpyinfo->font_table[i].name, fontname)
8262 || !strcmp (dpyinfo->font_table[i].full_name, fontname)))
8263 return (dpyinfo->font_table + i);
8264 return NULL;
8268 /* Find a CCL program for a font specified by FONTP, and set the member
8269 `encoder' of the structure. */
8271 void
8272 x_find_ccl_program (fontp)
8273 struct font_info *fontp;
8275 Lisp_Object list, elt;
8277 for (list = Vfont_ccl_encoder_alist; CONSP (list); list = XCDR (list))
8279 elt = XCAR (list);
8280 if (CONSP (elt)
8281 && STRINGP (XCAR (elt))
8282 && (fast_c_string_match_ignore_case (XCAR (elt), fontp->name)
8283 >= 0))
8284 break;
8286 if (! NILP (list))
8288 struct ccl_program *ccl
8289 = (struct ccl_program *) xmalloc (sizeof (struct ccl_program));
8291 if (setup_ccl_program (ccl, XCDR (elt)) < 0)
8292 xfree (ccl);
8293 else
8294 fontp->font_encoder = ccl;
8300 /* The Mac Event loop code */
8302 #if !TARGET_API_MAC_CARBON
8303 #include <Events.h>
8304 #include <Quickdraw.h>
8305 #include <Balloons.h>
8306 #include <Devices.h>
8307 #include <Fonts.h>
8308 #include <Gestalt.h>
8309 #include <Menus.h>
8310 #include <Processes.h>
8311 #include <Sound.h>
8312 #include <ToolUtils.h>
8313 #include <TextUtils.h>
8314 #include <Dialogs.h>
8315 #include <Script.h>
8316 #include <Types.h>
8317 #include <Resources.h>
8319 #if __MWERKS__
8320 #include <unix.h>
8321 #endif
8322 #endif /* ! TARGET_API_MAC_CARBON */
8324 #define M_APPLE 128
8325 #define I_ABOUT 1
8327 #define WINDOW_RESOURCE 128
8328 #define TERM_WINDOW_RESOURCE 129
8330 #define DEFAULT_NUM_COLS 80
8332 #define MIN_DOC_SIZE 64
8333 #define MAX_DOC_SIZE 32767
8335 #define EXTRA_STACK_ALLOC (256 * 1024)
8337 #define ARGV_STRING_LIST_ID 129
8338 #define ABOUT_ALERT_ID 128
8339 #define RAM_TOO_LARGE_ALERT_ID 129
8341 /* Contains the string "reverse", which is a constant for mouse button emu.*/
8342 Lisp_Object Qreverse;
8345 /* Modifier associated with the control key, or nil to ignore. */
8346 Lisp_Object Vmac_control_modifier;
8348 /* Modifier associated with the option key, or nil to ignore. */
8349 Lisp_Object Vmac_option_modifier;
8351 /* Modifier associated with the command key, or nil to ignore. */
8352 Lisp_Object Vmac_command_modifier;
8354 /* Modifier associated with the function key, or nil to ignore. */
8355 Lisp_Object Vmac_function_modifier;
8357 /* True if the option and command modifiers should be used to emulate
8358 a three button mouse */
8359 Lisp_Object Vmac_emulate_three_button_mouse;
8361 #if USE_CARBON_EVENTS
8362 /* Non-zero if the mouse wheel button (i.e. button 4) should map to
8363 mouse-2, instead of mouse-3. */
8364 int mac_wheel_button_is_mouse_2;
8366 /* If non-zero, the Mac "Command" key is passed on to the Mac Toolbox
8367 for processing before Emacs sees it. */
8368 int mac_pass_command_to_system;
8370 /* If non-zero, the Mac "Control" key is passed on to the Mac Toolbox
8371 for processing before Emacs sees it. */
8372 int mac_pass_control_to_system;
8373 #endif
8375 /* Points to the variable `inev' in the function XTread_socket. It is
8376 used for passing an input event to the function back from
8377 Carbon/Apple event handlers. */
8378 static struct input_event *read_socket_inev = NULL;
8380 Point saved_menu_event_location;
8382 /* Apple Events */
8383 #if USE_CARBON_EVENTS
8384 static Lisp_Object Qhicommand;
8385 #endif
8386 extern int mac_ready_for_apple_events;
8387 extern Lisp_Object Qundefined;
8388 extern void init_apple_event_handler P_ ((void));
8389 extern void mac_find_apple_event_spec P_ ((AEEventClass, AEEventID,
8390 Lisp_Object *, Lisp_Object *,
8391 Lisp_Object *));
8392 extern OSErr init_coercion_handler P_ ((void));
8394 #if TARGET_API_MAC_CARBON
8395 /* Drag and Drop */
8396 static pascal OSErr mac_do_track_drag (DragTrackingMessage, WindowPtr, void*, DragReference);
8397 static pascal OSErr mac_do_receive_drag (WindowPtr, void*, DragReference);
8398 static DragTrackingHandlerUPP mac_do_track_dragUPP = NULL;
8399 static DragReceiveHandlerUPP mac_do_receive_dragUPP = NULL;
8400 #endif
8402 #if USE_CARBON_EVENTS
8403 #ifdef MAC_OSX
8404 extern void init_service_handler ();
8405 static Lisp_Object Qservices, Qpaste, Qperform;
8406 #endif
8407 /* Window Event Handler */
8408 static pascal OSStatus mac_handle_window_event (EventHandlerCallRef,
8409 EventRef, void *);
8410 #endif
8411 OSErr install_window_handler (WindowPtr);
8413 extern void init_emacs_passwd_dir ();
8414 extern int emacs_main (int, char **, char **);
8416 extern void initialize_applescript();
8417 extern void terminate_applescript();
8419 static unsigned int
8420 #if USE_CARBON_EVENTS
8421 mac_to_emacs_modifiers (UInt32 mods)
8422 #else
8423 mac_to_emacs_modifiers (EventModifiers mods)
8424 #endif
8426 unsigned int result = 0;
8427 if (mods & shiftKey)
8428 result |= shift_modifier;
8430 /* Deactivated to simplify configuration:
8431 if Vmac_option_modifier is non-NIL, we fully process the Option
8432 key. Otherwise, we only process it if an additional Ctrl or Command
8433 is pressed. That way the system may convert the character to a
8434 composed one.
8435 if ((mods & optionKey) &&
8436 (( !NILP(Vmac_option_modifier) ||
8437 ((mods & cmdKey) || (mods & controlKey))))) */
8439 if (!NILP (Vmac_option_modifier) && (mods & optionKey)) {
8440 Lisp_Object val = Fget(Vmac_option_modifier, Qmodifier_value);
8441 if (INTEGERP(val))
8442 result |= XUINT(val);
8444 if (!NILP (Vmac_command_modifier) && (mods & cmdKey)) {
8445 Lisp_Object val = Fget(Vmac_command_modifier, Qmodifier_value);
8446 if (INTEGERP(val))
8447 result |= XUINT(val);
8449 if (!NILP (Vmac_control_modifier) && (mods & controlKey)) {
8450 Lisp_Object val = Fget(Vmac_control_modifier, Qmodifier_value);
8451 if (INTEGERP(val))
8452 result |= XUINT(val);
8455 #ifdef MAC_OSX
8456 if (!NILP (Vmac_function_modifier) && (mods & kEventKeyModifierFnMask)) {
8457 Lisp_Object val = Fget(Vmac_function_modifier, Qmodifier_value);
8458 if (INTEGERP(val))
8459 result |= XUINT(val);
8461 #endif
8463 return result;
8466 static int
8467 mac_get_emulated_btn ( UInt32 modifiers )
8469 int result = 0;
8470 if (!NILP (Vmac_emulate_three_button_mouse)) {
8471 int cmdIs3 = !EQ (Vmac_emulate_three_button_mouse, Qreverse);
8472 if (modifiers & cmdKey)
8473 result = cmdIs3 ? 2 : 1;
8474 else if (modifiers & optionKey)
8475 result = cmdIs3 ? 1 : 2;
8477 return result;
8480 #if USE_CARBON_EVENTS
8481 /* Obtains the event modifiers from the event ref and then calls
8482 mac_to_emacs_modifiers. */
8483 static UInt32
8484 mac_event_to_emacs_modifiers (EventRef eventRef)
8486 UInt32 mods = 0;
8487 GetEventParameter (eventRef, kEventParamKeyModifiers, typeUInt32, NULL,
8488 sizeof (UInt32), NULL, &mods);
8489 if (!NILP (Vmac_emulate_three_button_mouse) &&
8490 GetEventClass(eventRef) == kEventClassMouse)
8492 mods &= ~(optionKey | cmdKey);
8494 return mac_to_emacs_modifiers (mods);
8497 /* Given an event ref, return the code to use for the mouse button
8498 code in the emacs input_event. */
8499 static int
8500 mac_get_mouse_btn (EventRef ref)
8502 EventMouseButton result = kEventMouseButtonPrimary;
8503 GetEventParameter (ref, kEventParamMouseButton, typeMouseButton, NULL,
8504 sizeof (EventMouseButton), NULL, &result);
8505 switch (result)
8507 case kEventMouseButtonPrimary:
8508 if (NILP (Vmac_emulate_three_button_mouse))
8509 return 0;
8510 else {
8511 UInt32 mods = 0;
8512 GetEventParameter (ref, kEventParamKeyModifiers, typeUInt32, NULL,
8513 sizeof (UInt32), NULL, &mods);
8514 return mac_get_emulated_btn(mods);
8516 case kEventMouseButtonSecondary:
8517 return mac_wheel_button_is_mouse_2 ? 2 : 1;
8518 case kEventMouseButtonTertiary:
8519 case 4: /* 4 is the number for the mouse wheel button */
8520 return mac_wheel_button_is_mouse_2 ? 1 : 2;
8521 default:
8522 return 0;
8526 /* Normally, ConvertEventRefToEventRecord will correctly handle all
8527 events. However the click of the mouse wheel is not converted to a
8528 mouseDown or mouseUp event. Likewise for dead key down events.
8529 This calls ConvertEventRef, but then checks to see if it is a mouse
8530 up/down, or a dead key down carbon event that has not been
8531 converted, and if so, converts it by hand (to be picked up in the
8532 XTread_socket loop). */
8533 static Boolean mac_convert_event_ref (EventRef eventRef, EventRecord *eventRec)
8535 OSStatus err;
8536 Boolean result = ConvertEventRefToEventRecord (eventRef, eventRec);
8538 if (result)
8539 return result;
8541 switch (GetEventClass (eventRef))
8543 case kEventClassMouse:
8544 switch (GetEventKind (eventRef))
8546 case kEventMouseDown:
8547 eventRec->what = mouseDown;
8548 result = 1;
8549 break;
8551 case kEventMouseUp:
8552 eventRec->what = mouseUp;
8553 result = 1;
8554 break;
8556 default:
8557 break;
8559 break;
8561 case kEventClassKeyboard:
8562 switch (GetEventKind (eventRef))
8564 case kEventRawKeyDown:
8566 unsigned char char_codes;
8567 UInt32 key_code;
8569 err = GetEventParameter (eventRef, kEventParamKeyMacCharCodes,
8570 typeChar, NULL, sizeof (char),
8571 NULL, &char_codes);
8572 if (err == noErr)
8573 err = GetEventParameter (eventRef, kEventParamKeyCode,
8574 typeUInt32, NULL, sizeof (UInt32),
8575 NULL, &key_code);
8576 if (err == noErr)
8578 eventRec->what = keyDown;
8579 eventRec->message = char_codes | ((key_code & 0xff) << 8);
8580 result = 1;
8583 break;
8585 default:
8586 break;
8588 break;
8590 default:
8591 break;
8594 if (result)
8596 /* Need where and when. */
8597 UInt32 mods = 0;
8599 GetEventParameter (eventRef, kEventParamMouseLocation, typeQDPoint,
8600 NULL, sizeof (Point), NULL, &eventRec->where);
8601 /* Use two step process because new event modifiers are 32-bit
8602 and old are 16-bit. Currently, only loss is NumLock & Fn. */
8603 GetEventParameter (eventRef, kEventParamKeyModifiers, typeUInt32,
8604 NULL, sizeof (UInt32), NULL, &mods);
8605 eventRec->modifiers = mods;
8607 eventRec->when = EventTimeToTicks (GetEventTime (eventRef));
8610 return result;
8613 #endif
8615 #ifdef MAC_OS8
8616 static void
8617 do_get_menus (void)
8619 Handle menubar_handle;
8620 MenuHandle menu_handle;
8622 menubar_handle = GetNewMBar (128);
8623 if(menubar_handle == NULL)
8624 abort ();
8625 SetMenuBar (menubar_handle);
8626 DrawMenuBar ();
8628 #if !TARGET_API_MAC_CARBON
8629 menu_handle = GetMenuHandle (M_APPLE);
8630 if(menu_handle != NULL)
8631 AppendResMenu (menu_handle,'DRVR');
8632 else
8633 abort ();
8634 #endif
8638 static void
8639 do_init_managers (void)
8641 #if !TARGET_API_MAC_CARBON
8642 InitGraf (&qd.thePort);
8643 InitFonts ();
8644 FlushEvents (everyEvent, 0);
8645 InitWindows ();
8646 InitMenus ();
8647 TEInit ();
8648 InitDialogs (NULL);
8649 #endif /* !TARGET_API_MAC_CARBON */
8650 InitCursor ();
8652 #if !TARGET_API_MAC_CARBON
8653 /* set up some extra stack space for use by emacs */
8654 SetApplLimit ((Ptr) ((long) GetApplLimit () - EXTRA_STACK_ALLOC));
8656 /* MaxApplZone must be called for AppleScript to execute more
8657 complicated scripts */
8658 MaxApplZone ();
8659 MoreMasters ();
8660 #endif /* !TARGET_API_MAC_CARBON */
8663 static void
8664 do_check_ram_size (void)
8666 SInt32 physical_ram_size, logical_ram_size;
8668 if (Gestalt (gestaltPhysicalRAMSize, &physical_ram_size) != noErr
8669 || Gestalt (gestaltLogicalRAMSize, &logical_ram_size) != noErr
8670 || physical_ram_size > (1 << VALBITS)
8671 || logical_ram_size > (1 << VALBITS))
8673 StopAlert (RAM_TOO_LARGE_ALERT_ID, NULL);
8674 exit (1);
8677 #endif /* MAC_OS8 */
8679 static void
8680 do_window_update (WindowPtr win)
8682 struct frame *f = mac_window_to_frame (win);
8684 BeginUpdate (win);
8686 /* The tooltip has been drawn already. Avoid the SET_FRAME_GARBAGED
8687 below. */
8688 if (win != tip_window)
8690 if (f->async_visible == 0)
8692 /* Update events may occur when a frame gets iconified. */
8693 #if 0
8694 f->async_visible = 1;
8695 f->async_iconified = 0;
8696 SET_FRAME_GARBAGED (f);
8697 #endif
8699 else
8701 Rect r;
8702 #if TARGET_API_MAC_CARBON
8703 RgnHandle region = NewRgn ();
8705 GetPortVisibleRegion (GetWindowPort (win), region);
8706 GetRegionBounds (region, &r);
8707 expose_frame (f, r.left, r.top, r.right - r.left, r.bottom - r.top);
8708 UpdateControls (win, region);
8709 DisposeRgn (region);
8710 #else
8711 r = (*win->visRgn)->rgnBBox;
8712 expose_frame (f, r.left, r.top, r.right - r.left, r.bottom - r.top);
8713 UpdateControls (win, win->visRgn);
8714 #endif
8718 EndUpdate (win);
8721 static int
8722 is_emacs_window (WindowPtr win)
8724 Lisp_Object tail, frame;
8726 if (!win)
8727 return 0;
8729 FOR_EACH_FRAME (tail, frame)
8730 if (FRAME_MAC_P (XFRAME (frame)))
8731 if (FRAME_MAC_WINDOW (XFRAME (frame)) == win)
8732 return 1;
8734 return 0;
8737 static void
8738 do_app_resume ()
8740 /* Window-activate events will do the job. */
8743 static void
8744 do_app_suspend ()
8746 /* Window-deactivate events will do the job. */
8750 static void
8751 do_apple_menu (SInt16 menu_item)
8753 #if !TARGET_API_MAC_CARBON
8754 Str255 item_name;
8755 SInt16 da_driver_refnum;
8757 if (menu_item == I_ABOUT)
8758 NoteAlert (ABOUT_ALERT_ID, NULL);
8759 else
8761 GetMenuItemText (GetMenuHandle (M_APPLE), menu_item, item_name);
8762 da_driver_refnum = OpenDeskAcc (item_name);
8764 #endif /* !TARGET_API_MAC_CARBON */
8767 void
8768 do_menu_choice (SInt32 menu_choice)
8770 SInt16 menu_id, menu_item;
8772 menu_id = HiWord (menu_choice);
8773 menu_item = LoWord (menu_choice);
8775 switch (menu_id)
8777 case 0:
8778 break;
8780 case M_APPLE:
8781 do_apple_menu (menu_item);
8782 break;
8784 default:
8786 struct frame *f = mac_focus_frame (&one_mac_display_info);
8787 MenuHandle menu = GetMenuHandle (menu_id);
8788 if (menu)
8790 UInt32 refcon;
8792 GetMenuItemRefCon (menu, menu_item, &refcon);
8793 menubar_selection_callback (f, refcon);
8798 HiliteMenu (0);
8802 /* Handle drags in size box. Based on code contributed by Ben
8803 Mesander and IM - Window Manager A. */
8805 static void
8806 do_grow_window (WindowPtr w, EventRecord *e)
8808 Rect limit_rect;
8809 int rows, columns, width, height;
8810 struct frame *f = mac_window_to_frame (w);
8811 XSizeHints *size_hints = FRAME_SIZE_HINTS (f);
8812 int min_width = MIN_DOC_SIZE, min_height = MIN_DOC_SIZE;
8813 #if TARGET_API_MAC_CARBON
8814 Rect new_rect;
8815 #else
8816 long grow_size;
8817 #endif
8819 if (size_hints->flags & PMinSize)
8821 min_width = size_hints->min_width;
8822 min_height = size_hints->min_height;
8824 SetRect (&limit_rect, min_width, min_height, MAX_DOC_SIZE, MAX_DOC_SIZE);
8826 #if TARGET_API_MAC_CARBON
8827 if (!ResizeWindow (w, e->where, &limit_rect, &new_rect))
8828 return;
8829 height = new_rect.bottom - new_rect.top;
8830 width = new_rect.right - new_rect.left;
8831 #else
8832 grow_size = GrowWindow (w, e->where, &limit_rect);
8833 /* see if it really changed size */
8834 if (grow_size == 0)
8835 return;
8836 height = HiWord (grow_size);
8837 width = LoWord (grow_size);
8838 #endif
8840 if (width != FRAME_PIXEL_WIDTH (f)
8841 || height != FRAME_PIXEL_HEIGHT (f))
8843 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, height);
8844 columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, width);
8846 x_set_window_size (f, 0, columns, rows);
8851 /* Handle clicks in zoom box. Calculation of "standard state" based
8852 on code in IM - Window Manager A and code contributed by Ben
8853 Mesander. The standard state of an Emacs window is 80-characters
8854 wide (DEFAULT_NUM_COLS) and as tall as will fit on the screen. */
8856 static void
8857 do_zoom_window (WindowPtr w, int zoom_in_or_out)
8859 Rect zoom_rect, port_rect;
8860 int columns, rows, width, height;
8861 struct frame *f = mac_window_to_frame (w);
8862 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
8863 #if TARGET_API_MAC_CARBON
8864 Point standard_size;
8866 standard_size.h = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, DEFAULT_NUM_COLS);
8867 standard_size.v = dpyinfo->height;
8869 if (IsWindowInStandardState (w, &standard_size, &zoom_rect))
8870 zoom_in_or_out = inZoomIn;
8871 else
8873 /* Adjust the standard size according to character boundaries. */
8875 columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, zoom_rect.right - zoom_rect.left);
8876 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, zoom_rect.bottom - zoom_rect.top);
8877 standard_size.h = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, columns);
8878 standard_size.v = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
8879 GetWindowBounds (w, kWindowContentRgn, &port_rect);
8880 if (IsWindowInStandardState (w, &standard_size, &zoom_rect)
8881 && port_rect.left == zoom_rect.left
8882 && port_rect.top == zoom_rect.top)
8883 zoom_in_or_out = inZoomIn;
8884 else
8885 zoom_in_or_out = inZoomOut;
8888 ZoomWindowIdeal (w, zoom_in_or_out, &standard_size);
8889 #else /* not TARGET_API_MAC_CARBON */
8890 GrafPtr save_port;
8891 Point top_left;
8892 int w_title_height;
8894 GetPort (&save_port);
8896 SetPortWindowPort (w);
8898 /* Clear window to avoid flicker. */
8899 EraseRect (&(w->portRect));
8900 if (zoom_in_or_out == inZoomOut)
8902 SetPt (&top_left, w->portRect.left, w->portRect.top);
8903 LocalToGlobal (&top_left);
8905 /* calculate height of window's title bar */
8906 w_title_height = top_left.v - 1
8907 - (**((WindowPeek) w)->strucRgn).rgnBBox.top + GetMBarHeight ();
8909 /* get maximum height of window into zoom_rect.bottom - zoom_rect.top */
8910 zoom_rect = qd.screenBits.bounds;
8911 zoom_rect.top += w_title_height;
8912 InsetRect (&zoom_rect, 8, 4); /* not too tight */
8914 zoom_rect.right = zoom_rect.left
8915 + FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, DEFAULT_NUM_COLS);
8917 /* Adjust the standard size according to character boundaries. */
8918 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, zoom_rect.bottom - zoom_rect.top);
8919 zoom_rect.bottom =
8920 zoom_rect.top + FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
8922 (**((WStateDataHandle) ((WindowPeek) w)->dataHandle)).stdState
8923 = zoom_rect;
8926 ZoomWindow (w, zoom_in_or_out, f == mac_focus_frame (dpyinfo));
8928 SetPort (save_port);
8929 #endif /* not TARGET_API_MAC_CARBON */
8931 /* retrieve window size and update application values */
8932 #if TARGET_API_MAC_CARBON
8933 GetWindowPortBounds (w, &port_rect);
8934 #else
8935 port_rect = w->portRect;
8936 #endif
8937 height = port_rect.bottom - port_rect.top;
8938 width = port_rect.right - port_rect.left;
8940 if (width != FRAME_PIXEL_WIDTH (f)
8941 || height != FRAME_PIXEL_HEIGHT (f))
8943 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, height);
8944 columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, width);
8946 change_frame_size (f, rows, columns, 0, 1, 0);
8947 SET_FRAME_GARBAGED (f);
8948 cancel_mouse_face (f);
8950 FRAME_PIXEL_WIDTH (f) = width;
8951 FRAME_PIXEL_HEIGHT (f) = height;
8953 x_real_positions (f, &f->left_pos, &f->top_pos);
8956 OSErr
8957 mac_store_apple_event (class, id, desc)
8958 Lisp_Object class, id;
8959 const AEDesc *desc;
8961 OSErr err = noErr;
8962 struct input_event buf;
8963 AEDesc *desc_copy;
8965 desc_copy = xmalloc (sizeof (AEDesc));
8966 if (desc_copy == NULL)
8967 err = memFullErr;
8968 else
8969 err = AEDuplicateDesc (desc, desc_copy);
8970 if (err == noErr)
8972 EVENT_INIT (buf);
8974 buf.kind = MAC_APPLE_EVENT;
8975 buf.x = class;
8976 buf.y = id;
8977 buf.code = (int)desc_copy;
8978 XSETFRAME (buf.frame_or_window,
8979 mac_focus_frame (&one_mac_display_info));
8980 buf.arg = Qnil;
8981 kbd_buffer_store_event (&buf);
8984 return err;
8987 Lisp_Object
8988 mac_make_lispy_event_code (code)
8989 int code;
8991 AEDesc *desc = (AEDesc *)code;
8992 Lisp_Object obj;
8994 obj = mac_aedesc_to_lisp (desc);
8995 AEDisposeDesc (desc);
8996 xfree (desc);
8998 return obj;
9001 #if USE_CARBON_EVENTS
9002 static pascal OSStatus
9003 mac_handle_command_event (next_handler, event, data)
9004 EventHandlerCallRef next_handler;
9005 EventRef event;
9006 void *data;
9008 OSStatus result, err;
9009 HICommand command;
9010 Lisp_Object class_key, id_key, binding;
9012 result = CallNextEventHandler (next_handler, event);
9013 if (result != eventNotHandledErr)
9014 return result;
9016 err = GetEventParameter (event, kEventParamDirectObject, typeHICommand,
9017 NULL, sizeof (HICommand), NULL, &command);
9019 if (err != noErr || command.commandID == 0)
9020 return eventNotHandledErr;
9022 /* A HICommand event is mapped to an Apple event whose event class
9023 symbol is `hicommand' and event ID is its command ID. */
9024 class_key = Qhicommand;
9025 mac_find_apple_event_spec (0, command.commandID,
9026 &class_key, &id_key, &binding);
9027 if (!NILP (binding) && !EQ (binding, Qundefined))
9029 if (INTEGERP (binding))
9030 return XINT (binding);
9031 else
9033 AppleEvent apple_event;
9034 static EventParamName names[] = {kEventParamDirectObject,
9035 kEventParamKeyModifiers};
9036 static EventParamType types[] = {typeHICommand,
9037 typeUInt32};
9038 err = create_apple_event_from_event_ref (event, 2, names, types,
9039 &apple_event);
9040 if (err == noErr)
9042 err = mac_store_apple_event (class_key, id_key, &apple_event);
9043 AEDisposeDesc (&apple_event);
9045 if (err == noErr)
9046 return noErr;
9050 return eventNotHandledErr;
9053 static OSErr
9054 init_command_handler ()
9056 EventTypeSpec specs[] = {{kEventClassCommand, kEventCommandProcess}};
9057 static EventHandlerUPP handle_command_eventUPP = NULL;
9059 if (handle_command_eventUPP == NULL)
9060 handle_command_eventUPP = NewEventHandlerUPP (mac_handle_command_event);
9061 return InstallApplicationEventHandler (handle_command_eventUPP,
9062 GetEventTypeCount (specs), specs,
9063 NULL, NULL);
9066 static pascal OSStatus
9067 mac_handle_window_event (next_handler, event, data)
9068 EventHandlerCallRef next_handler;
9069 EventRef event;
9070 void *data;
9072 WindowPtr wp;
9073 OSStatus result, err;
9074 UInt32 attributes;
9075 XSizeHints *size_hints;
9077 err = GetEventParameter (event, kEventParamDirectObject, typeWindowRef,
9078 NULL, sizeof (WindowPtr), NULL, &wp);
9079 if (err != noErr)
9080 return eventNotHandledErr;
9082 switch (GetEventKind (event))
9084 case kEventWindowUpdate:
9085 result = CallNextEventHandler (next_handler, event);
9086 if (result != eventNotHandledErr)
9087 return result;
9089 do_window_update (wp);
9090 return noErr;
9092 case kEventWindowBoundsChanging:
9093 result = CallNextEventHandler (next_handler, event);
9094 if (result != eventNotHandledErr)
9095 return result;
9097 err = GetEventParameter (event, kEventParamAttributes, typeUInt32,
9098 NULL, sizeof (UInt32), NULL, &attributes);
9099 if (err != noErr)
9100 break;
9102 size_hints = FRAME_SIZE_HINTS (mac_window_to_frame (wp));
9103 if ((attributes & kWindowBoundsChangeUserResize)
9104 && ((size_hints->flags & (PResizeInc | PBaseSize | PMinSize))
9105 == (PResizeInc | PBaseSize | PMinSize)))
9107 Rect bounds;
9108 int width, height;
9110 err = GetEventParameter (event, kEventParamCurrentBounds,
9111 typeQDRectangle, NULL, sizeof (Rect),
9112 NULL, &bounds);
9113 if (err != noErr)
9114 break;
9116 width = bounds.right - bounds.left;
9117 height = bounds.bottom - bounds.top;
9119 if (width < size_hints->min_width)
9120 width = size_hints->min_width;
9121 else
9122 width = size_hints->base_width
9123 + (int) ((width - size_hints->base_width)
9124 / (float) size_hints->width_inc + .5)
9125 * size_hints->width_inc;
9127 if (height < size_hints->min_height)
9128 height = size_hints->min_height;
9129 else
9130 height = size_hints->base_height
9131 + (int) ((height - size_hints->base_height)
9132 / (float) size_hints->height_inc + .5)
9133 * size_hints->height_inc;
9135 bounds.right = bounds.left + width;
9136 bounds.bottom = bounds.top + height;
9137 SetEventParameter (event, kEventParamCurrentBounds,
9138 typeQDRectangle, sizeof (Rect), &bounds);
9139 return noErr;
9141 break;
9143 case kEventWindowShown:
9144 case kEventWindowHidden:
9145 case kEventWindowExpanded:
9146 case kEventWindowCollapsed:
9147 result = CallNextEventHandler (next_handler, event);
9149 mac_handle_visibility_change (mac_window_to_frame (wp));
9150 return noErr;
9152 break;
9155 return eventNotHandledErr;
9158 static pascal OSStatus
9159 mac_handle_mouse_event (next_handler, event, data)
9160 EventHandlerCallRef next_handler;
9161 EventRef event;
9162 void *data;
9164 OSStatus result, err;
9166 switch (GetEventKind (event))
9168 case kEventMouseWheelMoved:
9170 WindowPtr wp;
9171 struct frame *f;
9172 EventMouseWheelAxis axis;
9173 SInt32 delta;
9174 Point point;
9176 result = CallNextEventHandler (next_handler, event);
9177 if (result != eventNotHandledErr || read_socket_inev == NULL)
9178 return result;
9180 err = GetEventParameter (event, kEventParamWindowRef, typeWindowRef,
9181 NULL, sizeof (WindowRef), NULL, &wp);
9182 if (err != noErr)
9183 break;
9185 f = mac_window_to_frame (wp);
9186 if (f != mac_focus_frame (&one_mac_display_info))
9187 break;
9189 err = GetEventParameter (event, kEventParamMouseWheelAxis,
9190 typeMouseWheelAxis, NULL,
9191 sizeof (EventMouseWheelAxis), NULL, &axis);
9192 if (err != noErr || axis != kEventMouseWheelAxisY)
9193 break;
9195 err = GetEventParameter (event, kEventParamMouseWheelDelta,
9196 typeSInt32, NULL, sizeof (SInt32),
9197 NULL, &delta);
9198 if (err != noErr)
9199 break;
9200 err = GetEventParameter (event, kEventParamMouseLocation,
9201 typeQDPoint, NULL, sizeof (Point),
9202 NULL, &point);
9203 if (err != noErr)
9204 break;
9205 read_socket_inev->kind = WHEEL_EVENT;
9206 read_socket_inev->code = 0;
9207 read_socket_inev->modifiers =
9208 (mac_event_to_emacs_modifiers (event)
9209 | ((delta < 0) ? down_modifier : up_modifier));
9210 SetPortWindowPort (wp);
9211 GlobalToLocal (&point);
9212 XSETINT (read_socket_inev->x, point.h);
9213 XSETINT (read_socket_inev->y, point.v);
9214 XSETFRAME (read_socket_inev->frame_or_window, f);
9216 return noErr;
9218 break;
9220 default:
9221 break;
9224 return eventNotHandledErr;
9227 #ifdef MAC_OSX
9228 OSErr
9229 mac_store_services_event (event)
9230 EventRef event;
9232 OSErr err;
9233 AppleEvent apple_event;
9234 Lisp_Object id_key;
9236 switch (GetEventKind (event))
9238 case kEventServicePaste:
9239 id_key = Qpaste;
9240 err = create_apple_event_from_event_ref (event, 0, NULL, NULL,
9241 &apple_event);
9242 break;
9244 case kEventServicePerform:
9246 static EventParamName names[] = {kEventParamServiceMessageName,
9247 kEventParamServiceUserData};
9248 static EventParamType types[] = {typeCFStringRef,
9249 typeCFStringRef};
9251 id_key = Qperform;
9252 err = create_apple_event_from_event_ref (event, 2, names, types,
9253 &apple_event);
9255 break;
9257 default:
9258 abort ();
9261 if (err == noErr)
9263 err = mac_store_apple_event (Qservices, id_key, &apple_event);
9264 AEDisposeDesc (&apple_event);
9267 return err;
9269 #endif /* MAC_OSX */
9270 #endif /* USE_CARBON_EVENTS */
9273 OSErr
9274 install_window_handler (window)
9275 WindowPtr window;
9277 OSErr err = noErr;
9278 #if USE_CARBON_EVENTS
9279 EventTypeSpec specs_window[] =
9280 {{kEventClassWindow, kEventWindowUpdate},
9281 {kEventClassWindow, kEventWindowBoundsChanging},
9282 {kEventClassWindow, kEventWindowShown},
9283 {kEventClassWindow, kEventWindowHidden},
9284 {kEventClassWindow, kEventWindowExpanded},
9285 {kEventClassWindow, kEventWindowCollapsed}};
9286 EventTypeSpec specs_mouse[] = {{kEventClassMouse, kEventMouseWheelMoved}};
9287 static EventHandlerUPP handle_window_eventUPP = NULL;
9288 static EventHandlerUPP handle_mouse_eventUPP = NULL;
9290 if (handle_window_eventUPP == NULL)
9291 handle_window_eventUPP = NewEventHandlerUPP (mac_handle_window_event);
9292 if (handle_mouse_eventUPP == NULL)
9293 handle_mouse_eventUPP = NewEventHandlerUPP (mac_handle_mouse_event);
9294 err = InstallWindowEventHandler (window, handle_window_eventUPP,
9295 GetEventTypeCount (specs_window),
9296 specs_window, NULL, NULL);
9297 if (err == noErr)
9298 err = InstallWindowEventHandler (window, handle_mouse_eventUPP,
9299 GetEventTypeCount (specs_mouse),
9300 specs_mouse, NULL, NULL);
9301 #endif
9302 #if TARGET_API_MAC_CARBON
9303 if (mac_do_track_dragUPP == NULL)
9304 mac_do_track_dragUPP = NewDragTrackingHandlerUPP (mac_do_track_drag);
9305 if (mac_do_receive_dragUPP == NULL)
9306 mac_do_receive_dragUPP = NewDragReceiveHandlerUPP (mac_do_receive_drag);
9308 if (err == noErr)
9309 err = InstallTrackingHandler (mac_do_track_dragUPP, window, NULL);
9310 if (err == noErr)
9311 err = InstallReceiveHandler (mac_do_receive_dragUPP, window, NULL);
9312 #endif
9313 return err;
9316 void
9317 remove_window_handler (window)
9318 WindowPtr window;
9320 #if TARGET_API_MAC_CARBON
9321 if (mac_do_track_dragUPP)
9322 RemoveTrackingHandler (mac_do_track_dragUPP, window);
9323 if (mac_do_receive_dragUPP)
9324 RemoveReceiveHandler (mac_do_receive_dragUPP, window);
9325 #endif
9328 #if TARGET_API_MAC_CARBON
9329 static pascal OSErr
9330 mac_do_track_drag (DragTrackingMessage message, WindowPtr window,
9331 void *handlerRefCon, DragReference theDrag)
9333 static int can_accept;
9334 short items;
9335 short index;
9336 ItemReference theItem;
9337 FlavorFlags theFlags;
9338 OSErr result;
9340 if (GetFrontWindowOfClass (kMovableModalWindowClass, false))
9341 return dragNotAcceptedErr;
9343 switch (message)
9345 case kDragTrackingEnterHandler:
9346 CountDragItems (theDrag, &items);
9347 can_accept = 0;
9348 for (index = 1; index <= items; index++)
9350 GetDragItemReferenceNumber (theDrag, index, &theItem);
9351 result = GetFlavorFlags (theDrag, theItem, flavorTypeHFS, &theFlags);
9352 if (result == noErr)
9354 can_accept = 1;
9355 break;
9358 break;
9360 case kDragTrackingEnterWindow:
9361 if (can_accept)
9363 RgnHandle hilite_rgn = NewRgn ();
9364 Rect r;
9365 struct frame *f = mac_window_to_frame (window);
9367 GetWindowPortBounds (window, &r);
9368 OffsetRect (&r, -r.left, -r.top);
9369 RectRgn (hilite_rgn, &r);
9370 ShowDragHilite (theDrag, hilite_rgn, true);
9371 DisposeRgn (hilite_rgn);
9372 SetThemeCursor (kThemeCopyArrowCursor);
9374 break;
9376 case kDragTrackingInWindow:
9377 break;
9379 case kDragTrackingLeaveWindow:
9380 if (can_accept)
9382 struct frame *f = mac_window_to_frame (window);
9384 HideDragHilite (theDrag);
9385 SetThemeCursor (kThemeArrowCursor);
9387 break;
9389 case kDragTrackingLeaveHandler:
9390 break;
9393 return noErr;
9396 static pascal OSErr
9397 mac_do_receive_drag (WindowPtr window, void *handlerRefCon,
9398 DragReference theDrag)
9400 short items;
9401 short index;
9402 FlavorFlags theFlags;
9403 Point mouse;
9404 OSErr result;
9405 ItemReference theItem;
9406 HFSFlavor data;
9407 Size size = sizeof (HFSFlavor);
9408 Lisp_Object file_list;
9410 if (GetFrontWindowOfClass (kMovableModalWindowClass, false))
9411 return dragNotAcceptedErr;
9413 file_list = Qnil;
9414 GetDragMouse (theDrag, &mouse, 0L);
9415 CountDragItems (theDrag, &items);
9416 for (index = 1; index <= items; index++)
9418 /* Only handle file references. */
9419 GetDragItemReferenceNumber (theDrag, index, &theItem);
9420 result = GetFlavorFlags (theDrag, theItem, flavorTypeHFS, &theFlags);
9421 if (result == noErr)
9423 OSErr err;
9424 AEDesc desc;
9426 err = GetFlavorData (theDrag, theItem, flavorTypeHFS,
9427 &data, &size, 0L);
9428 if (err == noErr)
9429 err = AECoercePtr (typeFSS, &data.fileSpec, sizeof (FSSpec),
9430 TYPE_FILE_NAME, &desc);
9431 if (err == noErr)
9433 Lisp_Object file;
9435 /* x-dnd functions expect undecoded filenames. */
9436 file = make_uninit_string (AEGetDescDataSize (&desc));
9437 err = AEGetDescData (&desc, SDATA (file), SBYTES (file));
9438 if (err == noErr)
9439 file_list = Fcons (file, file_list);
9440 AEDisposeDesc (&desc);
9444 /* If there are items in the list, construct an event and post it to
9445 the queue like an interrupt using kbd_buffer_store_event. */
9446 if (!NILP (file_list))
9448 struct input_event event;
9449 Lisp_Object frame;
9450 struct frame *f = mac_window_to_frame (window);
9451 SInt16 modifiers;
9453 GlobalToLocal (&mouse);
9454 GetDragModifiers (theDrag, NULL, NULL, &modifiers);
9456 event.kind = DRAG_N_DROP_EVENT;
9457 event.code = 0;
9458 event.modifiers = mac_to_emacs_modifiers (modifiers);
9459 event.timestamp = TickCount () * (1000 / 60);
9460 XSETINT (event.x, mouse.h);
9461 XSETINT (event.y, mouse.v);
9462 XSETFRAME (frame, f);
9463 event.frame_or_window = frame;
9464 event.arg = file_list;
9465 /* Post to the interrupt queue */
9466 kbd_buffer_store_event (&event);
9467 /* MAC_TODO: Mimic behavior of windows by switching contexts to Emacs */
9469 ProcessSerialNumber psn;
9470 GetCurrentProcess (&psn);
9471 SetFrontProcess (&psn);
9474 return noErr;
9476 else
9477 return dragNotAcceptedErr;
9479 #endif
9482 #if __profile__
9483 void
9484 profiler_exit_proc ()
9486 ProfilerDump ("\pEmacs.prof");
9487 ProfilerTerm ();
9489 #endif
9491 /* These few functions implement Emacs as a normal Mac application
9492 (almost): set up the heap and the Toolbox, handle necessary system
9493 events plus a few simple menu events. They also set up Emacs's
9494 access to functions defined in the rest of this file. Emacs uses
9495 function hooks to perform all its terminal I/O. A complete list of
9496 these functions appear in termhooks.h. For what they do, read the
9497 comments there and see also w32term.c and xterm.c. What's
9498 noticeably missing here is the event loop, which is normally
9499 present in most Mac application. After performing the necessary
9500 Mac initializations, main passes off control to emacs_main
9501 (corresponding to main in emacs.c). Emacs_main calls XTread_socket
9502 (defined further below) to read input. This is where
9503 WaitNextEvent/ReceiveNextEvent is called to process Mac events. */
9505 #ifdef MAC_OS8
9506 #undef main
9508 main (void)
9510 #if __profile__ /* is the profiler on? */
9511 if (ProfilerInit(collectDetailed, bestTimeBase, 5000, 200))
9512 exit(1);
9513 #endif
9515 #if __MWERKS__
9516 /* set creator and type for files created by MSL */
9517 _fcreator = 'EMAx';
9518 _ftype = 'TEXT';
9519 #endif
9521 do_init_managers ();
9523 do_get_menus ();
9525 #ifndef USE_LSB_TAG
9526 do_check_ram_size ();
9527 #endif
9529 init_emacs_passwd_dir ();
9531 init_environ ();
9533 init_coercion_handler ();
9535 initialize_applescript ();
9537 init_apple_event_handler ();
9540 char **argv;
9541 int argc = 0;
9543 /* set up argv array from STR# resource */
9544 get_string_list (&argv, ARGV_STRING_LIST_ID);
9545 while (argv[argc])
9546 argc++;
9548 /* free up AppleScript resources on exit */
9549 atexit (terminate_applescript);
9551 #if __profile__ /* is the profiler on? */
9552 atexit (profiler_exit_proc);
9553 #endif
9555 /* 3rd param "envp" never used in emacs_main */
9556 (void) emacs_main (argc, argv, 0);
9559 /* Never reached - real exit in Fkill_emacs */
9560 return 0;
9562 #endif
9564 /* Table for translating Mac keycode to X keysym values. Contributed
9565 by Sudhir Shenoy.
9566 Mapping for special keys is now identical to that in Apple X11
9567 except `clear' (-> <clear>) on the KeyPad, `enter' (-> <kp-enter>)
9568 on the right of the Cmd key on laptops, and fn + `enter' (->
9569 <linefeed>). */
9570 static unsigned char keycode_to_xkeysym_table[] = {
9571 /*0x00*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9572 /*0x10*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9573 /*0x20*/ 0, 0, 0, 0, 0x0d /*return*/, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9575 /*0x30*/ 0x09 /*tab*/, 0 /*0x0020 space*/, 0, 0x08 /*backspace*/,
9576 /*0x34*/ 0x8d /*enter on laptops*/, 0x1b /*escape*/, 0, 0,
9577 /*0x38*/ 0, 0, 0, 0,
9578 /*0x3C*/ 0, 0, 0, 0,
9580 /*0x40*/ 0, 0xae /*kp-.*/, 0, 0xaa /*kp-**/,
9581 /*0x44*/ 0, 0xab /*kp-+*/, 0, 0x0b /*clear*/,
9582 /*0x48*/ 0, 0, 0, 0xaf /*kp-/*/,
9583 /*0x4C*/ 0x8d /*kp-enter*/, 0, 0xad /*kp--*/, 0,
9585 /*0x50*/ 0, 0xbd /*kp-=*/, 0xb0 /*kp-0*/, 0xb1 /*kp-1*/,
9586 /*0x54*/ 0xb2 /*kp-2*/, 0xb3 /*kp-3*/, 0xb4 /*kp-4*/, 0xb5 /*kp-5*/,
9587 /*0x58*/ 0xb6 /*kp-6*/, 0xb7 /*kp-7*/, 0, 0xb8 /*kp-8*/,
9588 /*0x5C*/ 0xb9 /*kp-9*/, 0, 0, 0,
9590 /*0x60*/ 0xc2 /*f5*/, 0xc3 /*f6*/, 0xc4 /*f7*/, 0xc0 /*f3*/,
9591 /*0x64*/ 0xc5 /*f8*/, 0xc6 /*f9*/, 0, 0xc8 /*f11*/,
9592 /*0x68*/ 0, 0xca /*f13*/, 0, 0xcb /*f14*/,
9593 /*0x6C*/ 0, 0xc7 /*f10*/, 0x0a /*fn+enter on laptops*/, 0xc9 /*f12*/,
9595 /*0x70*/ 0, 0xcc /*f15*/, 0x6a /*help*/, 0x50 /*home*/,
9596 /*0x74*/ 0x55 /*pgup*/, 0xff /*delete*/, 0xc1 /*f4*/, 0x57 /*end*/,
9597 /*0x78*/ 0xbf /*f2*/, 0x56 /*pgdown*/, 0xbe /*f1*/, 0x51 /*left*/,
9598 /*0x7C*/ 0x53 /*right*/, 0x54 /*down*/, 0x52 /*up*/, 0
9602 static int
9603 keycode_to_xkeysym (int keyCode, int *xKeySym)
9605 *xKeySym = keycode_to_xkeysym_table [keyCode & 0x7f];
9606 return *xKeySym != 0;
9609 static unsigned char fn_keycode_to_xkeysym_table[] = {
9610 /*0x00*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9611 /*0x10*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9612 /*0x20*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9614 /*0x30*/ 0, 0, 0, 0,
9615 /*0x34*/ 0, 0, 0, 0,
9616 /*0x38*/ 0, 0, 0, 0,
9617 /*0x3C*/ 0, 0, 0, 0,
9619 /*0x40*/ 0, 0x2e /*kp-. = .*/, 0, 0x50 /*kp-* = 'p'*/,
9620 /*0x44*/ 0, '/' /*kp-+*/, 0, 0,
9621 /*0x48*/ 0, 0, 0, 0x30 /*kp-/ = '0'*/,
9622 /*0x4C*/ 0, 0, 0x3b /*kp-- = ';'*/, 0,
9624 /*0x50*/ 0, 0x2d /*kp-= = '-'*/, 0x6d /*kp-0 = 'm'*/, 0x6a /*kp-1 = 'j'*/,
9625 /*0x54*/ 0x6b /*kp-2 = 'k'*/, 0x6c /*kp-3 = 'l'*/, 'u' /*kp-4*/, 'i' /*kp-5*/,
9626 /*0x58*/ 'o' /*kp-6*/, '7' /*kp-7*/, 0, '8' /*kp-8*/,
9627 /*0x5C*/ '9' /*kp-9*/, 0, 0, 0,
9629 /*0x60*/ 0, 0, 0, 0,
9630 /*0x64*/ 0, 0, 0, 0,
9631 /*0x68*/ 0, 0, 0, 0,
9632 /*0x6C*/ 0, 0, 0, 0,
9634 /*0x70*/ 0, 0, 0, 0,
9635 /*0x74*/ 0, 0, 0, 0,
9636 /*0x78*/ 0, 0, 0, 0,
9637 /*0x7C*/ 0, 0, 0, 0
9639 static int
9640 convert_fn_keycode (EventRef eventRef, int keyCode, int *newCode)
9642 #ifdef MAC_OSX
9643 /* Use the special map to translate keys when function modifier is
9644 to be caught. KeyTranslate can't be used in that case.
9645 We can't detect the function key using the input_event.modifiers,
9646 because this uses the high word of an UInt32. Therefore,
9647 we'll just read it out of the original eventRef.
9651 /* TODO / known issues
9653 - Fn-Shift-j is regonized as Fn-j and not Fn-J.
9654 The above table always translates to lower characters. We need to use
9655 the KCHR keyboard resource (KeyTranslate() ) to map k->K and 8->*.
9657 - The table is meant for English language keyboards, and it will work
9658 for many others with the exception of key combinations like Fn-ö on
9659 a German keyboard, which is currently mapped to Fn-;.
9660 How to solve this without keeping separate tables for all keyboards
9661 around? KeyTranslate isn't of much help here, as it only takes a 16-bit
9662 value for keycode with the modifiers in he high byte, i.e. no room for the
9663 Fn modifier. That's why we need the table.
9666 OSStatus err;
9667 UInt32 mods = 0;
9668 if (!NILP(Vmac_function_modifier))
9670 err = GetEventParameter (eventRef, kEventParamKeyModifiers, typeUInt32,
9671 NULL, sizeof (UInt32), NULL, &mods);
9672 if (err != noErr && mods & kEventKeyModifierFnMask)
9673 { *newCode = fn_keycode_to_xkeysym_table [keyCode & 0x7f];
9675 return (*newCode != 0);
9678 #endif
9679 return false;
9682 static int
9683 backtranslate_modified_keycode(int mods, int keycode, int def)
9685 EventModifiers mapped_modifiers =
9686 (NILP (Vmac_control_modifier) ? 0 : controlKey)
9687 | (NILP (Vmac_option_modifier) ? 0 : optionKey)
9688 | (NILP (Vmac_command_modifier) ? 0 : cmdKey);
9690 if (mods & mapped_modifiers)
9692 /* This code comes from Keyboard Resource,
9693 Appendix C of IM - Text. This is necessary
9694 since shift is ignored in KCHR table
9695 translation when option or command is pressed.
9696 It also does not translate correctly
9697 control-shift chars like C-% so mask off shift
9698 here also.
9700 Not done for combinations with the option key (alt)
9701 unless it is to be caught by Emacs: this is
9702 to preserve key combinations translated by the OS
9703 such as Alt-3.
9705 /* Mask off modifier keys that are mapped to some Emacs
9706 modifiers. */
9707 int new_modifiers = mods & ~mapped_modifiers;
9708 /* set high byte of keycode to modifier high byte*/
9709 int new_keycode = keycode | new_modifiers;
9710 Ptr kchr_ptr = (Ptr) GetScriptManagerVariable (smKCHRCache);
9711 unsigned long some_state = 0;
9712 return (int) KeyTranslate (kchr_ptr, new_keycode,
9713 &some_state) & 0xff;
9714 /* TO DO: Recognize two separate resulting characters, "for
9715 example, when the user presses Option-E followed by N, you
9716 can map this through the KeyTranslate function using the
9717 U.S. 'KCHR' resource to produce ´n, which KeyTranslate
9718 returns as two characters in the bytes labeled Character code
9719 1 and Character code 2." (from Carbon API doc) */
9722 else
9723 return def;
9727 #if !USE_CARBON_EVENTS
9728 static RgnHandle mouse_region = NULL;
9730 Boolean
9731 mac_wait_next_event (er, sleep_time, dequeue)
9732 EventRecord *er;
9733 UInt32 sleep_time;
9734 Boolean dequeue;
9736 static EventRecord er_buf = {nullEvent};
9737 UInt32 target_tick, current_tick;
9738 EventMask event_mask;
9740 if (mouse_region == NULL)
9741 mouse_region = NewRgn ();
9743 event_mask = everyEvent;
9744 if (!mac_ready_for_apple_events)
9745 event_mask -= highLevelEventMask;
9747 current_tick = TickCount ();
9748 target_tick = current_tick + sleep_time;
9750 if (er_buf.what == nullEvent)
9751 while (!WaitNextEvent (event_mask, &er_buf,
9752 target_tick - current_tick, mouse_region))
9754 current_tick = TickCount ();
9755 if (target_tick <= current_tick)
9756 return false;
9759 *er = er_buf;
9760 if (dequeue)
9761 er_buf.what = nullEvent;
9762 return true;
9764 #endif /* not USE_CARBON_EVENTS */
9766 /* Emacs calls this whenever it wants to read an input event from the
9767 user. */
9769 XTread_socket (sd, expected, hold_quit)
9770 int sd, expected;
9771 struct input_event *hold_quit;
9773 struct input_event inev;
9774 int count = 0;
9775 #if USE_CARBON_EVENTS
9776 EventRef eventRef;
9777 EventTargetRef toolbox_dispatcher;
9778 #endif
9779 EventRecord er;
9780 struct mac_display_info *dpyinfo = &one_mac_display_info;
9782 if (interrupt_input_blocked)
9784 interrupt_input_pending = 1;
9785 return -1;
9788 interrupt_input_pending = 0;
9789 BLOCK_INPUT;
9791 /* So people can tell when we have read the available input. */
9792 input_signal_count++;
9794 ++handling_signal;
9796 #if USE_CARBON_EVENTS
9797 toolbox_dispatcher = GetEventDispatcherTarget ();
9799 while (
9800 #if USE_CG_DRAWING
9801 mac_prepare_for_quickdraw (NULL),
9802 #endif
9803 !ReceiveNextEvent (0, NULL, kEventDurationNoWait,
9804 kEventRemoveFromQueue, &eventRef))
9805 #else /* !USE_CARBON_EVENTS */
9806 while (mac_wait_next_event (&er, 0, true))
9807 #endif /* !USE_CARBON_EVENTS */
9809 int do_help = 0;
9810 struct frame *f;
9811 unsigned long timestamp;
9813 /* It is necessary to set this (additional) argument slot of an
9814 event to nil because keyboard.c protects incompletely
9815 processed event from being garbage collected by placing them
9816 in the kbd_buffer_gcpro vector. */
9817 EVENT_INIT (inev);
9818 inev.kind = NO_EVENT;
9819 inev.arg = Qnil;
9821 #if USE_CARBON_EVENTS
9822 timestamp = GetEventTime (eventRef) / kEventDurationMillisecond;
9823 #else
9824 timestamp = er.when * (1000 / 60); /* ticks to milliseconds */
9825 #endif
9827 #if USE_CARBON_EVENTS
9828 /* Handle new events */
9829 if (!mac_convert_event_ref (eventRef, &er))
9831 /* There used to be a handler for the kEventMouseWheelMoved
9832 event here. But as of Mac OS X 10.4, this kind of event
9833 is not directly posted to the main event queue by
9834 two-finger scrolling on the trackpad. Instead, some
9835 private event is posted and it is converted to a wheel
9836 event by the default handler for the application target.
9837 The converted one can be received by a Carbon event
9838 handler installed on a window target. */
9839 read_socket_inev = &inev;
9840 SendEventToEventTarget (eventRef, toolbox_dispatcher);
9841 read_socket_inev = NULL;
9843 else
9844 #endif /* USE_CARBON_EVENTS */
9845 switch (er.what)
9847 case mouseDown:
9848 case mouseUp:
9850 WindowPtr window_ptr;
9851 ControlPartCode part_code;
9852 int tool_bar_p = 0;
9854 #if USE_CARBON_EVENTS
9855 /* This is needed to send mouse events like aqua window
9856 buttons to the correct handler. */
9857 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
9858 != eventNotHandledErr)
9859 break;
9860 #endif
9861 last_mouse_glyph_frame = 0;
9863 if (dpyinfo->grabbed && last_mouse_frame
9864 && FRAME_LIVE_P (last_mouse_frame))
9866 window_ptr = FRAME_MAC_WINDOW (last_mouse_frame);
9867 part_code = inContent;
9869 else
9871 part_code = FindWindow (er.where, &window_ptr);
9872 if (tip_window && window_ptr == tip_window)
9874 HideWindow (tip_window);
9875 part_code = FindWindow (er.where, &window_ptr);
9879 if (er.what != mouseDown &&
9880 (part_code != inContent || dpyinfo->grabbed == 0))
9881 break;
9883 switch (part_code)
9885 case inMenuBar:
9886 f = mac_focus_frame (dpyinfo);
9887 saved_menu_event_location = er.where;
9888 inev.kind = MENU_BAR_ACTIVATE_EVENT;
9889 XSETFRAME (inev.frame_or_window, f);
9890 break;
9892 case inContent:
9893 if (window_ptr != FRAME_MAC_WINDOW (mac_focus_frame (dpyinfo)))
9894 SelectWindow (window_ptr);
9895 else
9897 ControlPartCode control_part_code;
9898 ControlHandle ch;
9899 Point mouse_loc = er.where;
9900 #ifdef MAC_OSX
9901 ControlKind control_kind;
9902 #endif
9904 f = mac_window_to_frame (window_ptr);
9905 /* convert to local coordinates of new window */
9906 SetPortWindowPort (window_ptr);
9908 GlobalToLocal (&mouse_loc);
9909 #if TARGET_API_MAC_CARBON
9910 ch = FindControlUnderMouse (mouse_loc, window_ptr,
9911 &control_part_code);
9912 #ifdef MAC_OSX
9913 if (ch)
9914 GetControlKind (ch, &control_kind);
9915 #endif
9916 #else
9917 control_part_code = FindControl (mouse_loc, window_ptr,
9918 &ch);
9919 #endif
9921 #if USE_CARBON_EVENTS
9922 inev.code = mac_get_mouse_btn (eventRef);
9923 inev.modifiers = mac_event_to_emacs_modifiers (eventRef);
9924 #else
9925 inev.code = mac_get_emulated_btn (er.modifiers);
9926 inev.modifiers = mac_to_emacs_modifiers (er.modifiers);
9927 #endif
9928 XSETINT (inev.x, mouse_loc.h);
9929 XSETINT (inev.y, mouse_loc.v);
9931 if ((dpyinfo->grabbed && tracked_scroll_bar)
9932 || (ch != 0
9933 #ifndef USE_TOOLKIT_SCROLL_BARS
9934 /* control_part_code becomes kControlNoPart if
9935 a progress indicator is clicked. */
9936 && control_part_code != kControlNoPart
9937 #else /* USE_TOOLKIT_SCROLL_BARS */
9938 #ifdef MAC_OSX
9939 && control_kind.kind == kControlKindScrollBar
9940 #endif /* MAC_OSX */
9941 #endif /* USE_TOOLKIT_SCROLL_BARS */
9944 struct scroll_bar *bar;
9946 if (dpyinfo->grabbed && tracked_scroll_bar)
9948 bar = tracked_scroll_bar;
9949 #ifndef USE_TOOLKIT_SCROLL_BARS
9950 control_part_code = kControlIndicatorPart;
9951 #endif
9953 else
9954 bar = (struct scroll_bar *) GetControlReference (ch);
9955 #ifdef USE_TOOLKIT_SCROLL_BARS
9956 /* Make the "Ctrl-Mouse-2 splits window" work
9957 for toolkit scroll bars. */
9958 if (er.modifiers & controlKey)
9959 x_scroll_bar_handle_click (bar, control_part_code,
9960 &er, &inev);
9961 else if (er.what == mouseDown)
9962 x_scroll_bar_handle_press (bar, control_part_code,
9963 &inev);
9964 else
9965 x_scroll_bar_handle_release (bar, &inev);
9966 #else /* not USE_TOOLKIT_SCROLL_BARS */
9967 x_scroll_bar_handle_click (bar, control_part_code,
9968 &er, &inev);
9969 if (er.what == mouseDown
9970 && control_part_code == kControlIndicatorPart)
9971 tracked_scroll_bar = bar;
9972 else
9973 tracked_scroll_bar = NULL;
9974 #endif /* not USE_TOOLKIT_SCROLL_BARS */
9976 else
9978 Lisp_Object window;
9979 int x = mouse_loc.h;
9980 int y = mouse_loc.v;
9982 window = window_from_coordinates (f, x, y, 0, 0, 0, 1);
9983 if (EQ (window, f->tool_bar_window))
9985 if (er.what == mouseDown)
9986 handle_tool_bar_click (f, x, y, 1, 0);
9987 else
9988 handle_tool_bar_click (f, x, y, 0,
9989 inev.modifiers);
9990 tool_bar_p = 1;
9992 else
9994 XSETFRAME (inev.frame_or_window, f);
9995 inev.kind = MOUSE_CLICK_EVENT;
9999 if (er.what == mouseDown)
10001 dpyinfo->grabbed |= (1 << inev.code);
10002 last_mouse_frame = f;
10004 if (!tool_bar_p)
10005 last_tool_bar_item = -1;
10007 else
10009 if ((dpyinfo->grabbed & (1 << inev.code)) == 0)
10010 /* If a button is released though it was not
10011 previously pressed, that would be because
10012 of multi-button emulation. */
10013 dpyinfo->grabbed = 0;
10014 else
10015 dpyinfo->grabbed &= ~(1 << inev.code);
10018 /* Ignore any mouse motion that happened before
10019 this event; any subsequent mouse-movement Emacs
10020 events should reflect only motion after the
10021 ButtonPress. */
10022 if (f != 0)
10023 f->mouse_moved = 0;
10025 #ifdef USE_TOOLKIT_SCROLL_BARS
10026 if (inev.kind == MOUSE_CLICK_EVENT)
10027 #endif
10028 switch (er.what)
10030 case mouseDown:
10031 inev.modifiers |= down_modifier;
10032 break;
10033 case mouseUp:
10034 inev.modifiers |= up_modifier;
10035 break;
10038 break;
10040 case inDrag:
10041 #if TARGET_API_MAC_CARBON
10042 DragWindow (window_ptr, er.where, NULL);
10043 #else /* not TARGET_API_MAC_CARBON */
10044 DragWindow (window_ptr, er.where, &qd.screenBits.bounds);
10045 #endif /* not TARGET_API_MAC_CARBON */
10046 /* Update the frame parameters. */
10048 struct frame *f = mac_window_to_frame (window_ptr);
10050 if (f && !f->async_iconified)
10051 x_real_positions (f, &f->left_pos, &f->top_pos);
10053 break;
10055 case inGoAway:
10056 if (TrackGoAway (window_ptr, er.where))
10058 inev.kind = DELETE_WINDOW_EVENT;
10059 XSETFRAME (inev.frame_or_window,
10060 mac_window_to_frame (window_ptr));
10062 break;
10064 /* window resize handling added --ben */
10065 case inGrow:
10066 do_grow_window (window_ptr, &er);
10067 break;
10069 /* window zoom handling added --ben */
10070 case inZoomIn:
10071 case inZoomOut:
10072 if (TrackBox (window_ptr, er.where, part_code))
10073 do_zoom_window (window_ptr, part_code);
10074 break;
10076 default:
10077 break;
10080 break;
10082 case updateEvt:
10083 #if USE_CARBON_EVENTS
10084 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
10085 != eventNotHandledErr)
10086 break;
10087 #else
10088 do_window_update ((WindowPtr) er.message);
10089 #endif
10090 break;
10092 case osEvt:
10093 #if USE_CARBON_EVENTS
10094 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
10095 != eventNotHandledErr)
10096 break;
10097 #endif
10098 switch ((er.message >> 24) & 0x000000FF)
10100 case suspendResumeMessage:
10101 if ((er.message & resumeFlag) == 1)
10102 do_app_resume ();
10103 else
10104 do_app_suspend ();
10105 break;
10107 case mouseMovedMessage:
10108 #if !USE_CARBON_EVENTS
10109 SetRectRgn (mouse_region, er.where.h, er.where.v,
10110 er.where.h + 1, er.where.v + 1);
10111 #endif
10112 previous_help_echo_string = help_echo_string;
10113 help_echo_string = Qnil;
10115 if (dpyinfo->grabbed && last_mouse_frame
10116 && FRAME_LIVE_P (last_mouse_frame))
10117 f = last_mouse_frame;
10118 else
10119 f = dpyinfo->x_focus_frame;
10121 if (dpyinfo->mouse_face_hidden)
10123 dpyinfo->mouse_face_hidden = 0;
10124 clear_mouse_face (dpyinfo);
10127 if (f)
10129 WindowPtr wp = FRAME_MAC_WINDOW (f);
10130 Point mouse_pos = er.where;
10132 SetPortWindowPort (wp);
10134 GlobalToLocal (&mouse_pos);
10136 if (dpyinfo->grabbed && tracked_scroll_bar)
10137 #ifdef USE_TOOLKIT_SCROLL_BARS
10138 x_scroll_bar_handle_drag (wp, tracked_scroll_bar,
10139 mouse_pos, &inev);
10140 #else /* not USE_TOOLKIT_SCROLL_BARS */
10141 x_scroll_bar_note_movement (tracked_scroll_bar,
10142 mouse_pos.v
10143 - XINT (tracked_scroll_bar->top),
10144 er.when * (1000 / 60));
10145 #endif /* not USE_TOOLKIT_SCROLL_BARS */
10146 else
10148 /* Generate SELECT_WINDOW_EVENTs when needed. */
10149 if (mouse_autoselect_window)
10151 Lisp_Object window;
10153 window = window_from_coordinates (f,
10154 mouse_pos.h,
10155 mouse_pos.v,
10156 0, 0, 0, 0);
10158 /* Window will be selected only when it is
10159 not selected now and last mouse movement
10160 event was not in it. Minibuffer window
10161 will be selected iff it is active. */
10162 if (WINDOWP (window)
10163 && !EQ (window, last_window)
10164 && !EQ (window, selected_window))
10166 inev.kind = SELECT_WINDOW_EVENT;
10167 inev.frame_or_window = window;
10170 last_window=window;
10172 if (!note_mouse_movement (f, &mouse_pos))
10173 help_echo_string = previous_help_echo_string;
10177 /* If the contents of the global variable
10178 help_echo_string has changed, generate a
10179 HELP_EVENT. */
10180 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
10181 do_help = 1;
10182 break;
10184 break;
10186 case activateEvt:
10188 WindowPtr window_ptr = (WindowPtr) er.message;
10190 #if USE_CARBON_EVENTS
10191 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
10192 != eventNotHandledErr)
10193 break;
10194 #endif
10195 if (window_ptr == tip_window)
10197 HideWindow (tip_window);
10198 break;
10201 if (!is_emacs_window (window_ptr))
10202 break;
10204 if ((er.modifiers & activeFlag) != 0)
10206 /* A window has been activated */
10207 Point mouse_loc = er.where;
10209 x_detect_focus_change (dpyinfo, &er, &inev);
10211 SetPortWindowPort (window_ptr);
10212 GlobalToLocal (&mouse_loc);
10213 /* Window-activated event counts as mouse movement,
10214 so update things that depend on mouse position. */
10215 note_mouse_movement (mac_window_to_frame (window_ptr),
10216 &mouse_loc);
10218 else
10220 /* A window has been deactivated */
10221 #if USE_TOOLKIT_SCROLL_BARS
10222 if (dpyinfo->grabbed && tracked_scroll_bar)
10224 struct input_event event;
10226 EVENT_INIT (event);
10227 event.kind = NO_EVENT;
10228 x_scroll_bar_handle_release (tracked_scroll_bar, &event);
10229 if (event.kind != NO_EVENT)
10231 event.timestamp = timestamp;
10232 kbd_buffer_store_event_hold (&event, hold_quit);
10233 count++;
10236 #endif
10237 dpyinfo->grabbed = 0;
10239 x_detect_focus_change (dpyinfo, &er, &inev);
10241 f = mac_window_to_frame (window_ptr);
10242 if (f == dpyinfo->mouse_face_mouse_frame)
10244 /* If we move outside the frame, then we're
10245 certainly no longer on any text in the
10246 frame. */
10247 clear_mouse_face (dpyinfo);
10248 dpyinfo->mouse_face_mouse_frame = 0;
10251 /* Generate a nil HELP_EVENT to cancel a help-echo.
10252 Do it only if there's something to cancel.
10253 Otherwise, the startup message is cleared when the
10254 mouse leaves the frame. */
10255 if (any_help_event_p)
10256 do_help = -1;
10259 break;
10261 case keyDown:
10262 case autoKey:
10264 int keycode = (er.message & keyCodeMask) >> 8;
10265 int xkeysym;
10267 #if USE_CARBON_EVENTS && defined (MAC_OSX)
10268 /* When using Carbon Events, we need to pass raw keyboard
10269 events to the TSM ourselves. If TSM handles it, it
10270 will pass back noErr, otherwise it will pass back
10271 "eventNotHandledErr" and we can process it
10272 normally. */
10273 if ((mac_pass_command_to_system
10274 || !(er.modifiers & cmdKey))
10275 && (mac_pass_control_to_system
10276 || !(er.modifiers & controlKey))
10277 && (NILP (Vmac_option_modifier)
10278 || !(er.modifiers & optionKey)))
10279 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
10280 != eventNotHandledErr)
10281 break;
10282 #endif
10284 #if 0
10285 if (dpyinfo->x_focus_frame == NULL)
10287 /* Beep if keyboard input occurs when all the frames
10288 are invisible. */
10289 SysBeep (1);
10290 break;
10292 #endif
10295 static SInt16 last_key_script = -1;
10296 SInt16 current_key_script = GetScriptManagerVariable (smKeyScript);
10298 if (last_key_script != current_key_script)
10300 struct input_event event;
10302 EVENT_INIT (event);
10303 event.kind = LANGUAGE_CHANGE_EVENT;
10304 event.arg = Qnil;
10305 event.code = current_key_script;
10306 event.timestamp = timestamp;
10307 kbd_buffer_store_event (&event);
10308 count++;
10310 last_key_script = current_key_script;
10313 ObscureCursor ();
10315 f = mac_focus_frame (dpyinfo);
10317 if (!dpyinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight)
10318 && !EQ (f->tool_bar_window, dpyinfo->mouse_face_window))
10320 clear_mouse_face (dpyinfo);
10321 dpyinfo->mouse_face_hidden = 1;
10324 /* translate the keycode back to determine the original key */
10325 /* Convert key code if function key is pressed.
10326 Otherwise, if non-ASCII-event, take care of that
10327 without re-translating the key code. */
10328 #if USE_CARBON_EVENTS
10329 if (convert_fn_keycode (eventRef, keycode, &xkeysym))
10331 inev.code = xkeysym;
10332 /* this doesn't work - tried to add shift modifiers */
10333 inev.code =
10334 backtranslate_modified_keycode(er.modifiers & (~0x2200),
10335 xkeysym | 0x80, xkeysym);
10336 inev.kind = ASCII_KEYSTROKE_EVENT;
10338 else
10339 #endif
10340 if (keycode_to_xkeysym (keycode, &xkeysym))
10342 inev.code = 0xff00 | xkeysym;
10343 inev.kind = NON_ASCII_KEYSTROKE_EVENT;
10345 else
10347 inev.code =
10348 backtranslate_modified_keycode(er.modifiers, keycode,
10349 er.message & charCodeMask);
10350 inev.kind = ASCII_KEYSTROKE_EVENT;
10354 #if USE_CARBON_EVENTS
10355 inev.modifiers = mac_event_to_emacs_modifiers (eventRef);
10356 #else
10357 inev.modifiers = mac_to_emacs_modifiers (er.modifiers);
10358 #endif
10359 inev.modifiers |= (extra_keyboard_modifiers
10360 & (meta_modifier | alt_modifier
10361 | hyper_modifier | super_modifier));
10362 XSETFRAME (inev.frame_or_window, f);
10363 break;
10365 case kHighLevelEvent:
10366 read_socket_inev = &inev;
10367 AEProcessAppleEvent (&er);
10368 read_socket_inev = NULL;
10369 break;
10371 default:
10372 break;
10374 #if USE_CARBON_EVENTS
10375 ReleaseEvent (eventRef);
10376 #endif
10378 if (inev.kind != NO_EVENT)
10380 inev.timestamp = timestamp;
10381 kbd_buffer_store_event_hold (&inev, hold_quit);
10382 count++;
10385 if (do_help
10386 && !(hold_quit && hold_quit->kind != NO_EVENT))
10388 Lisp_Object frame;
10390 if (f)
10391 XSETFRAME (frame, f);
10392 else
10393 frame = Qnil;
10395 if (do_help > 0)
10397 any_help_event_p = 1;
10398 gen_help_event (help_echo_string, frame, help_echo_window,
10399 help_echo_object, help_echo_pos);
10401 else
10403 help_echo_string = Qnil;
10404 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
10406 count++;
10411 /* If the focus was just given to an autoraising frame,
10412 raise it now. */
10413 /* ??? This ought to be able to handle more than one such frame. */
10414 if (pending_autoraise_frame)
10416 x_raise_frame (pending_autoraise_frame);
10417 pending_autoraise_frame = 0;
10420 #if !USE_CARBON_EVENTS
10421 /* Check which frames are still visible. We do this here because
10422 there doesn't seem to be any direct notification from the Window
10423 Manager that the visibility of a window has changed (at least,
10424 not in all cases). */
10426 Lisp_Object tail, frame;
10428 FOR_EACH_FRAME (tail, frame)
10430 struct frame *f = XFRAME (frame);
10432 /* The tooltip has been drawn already. Avoid the
10433 SET_FRAME_GARBAGED in mac_handle_visibility_change. */
10434 if (EQ (frame, tip_frame))
10435 continue;
10437 if (FRAME_MAC_P (f))
10438 mac_handle_visibility_change (f);
10441 #endif
10443 --handling_signal;
10444 UNBLOCK_INPUT;
10445 return count;
10449 /* Need to override CodeWarrior's input function so no conversion is
10450 done on newlines Otherwise compiled functions in .elc files will be
10451 read incorrectly. Defined in ...:MSL C:MSL
10452 Common:Source:buffer_io.c. */
10453 #ifdef __MWERKS__
10454 void
10455 __convert_to_newlines (unsigned char * p, size_t * n)
10457 #pragma unused(p,n)
10460 void
10461 __convert_from_newlines (unsigned char * p, size_t * n)
10463 #pragma unused(p,n)
10465 #endif
10467 #ifdef MAC_OS8
10468 void
10469 make_mac_terminal_frame (struct frame *f)
10471 Lisp_Object frame;
10472 Rect r;
10474 XSETFRAME (frame, f);
10476 f->output_method = output_mac;
10477 f->output_data.mac = (struct mac_output *)
10478 xmalloc (sizeof (struct mac_output));
10479 bzero (f->output_data.mac, sizeof (struct mac_output));
10481 XSETFRAME (FRAME_KBOARD (f)->Vdefault_minibuffer_frame, f);
10483 FRAME_COLS (f) = 96;
10484 FRAME_LINES (f) = 4;
10486 FRAME_CAN_HAVE_SCROLL_BARS (f) = 1;
10487 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = vertical_scroll_bar_right;
10489 FRAME_DESIRED_CURSOR (f) = FILLED_BOX_CURSOR;
10491 f->output_data.mac->cursor_pixel = 0;
10492 f->output_data.mac->border_pixel = 0x00ff00;
10493 f->output_data.mac->mouse_pixel = 0xff00ff;
10494 f->output_data.mac->cursor_foreground_pixel = 0x0000ff;
10496 f->output_data.mac->text_cursor = kThemeIBeamCursor;
10497 f->output_data.mac->nontext_cursor = kThemeArrowCursor;
10498 f->output_data.mac->modeline_cursor = kThemeArrowCursor;
10499 f->output_data.mac->hand_cursor = kThemePointingHandCursor;
10500 f->output_data.mac->hourglass_cursor = kThemeWatchCursor;
10501 f->output_data.mac->horizontal_drag_cursor = kThemeResizeLeftRightCursor;
10503 FRAME_FONTSET (f) = -1;
10504 f->output_data.mac->explicit_parent = 0;
10505 f->left_pos = 8;
10506 f->top_pos = 32;
10507 f->border_width = 0;
10509 f->internal_border_width = 0;
10511 f->auto_raise = 1;
10512 f->auto_lower = 1;
10514 f->new_text_cols = 0;
10515 f->new_text_lines = 0;
10517 SetRect (&r, f->left_pos, f->top_pos,
10518 f->left_pos + FRAME_PIXEL_WIDTH (f),
10519 f->top_pos + FRAME_PIXEL_HEIGHT (f));
10521 BLOCK_INPUT;
10523 if (!(FRAME_MAC_WINDOW (f) =
10524 NewCWindow (NULL, &r, "\p", true, dBoxProc,
10525 (WindowPtr) -1, 1, (long) f->output_data.mac)))
10526 abort ();
10527 /* so that update events can find this mac_output struct */
10528 f->output_data.mac->mFP = f; /* point back to emacs frame */
10530 UNBLOCK_INPUT;
10532 x_make_gc (f);
10534 /* Need to be initialized for unshow_buffer in window.c. */
10535 selected_window = f->selected_window;
10537 Fmodify_frame_parameters (frame,
10538 Fcons (Fcons (Qfont,
10539 build_string ("-*-monaco-medium-r-*--*-90-*-*-*-*-mac-roman")), Qnil));
10540 Fmodify_frame_parameters (frame,
10541 Fcons (Fcons (Qforeground_color,
10542 build_string ("black")), Qnil));
10543 Fmodify_frame_parameters (frame,
10544 Fcons (Fcons (Qbackground_color,
10545 build_string ("white")), Qnil));
10547 #endif
10550 /***********************************************************************
10551 Initialization
10552 ***********************************************************************/
10554 int mac_initialized = 0;
10556 void
10557 mac_initialize_display_info ()
10559 struct mac_display_info *dpyinfo = &one_mac_display_info;
10560 GDHandle main_device_handle;
10562 bzero (dpyinfo, sizeof (*dpyinfo));
10564 #ifdef MAC_OSX
10565 dpyinfo->mac_id_name
10566 = (char *) xmalloc (SCHARS (Vinvocation_name)
10567 + SCHARS (Vsystem_name)
10568 + 2);
10569 sprintf (dpyinfo->mac_id_name, "%s@%s",
10570 SDATA (Vinvocation_name), SDATA (Vsystem_name));
10571 #else
10572 dpyinfo->mac_id_name = (char *) xmalloc (strlen ("Mac Display") + 1);
10573 strcpy (dpyinfo->mac_id_name, "Mac Display");
10574 #endif
10576 main_device_handle = LMGetMainDevice();
10578 dpyinfo->reference_count = 0;
10579 dpyinfo->resx = 72.0;
10580 dpyinfo->resy = 72.0;
10581 dpyinfo->color_p = TestDeviceAttribute (main_device_handle, gdDevType);
10582 #ifdef MAC_OSX
10583 /* HasDepth returns true if it is possible to have a 32 bit display,
10584 but this may not be what is actually used. Mac OSX can do better.
10585 CGMainDisplayID is only available on OSX 10.2 and higher, but the
10586 header for CGGetActiveDisplayList says that the first display returned
10587 is the active one, so we use that. */
10589 CGDirectDisplayID disp_id[1];
10590 CGDisplayCount disp_count;
10591 CGDisplayErr error_code;
10593 error_code = CGGetActiveDisplayList (1, disp_id, &disp_count);
10594 if (error_code != 0)
10595 error ("No display found, CGGetActiveDisplayList error %d", error_code);
10597 dpyinfo->n_planes = CGDisplayBitsPerPixel (disp_id[0]);
10599 #else
10600 for (dpyinfo->n_planes = 32; dpyinfo->n_planes > 0; dpyinfo->n_planes >>= 1)
10601 if (HasDepth (main_device_handle, dpyinfo->n_planes,
10602 gdDevType, dpyinfo->color_p))
10603 break;
10604 #endif
10605 dpyinfo->height = (**main_device_handle).gdRect.bottom;
10606 dpyinfo->width = (**main_device_handle).gdRect.right;
10607 dpyinfo->grabbed = 0;
10608 dpyinfo->root_window = NULL;
10609 dpyinfo->image_cache = make_image_cache ();
10611 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
10612 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
10613 dpyinfo->mouse_face_face_id = DEFAULT_FACE_ID;
10614 dpyinfo->mouse_face_window = Qnil;
10615 dpyinfo->mouse_face_overlay = Qnil;
10616 dpyinfo->mouse_face_hidden = 0;
10620 static XrmDatabase
10621 mac_make_rdb (xrm_option)
10622 char *xrm_option;
10624 XrmDatabase database;
10626 database = xrm_get_preference_database (NULL);
10627 if (xrm_option)
10628 xrm_merge_string_database (database, xrm_option);
10630 return database;
10633 struct mac_display_info *
10634 mac_term_init (display_name, xrm_option, resource_name)
10635 Lisp_Object display_name;
10636 char *xrm_option;
10637 char *resource_name;
10639 struct mac_display_info *dpyinfo;
10641 BLOCK_INPUT;
10643 if (!mac_initialized)
10645 mac_initialize ();
10646 mac_initialized = 1;
10649 if (x_display_list)
10650 error ("Sorry, this version can only handle one display");
10652 mac_initialize_display_info ();
10654 dpyinfo = &one_mac_display_info;
10656 dpyinfo->xrdb = mac_make_rdb (xrm_option);
10658 /* Put this display on the chain. */
10659 dpyinfo->next = x_display_list;
10660 x_display_list = dpyinfo;
10662 /* Put it on x_display_name_list. */
10663 x_display_name_list = Fcons (Fcons (display_name,
10664 Fcons (Qnil, dpyinfo->xrdb)),
10665 x_display_name_list);
10666 dpyinfo->name_list_element = XCAR (x_display_name_list);
10668 UNBLOCK_INPUT;
10670 return dpyinfo;
10672 /* Get rid of display DPYINFO, assuming all frames are already gone. */
10674 void
10675 x_delete_display (dpyinfo)
10676 struct mac_display_info *dpyinfo;
10678 int i;
10680 /* Discard this display from x_display_name_list and x_display_list.
10681 We can't use Fdelq because that can quit. */
10682 if (! NILP (x_display_name_list)
10683 && EQ (XCAR (x_display_name_list), dpyinfo->name_list_element))
10684 x_display_name_list = XCDR (x_display_name_list);
10685 else
10687 Lisp_Object tail;
10689 tail = x_display_name_list;
10690 while (CONSP (tail) && CONSP (XCDR (tail)))
10692 if (EQ (XCAR (XCDR (tail)), dpyinfo->name_list_element))
10694 XSETCDR (tail, XCDR (XCDR (tail)));
10695 break;
10697 tail = XCDR (tail);
10701 if (x_display_list == dpyinfo)
10702 x_display_list = dpyinfo->next;
10703 else
10705 struct x_display_info *tail;
10707 for (tail = x_display_list; tail; tail = tail->next)
10708 if (tail->next == dpyinfo)
10709 tail->next = tail->next->next;
10712 /* Free the font names in the font table. */
10713 for (i = 0; i < dpyinfo->n_fonts; i++)
10714 if (dpyinfo->font_table[i].name)
10716 if (dpyinfo->font_table[i].name != dpyinfo->font_table[i].full_name)
10717 xfree (dpyinfo->font_table[i].full_name);
10718 xfree (dpyinfo->font_table[i].name);
10721 if (dpyinfo->font_table->font_encoder)
10722 xfree (dpyinfo->font_table->font_encoder);
10724 xfree (dpyinfo->font_table);
10725 xfree (dpyinfo->mac_id_name);
10727 if (x_display_list == 0)
10729 mac_clear_font_name_table ();
10730 bzero (dpyinfo, sizeof (*dpyinfo));
10735 #ifdef MAC_OSX
10736 void
10737 mac_check_bundle()
10739 extern int inhibit_window_system;
10740 extern int noninteractive;
10741 CFBundleRef appsBundle;
10743 /* No need to test if already -nw*/
10744 if (inhibit_window_system || noninteractive)
10745 return;
10747 appsBundle = CFBundleGetMainBundle();
10748 if (appsBundle != NULL)
10750 CFStringRef cfBI = CFSTR("CFBundleIdentifier");
10751 CFTypeRef res = CFBundleGetValueForInfoDictionaryKey(appsBundle, cfBI);
10752 /* We found the bundle identifier, now we know we are valid. */
10753 if (res != NULL)
10755 CFRelease(res);
10756 return;
10759 /* MAC_TODO: Have this start the bundled executable */
10761 /* For now, prevent the fatal error by bringing it up in the terminal */
10762 inhibit_window_system = 1;
10765 void
10766 MakeMeTheFrontProcess ()
10768 ProcessSerialNumber psn;
10769 OSErr err;
10771 err = GetCurrentProcess (&psn);
10772 if (err == noErr)
10773 (void) SetFrontProcess (&psn);
10776 /***** Code to handle C-g testing *****/
10778 /* Contains the Mac modifier formed from quit_char */
10779 int mac_quit_char_modifiers = 0;
10780 int mac_quit_char_keycode;
10781 extern int quit_char;
10783 static void
10784 mac_determine_quit_char_modifiers()
10786 /* Todo: Determine modifiers from quit_char. */
10787 UInt32 qc_modifiers = ctrl_modifier;
10789 /* Map modifiers */
10790 mac_quit_char_modifiers = 0;
10791 if (qc_modifiers & ctrl_modifier) mac_quit_char_modifiers |= controlKey;
10792 if (qc_modifiers & shift_modifier) mac_quit_char_modifiers |= shiftKey;
10793 if (qc_modifiers & alt_modifier) mac_quit_char_modifiers |= optionKey;
10796 static void
10797 init_quit_char_handler ()
10799 /* TODO: Let this support keys other the 'g' */
10800 mac_quit_char_keycode = 5;
10801 /* Look at <architecture/adb_kb_map.h> for details */
10802 /* http://gemma.apple.com/techpubs/mac/Toolbox/Toolbox-40.html#MARKER-9-184*/
10804 mac_determine_quit_char_modifiers();
10806 #endif /* MAC_OSX */
10808 static void
10809 init_menu_bar ()
10811 #ifdef MAC_OSX
10812 OSErr err;
10813 MenuRef menu;
10814 MenuItemIndex menu_index;
10816 err = GetIndMenuItemWithCommandID (NULL, kHICommandQuit, 1,
10817 &menu, &menu_index);
10818 if (err == noErr)
10819 SetMenuItemCommandKey (menu, menu_index, false, 0);
10820 #if USE_CARBON_EVENTS
10821 EnableMenuCommand (NULL, kHICommandPreferences);
10822 err = GetIndMenuItemWithCommandID (NULL, kHICommandPreferences, 1,
10823 &menu, &menu_index);
10824 if (err == noErr)
10826 SetMenuItemCommandKey (menu, menu_index, false, 0);
10827 InsertMenuItemTextWithCFString (menu, NULL,
10828 0, kMenuItemAttrSeparator, 0);
10829 InsertMenuItemTextWithCFString (menu, CFSTR ("About Emacs"),
10830 0, 0, kHICommandAbout);
10832 #endif /* USE_CARBON_EVENTS */
10833 #else /* !MAC_OSX */
10834 #if USE_CARBON_EVENTS
10835 SetMenuItemCommandID (GetMenuHandle (M_APPLE), I_ABOUT, kHICommandAbout);
10836 #endif
10837 #endif
10841 /* Set up use of X before we make the first connection. */
10843 extern frame_parm_handler mac_frame_parm_handlers[];
10845 static struct redisplay_interface x_redisplay_interface =
10847 mac_frame_parm_handlers,
10848 x_produce_glyphs,
10849 x_write_glyphs,
10850 x_insert_glyphs,
10851 x_clear_end_of_line,
10852 x_scroll_run,
10853 x_after_update_window_line,
10854 x_update_window_begin,
10855 x_update_window_end,
10856 x_cursor_to,
10857 x_flush,
10858 0, /* flush_display_optional */
10859 x_clear_window_mouse_face,
10860 x_get_glyph_overhangs,
10861 x_fix_overlapping_area,
10862 x_draw_fringe_bitmap,
10863 #if USE_CG_DRAWING
10864 mac_define_fringe_bitmap,
10865 mac_destroy_fringe_bitmap,
10866 #else
10867 0, /* define_fringe_bitmap */
10868 0, /* destroy_fringe_bitmap */
10869 #endif
10870 mac_per_char_metric,
10871 mac_encode_char,
10872 mac_compute_glyph_string_overhangs,
10873 x_draw_glyph_string,
10874 mac_define_frame_cursor,
10875 mac_clear_frame_area,
10876 mac_draw_window_cursor,
10877 mac_draw_vertical_window_border,
10878 mac_shift_glyphs_for_insert
10881 void
10882 mac_initialize ()
10884 rif = &x_redisplay_interface;
10886 clear_frame_hook = x_clear_frame;
10887 ins_del_lines_hook = x_ins_del_lines;
10888 delete_glyphs_hook = x_delete_glyphs;
10889 ring_bell_hook = XTring_bell;
10890 reset_terminal_modes_hook = XTreset_terminal_modes;
10891 set_terminal_modes_hook = XTset_terminal_modes;
10892 update_begin_hook = x_update_begin;
10893 update_end_hook = x_update_end;
10894 set_terminal_window_hook = XTset_terminal_window;
10895 read_socket_hook = XTread_socket;
10896 frame_up_to_date_hook = XTframe_up_to_date;
10897 mouse_position_hook = XTmouse_position;
10898 frame_rehighlight_hook = XTframe_rehighlight;
10899 frame_raise_lower_hook = XTframe_raise_lower;
10901 set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
10902 condemn_scroll_bars_hook = XTcondemn_scroll_bars;
10903 redeem_scroll_bar_hook = XTredeem_scroll_bar;
10904 judge_scroll_bars_hook = XTjudge_scroll_bars;
10906 scroll_region_ok = 1; /* we'll scroll partial frames */
10907 char_ins_del_ok = 1;
10908 line_ins_del_ok = 1; /* we'll just blt 'em */
10909 fast_clear_end_of_line = 1; /* X does this well */
10910 memory_below_frame = 0; /* we don't remember what scrolls
10911 off the bottom */
10912 baud_rate = 19200;
10914 last_tool_bar_item = -1;
10915 any_help_event_p = 0;
10917 /* Try to use interrupt input; if we can't, then start polling. */
10918 Fset_input_mode (Qt, Qnil, Qt, Qnil);
10920 BLOCK_INPUT;
10922 #if TARGET_API_MAC_CARBON
10924 #if USE_CARBON_EVENTS
10925 #ifdef MAC_OSX
10926 init_service_handler ();
10928 init_quit_char_handler ();
10929 #endif /* MAC_OSX */
10931 init_command_handler ();
10933 init_menu_bar ();
10934 #endif /* USE_CARBON_EVENTS */
10936 #ifdef MAC_OSX
10937 init_coercion_handler ();
10939 init_apple_event_handler ();
10941 if (!inhibit_window_system)
10942 MakeMeTheFrontProcess ();
10943 #endif
10944 #endif
10946 #if USE_CG_DRAWING
10947 mac_init_fringe ();
10948 #endif
10950 UNBLOCK_INPUT;
10954 void
10955 syms_of_macterm ()
10957 #if 0
10958 staticpro (&x_error_message_string);
10959 x_error_message_string = Qnil;
10960 #endif
10962 Qcontrol = intern ("control"); staticpro (&Qcontrol);
10963 Qmeta = intern ("meta"); staticpro (&Qmeta);
10964 Qalt = intern ("alt"); staticpro (&Qalt);
10965 Qhyper = intern ("hyper"); staticpro (&Qhyper);
10966 Qsuper = intern ("super"); staticpro (&Qsuper);
10967 Qmodifier_value = intern ("modifier-value");
10968 staticpro (&Qmodifier_value);
10970 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
10971 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
10972 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
10973 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
10974 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
10976 #if USE_CARBON_EVENTS
10977 Qhicommand = intern ("hicommand"); staticpro (&Qhicommand);
10978 #ifdef MAC_OSX
10979 Qservices = intern ("services"); staticpro (&Qservices);
10980 Qpaste = intern ("paste"); staticpro (&Qpaste);
10981 Qperform = intern ("perform"); staticpro (&Qperform);
10982 #endif
10983 #endif
10985 #ifdef MAC_OSX
10986 Fprovide (intern ("mac-carbon"), Qnil);
10987 #endif
10989 staticpro (&Qreverse);
10990 Qreverse = intern ("reverse");
10992 staticpro (&x_display_name_list);
10993 x_display_name_list = Qnil;
10995 staticpro (&last_mouse_scroll_bar);
10996 last_mouse_scroll_bar = Qnil;
10998 staticpro (&fm_font_family_alist);
10999 fm_font_family_alist = Qnil;
11001 #if USE_ATSUI
11002 staticpro (&atsu_font_id_hash);
11003 atsu_font_id_hash = Qnil;
11004 #endif
11006 /* We don't yet support this, but defining this here avoids whining
11007 from cus-start.el and other places, like "M-x set-variable". */
11008 DEFVAR_BOOL ("x-use-underline-position-properties",
11009 &x_use_underline_position_properties,
11010 doc: /* *Non-nil means make use of UNDERLINE_POSITION font properties.
11011 nil means ignore them. If you encounter fonts with bogus
11012 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
11013 to 4.1, set this to nil.
11015 NOTE: Not supported on Mac yet. */);
11016 x_use_underline_position_properties = 0;
11018 DEFVAR_LISP ("x-toolkit-scroll-bars", &Vx_toolkit_scroll_bars,
11019 doc: /* If not nil, Emacs uses toolkit scroll bars. */);
11020 #ifdef USE_TOOLKIT_SCROLL_BARS
11021 Vx_toolkit_scroll_bars = Qt;
11022 #else
11023 Vx_toolkit_scroll_bars = Qnil;
11024 #endif
11026 staticpro (&last_mouse_motion_frame);
11027 last_mouse_motion_frame = Qnil;
11029 /* Variables to configure modifier key assignment. */
11031 DEFVAR_LISP ("mac-control-modifier", &Vmac_control_modifier,
11032 doc: /* *Modifier key assumed when the Mac control key is pressed.
11033 The value can be `control', `meta', `alt', `hyper', or `super' for the
11034 respective modifier. The default is `control'. */);
11035 Vmac_control_modifier = Qcontrol;
11037 DEFVAR_LISP ("mac-option-modifier", &Vmac_option_modifier,
11038 doc: /* *Modifier key assumed when the Mac alt/option key is pressed.
11039 The value can be `control', `meta', `alt', `hyper', or `super' for the
11040 respective modifier. If the value is nil then the key will act as the
11041 normal Mac control modifier, and the option key can be used to compose
11042 characters depending on the chosen Mac keyboard setting. */);
11043 Vmac_option_modifier = Qnil;
11045 DEFVAR_LISP ("mac-command-modifier", &Vmac_command_modifier,
11046 doc: /* *Modifier key assumed when the Mac command key is pressed.
11047 The value can be `control', `meta', `alt', `hyper', or `super' for the
11048 respective modifier. The default is `meta'. */);
11049 Vmac_command_modifier = Qmeta;
11051 DEFVAR_LISP ("mac-function-modifier", &Vmac_function_modifier,
11052 doc: /* *Modifier key assumed when the Mac function key is pressed.
11053 The value can be `control', `meta', `alt', `hyper', or `super' for the
11054 respective modifier. Note that remapping the function key may lead to
11055 unexpected results for some keys on non-US/GB keyboards. */);
11056 Vmac_function_modifier = Qnil;
11058 DEFVAR_LISP ("mac-emulate-three-button-mouse",
11059 &Vmac_emulate_three_button_mouse,
11060 doc: /* *Specify a way of three button mouse emulation.
11061 The value can be nil, t, or the symbol `reverse'.
11062 nil means that no emulation should be done and the modifiers should be
11063 placed on the mouse-1 event.
11064 t means that when the option-key is held down while pressing the mouse
11065 button, the click will register as mouse-2 and while the command-key
11066 is held down, the click will register as mouse-3.
11067 The symbol `reverse' means that the option-key will register for
11068 mouse-3 and the command-key will register for mouse-2. */);
11069 Vmac_emulate_three_button_mouse = Qnil;
11071 #if USE_CARBON_EVENTS
11072 DEFVAR_BOOL ("mac-wheel-button-is-mouse-2", &mac_wheel_button_is_mouse_2,
11073 doc: /* *Non-nil if the wheel button is mouse-2 and the right click mouse-3.
11074 Otherwise, the right click will be treated as mouse-2 and the wheel
11075 button will be mouse-3. */);
11076 mac_wheel_button_is_mouse_2 = 1;
11078 DEFVAR_BOOL ("mac-pass-command-to-system", &mac_pass_command_to_system,
11079 doc: /* *Non-nil if command key presses are passed on to the Mac Toolbox. */);
11080 mac_pass_command_to_system = 1;
11082 DEFVAR_BOOL ("mac-pass-control-to-system", &mac_pass_control_to_system,
11083 doc: /* *Non-nil if control key presses are passed on to the Mac Toolbox. */);
11084 mac_pass_control_to_system = 1;
11086 #endif
11088 DEFVAR_BOOL ("mac-allow-anti-aliasing", &mac_use_core_graphics,
11089 doc: /* *If non-nil, allow anti-aliasing.
11090 The text will be rendered using Core Graphics text rendering which
11091 may anti-alias the text. */);
11092 mac_use_core_graphics = 0;
11094 /* Register an entry for `mac-roman' so that it can be used when
11095 creating the terminal frame on Mac OS 9 before loading
11096 term/mac-win.elc. */
11097 DEFVAR_LISP ("mac-charset-info-alist", &Vmac_charset_info_alist,
11098 doc: /* Alist of Emacs character sets vs text encodings and coding systems.
11099 Each entry should be of the form:
11101 (CHARSET-NAME TEXT-ENCODING CODING-SYSTEM)
11103 where CHARSET-NAME is a string used in font names to identify the
11104 charset, TEXT-ENCODING is a TextEncodingBase value in Mac, and
11105 CODING_SYSTEM is a coding system corresponding to TEXT-ENCODING. */);
11106 Vmac_charset_info_alist =
11107 Fcons (list3 (build_string ("mac-roman"),
11108 make_number (smRoman), Qnil), Qnil);
11111 /* arch-tag: f2259165-4454-4c04-a029-a133c8af7b5b
11112 (do not change this comment) */