]> code.delx.au - gnu-emacs/blob - src/macterm.c
Revision: emacs@sv.gnu.org/emacs--unicode--0--patch-57
[gnu-emacs] / src / macterm.c
1 /* Implementation of GUI terminal on the Mac OS.
2 Copyright (C) 2000, 2001, 2002, 2003, 2004,
3 2005, 2006 Free Software Foundation, Inc.
4
5 This file is part of GNU Emacs.
6
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.
11
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.
16
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. */
21
22 /* Contributed by Andrew Choi (akochoi@mac.com). */
23
24 #include <config.h>
25 #include <signal.h>
26
27 #include <stdio.h>
28
29 #include "lisp.h"
30 #include "blockinput.h"
31
32 #include "macterm.h"
33
34 #ifndef MAC_OSX
35 #include <alloca.h>
36 #endif
37
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
58
59 #if __profile__
60 #include <profiler.h>
61 #endif
62 #endif /* not TARGET_API_MAC_CARBON */
63
64 #include "systty.h"
65 #include "systime.h"
66
67 #include <ctype.h>
68 #include <errno.h>
69 #include <setjmp.h>
70 #include <sys/stat.h>
71
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"
87 #include "character.h"
88 #include "ccl.h"
89
90 \f
91
92 /* Non-nil means Emacs uses toolkit scroll bars. */
93
94 Lisp_Object Vx_toolkit_scroll_bars;
95
96 /* If non-zero, the text will be rendered using Core Graphics text
97 rendering which may anti-alias the text. */
98 int mac_use_core_graphics;
99
100
101 /* Non-zero means that a HELP_EVENT has been generated since Emacs
102 start. */
103
104 static int any_help_event_p;
105
106 /* Last window where we saw the mouse. Used by mouse-autoselect-window. */
107 static Lisp_Object last_window;
108
109 /* Non-zero means make use of UNDERLINE_POSITION font properties.
110 (Not yet supported.) */
111 int x_use_underline_position_properties;
112
113 /* This is a chain of structures for all the X displays currently in
114 use. */
115
116 struct x_display_info *x_display_list;
117
118 /* This is a list of cons cells, each of the form (NAME
119 FONT-LIST-CACHE . RESOURCE-DATABASE), one for each element of
120 x_display_list and in the same order. NAME is the name of the
121 frame. FONT-LIST-CACHE records previous values returned by
122 x-list-fonts. RESOURCE-DATABASE preserves the X Resource Database
123 equivalent, which is implemented with a Lisp object, for the
124 display. */
125
126 Lisp_Object x_display_name_list;
127
128 /* This is display since Mac does not support multiple ones. */
129 struct mac_display_info one_mac_display_info;
130
131 /* Frame being updated by update_frame. This is declared in term.c.
132 This is set by update_begin and looked at by all the XT functions.
133 It is zero while not inside an update. In that case, the XT
134 functions assume that `selected_frame' is the frame to apply to. */
135
136 extern struct frame *updating_frame;
137
138 /* This is a frame waiting to be auto-raised, within XTread_socket. */
139
140 struct frame *pending_autoraise_frame;
141
142 /* Mouse movement.
143
144 Formerly, we used PointerMotionHintMask (in standard_event_mask)
145 so that we would have to call XQueryPointer after each MotionNotify
146 event to ask for another such event. However, this made mouse tracking
147 slow, and there was a bug that made it eventually stop.
148
149 Simply asking for MotionNotify all the time seems to work better.
150
151 In order to avoid asking for motion events and then throwing most
152 of them away or busy-polling the server for mouse positions, we ask
153 the server for pointer motion hints. This means that we get only
154 one event per group of mouse movements. "Groups" are delimited by
155 other kinds of events (focus changes and button clicks, for
156 example), or by XQueryPointer calls; when one of these happens, we
157 get another MotionNotify event the next time the mouse moves. This
158 is at least as efficient as getting motion events when mouse
159 tracking is on, and I suspect only negligibly worse when tracking
160 is off. */
161
162 /* Where the mouse was last time we reported a mouse event. */
163
164 static Rect last_mouse_glyph;
165 static FRAME_PTR last_mouse_glyph_frame;
166
167 /* The scroll bar in which the last X motion event occurred.
168
169 If the last X motion event occurred in a scroll bar, we set this so
170 XTmouse_position can know whether to report a scroll bar motion or
171 an ordinary motion.
172
173 If the last X motion event didn't occur in a scroll bar, we set
174 this to Qnil, to tell XTmouse_position to return an ordinary motion
175 event. */
176
177 static Lisp_Object last_mouse_scroll_bar;
178
179 /* This is a hack. We would really prefer that XTmouse_position would
180 return the time associated with the position it returns, but there
181 doesn't seem to be any way to wrest the time-stamp from the server
182 along with the position query. So, we just keep track of the time
183 of the last movement we received, and return that in hopes that
184 it's somewhat accurate. */
185
186 static Time last_mouse_movement_time;
187
188 struct scroll_bar *tracked_scroll_bar = NULL;
189
190 /* Incremented by XTread_socket whenever it really tries to read
191 events. */
192
193 #ifdef __STDC__
194 static int volatile input_signal_count;
195 #else
196 static int input_signal_count;
197 #endif
198
199 extern Lisp_Object Vsystem_name;
200
201 /* A mask of extra modifier bits to put into every keyboard char. */
202
203 extern EMACS_INT extra_keyboard_modifiers;
204
205 /* The keysyms to use for the various modifiers. */
206
207 static Lisp_Object Qalt, Qhyper, Qsuper, Qcontrol, Qmeta, Qmodifier_value;
208
209 extern int inhibit_window_system;
210
211 #if __MRC__ && !TARGET_API_MAC_CARBON
212 QDGlobals qd; /* QuickDraw global information structure. */
213 #endif
214
215 #define mac_window_to_frame(wp) (((mac_output *) GetWRefCon (wp))->mFP)
216
217 struct mac_display_info *mac_display_info_for_display (Display *);
218 static void x_update_window_end P_ ((struct window *, int, int));
219 int x_catch_errors P_ ((Display *));
220 void x_uncatch_errors P_ ((Display *, int));
221 void x_lower_frame P_ ((struct frame *));
222 void x_scroll_bar_clear P_ ((struct frame *));
223 int x_had_errors_p P_ ((Display *));
224 void x_wm_set_size_hint P_ ((struct frame *, long, int));
225 void x_raise_frame P_ ((struct frame *));
226 void x_set_window_size P_ ((struct frame *, int, int, int));
227 void x_wm_set_window_state P_ ((struct frame *, int));
228 void x_wm_set_icon_pixmap P_ ((struct frame *, int));
229 void mac_initialize P_ ((void));
230 static void x_font_min_bounds P_ ((XFontStruct *, int *, int *));
231 static int x_compute_min_glyph_bounds P_ ((struct frame *));
232 static void x_update_end P_ ((struct frame *));
233 static void XTframe_up_to_date P_ ((struct frame *));
234 static void XTset_terminal_modes P_ ((void));
235 static void XTreset_terminal_modes P_ ((void));
236 static void x_clear_frame P_ ((void));
237 static void frame_highlight P_ ((struct frame *));
238 static void frame_unhighlight P_ ((struct frame *));
239 static void x_new_focus_frame P_ ((struct x_display_info *, struct frame *));
240 static void mac_focus_changed P_ ((int, struct mac_display_info *,
241 struct frame *, struct input_event *));
242 static void x_detect_focus_change P_ ((struct mac_display_info *,
243 EventRecord *, struct input_event *));
244 static void XTframe_rehighlight P_ ((struct frame *));
245 static void x_frame_rehighlight P_ ((struct x_display_info *));
246 static void x_draw_hollow_cursor P_ ((struct window *, struct glyph_row *));
247 static void x_draw_bar_cursor P_ ((struct window *, struct glyph_row *, int,
248 enum text_cursor_kinds));
249
250 static void x_clip_to_row P_ ((struct window *, struct glyph_row *, int, GC));
251 static void x_flush P_ ((struct frame *f));
252 static void x_update_begin P_ ((struct frame *));
253 static void x_update_window_begin P_ ((struct window *));
254 static void x_after_update_window_line P_ ((struct glyph_row *));
255 static void x_scroll_bar_report_motion P_ ((struct frame **, Lisp_Object *,
256 enum scroll_bar_part *,
257 Lisp_Object *, Lisp_Object *,
258 unsigned long *));
259
260 static int is_emacs_window P_ ((WindowPtr));
261 static XCharStruct *mac_per_char_metric P_ ((XFontStruct *, XChar2b *, int));
262 static void XSetFont P_ ((Display *, GC, XFontStruct *));
263
264 /* Defined in macmenu.h. */
265 extern void menubar_selection_callback (FRAME_PTR, int);
266
267 #define GC_FORE_COLOR(gc) (&(gc)->fore_color)
268 #define GC_BACK_COLOR(gc) (&(gc)->back_color)
269 #define GC_FONT(gc) ((gc)->xgcv.font)
270 #define FRAME_NORMAL_GC(f) ((f)->output_data.mac->normal_gc)
271 #define CG_SET_FILL_COLOR(context, color) \
272 CGContextSetRGBFillColor (context, \
273 RED_FROM_ULONG (color) / 255.0f, \
274 GREEN_FROM_ULONG (color) / 255.0f, \
275 BLUE_FROM_ULONG (color) / 255.0f, 1.0f)
276 #define CG_SET_STROKE_COLOR(context, color) \
277 CGContextSetRGBStrokeColor (context, \
278 RED_FROM_ULONG (color) / 255.0f, \
279 GREEN_FROM_ULONG (color) / 255.0f, \
280 BLUE_FROM_ULONG (color) / 255.0f, 1.0f)
281 #if USE_CG_DRAWING
282 #define FRAME_CG_CONTEXT(f) ((f)->output_data.mac->cg_context)
283
284 /* Fringe bitmaps. */
285
286 static int max_fringe_bmp = 0;
287 static CGImageRef *fringe_bmp = 0;
288
289 static CGContextRef
290 mac_begin_cg_clip (f, gc)
291 struct frame *f;
292 GC gc;
293 {
294 CGContextRef context = FRAME_CG_CONTEXT (f);
295
296 if (!context)
297 {
298 QDBeginCGContext (GetWindowPort (FRAME_MAC_WINDOW (f)), &context);
299 FRAME_CG_CONTEXT (f) = context;
300 }
301
302 CGContextSaveGState (context);
303 CGContextTranslateCTM (context, 0, FRAME_PIXEL_HEIGHT (f));
304 CGContextScaleCTM (context, 1, -1);
305 if (gc && gc->n_clip_rects)
306 CGContextClipToRects (context, gc->clip_rects, gc->n_clip_rects);
307
308 return context;
309 }
310
311 static void
312 mac_end_cg_clip (f)
313 struct frame *f;
314 {
315 CGContextRestoreGState (FRAME_CG_CONTEXT (f));
316 }
317
318 void
319 mac_prepare_for_quickdraw (f)
320 struct frame *f;
321 {
322 if (f == NULL)
323 {
324 Lisp_Object rest, frame;
325 FOR_EACH_FRAME (rest, frame)
326 if (FRAME_MAC_P (XFRAME (frame)))
327 mac_prepare_for_quickdraw (XFRAME (frame));
328 }
329 else
330 {
331 CGContextRef context = FRAME_CG_CONTEXT (f);
332
333 if (context)
334 {
335 CGContextSynchronize (context);
336 QDEndCGContext (GetWindowPort (FRAME_MAC_WINDOW (f)),
337 &FRAME_CG_CONTEXT (f));
338 }
339 }
340 }
341 #endif
342
343 static RgnHandle saved_port_clip_region = NULL;
344
345 static void
346 mac_begin_clip (gc)
347 GC gc;
348 {
349 static RgnHandle new_region = NULL;
350
351 if (saved_port_clip_region == NULL)
352 saved_port_clip_region = NewRgn ();
353 if (new_region == NULL)
354 new_region = NewRgn ();
355
356 if (gc->n_clip_rects)
357 {
358 GetClip (saved_port_clip_region);
359 SectRgn (saved_port_clip_region, gc->clip_region, new_region);
360 SetClip (new_region);
361 }
362 }
363
364 static void
365 mac_end_clip (gc)
366 GC gc;
367 {
368 if (gc->n_clip_rects)
369 SetClip (saved_port_clip_region);
370 }
371
372
373 /* X display function emulation */
374
375 void
376 XFreePixmap (display, pixmap)
377 Display *display; /* not used */
378 Pixmap pixmap;
379 {
380 DisposeGWorld (pixmap);
381 }
382
383
384 /* Mac version of XDrawLine. */
385
386 static void
387 mac_draw_line (f, gc, x1, y1, x2, y2)
388 struct frame *f;
389 GC gc;
390 int x1, y1, x2, y2;
391 {
392 #if USE_CG_DRAWING
393 CGContextRef context;
394
395 context = mac_begin_cg_clip (f, gc);
396 CG_SET_STROKE_COLOR (context, gc->xgcv.foreground);
397 CGContextBeginPath (context);
398 CGContextMoveToPoint (context, x1 + 0.5f, y1 + 0.5f);
399 CGContextAddLineToPoint (context, x2 + 0.5f, y2 + 0.5f);
400 CGContextClosePath (context);
401 CGContextStrokePath (context);
402 mac_end_cg_clip (f);
403 #else
404 SetPortWindowPort (FRAME_MAC_WINDOW (f));
405
406 RGBForeColor (GC_FORE_COLOR (gc));
407
408 mac_begin_clip (gc);
409 MoveTo (x1, y1);
410 LineTo (x2, y2);
411 mac_end_clip (gc);
412 #endif
413 }
414
415 void
416 mac_draw_line_to_pixmap (display, p, gc, x1, y1, x2, y2)
417 Display *display;
418 Pixmap p;
419 GC gc;
420 int x1, y1, x2, y2;
421 {
422 CGrafPtr old_port;
423 GDHandle old_gdh;
424
425 GetGWorld (&old_port, &old_gdh);
426 SetGWorld (p, NULL);
427
428 RGBForeColor (GC_FORE_COLOR (gc));
429
430 LockPixels (GetGWorldPixMap (p));
431 MoveTo (x1, y1);
432 LineTo (x2, y2);
433 UnlockPixels (GetGWorldPixMap (p));
434
435 SetGWorld (old_port, old_gdh);
436 }
437
438
439 static void
440 mac_erase_rectangle (f, gc, x, y, width, height)
441 struct frame *f;
442 GC gc;
443 int x, y;
444 unsigned int width, height;
445 {
446 #if USE_CG_DRAWING
447 CGContextRef context;
448
449 context = mac_begin_cg_clip (f, gc);
450 CG_SET_FILL_COLOR (context, gc->xgcv.background);
451 CGContextFillRect (context, CGRectMake (x, y, width, height));
452 mac_end_cg_clip (f);
453 #else
454 Rect r;
455
456 SetPortWindowPort (FRAME_MAC_WINDOW (f));
457
458 RGBBackColor (GC_BACK_COLOR (gc));
459 SetRect (&r, x, y, x + width, y + height);
460
461 mac_begin_clip (gc);
462 EraseRect (&r);
463 mac_end_clip (gc);
464
465 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
466 #endif
467 }
468
469
470 /* Mac version of XClearArea. */
471
472 void
473 mac_clear_area (f, x, y, width, height)
474 struct frame *f;
475 int x, y;
476 unsigned int width, height;
477 {
478 mac_erase_rectangle (f, FRAME_NORMAL_GC (f), x, y, width, height);
479 }
480
481 /* Mac version of XClearWindow. */
482
483 static void
484 mac_clear_window (f)
485 struct frame *f;
486 {
487 #if USE_CG_DRAWING
488 CGContextRef context;
489 GC gc = FRAME_NORMAL_GC (f);
490
491 context = mac_begin_cg_clip (f, NULL);
492 CG_SET_FILL_COLOR (context, gc->xgcv.background);
493 CGContextFillRect (context, CGRectMake (0, 0, FRAME_PIXEL_WIDTH (f),
494 FRAME_PIXEL_HEIGHT (f)));
495 mac_end_cg_clip (f);
496 #else
497 SetPortWindowPort (FRAME_MAC_WINDOW (f));
498
499 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
500
501 #if TARGET_API_MAC_CARBON
502 {
503 Rect r;
504
505 GetWindowPortBounds (FRAME_MAC_WINDOW (f), &r);
506 EraseRect (&r);
507 }
508 #else /* not TARGET_API_MAC_CARBON */
509 EraseRect (&(FRAME_MAC_WINDOW (f)->portRect));
510 #endif /* not TARGET_API_MAC_CARBON */
511 #endif
512 }
513
514
515 /* Mac replacement for XCopyArea. */
516
517 #if USE_CG_DRAWING
518 static void
519 mac_draw_cg_image (image, f, gc, src_x, src_y, width, height,
520 dest_x, dest_y, overlay_p)
521 CGImageRef image;
522 struct frame *f;
523 GC gc;
524 int src_x, src_y;
525 unsigned int width, height;
526 int dest_x, dest_y, overlay_p;
527 {
528 CGContextRef context;
529 float port_height = FRAME_PIXEL_HEIGHT (f);
530 CGRect dest_rect = CGRectMake (dest_x, dest_y, width, height);
531
532 context = mac_begin_cg_clip (f, gc);
533 if (!overlay_p)
534 {
535 CG_SET_FILL_COLOR (context, gc->xgcv.background);
536 CGContextFillRect (context, dest_rect);
537 }
538 CGContextClipToRect (context, dest_rect);
539 CGContextScaleCTM (context, 1, -1);
540 CGContextTranslateCTM (context, 0, -port_height);
541 if (CGImageIsMask (image))
542 CG_SET_FILL_COLOR (context, gc->xgcv.foreground);
543 CGContextDrawImage (context,
544 CGRectMake (dest_x - src_x,
545 port_height - (dest_y - src_y
546 + CGImageGetHeight (image)),
547 CGImageGetWidth (image),
548 CGImageGetHeight (image)),
549 image);
550 mac_end_cg_clip (f);
551 }
552
553 #else /* !USE_CG_DRAWING */
554
555 static void
556 mac_draw_bitmap (f, gc, x, y, width, height, bits, overlay_p)
557 struct frame *f;
558 GC gc;
559 int x, y, width, height;
560 unsigned short *bits;
561 int overlay_p;
562 {
563 BitMap bitmap;
564 Rect r;
565
566 bitmap.rowBytes = sizeof(unsigned short);
567 bitmap.baseAddr = (char *)bits;
568 SetRect (&(bitmap.bounds), 0, 0, width, height);
569
570 SetPortWindowPort (FRAME_MAC_WINDOW (f));
571
572 RGBForeColor (GC_FORE_COLOR (gc));
573 RGBBackColor (GC_BACK_COLOR (gc));
574 SetRect (&r, x, y, x + width, y + height);
575
576 mac_begin_clip (gc);
577 #if TARGET_API_MAC_CARBON
578 {
579 CGrafPtr port;
580
581 GetPort (&port);
582 LockPortBits (port);
583 CopyBits (&bitmap, GetPortBitMapForCopyBits (port),
584 &(bitmap.bounds), &r, overlay_p ? srcOr : srcCopy, 0);
585 UnlockPortBits (port);
586 }
587 #else /* not TARGET_API_MAC_CARBON */
588 CopyBits (&bitmap, &(FRAME_MAC_WINDOW (f)->portBits), &(bitmap.bounds), &r,
589 overlay_p ? srcOr : srcCopy, 0);
590 #endif /* not TARGET_API_MAC_CARBON */
591 mac_end_clip (gc);
592
593 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
594 }
595 #endif /* !USE_CG_DRAWING */
596
597
598 /* Mac replacement for XCreateBitmapFromBitmapData. */
599
600 static void
601 mac_create_bitmap_from_bitmap_data (bitmap, bits, w, h)
602 BitMap *bitmap;
603 char *bits;
604 int w, h;
605 {
606 static unsigned char swap_nibble[16]
607 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
608 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
609 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
610 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
611 int i, j, w1;
612 char *p;
613
614 w1 = (w + 7) / 8; /* nb of 8bits elt in X bitmap */
615 bitmap->rowBytes = ((w + 15) / 16) * 2; /* nb of 16bits elt in Mac bitmap */
616 bitmap->baseAddr = xmalloc (bitmap->rowBytes * h);
617 bzero (bitmap->baseAddr, bitmap->rowBytes * h);
618 for (i = 0; i < h; i++)
619 {
620 p = bitmap->baseAddr + i * bitmap->rowBytes;
621 for (j = 0; j < w1; j++)
622 {
623 /* Bitswap XBM bytes to match how Mac does things. */
624 unsigned char c = *bits++;
625 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
626 | (swap_nibble[(c>>4) & 0xf]));;
627 }
628 }
629
630 SetRect (&(bitmap->bounds), 0, 0, w, h);
631 }
632
633
634 static void
635 mac_free_bitmap (bitmap)
636 BitMap *bitmap;
637 {
638 xfree (bitmap->baseAddr);
639 }
640
641
642 Pixmap
643 XCreatePixmap (display, w, width, height, depth)
644 Display *display; /* not used */
645 WindowPtr w;
646 unsigned int width, height;
647 unsigned int depth;
648 {
649 Pixmap pixmap;
650 Rect r;
651 QDErr err;
652
653 SetPortWindowPort (w);
654
655 SetRect (&r, 0, 0, width, height);
656 #if !defined (WORDS_BIG_ENDIAN) && USE_CG_DRAWING
657 if (depth == 1)
658 #endif
659 err = NewGWorld (&pixmap, depth, &r, NULL, NULL, 0);
660 #if !defined (WORDS_BIG_ENDIAN) && USE_CG_DRAWING
661 else
662 /* CreateCGImageFromPixMaps requires ARGB format. */
663 err = QTNewGWorld (&pixmap, k32ARGBPixelFormat, &r, NULL, NULL, 0);
664 #endif
665 if (err != noErr)
666 return NULL;
667 return pixmap;
668 }
669
670
671 Pixmap
672 XCreatePixmapFromBitmapData (display, w, data, width, height, fg, bg, depth)
673 Display *display; /* not used */
674 WindowPtr w;
675 char *data;
676 unsigned int width, height;
677 unsigned long fg, bg;
678 unsigned int depth;
679 {
680 Pixmap pixmap;
681 BitMap bitmap;
682 CGrafPtr old_port;
683 GDHandle old_gdh;
684 static GC gc = NULL; /* not reentrant */
685
686 if (gc == NULL)
687 gc = XCreateGC (display, w, 0, NULL);
688
689 pixmap = XCreatePixmap (display, w, width, height, depth);
690 if (pixmap == NULL)
691 return NULL;
692
693 GetGWorld (&old_port, &old_gdh);
694 SetGWorld (pixmap, NULL);
695 mac_create_bitmap_from_bitmap_data (&bitmap, data, width, height);
696 XSetForeground (display, gc, fg);
697 XSetBackground (display, gc, bg);
698 RGBForeColor (GC_FORE_COLOR (gc));
699 RGBBackColor (GC_BACK_COLOR (gc));
700 LockPixels (GetGWorldPixMap (pixmap));
701 #if TARGET_API_MAC_CARBON
702 CopyBits (&bitmap, GetPortBitMapForCopyBits (pixmap),
703 &bitmap.bounds, &bitmap.bounds, srcCopy, 0);
704 #else /* not TARGET_API_MAC_CARBON */
705 CopyBits (&bitmap, &(((GrafPtr)pixmap)->portBits),
706 &bitmap.bounds, &bitmap.bounds, srcCopy, 0);
707 #endif /* not TARGET_API_MAC_CARBON */
708 UnlockPixels (GetGWorldPixMap (pixmap));
709 SetGWorld (old_port, old_gdh);
710 mac_free_bitmap (&bitmap);
711
712 return pixmap;
713 }
714
715
716 /* Mac replacement for XFillRectangle. */
717
718 static void
719 mac_fill_rectangle (f, gc, x, y, width, height)
720 struct frame *f;
721 GC gc;
722 int x, y;
723 unsigned int width, height;
724 {
725 #if USE_CG_DRAWING
726 CGContextRef context;
727
728 context = mac_begin_cg_clip (f, gc);
729 CG_SET_FILL_COLOR (context, gc->xgcv.foreground);
730 CGContextFillRect (context, CGRectMake (x, y, width, height));
731 mac_end_cg_clip (f);
732 #else
733 Rect r;
734
735 SetPortWindowPort (FRAME_MAC_WINDOW (f));
736
737 RGBForeColor (GC_FORE_COLOR (gc));
738 SetRect (&r, x, y, x + width, y + height);
739
740 mac_begin_clip (gc);
741 PaintRect (&r); /* using foreground color of gc */
742 mac_end_clip (gc);
743 #endif
744 }
745
746
747 /* Mac replacement for XDrawRectangle: dest is a window. */
748
749 static void
750 mac_draw_rectangle (f, gc, x, y, width, height)
751 struct frame *f;
752 GC gc;
753 int x, y;
754 unsigned int width, height;
755 {
756 #if USE_CG_DRAWING
757 CGContextRef context;
758
759 context = mac_begin_cg_clip (f, gc);
760 CG_SET_STROKE_COLOR (context, gc->xgcv.foreground);
761 CGContextStrokeRect (context,
762 CGRectMake (x + 0.5f, y + 0.5f, width, height));
763 mac_end_cg_clip (f);
764 #else
765 Rect r;
766
767 SetPortWindowPort (FRAME_MAC_WINDOW (f));
768
769 RGBForeColor (GC_FORE_COLOR (gc));
770 SetRect (&r, x, y, x + width + 1, y + height + 1);
771
772 mac_begin_clip (gc);
773 FrameRect (&r); /* using foreground color of gc */
774 mac_end_clip (gc);
775 #endif
776 }
777
778
779 #if USE_ATSUI
780 static OSStatus
781 atsu_get_text_layout_with_text_ptr (text, text_length, style, text_layout)
782 ConstUniCharArrayPtr text;
783 UniCharCount text_length;
784 ATSUStyle style;
785 ATSUTextLayout *text_layout;
786 {
787 OSStatus err;
788 static ATSUTextLayout saved_text_layout = NULL; /* not reentrant */
789
790 if (saved_text_layout == NULL)
791 {
792 UniCharCount lengths[] = {kATSUToTextEnd};
793 ATSUAttributeTag tags[] = {kATSULineLayoutOptionsTag};
794 ByteCount sizes[] = {sizeof (ATSLineLayoutOptions)};
795 static ATSLineLayoutOptions line_layout =
796 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
797 kATSLineDisableAllLayoutOperations | kATSLineUseDeviceMetrics
798 | kATSLineUseQDRendering
799 #else
800 kATSLineIsDisplayOnly | kATSLineFractDisable
801 #endif
802 ;
803 ATSUAttributeValuePtr values[] = {&line_layout};
804
805 err = ATSUCreateTextLayoutWithTextPtr (text,
806 kATSUFromTextBeginning,
807 kATSUToTextEnd,
808 text_length,
809 1, lengths, &style,
810 &saved_text_layout);
811 if (err == noErr)
812 err = ATSUSetLayoutControls (saved_text_layout,
813 sizeof (tags) / sizeof (tags[0]),
814 tags, sizes, values);
815 /* XXX: Should we do this? */
816 if (err == noErr)
817 err = ATSUSetTransientFontMatching (saved_text_layout, true);
818 }
819 else
820 {
821 err = ATSUSetRunStyle (saved_text_layout, style,
822 kATSUFromTextBeginning, kATSUToTextEnd);
823 if (err == noErr)
824 err = ATSUSetTextPointerLocation (saved_text_layout, text,
825 kATSUFromTextBeginning,
826 kATSUToTextEnd,
827 text_length);
828 }
829
830 if (err == noErr)
831 *text_layout = saved_text_layout;
832 return err;
833 }
834 #endif
835
836
837 static void
838 mac_invert_rectangle (f, x, y, width, height)
839 struct frame *f;
840 int x, y;
841 unsigned int width, height;
842 {
843 Rect r;
844
845 #if USE_CG_DRAWING
846 mac_prepare_for_quickdraw (f);
847 #endif
848 SetPortWindowPort (FRAME_MAC_WINDOW (f));
849
850 SetRect (&r, x, y, x + width, y + height);
851
852 InvertRect (&r);
853 }
854
855
856 static void
857 mac_draw_string_common (f, gc, x, y, buf, nchars, bg_width, bytes_per_char)
858 struct frame *f;
859 GC gc;
860 int x, y;
861 char *buf;
862 int nchars, bg_width, bytes_per_char;
863 {
864 SetPortWindowPort (FRAME_MAC_WINDOW (f));
865
866 #if USE_ATSUI
867 if (GC_FONT (gc)->mac_style)
868 {
869 OSErr err;
870 ATSUTextLayout text_layout;
871
872 xassert (bytes_per_char == 2);
873
874 #ifndef WORDS_BIG_ENDIAN
875 {
876 int i;
877 UniChar *text = (UniChar *)buf;
878
879 for (i = 0; i < nchars; i++)
880 text[i] = EndianU16_BtoN (text[i]);
881 }
882 #endif
883 err = atsu_get_text_layout_with_text_ptr ((ConstUniCharArrayPtr)buf,
884 nchars,
885 GC_FONT (gc)->mac_style,
886 &text_layout);
887 if (err != noErr)
888 return;
889 #ifdef MAC_OSX
890 if (!mac_use_core_graphics)
891 {
892 #endif
893 #if USE_CG_DRAWING
894 mac_prepare_for_quickdraw (f);
895 #endif
896 mac_begin_clip (gc);
897 RGBForeColor (GC_FORE_COLOR (gc));
898 if (bg_width)
899 {
900 Rect r;
901
902 SetRect (&r, x, y - FONT_BASE (GC_FONT (gc)),
903 x + bg_width, y + FONT_DESCENT (GC_FONT (gc)));
904 RGBBackColor (GC_BACK_COLOR (gc));
905 EraseRect (&r);
906 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
907 }
908 MoveTo (x, y);
909 ATSUDrawText (text_layout,
910 kATSUFromTextBeginning, kATSUToTextEnd,
911 kATSUUseGrafPortPenLoc, kATSUUseGrafPortPenLoc);
912 mac_end_clip (gc);
913 #ifdef MAC_OSX
914 }
915 else
916 {
917 CGrafPtr port;
918 CGContextRef context;
919 float port_height = FRAME_PIXEL_HEIGHT (f);
920 ATSUAttributeTag tags[] = {kATSUCGContextTag};
921 ByteCount sizes[] = {sizeof (CGContextRef)};
922 ATSUAttributeValuePtr values[] = {&context};
923
924 #if USE_CG_DRAWING
925 context = mac_begin_cg_clip (f, gc);
926 #else
927 GetPort (&port);
928 QDBeginCGContext (port, &context);
929 if (gc->n_clip_rects || bg_width)
930 {
931 CGContextTranslateCTM (context, 0, port_height);
932 CGContextScaleCTM (context, 1, -1);
933 if (gc->n_clip_rects)
934 CGContextClipToRects (context, gc->clip_rects,
935 gc->n_clip_rects);
936 #endif
937 if (bg_width)
938 {
939 CG_SET_FILL_COLOR (context, gc->xgcv.background);
940 CGContextFillRect
941 (context,
942 CGRectMake (x, y - FONT_BASE (GC_FONT (gc)),
943 bg_width, FONT_HEIGHT (GC_FONT (gc))));
944 }
945 CGContextScaleCTM (context, 1, -1);
946 CGContextTranslateCTM (context, 0, -port_height);
947 #if !USE_CG_DRAWING
948 }
949 #endif
950 CG_SET_FILL_COLOR (context, gc->xgcv.foreground);
951 err = ATSUSetLayoutControls (text_layout,
952 sizeof (tags) / sizeof (tags[0]),
953 tags, sizes, values);
954 if (err == noErr)
955 ATSUDrawText (text_layout,
956 kATSUFromTextBeginning, kATSUToTextEnd,
957 Long2Fix (x), Long2Fix (port_height - y));
958 #if USE_CG_DRAWING
959 mac_end_cg_clip (f);
960 context = NULL;
961 #else
962 CGContextSynchronize (context);
963 QDEndCGContext (port, &context);
964 #endif
965 #if 0
966 /* This doesn't work on Mac OS X 10.1. */
967 ATSUClearLayoutControls (text_layout,
968 sizeof (tags) / sizeof (tags[0]), tags);
969 #else
970 ATSUSetLayoutControls (text_layout,
971 sizeof (tags) / sizeof (tags[0]),
972 tags, sizes, values);
973 #endif
974 }
975 #endif /* MAC_OSX */
976 }
977 else
978 #endif /* USE_ATSUI */
979 {
980 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
981 UInt32 savedFlags;
982
983 if (mac_use_core_graphics)
984 savedFlags = SwapQDTextFlags (kQDUseCGTextRendering);
985 #endif
986 #if USE_CG_DRAWING
987 mac_prepare_for_quickdraw (f);
988 #endif
989 mac_begin_clip (gc);
990 RGBForeColor (GC_FORE_COLOR (gc));
991 #ifdef MAC_OS8
992 if (bg_width)
993 {
994 RGBBackColor (GC_BACK_COLOR (gc));
995 TextMode (srcCopy);
996 }
997 else
998 TextMode (srcOr);
999 #else
1000 /* We prefer not to use srcCopy text transfer mode on Mac OS X
1001 because:
1002 - Screen is double-buffered. (In srcCopy mode, a text is
1003 drawn into an offscreen graphics world first. So
1004 performance gain cannot be expected.)
1005 - It lowers rendering quality.
1006 - Some fonts leave garbage on cursor movement. */
1007 if (bg_width)
1008 {
1009 Rect r;
1010
1011 RGBBackColor (GC_BACK_COLOR (gc));
1012 SetRect (&r, x, y - FONT_BASE (GC_FONT (gc)),
1013 x + bg_width, y + FONT_DESCENT (GC_FONT (gc)));
1014 EraseRect (&r);
1015 }
1016 TextMode (srcOr);
1017 #endif
1018 TextFont (GC_FONT (gc)->mac_fontnum);
1019 TextSize (GC_FONT (gc)->mac_fontsize);
1020 TextFace (GC_FONT (gc)->mac_fontface);
1021 MoveTo (x, y);
1022 DrawText (buf, 0, nchars * bytes_per_char);
1023 if (bg_width)
1024 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
1025 mac_end_clip (gc);
1026
1027 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
1028 if (mac_use_core_graphics)
1029 SwapQDTextFlags(savedFlags);
1030 #endif
1031 }
1032 }
1033
1034
1035 /* Mac replacement for XDrawString. */
1036
1037 static void
1038 mac_draw_string (f, gc, x, y, buf, nchars)
1039 struct frame *f;
1040 GC gc;
1041 int x, y;
1042 char *buf;
1043 int nchars;
1044 {
1045 mac_draw_string_common (f, gc, x, y, buf, nchars, 0, 1);
1046 }
1047
1048
1049 /* Mac replacement for XDrawString16. */
1050
1051 static void
1052 mac_draw_string_16 (f, gc, x, y, buf, nchars)
1053 struct frame *f;
1054 GC gc;
1055 int x, y;
1056 XChar2b *buf;
1057 int nchars;
1058 {
1059 mac_draw_string_common (f, gc, x, y, (char *) buf, nchars, 0, 2);
1060 }
1061
1062
1063 /* Mac replacement for XDrawImageString. */
1064
1065 static void
1066 mac_draw_image_string (f, gc, x, y, buf, nchars, bg_width)
1067 struct frame *f;
1068 GC gc;
1069 int x, y;
1070 char *buf;
1071 int nchars, bg_width;
1072 {
1073 mac_draw_string_common (f, gc, x, y, buf, nchars, bg_width, 1);
1074 }
1075
1076
1077 /* Mac replacement for XDrawString16. */
1078
1079 static void
1080 mac_draw_image_string_16 (f, gc, x, y, buf, nchars, bg_width)
1081 struct frame *f;
1082 GC gc;
1083 int x, y;
1084 XChar2b *buf;
1085 int nchars, bg_width;
1086 {
1087 mac_draw_string_common (f, gc, x, y, (char *) buf, nchars, bg_width, 2);
1088 }
1089
1090
1091 /* Mac replacement for XQueryTextExtents, but takes a character. If
1092 STYLE is NULL, measurement is done by QuickDraw Text routines for
1093 the font of the current graphics port. If CG_GLYPH is not NULL,
1094 *CG_GLYPH is set to the glyph ID or 0 if it cannot be obtained. */
1095
1096 static OSErr
1097 mac_query_char_extents (style, c,
1098 font_ascent_return, font_descent_return,
1099 overall_return, cg_glyph)
1100 #if USE_ATSUI
1101 ATSUStyle style;
1102 #else
1103 void *style;
1104 #endif
1105 int c;
1106 int *font_ascent_return, *font_descent_return;
1107 XCharStruct *overall_return;
1108 #if USE_CG_TEXT_DRAWING
1109 CGGlyph *cg_glyph;
1110 #else
1111 void *cg_glyph;
1112 #endif
1113 {
1114 OSErr err = noErr;
1115 int width;
1116 Rect char_bounds;
1117
1118 #if USE_ATSUI
1119 if (style)
1120 {
1121 ATSUTextLayout text_layout;
1122 UniChar ch = c;
1123
1124 err = atsu_get_text_layout_with_text_ptr (&ch, 1, style, &text_layout);
1125 if (err == noErr)
1126 {
1127 ATSTrapezoid glyph_bounds;
1128
1129 err = ATSUGetGlyphBounds (text_layout, 0, 0,
1130 kATSUFromTextBeginning, kATSUToTextEnd,
1131 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
1132 kATSUseFractionalOrigins,
1133 #else
1134 kATSUseDeviceOrigins,
1135 #endif
1136 1, &glyph_bounds, NULL);
1137 if (err == noErr)
1138 {
1139 xassert (glyph_bounds.lowerRight.x - glyph_bounds.lowerLeft.x
1140 == glyph_bounds.upperRight.x - glyph_bounds.upperLeft.x);
1141
1142 width = Fix2Long (glyph_bounds.upperRight.x
1143 - glyph_bounds.upperLeft.x);
1144 if (font_ascent_return)
1145 *font_ascent_return = -Fix2Long (glyph_bounds.upperLeft.y);
1146 if (font_descent_return)
1147 *font_descent_return = Fix2Long (glyph_bounds.lowerLeft.y);
1148 }
1149 }
1150 if (err == noErr && overall_return)
1151 {
1152 err = ATSUMeasureTextImage (text_layout,
1153 kATSUFromTextBeginning, kATSUToTextEnd,
1154 0, 0, &char_bounds);
1155 if (err == noErr)
1156 STORE_XCHARSTRUCT (*overall_return, width, char_bounds);
1157 #if USE_CG_TEXT_DRAWING
1158 if (err == noErr && cg_glyph)
1159 {
1160 OSErr err1;
1161 ATSUGlyphInfoArray glyph_info_array;
1162 ByteCount count = sizeof (ATSUGlyphInfoArray);
1163
1164 err1 = ATSUMatchFontsToText (text_layout, kATSUFromTextBeginning,
1165 kATSUToTextEnd, NULL, NULL, NULL);
1166 if (err1 == noErr)
1167 err1 = ATSUGetGlyphInfo (text_layout, kATSUFromTextBeginning,
1168 kATSUToTextEnd, &count,
1169 &glyph_info_array);
1170 if (err1 == noErr)
1171 {
1172 xassert (glyph_info_array.glyphs[0].glyphID);
1173 *cg_glyph = glyph_info_array.glyphs[0].glyphID;
1174 }
1175 else
1176 *cg_glyph = 0;
1177 }
1178 #endif
1179 }
1180 }
1181 else
1182 #endif
1183 {
1184 if (font_ascent_return || font_descent_return)
1185 {
1186 FontInfo font_info;
1187
1188 GetFontInfo (&font_info);
1189 if (font_ascent_return)
1190 *font_ascent_return = font_info.ascent;
1191 if (font_descent_return)
1192 *font_descent_return = font_info.descent;
1193 }
1194 if (overall_return)
1195 {
1196 char ch = c;
1197
1198 width = CharWidth (ch);
1199 QDTextBounds (1, &ch, &char_bounds);
1200 STORE_XCHARSTRUCT (*overall_return, width, char_bounds);
1201 }
1202 }
1203
1204 return err;
1205 }
1206
1207
1208 /* Mac replacement for XTextExtents16. Only sets horizontal metrics. */
1209
1210 static int
1211 mac_text_extents_16 (font_struct, string, nchars, overall_return)
1212 XFontStruct *font_struct;
1213 XChar2b *string;
1214 int nchars;
1215 XCharStruct *overall_return;
1216 {
1217 int i;
1218 short width = 0, lbearing = 0, rbearing = 0;
1219 XCharStruct *pcm;
1220
1221 for (i = 0; i < nchars; i++)
1222 {
1223 pcm = mac_per_char_metric (font_struct, string, 0);
1224 if (pcm == NULL)
1225 width += FONT_WIDTH (font_struct);
1226 else
1227 {
1228 lbearing = min (lbearing, width + pcm->lbearing);
1229 rbearing = max (rbearing, width + pcm->rbearing);
1230 width += pcm->width;
1231 }
1232 string++;
1233 }
1234
1235 overall_return->lbearing = lbearing;
1236 overall_return->rbearing = rbearing;
1237 overall_return->width = width;
1238
1239 /* What's the meaning of the return value of XTextExtents16? */
1240 }
1241
1242
1243 #if USE_CG_TEXT_DRAWING
1244 static int cg_text_anti_aliasing_threshold = 8;
1245
1246 static void
1247 init_cg_text_anti_aliasing_threshold ()
1248 {
1249 int threshold;
1250 Boolean valid_p;
1251
1252 threshold =
1253 CFPreferencesGetAppIntegerValue (CFSTR ("AppleAntiAliasingThreshold"),
1254 kCFPreferencesCurrentApplication,
1255 &valid_p);
1256 if (valid_p)
1257 cg_text_anti_aliasing_threshold = threshold;
1258 }
1259
1260 static int
1261 mac_draw_image_string_cg (f, gc, x, y, buf, nchars, bg_width)
1262 struct frame *f;
1263 GC gc;
1264 int x, y;
1265 XChar2b *buf;
1266 int nchars, bg_width;
1267 {
1268 CGrafPtr port;
1269 float port_height, gx, gy;
1270 int i;
1271 CGContextRef context;
1272 CGGlyph *glyphs;
1273 CGSize *advances;
1274
1275 if (!mac_use_core_graphics || GC_FONT (gc)->cg_font == NULL)
1276 return 0;
1277
1278 port = GetWindowPort (FRAME_MAC_WINDOW (f));
1279 port_height = FRAME_PIXEL_HEIGHT (f);
1280 gx = x;
1281 gy = port_height - y;
1282 glyphs = (CGGlyph *)buf;
1283 advances = alloca (sizeof (CGSize) * nchars);
1284 if (advances == NULL)
1285 return 0;
1286 for (i = 0; i < nchars; i++)
1287 {
1288 XCharStruct *pcm = mac_per_char_metric (GC_FONT (gc), buf, 0);
1289
1290 advances[i].width = pcm->width;
1291 advances[i].height = 0;
1292 glyphs[i] = GC_FONT (gc)->cg_glyphs[buf->byte2];
1293 buf++;
1294 }
1295
1296 #if USE_CG_DRAWING
1297 context = mac_begin_cg_clip (f, gc);
1298 #else
1299 QDBeginCGContext (port, &context);
1300 if (gc->n_clip_rects || bg_width)
1301 {
1302 CGContextTranslateCTM (context, 0, port_height);
1303 CGContextScaleCTM (context, 1, -1);
1304 if (gc->n_clip_rects)
1305 CGContextClipToRects (context, gc->clip_rects, gc->n_clip_rects);
1306 #endif
1307 if (bg_width)
1308 {
1309 CG_SET_FILL_COLOR (context, gc->xgcv.background);
1310 CGContextFillRect
1311 (context,
1312 CGRectMake (gx, y - FONT_BASE (GC_FONT (gc)),
1313 bg_width, FONT_HEIGHT (GC_FONT (gc))));
1314 }
1315 CGContextScaleCTM (context, 1, -1);
1316 CGContextTranslateCTM (context, 0, -port_height);
1317 #if !USE_CG_DRAWING
1318 }
1319 #endif
1320 CG_SET_FILL_COLOR (context, gc->xgcv.foreground);
1321 CGContextSetFont (context, GC_FONT (gc)->cg_font);
1322 CGContextSetFontSize (context, GC_FONT (gc)->mac_fontsize);
1323 if (GC_FONT (gc)->mac_fontsize <= cg_text_anti_aliasing_threshold)
1324 CGContextSetShouldAntialias (context, false);
1325 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1030
1326 CGContextSetTextPosition (context, gx, gy);
1327 CGContextShowGlyphsWithAdvances (context, glyphs, advances, nchars);
1328 #else
1329 for (i = 0; i < nchars; i++)
1330 {
1331 CGContextShowGlyphsAtPoint (context, gx, gy, glyphs + i, 1);
1332 gx += advances[i].width;
1333 }
1334 #endif
1335 #if USE_CG_DRAWING
1336 mac_end_cg_clip (f);
1337 #else
1338 CGContextSynchronize (context);
1339 QDEndCGContext (port, &context);
1340 #endif
1341
1342 return 1;
1343 }
1344 #endif
1345
1346
1347 #if !USE_CG_DRAWING
1348 /* Mac replacement for XCopyArea: dest must be window. */
1349
1350 static void
1351 mac_copy_area (src, f, gc, src_x, src_y, width, height, dest_x, dest_y)
1352 Pixmap src;
1353 struct frame *f;
1354 GC gc;
1355 int src_x, src_y;
1356 unsigned int width, height;
1357 int dest_x, dest_y;
1358 {
1359 Rect src_r, dest_r;
1360
1361 SetPortWindowPort (FRAME_MAC_WINDOW (f));
1362
1363 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
1364 SetRect (&dest_r, dest_x, dest_y, dest_x + width, dest_y + height);
1365
1366 ForeColor (blackColor);
1367 BackColor (whiteColor);
1368
1369 mac_begin_clip (gc);
1370 LockPixels (GetGWorldPixMap (src));
1371 #if TARGET_API_MAC_CARBON
1372 {
1373 CGrafPtr port;
1374
1375 GetPort (&port);
1376 LockPortBits (port);
1377 CopyBits (GetPortBitMapForCopyBits (src),
1378 GetPortBitMapForCopyBits (port),
1379 &src_r, &dest_r, srcCopy, 0);
1380 UnlockPortBits (port);
1381 }
1382 #else /* not TARGET_API_MAC_CARBON */
1383 CopyBits (&(((GrafPtr)src)->portBits), &(FRAME_MAC_WINDOW (f)->portBits),
1384 &src_r, &dest_r, srcCopy, 0);
1385 #endif /* not TARGET_API_MAC_CARBON */
1386 UnlockPixels (GetGWorldPixMap (src));
1387 mac_end_clip (gc);
1388
1389 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
1390 }
1391
1392
1393 static void
1394 mac_copy_area_with_mask (src, mask, f, gc, src_x, src_y,
1395 width, height, dest_x, dest_y)
1396 Pixmap src, mask;
1397 struct frame *f;
1398 GC gc;
1399 int src_x, src_y;
1400 unsigned int width, height;
1401 int dest_x, dest_y;
1402 {
1403 Rect src_r, dest_r;
1404
1405 SetPortWindowPort (FRAME_MAC_WINDOW (f));
1406
1407 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
1408 SetRect (&dest_r, dest_x, dest_y, dest_x + width, dest_y + height);
1409
1410 ForeColor (blackColor);
1411 BackColor (whiteColor);
1412
1413 mac_begin_clip (gc);
1414 LockPixels (GetGWorldPixMap (src));
1415 LockPixels (GetGWorldPixMap (mask));
1416 #if TARGET_API_MAC_CARBON
1417 {
1418 CGrafPtr port;
1419
1420 GetPort (&port);
1421 LockPortBits (port);
1422 CopyMask (GetPortBitMapForCopyBits (src), GetPortBitMapForCopyBits (mask),
1423 GetPortBitMapForCopyBits (port),
1424 &src_r, &src_r, &dest_r);
1425 UnlockPortBits (port);
1426 }
1427 #else /* not TARGET_API_MAC_CARBON */
1428 CopyMask (&(((GrafPtr)src)->portBits), &(((GrafPtr)mask)->portBits),
1429 &(FRAME_MAC_WINDOW (f)->portBits), &src_r, &src_r, &dest_r);
1430 #endif /* not TARGET_API_MAC_CARBON */
1431 UnlockPixels (GetGWorldPixMap (mask));
1432 UnlockPixels (GetGWorldPixMap (src));
1433 mac_end_clip (gc);
1434
1435 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
1436 }
1437 #endif /* !USE_CG_DRAWING */
1438
1439
1440 /* Mac replacement for XCopyArea: used only for scrolling. */
1441
1442 static void
1443 mac_scroll_area (f, gc, src_x, src_y, width, height, dest_x, dest_y)
1444 struct frame *f;
1445 GC gc;
1446 int src_x, src_y;
1447 unsigned int width, height;
1448 int dest_x, dest_y;
1449 {
1450 #if TARGET_API_MAC_CARBON
1451 Rect src_r;
1452 RgnHandle dummy = NewRgn (); /* For avoiding update events. */
1453
1454 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
1455 #if USE_CG_DRAWING
1456 mac_prepare_for_quickdraw (f);
1457 #endif
1458 ScrollWindowRect (FRAME_MAC_WINDOW (f),
1459 &src_r, dest_x - src_x, dest_y - src_y,
1460 kScrollWindowNoOptions, dummy);
1461 DisposeRgn (dummy);
1462 #else /* not TARGET_API_MAC_CARBON */
1463 Rect src_r, dest_r;
1464 WindowPtr w = FRAME_MAC_WINDOW (f);
1465
1466 SetPort (w);
1467
1468 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
1469 SetRect (&dest_r, dest_x, dest_y, dest_x + width, dest_y + height);
1470
1471 /* In Color QuickDraw, set ForeColor and BackColor as follows to avoid
1472 color mapping in CopyBits. Otherwise, it will be slow. */
1473 ForeColor (blackColor);
1474 BackColor (whiteColor);
1475 mac_begin_clip (gc);
1476 CopyBits (&(w->portBits), &(w->portBits), &src_r, &dest_r, srcCopy, 0);
1477 mac_end_clip (gc);
1478
1479 RGBBackColor (GC_BACK_COLOR (FRAME_NORMAL_GC (f)));
1480 #endif /* not TARGET_API_MAC_CARBON */
1481 }
1482
1483
1484 /* Mac replacement for XChangeGC. */
1485
1486 static void
1487 XChangeGC (display, gc, mask, xgcv)
1488 Display *display;
1489 GC gc;
1490 unsigned long mask;
1491 XGCValues *xgcv;
1492 {
1493 if (mask & GCForeground)
1494 XSetForeground (display, gc, xgcv->foreground);
1495 if (mask & GCBackground)
1496 XSetBackground (display, gc, xgcv->background);
1497 if (mask & GCFont)
1498 XSetFont (display, gc, xgcv->font);
1499 }
1500
1501
1502 /* Mac replacement for XCreateGC. */
1503
1504 GC
1505 XCreateGC (display, window, mask, xgcv)
1506 Display *display;
1507 Window window;
1508 unsigned long mask;
1509 XGCValues *xgcv;
1510 {
1511 GC gc = xmalloc (sizeof (*gc));
1512
1513 bzero (gc, sizeof (*gc));
1514 XChangeGC (display, gc, mask, xgcv);
1515
1516 return gc;
1517 }
1518
1519
1520 /* Used in xfaces.c. */
1521
1522 void
1523 XFreeGC (display, gc)
1524 Display *display;
1525 GC gc;
1526 {
1527 if (gc->clip_region)
1528 DisposeRgn (gc->clip_region);
1529 xfree (gc);
1530 }
1531
1532
1533 /* Mac replacement for XGetGCValues. */
1534
1535 static void
1536 XGetGCValues (display, gc, mask, xgcv)
1537 Display *display;
1538 GC gc;
1539 unsigned long mask;
1540 XGCValues *xgcv;
1541 {
1542 if (mask & GCForeground)
1543 xgcv->foreground = gc->xgcv.foreground;
1544 if (mask & GCBackground)
1545 xgcv->background = gc->xgcv.background;
1546 if (mask & GCFont)
1547 xgcv->font = gc->xgcv.font;
1548 }
1549
1550
1551 /* Mac replacement for XSetForeground. */
1552
1553 void
1554 XSetForeground (display, gc, color)
1555 Display *display;
1556 GC gc;
1557 unsigned long color;
1558 {
1559 if (gc->xgcv.foreground != color)
1560 {
1561 gc->xgcv.foreground = color;
1562 gc->fore_color.red = RED16_FROM_ULONG (color);
1563 gc->fore_color.green = GREEN16_FROM_ULONG (color);
1564 gc->fore_color.blue = BLUE16_FROM_ULONG (color);
1565 }
1566 }
1567
1568
1569 /* Mac replacement for XSetBackground. */
1570
1571 void
1572 XSetBackground (display, gc, color)
1573 Display *display;
1574 GC gc;
1575 unsigned long color;
1576 {
1577 if (gc->xgcv.background != color)
1578 {
1579 gc->xgcv.background = color;
1580 gc->back_color.red = RED16_FROM_ULONG (color);
1581 gc->back_color.green = GREEN16_FROM_ULONG (color);
1582 gc->back_color.blue = BLUE16_FROM_ULONG (color);
1583 }
1584 }
1585
1586
1587 /* Mac replacement for XSetFont. */
1588
1589 static void
1590 XSetFont (display, gc, font)
1591 Display *display;
1592 GC gc;
1593 XFontStruct *font;
1594 {
1595 gc->xgcv.font = font;
1596 }
1597
1598
1599 /* Mac replacement for XSetClipRectangles. */
1600
1601 static void
1602 mac_set_clip_rectangles (display, gc, rectangles, n)
1603 Display *display;
1604 GC gc;
1605 Rect *rectangles;
1606 int n;
1607 {
1608 int i;
1609
1610 xassert (n >= 0 && n <= MAX_CLIP_RECTS);
1611
1612 gc->n_clip_rects = n;
1613 if (n > 0)
1614 {
1615 if (gc->clip_region == NULL)
1616 gc->clip_region = NewRgn ();
1617 RectRgn (gc->clip_region, rectangles);
1618 if (n > 1)
1619 {
1620 RgnHandle region = NewRgn ();
1621
1622 for (i = 1; i < n; i++)
1623 {
1624 RectRgn (region, rectangles + i);
1625 UnionRgn (gc->clip_region, region, gc->clip_region);
1626 }
1627 DisposeRgn (region);
1628 }
1629 }
1630 #if defined (MAC_OSX) && USE_ATSUI
1631 for (i = 0; i < n; i++)
1632 {
1633 Rect *rect = rectangles + i;
1634
1635 gc->clip_rects[i] = CGRectMake (rect->left, rect->top,
1636 rect->right - rect->left,
1637 rect->bottom - rect->top);
1638 }
1639 #endif
1640 }
1641
1642
1643 /* Mac replacement for XSetClipMask. */
1644
1645 static INLINE void
1646 mac_reset_clip_rectangles (display, gc)
1647 Display *display;
1648 GC gc;
1649 {
1650 gc->n_clip_rects = 0;
1651 }
1652
1653
1654 /* Mac replacement for XSetWindowBackground. */
1655
1656 void
1657 XSetWindowBackground (display, w, color)
1658 Display *display;
1659 WindowPtr w;
1660 unsigned long color;
1661 {
1662 #if !TARGET_API_MAC_CARBON
1663 AuxWinHandle aw_handle;
1664 CTabHandle ctab_handle;
1665 ColorSpecPtr ct_table;
1666 short ct_size;
1667 #endif
1668 RGBColor bg_color;
1669
1670 bg_color.red = RED16_FROM_ULONG (color);
1671 bg_color.green = GREEN16_FROM_ULONG (color);
1672 bg_color.blue = BLUE16_FROM_ULONG (color);
1673
1674 #if TARGET_API_MAC_CARBON
1675 SetWindowContentColor (w, &bg_color);
1676 #else
1677 if (GetAuxWin (w, &aw_handle))
1678 {
1679 ctab_handle = (*aw_handle)->awCTable;
1680 HandToHand ((Handle *) &ctab_handle);
1681 ct_table = (*ctab_handle)->ctTable;
1682 ct_size = (*ctab_handle)->ctSize;
1683 while (ct_size > -1)
1684 {
1685 if (ct_table->value == 0)
1686 {
1687 ct_table->rgb = bg_color;
1688 CTabChanged (ctab_handle);
1689 SetWinColor (w, (WCTabHandle) ctab_handle);
1690 }
1691 ct_size--;
1692 }
1693 }
1694 #endif
1695 }
1696
1697 /* Flush display of frame F, or of all frames if F is null. */
1698
1699 static void
1700 x_flush (f)
1701 struct frame *f;
1702 {
1703 #if TARGET_API_MAC_CARBON
1704 BLOCK_INPUT;
1705 #if USE_CG_DRAWING
1706 mac_prepare_for_quickdraw (f);
1707 #endif
1708 if (f)
1709 QDFlushPortBuffer (GetWindowPort (FRAME_MAC_WINDOW (f)), NULL);
1710 else
1711 QDFlushPortBuffer (GetQDGlobalsThePort (), NULL);
1712 UNBLOCK_INPUT;
1713 #endif
1714 }
1715
1716
1717 /* Remove calls to XFlush by defining XFlush to an empty replacement.
1718 Calls to XFlush should be unnecessary because the X output buffer
1719 is flushed automatically as needed by calls to XPending,
1720 XNextEvent, or XWindowEvent according to the XFlush man page.
1721 XTread_socket calls XPending. Removing XFlush improves
1722 performance. */
1723
1724 #define XFlush(DISPLAY) (void) 0
1725
1726 \f
1727 /* Return the struct mac_display_info corresponding to DPY. There's
1728 only one. */
1729
1730 struct mac_display_info *
1731 mac_display_info_for_display (dpy)
1732 Display *dpy;
1733 {
1734 return &one_mac_display_info;
1735 }
1736
1737
1738 \f
1739 /***********************************************************************
1740 Starting and ending an update
1741 ***********************************************************************/
1742
1743 /* Start an update of frame F. This function is installed as a hook
1744 for update_begin, i.e. it is called when update_begin is called.
1745 This function is called prior to calls to x_update_window_begin for
1746 each window being updated. */
1747
1748 static void
1749 x_update_begin (f)
1750 struct frame *f;
1751 {
1752 #if TARGET_API_MAC_CARBON
1753 /* During update of a frame, availability of input events is
1754 periodically checked with ReceiveNextEvent if
1755 redisplay-dont-pause is nil. That normally flushes window buffer
1756 changes for every check, and thus screen update looks waving even
1757 if no input is available. So we disable screen updates during
1758 update of a frame. */
1759 BLOCK_INPUT;
1760 DisableScreenUpdates ();
1761 UNBLOCK_INPUT;
1762 #endif
1763 }
1764
1765
1766 /* Start update of window W. Set the global variable updated_window
1767 to the window being updated and set output_cursor to the cursor
1768 position of W. */
1769
1770 static void
1771 x_update_window_begin (w)
1772 struct window *w;
1773 {
1774 struct frame *f = XFRAME (WINDOW_FRAME (w));
1775 struct mac_display_info *display_info = FRAME_MAC_DISPLAY_INFO (f);
1776
1777 updated_window = w;
1778 set_output_cursor (&w->cursor);
1779
1780 BLOCK_INPUT;
1781
1782 if (f == display_info->mouse_face_mouse_frame)
1783 {
1784 /* Don't do highlighting for mouse motion during the update. */
1785 display_info->mouse_face_defer = 1;
1786
1787 /* If F needs to be redrawn, simply forget about any prior mouse
1788 highlighting. */
1789 if (FRAME_GARBAGED_P (f))
1790 display_info->mouse_face_window = Qnil;
1791
1792 #if 0 /* Rows in a current matrix containing glyphs in mouse-face have
1793 their mouse_face_p flag set, which means that they are always
1794 unequal to rows in a desired matrix which never have that
1795 flag set. So, rows containing mouse-face glyphs are never
1796 scrolled, and we don't have to switch the mouse highlight off
1797 here to prevent it from being scrolled. */
1798
1799 /* Can we tell that this update does not affect the window
1800 where the mouse highlight is? If so, no need to turn off.
1801 Likewise, don't do anything if the frame is garbaged;
1802 in that case, the frame's current matrix that we would use
1803 is all wrong, and we will redisplay that line anyway. */
1804 if (!NILP (display_info->mouse_face_window)
1805 && w == XWINDOW (display_info->mouse_face_window))
1806 {
1807 int i;
1808
1809 for (i = 0; i < w->desired_matrix->nrows; ++i)
1810 if (MATRIX_ROW_ENABLED_P (w->desired_matrix, i))
1811 break;
1812
1813 if (i < w->desired_matrix->nrows)
1814 clear_mouse_face (display_info);
1815 }
1816 #endif /* 0 */
1817 }
1818
1819 UNBLOCK_INPUT;
1820 }
1821
1822
1823 /* Draw a vertical window border from (x,y0) to (x,y1) */
1824
1825 static void
1826 mac_draw_vertical_window_border (w, x, y0, y1)
1827 struct window *w;
1828 int x, y0, y1;
1829 {
1830 struct frame *f = XFRAME (WINDOW_FRAME (w));
1831 struct face *face;
1832
1833 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
1834 if (face)
1835 XSetForeground (FRAME_MAC_DISPLAY (f), f->output_data.mac->normal_gc,
1836 face->foreground);
1837
1838 mac_draw_line (f, f->output_data.mac->normal_gc, x, y0, x, y1);
1839 }
1840
1841 /* End update of window W (which is equal to updated_window).
1842
1843 Draw vertical borders between horizontally adjacent windows, and
1844 display W's cursor if CURSOR_ON_P is non-zero.
1845
1846 MOUSE_FACE_OVERWRITTEN_P non-zero means that some row containing
1847 glyphs in mouse-face were overwritten. In that case we have to
1848 make sure that the mouse-highlight is properly redrawn.
1849
1850 W may be a menu bar pseudo-window in case we don't have X toolkit
1851 support. Such windows don't have a cursor, so don't display it
1852 here. */
1853
1854 static void
1855 x_update_window_end (w, cursor_on_p, mouse_face_overwritten_p)
1856 struct window *w;
1857 int cursor_on_p, mouse_face_overwritten_p;
1858 {
1859 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (XFRAME (w->frame));
1860
1861 if (!w->pseudo_window_p)
1862 {
1863 BLOCK_INPUT;
1864
1865 if (cursor_on_p)
1866 display_and_set_cursor (w, 1, output_cursor.hpos,
1867 output_cursor.vpos,
1868 output_cursor.x, output_cursor.y);
1869
1870 if (draw_window_fringes (w, 1))
1871 x_draw_vertical_border (w);
1872
1873 UNBLOCK_INPUT;
1874 }
1875
1876 /* If a row with mouse-face was overwritten, arrange for
1877 XTframe_up_to_date to redisplay the mouse highlight. */
1878 if (mouse_face_overwritten_p)
1879 {
1880 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
1881 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
1882 dpyinfo->mouse_face_window = Qnil;
1883 }
1884
1885 updated_window = NULL;
1886 }
1887
1888
1889 /* End update of frame F. This function is installed as a hook in
1890 update_end. */
1891
1892 static void
1893 x_update_end (f)
1894 struct frame *f;
1895 {
1896 /* Mouse highlight may be displayed again. */
1897 FRAME_MAC_DISPLAY_INFO (f)->mouse_face_defer = 0;
1898
1899 BLOCK_INPUT;
1900 #if TARGET_API_MAC_CARBON
1901 EnableScreenUpdates ();
1902 #endif
1903 XFlush (FRAME_MAC_DISPLAY (f));
1904 UNBLOCK_INPUT;
1905 }
1906
1907
1908 /* This function is called from various places in xdisp.c whenever a
1909 complete update has been performed. The global variable
1910 updated_window is not available here. */
1911
1912 static void
1913 XTframe_up_to_date (f)
1914 struct frame *f;
1915 {
1916 if (FRAME_MAC_P (f))
1917 {
1918 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
1919
1920 if (dpyinfo->mouse_face_deferred_gc
1921 || f == dpyinfo->mouse_face_mouse_frame)
1922 {
1923 BLOCK_INPUT;
1924 if (dpyinfo->mouse_face_mouse_frame)
1925 note_mouse_highlight (dpyinfo->mouse_face_mouse_frame,
1926 dpyinfo->mouse_face_mouse_x,
1927 dpyinfo->mouse_face_mouse_y);
1928 dpyinfo->mouse_face_deferred_gc = 0;
1929 UNBLOCK_INPUT;
1930 }
1931 }
1932 }
1933
1934
1935 /* Draw truncation mark bitmaps, continuation mark bitmaps, overlay
1936 arrow bitmaps, or clear the fringes if no bitmaps are required
1937 before DESIRED_ROW is made current. The window being updated is
1938 found in updated_window. This function is called from
1939 update_window_line only if it is known that there are differences
1940 between bitmaps to be drawn between current row and DESIRED_ROW. */
1941
1942 static void
1943 x_after_update_window_line (desired_row)
1944 struct glyph_row *desired_row;
1945 {
1946 struct window *w = updated_window;
1947 struct frame *f;
1948 int width, height;
1949
1950 xassert (w);
1951
1952 if (!desired_row->mode_line_p && !w->pseudo_window_p)
1953 desired_row->redraw_fringe_bitmaps_p = 1;
1954
1955 /* When a window has disappeared, make sure that no rest of
1956 full-width rows stays visible in the internal border. Could
1957 check here if updated_window is the leftmost/rightmost window,
1958 but I guess it's not worth doing since vertically split windows
1959 are almost never used, internal border is rarely set, and the
1960 overhead is very small. */
1961 if (windows_or_buffers_changed
1962 && desired_row->full_width_p
1963 && (f = XFRAME (w->frame),
1964 width = FRAME_INTERNAL_BORDER_WIDTH (f),
1965 width != 0)
1966 && (height = desired_row->visible_height,
1967 height > 0))
1968 {
1969 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
1970
1971 /* Internal border is drawn below the tool bar. */
1972 if (WINDOWP (f->tool_bar_window)
1973 && w == XWINDOW (f->tool_bar_window))
1974 y -= width;
1975
1976 BLOCK_INPUT;
1977 mac_clear_area (f, 0, y, width, height);
1978 mac_clear_area (f, FRAME_PIXEL_WIDTH (f) - width, y, width, height);
1979 UNBLOCK_INPUT;
1980 }
1981 }
1982
1983
1984 /* Draw the bitmap WHICH in one of the left or right fringes of
1985 window W. ROW is the glyph row for which to display the bitmap; it
1986 determines the vertical position at which the bitmap has to be
1987 drawn. */
1988
1989 static void
1990 x_draw_fringe_bitmap (w, row, p)
1991 struct window *w;
1992 struct glyph_row *row;
1993 struct draw_fringe_bitmap_params *p;
1994 {
1995 struct frame *f = XFRAME (WINDOW_FRAME (w));
1996 Display *display = FRAME_MAC_DISPLAY (f);
1997 struct face *face = p->face;
1998 int rowY;
1999
2000 /* Must clip because of partially visible lines. */
2001 rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
2002 if (p->y < rowY)
2003 {
2004 /* Adjust position of "bottom aligned" bitmap on partially
2005 visible last row. */
2006 int oldY = row->y;
2007 int oldVH = row->visible_height;
2008 row->visible_height = p->h;
2009 row->y -= rowY - p->y;
2010 x_clip_to_row (w, row, -1, face->gc);
2011 row->y = oldY;
2012 row->visible_height = oldVH;
2013 }
2014 else
2015 x_clip_to_row (w, row, -1, face->gc);
2016
2017 if (p->bx >= 0 && !p->overlay_p)
2018 {
2019 #if 0 /* MAC_TODO: stipple */
2020 /* In case the same realized face is used for fringes and
2021 for something displayed in the text (e.g. face `region' on
2022 mono-displays, the fill style may have been changed to
2023 FillSolid in x_draw_glyph_string_background. */
2024 if (face->stipple)
2025 XSetFillStyle (FRAME_X_DISPLAY (f), face->gc, FillOpaqueStippled);
2026 else
2027 XSetForeground (FRAME_X_DISPLAY (f), face->gc, face->background);
2028 #endif
2029
2030 mac_erase_rectangle (f, face->gc, p->bx, p->by, p->nx, p->ny);
2031
2032 #if 0 /* MAC_TODO: stipple */
2033 if (!face->stipple)
2034 XSetForeground (FRAME_X_DISPLAY (f), face->gc, face->foreground);
2035 #endif
2036 }
2037
2038 if (p->which
2039 #if USE_CG_DRAWING
2040 && p->which < max_fringe_bmp
2041 #endif
2042 )
2043 {
2044 XGCValues gcv;
2045
2046 XGetGCValues (display, face->gc, GCForeground, &gcv);
2047 XSetForeground (display, face->gc,
2048 (p->cursor_p
2049 ? (p->overlay_p ? face->background
2050 : f->output_data.mac->cursor_pixel)
2051 : face->foreground));
2052 #if USE_CG_DRAWING
2053 mac_draw_cg_image (fringe_bmp[p->which], f, face->gc, 0, p->dh,
2054 p->wd, p->h, p->x, p->y, p->overlay_p);
2055 #else
2056 mac_draw_bitmap (f, face->gc, p->x, p->y,
2057 p->wd, p->h, p->bits + p->dh, p->overlay_p);
2058 #endif
2059 XSetForeground (display, face->gc, gcv.foreground);
2060 }
2061
2062 mac_reset_clip_rectangles (display, face->gc);
2063 }
2064
2065 #if USE_CG_DRAWING
2066 static void
2067 mac_define_fringe_bitmap (which, bits, h, wd)
2068 int which;
2069 unsigned short *bits;
2070 int h, wd;
2071 {
2072 int i;
2073 CGDataProviderRef provider;
2074
2075 if (which >= max_fringe_bmp)
2076 {
2077 i = max_fringe_bmp;
2078 max_fringe_bmp = which + 20;
2079 fringe_bmp = (CGImageRef *) xrealloc (fringe_bmp, max_fringe_bmp * sizeof (CGImageRef));
2080 while (i < max_fringe_bmp)
2081 fringe_bmp[i++] = 0;
2082 }
2083
2084 for (i = 0; i < h; i++)
2085 bits[i] = ~bits[i];
2086 provider = CGDataProviderCreateWithData (NULL, bits,
2087 sizeof (unsigned short) * h, NULL);
2088 if (provider)
2089 {
2090 fringe_bmp[which] = CGImageMaskCreate (wd, h, 1, 1,
2091 sizeof (unsigned short),
2092 provider, NULL, 0);
2093 CGDataProviderRelease (provider);
2094 }
2095 }
2096
2097 static void
2098 mac_destroy_fringe_bitmap (which)
2099 int which;
2100 {
2101 if (which >= max_fringe_bmp)
2102 return;
2103
2104 if (fringe_bmp[which])
2105 CGImageRelease (fringe_bmp[which]);
2106 fringe_bmp[which] = 0;
2107 }
2108 #endif
2109 \f
2110
2111 /* This is called when starting Emacs and when restarting after
2112 suspend. When starting Emacs, no window is mapped. And nothing
2113 must be done to Emacs's own window if it is suspended (though that
2114 rarely happens). */
2115
2116 static void
2117 XTset_terminal_modes ()
2118 {
2119 }
2120
2121 /* This is called when exiting or suspending Emacs. Exiting will make
2122 the windows go away, and suspending requires no action. */
2123
2124 static void
2125 XTreset_terminal_modes ()
2126 {
2127 }
2128
2129
2130 \f
2131 /***********************************************************************
2132 Display Iterator
2133 ***********************************************************************/
2134
2135 /* Function prototypes of this page. */
2136
2137 static XCharStruct *x_per_char_metric P_ ((XFontStruct *, XChar2b *));
2138 static int mac_encode_char P_ ((int, XChar2b *, struct font_info *,
2139 struct charset *, int *));
2140
2141
2142 /* Get metrics of character CHAR2B in FONT. Value is null if CHAR2B
2143 is not contained in the font. */
2144
2145 static INLINE XCharStruct *
2146 x_per_char_metric (font, char2b)
2147 XFontStruct *font;
2148 XChar2b *char2b;
2149 {
2150 /* The result metric information. */
2151 XCharStruct *pcm = NULL;
2152
2153 xassert (font && char2b);
2154
2155 #if USE_ATSUI
2156 if (font->mac_style)
2157 {
2158 XCharStructRow **row = font->bounds.rows + char2b->byte1;
2159
2160 if (*row == NULL)
2161 {
2162 *row = xmalloc (sizeof (XCharStructRow));
2163 bzero (*row, sizeof (XCharStructRow));
2164 }
2165 pcm = (*row)->per_char + char2b->byte2;
2166 if (!XCHARSTRUCTROW_CHAR_VALID_P (*row, char2b->byte2))
2167 {
2168 BLOCK_INPUT;
2169 mac_query_char_extents (font->mac_style,
2170 (char2b->byte1 << 8) + char2b->byte2,
2171 NULL, NULL, pcm, NULL);
2172 UNBLOCK_INPUT;
2173 XCHARSTRUCTROW_SET_CHAR_VALID (*row, char2b->byte2);
2174 }
2175 }
2176 else
2177 {
2178 #endif
2179 if (font->bounds.per_char != NULL)
2180 {
2181 if (font->min_byte1 == 0 && font->max_byte1 == 0)
2182 {
2183 /* min_char_or_byte2 specifies the linear character index
2184 corresponding to the first element of the per_char array,
2185 max_char_or_byte2 is the index of the last character. A
2186 character with non-zero CHAR2B->byte1 is not in the font.
2187 A character with byte2 less than min_char_or_byte2 or
2188 greater max_char_or_byte2 is not in the font. */
2189 if (char2b->byte1 == 0
2190 && char2b->byte2 >= font->min_char_or_byte2
2191 && char2b->byte2 <= font->max_char_or_byte2)
2192 pcm = font->bounds.per_char
2193 + (char2b->byte2 - font->min_char_or_byte2);
2194 }
2195 else
2196 {
2197 /* If either min_byte1 or max_byte1 are nonzero, both
2198 min_char_or_byte2 and max_char_or_byte2 are less than
2199 256, and the 2-byte character index values corresponding
2200 to the per_char array element N (counting from 0) are:
2201
2202 byte1 = N/D + min_byte1
2203 byte2 = N\D + min_char_or_byte2
2204
2205 where:
2206
2207 D = max_char_or_byte2 - min_char_or_byte2 + 1
2208 / = integer division
2209 \ = integer modulus */
2210 if (char2b->byte1 >= font->min_byte1
2211 && char2b->byte1 <= font->max_byte1
2212 && char2b->byte2 >= font->min_char_or_byte2
2213 && char2b->byte2 <= font->max_char_or_byte2)
2214 {
2215 pcm = (font->bounds.per_char
2216 + ((font->max_char_or_byte2 - font->min_char_or_byte2 + 1)
2217 * (char2b->byte1 - font->min_byte1))
2218 + (char2b->byte2 - font->min_char_or_byte2));
2219 }
2220 }
2221 }
2222 else
2223 {
2224 /* If the per_char pointer is null, all glyphs between the first
2225 and last character indexes inclusive have the same
2226 information, as given by both min_bounds and max_bounds. */
2227 if (char2b->byte2 >= font->min_char_or_byte2
2228 && char2b->byte2 <= font->max_char_or_byte2)
2229 pcm = &font->max_bounds;
2230 }
2231 #if USE_ATSUI
2232 }
2233 #endif
2234
2235 return ((pcm == NULL
2236 || (pcm->width == 0 && (pcm->rbearing - pcm->lbearing) == 0))
2237 ? NULL : pcm);
2238 }
2239
2240 /* RIF:
2241 */
2242
2243 static XCharStruct *
2244 mac_per_char_metric (font, char2b, font_type)
2245 XFontStruct *font;
2246 XChar2b *char2b;
2247 int font_type;
2248 {
2249 return x_per_char_metric (font, char2b);
2250 }
2251
2252 /* RIF:
2253 Encode CHAR2B using encoding information from FONT_INFO. CHAR2B is
2254 the two-byte form of C. Encoding is returned in *CHAR2B. */
2255
2256 static int
2257 mac_encode_char (c, char2b, font_info, charset, two_byte_p)
2258 int c;
2259 XChar2b *char2b;
2260 struct font_info *font_info;
2261 struct charset *charset;
2262 int *two_byte_p;
2263 {
2264 XFontStruct *font = font_info->font;
2265
2266 /* FONT_INFO may define a scheme by which to encode byte1 and byte2.
2267 This may be either a program in a special encoder language or a
2268 fixed encoding. */
2269 if (font_info->font_encoder)
2270 {
2271 /* It's a program. */
2272 struct ccl_program *ccl = font_info->font_encoder;
2273
2274 check_ccl_update (ccl);
2275 if (CHARSET_DIMENSION (charset) == 1)
2276 {
2277 ccl->reg[0] = CHARSET_ID (charset);
2278 ccl->reg[1] = XCHAR2B_BYTE2 (char2b);
2279 ccl->reg[2] = -1;
2280 }
2281 else
2282 {
2283 ccl->reg[0] = CHARSET_ID (charset);
2284 ccl->reg[1] = XCHAR2B_BYTE1 (char2b);
2285 ccl->reg[2] = XCHAR2B_BYTE2 (char2b);
2286 }
2287
2288 ccl_driver (ccl, NULL, NULL, 0, 0, Qnil);
2289
2290 /* We assume that MSBs are appropriately set/reset by CCL
2291 program. */
2292 if (font->max_byte1 == 0) /* 1-byte font */
2293 STORE_XCHAR2B (char2b, 0, ccl->reg[1]);
2294 else
2295 STORE_XCHAR2B (char2b, ccl->reg[1], ccl->reg[2]);
2296 }
2297 else if (font_info->encoding_type)
2298 {
2299 /* Fixed encoding scheme. See fontset.h for the meaning of the
2300 encoding numbers. */
2301 unsigned char enc = font_info->encoding_type;
2302
2303 if ((enc == 1 || enc == 2)
2304 && CHARSET_DIMENSION (charset) == 2)
2305 char2b->byte1 |= 0x80;
2306
2307 if (enc == 1 || enc == 3)
2308 char2b->byte2 |= 0x80;
2309
2310 if (enc == 4)
2311 {
2312 int code = (char2b->byte1 << 8) | char2b->byte2;
2313
2314 JIS_TO_SJIS (code);
2315 STORE_XCHAR2B (char2b, (code >> 8), (code & 0xFF));
2316 }
2317 }
2318
2319 if (two_byte_p)
2320 *two_byte_p = ((XFontStruct *) (font_info->font))->max_byte1 > 0;
2321
2322 return FONT_TYPE_UNKNOWN;
2323 }
2324
2325
2326 \f
2327 /***********************************************************************
2328 Glyph display
2329 ***********************************************************************/
2330
2331
2332
2333 static void x_set_glyph_string_clipping P_ ((struct glyph_string *));
2334 static void x_set_glyph_string_gc P_ ((struct glyph_string *));
2335 static void x_draw_glyph_string_background P_ ((struct glyph_string *,
2336 int));
2337 static void x_draw_glyph_string_foreground P_ ((struct glyph_string *));
2338 static void x_draw_composite_glyph_string_foreground P_ ((struct glyph_string *));
2339 static void x_draw_glyph_string_box P_ ((struct glyph_string *));
2340 static void x_draw_glyph_string P_ ((struct glyph_string *));
2341 static void mac_compute_glyph_string_overhangs P_ ((struct glyph_string *));
2342 static void x_set_cursor_gc P_ ((struct glyph_string *));
2343 static void x_set_mode_line_face_gc P_ ((struct glyph_string *));
2344 static void x_set_mouse_face_gc P_ ((struct glyph_string *));
2345 /*static int x_alloc_lighter_color P_ ((struct frame *, Display *, Colormap,
2346 unsigned long *, double, int));*/
2347 static void x_setup_relief_color P_ ((struct frame *, struct relief *,
2348 double, int, unsigned long));
2349 static void x_setup_relief_colors P_ ((struct glyph_string *));
2350 static void x_draw_image_glyph_string P_ ((struct glyph_string *));
2351 static void x_draw_image_relief P_ ((struct glyph_string *));
2352 static void x_draw_image_foreground P_ ((struct glyph_string *));
2353 static void x_clear_glyph_string_rect P_ ((struct glyph_string *, int,
2354 int, int, int));
2355 static void x_draw_relief_rect P_ ((struct frame *, int, int, int, int,
2356 int, int, int, int, int, int,
2357 Rect *));
2358 static void x_draw_box_rect P_ ((struct glyph_string *, int, int, int, int,
2359 int, int, int, Rect *));
2360
2361 #if GLYPH_DEBUG
2362 static void x_check_font P_ ((struct frame *, XFontStruct *));
2363 #endif
2364
2365
2366 /* Set S->gc to a suitable GC for drawing glyph string S in cursor
2367 face. */
2368
2369 static void
2370 x_set_cursor_gc (s)
2371 struct glyph_string *s;
2372 {
2373 if (s->font == FRAME_FONT (s->f)
2374 && s->face->background == FRAME_BACKGROUND_PIXEL (s->f)
2375 && s->face->foreground == FRAME_FOREGROUND_PIXEL (s->f)
2376 && !s->cmp)
2377 s->gc = s->f->output_data.mac->cursor_gc;
2378 else
2379 {
2380 /* Cursor on non-default face: must merge. */
2381 XGCValues xgcv;
2382 unsigned long mask;
2383
2384 xgcv.background = s->f->output_data.mac->cursor_pixel;
2385 xgcv.foreground = s->face->background;
2386
2387 /* If the glyph would be invisible, try a different foreground. */
2388 if (xgcv.foreground == xgcv.background)
2389 xgcv.foreground = s->face->foreground;
2390 if (xgcv.foreground == xgcv.background)
2391 xgcv.foreground = s->f->output_data.mac->cursor_foreground_pixel;
2392 if (xgcv.foreground == xgcv.background)
2393 xgcv.foreground = s->face->foreground;
2394
2395 /* Make sure the cursor is distinct from text in this face. */
2396 if (xgcv.background == s->face->background
2397 && xgcv.foreground == s->face->foreground)
2398 {
2399 xgcv.background = s->face->foreground;
2400 xgcv.foreground = s->face->background;
2401 }
2402
2403 IF_DEBUG (x_check_font (s->f, s->font));
2404 xgcv.font = s->font;
2405 mask = GCForeground | GCBackground | GCFont;
2406
2407 if (FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc)
2408 XChangeGC (s->display, FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc,
2409 mask, &xgcv);
2410 else
2411 FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc
2412 = XCreateGC (s->display, s->window, mask, &xgcv);
2413
2414 s->gc = FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc;
2415 }
2416 }
2417
2418
2419 /* Set up S->gc of glyph string S for drawing text in mouse face. */
2420
2421 static void
2422 x_set_mouse_face_gc (s)
2423 struct glyph_string *s;
2424 {
2425 int face_id;
2426 struct face *face;
2427
2428 /* What face has to be used last for the mouse face? */
2429 face_id = FRAME_X_DISPLAY_INFO (s->f)->mouse_face_face_id;
2430 face = FACE_FROM_ID (s->f, face_id);
2431 if (face == NULL)
2432 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2433
2434 if (s->first_glyph->type == CHAR_GLYPH)
2435 face_id = FACE_FOR_CHAR (s->f, face, s->first_glyph->u.ch, -1, Qnil);
2436 else
2437 face_id = FACE_FOR_CHAR (s->f, face, 0, -1, Qnil);
2438 s->face = FACE_FROM_ID (s->f, face_id);
2439 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
2440
2441 /* If font in this face is same as S->font, use it. */
2442 if (s->font == s->face->font)
2443 s->gc = s->face->gc;
2444 else
2445 {
2446 /* Otherwise construct scratch_cursor_gc with values from FACE
2447 but font FONT. */
2448 XGCValues xgcv;
2449 unsigned long mask;
2450
2451 xgcv.background = s->face->background;
2452 xgcv.foreground = s->face->foreground;
2453 IF_DEBUG (x_check_font (s->f, s->font));
2454 xgcv.font = s->font;
2455 mask = GCForeground | GCBackground | GCFont;
2456
2457 if (FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc)
2458 XChangeGC (s->display, FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc,
2459 mask, &xgcv);
2460 else
2461 FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc
2462 = XCreateGC (s->display, s->window, mask, &xgcv);
2463
2464 s->gc = FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc;
2465 }
2466
2467 xassert (s->gc != 0);
2468 }
2469
2470
2471 /* Set S->gc of glyph string S to a GC suitable for drawing a mode line.
2472 Faces to use in the mode line have already been computed when the
2473 matrix was built, so there isn't much to do, here. */
2474
2475 static INLINE void
2476 x_set_mode_line_face_gc (s)
2477 struct glyph_string *s;
2478 {
2479 s->gc = s->face->gc;
2480 }
2481
2482
2483 /* Set S->gc of glyph string S for drawing that glyph string. Set
2484 S->stippled_p to a non-zero value if the face of S has a stipple
2485 pattern. */
2486
2487 static INLINE void
2488 x_set_glyph_string_gc (s)
2489 struct glyph_string *s;
2490 {
2491 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
2492
2493 if (s->hl == DRAW_NORMAL_TEXT)
2494 {
2495 s->gc = s->face->gc;
2496 s->stippled_p = s->face->stipple != 0;
2497 }
2498 else if (s->hl == DRAW_INVERSE_VIDEO)
2499 {
2500 x_set_mode_line_face_gc (s);
2501 s->stippled_p = s->face->stipple != 0;
2502 }
2503 else if (s->hl == DRAW_CURSOR)
2504 {
2505 x_set_cursor_gc (s);
2506 s->stippled_p = 0;
2507 }
2508 else if (s->hl == DRAW_MOUSE_FACE)
2509 {
2510 x_set_mouse_face_gc (s);
2511 s->stippled_p = s->face->stipple != 0;
2512 }
2513 else if (s->hl == DRAW_IMAGE_RAISED
2514 || s->hl == DRAW_IMAGE_SUNKEN)
2515 {
2516 s->gc = s->face->gc;
2517 s->stippled_p = s->face->stipple != 0;
2518 }
2519 else
2520 {
2521 s->gc = s->face->gc;
2522 s->stippled_p = s->face->stipple != 0;
2523 }
2524
2525 /* GC must have been set. */
2526 xassert (s->gc != 0);
2527 }
2528
2529
2530 /* Set clipping for output of glyph string S. S may be part of a mode
2531 line or menu if we don't have X toolkit support. */
2532
2533 static INLINE void
2534 x_set_glyph_string_clipping (s)
2535 struct glyph_string *s;
2536 {
2537 Rect rects[MAX_CLIP_RECTS];
2538 int n;
2539
2540 n = get_glyph_string_clip_rects (s, rects, MAX_CLIP_RECTS);
2541 mac_set_clip_rectangles (s->display, s->gc, rects, n);
2542 }
2543
2544
2545 /* RIF:
2546 Compute left and right overhang of glyph string S. If S is a glyph
2547 string for a composition, assume overhangs don't exist. */
2548
2549 static void
2550 mac_compute_glyph_string_overhangs (s)
2551 struct glyph_string *s;
2552 {
2553 if (!(s->cmp == NULL
2554 && s->first_glyph->type == CHAR_GLYPH))
2555 return;
2556
2557 if (!s->two_byte_p
2558 #if USE_ATSUI
2559 || s->font->mac_style
2560 #endif
2561 )
2562 {
2563 XCharStruct cs;
2564
2565 mac_text_extents_16 (s->font, s->char2b, s->nchars, &cs);
2566 s->right_overhang = cs.rbearing > cs.width ? cs.rbearing - cs.width : 0;
2567 s->left_overhang = cs.lbearing < 0 ? -cs.lbearing : 0;
2568 }
2569 else
2570 {
2571 Rect r;
2572 MacFontStruct *font = s->font;
2573
2574 TextFont (font->mac_fontnum);
2575 TextSize (font->mac_fontsize);
2576 TextFace (font->mac_fontface);
2577
2578 QDTextBounds (s->nchars * 2, (char *)s->char2b, &r);
2579
2580 s->right_overhang = r.right > s->width ? r.right - s->width : 0;
2581 s->left_overhang = r.left < 0 ? -r.left : 0;
2582 }
2583 }
2584
2585
2586 /* Fill rectangle X, Y, W, H with background color of glyph string S. */
2587
2588 static INLINE void
2589 x_clear_glyph_string_rect (s, x, y, w, h)
2590 struct glyph_string *s;
2591 int x, y, w, h;
2592 {
2593 mac_erase_rectangle (s->f, s->gc, x, y, w, h);
2594 }
2595
2596
2597 /* Draw the background of glyph_string S. If S->background_filled_p
2598 is non-zero don't draw it. FORCE_P non-zero means draw the
2599 background even if it wouldn't be drawn normally. This is used
2600 when a string preceding S draws into the background of S, or S
2601 contains the first component of a composition. */
2602
2603 static void
2604 x_draw_glyph_string_background (s, force_p)
2605 struct glyph_string *s;
2606 int force_p;
2607 {
2608 /* Nothing to do if background has already been drawn or if it
2609 shouldn't be drawn in the first place. */
2610 if (!s->background_filled_p)
2611 {
2612 int box_line_width = max (s->face->box_line_width, 0);
2613
2614 #if 0 /* MAC_TODO: stipple */
2615 if (s->stippled_p)
2616 {
2617 /* Fill background with a stipple pattern. */
2618 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2619 XFillRectangle (s->display, s->window, s->gc, s->x,
2620 s->y + box_line_width,
2621 s->background_width,
2622 s->height - 2 * box_line_width);
2623 XSetFillStyle (s->display, s->gc, FillSolid);
2624 s->background_filled_p = 1;
2625 }
2626 else
2627 #endif
2628 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2629 || s->font_not_found_p
2630 || s->extends_to_end_of_line_p
2631 || force_p)
2632 {
2633 x_clear_glyph_string_rect (s, s->x, s->y + box_line_width,
2634 s->background_width,
2635 s->height - 2 * box_line_width);
2636 s->background_filled_p = 1;
2637 }
2638 }
2639 }
2640
2641
2642 /* Draw the foreground of glyph string S. */
2643
2644 static void
2645 x_draw_glyph_string_foreground (s)
2646 struct glyph_string *s;
2647 {
2648 int i, x, bg_width;
2649
2650 /* If first glyph of S has a left box line, start drawing the text
2651 of S to the right of that box line. */
2652 if (s->face->box != FACE_NO_BOX
2653 && s->first_glyph->left_box_line_p)
2654 x = s->x + abs (s->face->box_line_width);
2655 else
2656 x = s->x;
2657
2658 /* Draw characters of S as rectangles if S's font could not be
2659 loaded. */
2660 if (s->font_not_found_p)
2661 {
2662 for (i = 0; i < s->nchars; ++i)
2663 {
2664 struct glyph *g = s->first_glyph + i;
2665 mac_draw_rectangle (s->f, s->gc, x, s->y,
2666 g->pixel_width - 1, s->height - 1);
2667 x += g->pixel_width;
2668 }
2669 }
2670 else
2671 {
2672 char *char1b = (char *) s->char2b;
2673 int boff = s->font_info->baseline_offset;
2674
2675 if (s->font_info->vertical_centering)
2676 boff = VCENTER_BASELINE_OFFSET (s->font, s->f) - boff;
2677
2678 /* If we can use 8-bit functions, condense S->char2b. */
2679 if (!s->two_byte_p
2680 #if USE_ATSUI
2681 && GC_FONT (s->gc)->mac_style == NULL
2682 #endif
2683 )
2684 for (i = 0; i < s->nchars; ++i)
2685 char1b[i] = s->char2b[i].byte2;
2686
2687 /* Draw text with XDrawString if background has already been
2688 filled. Otherwise, use XDrawImageString. (Note that
2689 XDrawImageString is usually faster than XDrawString.) Always
2690 use XDrawImageString when drawing the cursor so that there is
2691 no chance that characters under a box cursor are invisible. */
2692 if (s->for_overlaps
2693 || (s->background_filled_p && s->hl != DRAW_CURSOR))
2694 bg_width = 0; /* Corresponds to XDrawString. */
2695 else
2696 bg_width = s->background_width; /* Corresponds to XDrawImageString. */
2697
2698 if (s->two_byte_p
2699 #if USE_ATSUI
2700 || GC_FONT (s->gc)->mac_style
2701 #endif
2702 )
2703 #if USE_CG_TEXT_DRAWING
2704 if (!s->two_byte_p
2705 && mac_draw_image_string_cg (s->f, s->gc, x, s->ybase - boff,
2706 s->char2b, s->nchars, bg_width))
2707 ;
2708 else
2709 #endif
2710 mac_draw_image_string_16 (s->f, s->gc, x, s->ybase - boff,
2711 s->char2b, s->nchars, bg_width);
2712 else
2713 mac_draw_image_string (s->f, s->gc, x, s->ybase - boff,
2714 char1b, s->nchars, bg_width);
2715 }
2716 }
2717
2718 /* Draw the foreground of composite glyph string S. */
2719
2720 static void
2721 x_draw_composite_glyph_string_foreground (s)
2722 struct glyph_string *s;
2723 {
2724 int i, x;
2725
2726 /* If first glyph of S has a left box line, start drawing the text
2727 of S to the right of that box line. */
2728 if (s->face->box != FACE_NO_BOX
2729 && s->first_glyph->left_box_line_p)
2730 x = s->x + abs (s->face->box_line_width);
2731 else
2732 x = s->x;
2733
2734 /* S is a glyph string for a composition. S->gidx is the index of
2735 the first character drawn for glyphs of this composition.
2736 S->gidx == 0 means we are drawing the very first character of
2737 this composition. */
2738
2739 /* Draw a rectangle for the composition if the font for the very
2740 first character of the composition could not be loaded. */
2741 if (s->font_not_found_p)
2742 {
2743 if (s->gidx == 0)
2744 mac_draw_rectangle (s->f, s->gc, x, s->y,
2745 s->width - 1, s->height - 1);
2746 }
2747 else
2748 {
2749 for (i = 0; i < s->nchars; i++, ++s->gidx)
2750 mac_draw_string_16 (s->f, s->gc,
2751 x + s->cmp->offsets[s->gidx * 2],
2752 s->ybase - s->cmp->offsets[s->gidx * 2 + 1],
2753 s->char2b + i, 1);
2754 }
2755 }
2756
2757
2758 #ifdef USE_X_TOOLKIT
2759
2760 static struct frame *x_frame_of_widget P_ ((Widget));
2761
2762
2763 /* Return the frame on which widget WIDGET is used.. Abort if frame
2764 cannot be determined. */
2765
2766 static struct frame *
2767 x_frame_of_widget (widget)
2768 Widget widget;
2769 {
2770 struct x_display_info *dpyinfo;
2771 Lisp_Object tail;
2772 struct frame *f;
2773
2774 dpyinfo = x_display_info_for_display (XtDisplay (widget));
2775
2776 /* Find the top-level shell of the widget. Note that this function
2777 can be called when the widget is not yet realized, so XtWindow
2778 (widget) == 0. That's the reason we can't simply use
2779 x_any_window_to_frame. */
2780 while (!XtIsTopLevelShell (widget))
2781 widget = XtParent (widget);
2782
2783 /* Look for a frame with that top-level widget. Allocate the color
2784 on that frame to get the right gamma correction value. */
2785 for (tail = Vframe_list; GC_CONSP (tail); tail = XCDR (tail))
2786 if (GC_FRAMEP (XCAR (tail))
2787 && (f = XFRAME (XCAR (tail)),
2788 (f->output_data.nothing != 1
2789 && FRAME_X_DISPLAY_INFO (f) == dpyinfo))
2790 && f->output_data.x->widget == widget)
2791 return f;
2792
2793 abort ();
2794 }
2795
2796
2797 /* Allocate the color COLOR->pixel on the screen and display of
2798 widget WIDGET in colormap CMAP. If an exact match cannot be
2799 allocated, try the nearest color available. Value is non-zero
2800 if successful. This is called from lwlib. */
2801
2802 int
2803 x_alloc_nearest_color_for_widget (widget, cmap, color)
2804 Widget widget;
2805 Colormap cmap;
2806 XColor *color;
2807 {
2808 struct frame *f = x_frame_of_widget (widget);
2809 return x_alloc_nearest_color (f, cmap, color);
2810 }
2811
2812
2813 #endif /* USE_X_TOOLKIT */
2814
2815 #if 0 /* MAC_TODO */
2816
2817 /* Allocate the color COLOR->pixel on SCREEN of DISPLAY, colormap
2818 CMAP. If an exact match can't be allocated, try the nearest color
2819 available. Value is non-zero if successful. Set *COLOR to the
2820 color allocated. */
2821
2822 int
2823 x_alloc_nearest_color (f, cmap, color)
2824 struct frame *f;
2825 Colormap cmap;
2826 XColor *color;
2827 {
2828 Display *display = FRAME_X_DISPLAY (f);
2829 Screen *screen = FRAME_X_SCREEN (f);
2830 int rc;
2831
2832 gamma_correct (f, color);
2833 rc = XAllocColor (display, cmap, color);
2834 if (rc == 0)
2835 {
2836 /* If we got to this point, the colormap is full, so we're going
2837 to try to get the next closest color. The algorithm used is
2838 a least-squares matching, which is what X uses for closest
2839 color matching with StaticColor visuals. */
2840 int nearest, i;
2841 unsigned long nearest_delta = ~0;
2842 int ncells = XDisplayCells (display, XScreenNumberOfScreen (screen));
2843 XColor *cells = (XColor *) alloca (ncells * sizeof *cells);
2844
2845 for (i = 0; i < ncells; ++i)
2846 cells[i].pixel = i;
2847 XQueryColors (display, cmap, cells, ncells);
2848
2849 for (nearest = i = 0; i < ncells; ++i)
2850 {
2851 long dred = (color->red >> 8) - (cells[i].red >> 8);
2852 long dgreen = (color->green >> 8) - (cells[i].green >> 8);
2853 long dblue = (color->blue >> 8) - (cells[i].blue >> 8);
2854 unsigned long delta = dred * dred + dgreen * dgreen + dblue * dblue;
2855
2856 if (delta < nearest_delta)
2857 {
2858 nearest = i;
2859 nearest_delta = delta;
2860 }
2861 }
2862
2863 color->red = cells[nearest].red;
2864 color->green = cells[nearest].green;
2865 color->blue = cells[nearest].blue;
2866 rc = XAllocColor (display, cmap, color);
2867 }
2868
2869 #ifdef DEBUG_X_COLORS
2870 if (rc)
2871 register_color (color->pixel);
2872 #endif /* DEBUG_X_COLORS */
2873
2874 return rc;
2875 }
2876
2877
2878 /* Allocate color PIXEL on frame F. PIXEL must already be allocated.
2879 It's necessary to do this instead of just using PIXEL directly to
2880 get color reference counts right. */
2881
2882 unsigned long
2883 x_copy_color (f, pixel)
2884 struct frame *f;
2885 unsigned long pixel;
2886 {
2887 XColor color;
2888
2889 color.pixel = pixel;
2890 BLOCK_INPUT;
2891 XQueryColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
2892 XAllocColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
2893 UNBLOCK_INPUT;
2894 #ifdef DEBUG_X_COLORS
2895 register_color (pixel);
2896 #endif
2897 return color.pixel;
2898 }
2899
2900
2901 /* Allocate color PIXEL on display DPY. PIXEL must already be allocated.
2902 It's necessary to do this instead of just using PIXEL directly to
2903 get color reference counts right. */
2904
2905 unsigned long
2906 x_copy_dpy_color (dpy, cmap, pixel)
2907 Display *dpy;
2908 Colormap cmap;
2909 unsigned long pixel;
2910 {
2911 XColor color;
2912
2913 color.pixel = pixel;
2914 BLOCK_INPUT;
2915 XQueryColor (dpy, cmap, &color);
2916 XAllocColor (dpy, cmap, &color);
2917 UNBLOCK_INPUT;
2918 #ifdef DEBUG_X_COLORS
2919 register_color (pixel);
2920 #endif
2921 return color.pixel;
2922 }
2923
2924 #endif /* MAC_TODO */
2925
2926
2927 /* Brightness beyond which a color won't have its highlight brightness
2928 boosted.
2929
2930 Nominally, highlight colors for `3d' faces are calculated by
2931 brightening an object's color by a constant scale factor, but this
2932 doesn't yield good results for dark colors, so for colors who's
2933 brightness is less than this value (on a scale of 0-255) have to
2934 use an additional additive factor.
2935
2936 The value here is set so that the default menu-bar/mode-line color
2937 (grey75) will not have its highlights changed at all. */
2938 #define HIGHLIGHT_COLOR_DARK_BOOST_LIMIT 187
2939
2940
2941 /* Allocate a color which is lighter or darker than *COLOR by FACTOR
2942 or DELTA. Try a color with RGB values multiplied by FACTOR first.
2943 If this produces the same color as COLOR, try a color where all RGB
2944 values have DELTA added. Return the allocated color in *COLOR.
2945 DISPLAY is the X display, CMAP is the colormap to operate on.
2946 Value is non-zero if successful. */
2947
2948 static int
2949 mac_alloc_lighter_color (f, color, factor, delta)
2950 struct frame *f;
2951 unsigned long *color;
2952 double factor;
2953 int delta;
2954 {
2955 unsigned long new;
2956 long bright;
2957
2958 /* On Mac, RGB values are 0-255, not 0-65535, so scale delta. */
2959 delta /= 256;
2960
2961 /* Change RGB values by specified FACTOR. Avoid overflow! */
2962 xassert (factor >= 0);
2963 new = RGB_TO_ULONG (min (0xff, (int) (factor * RED_FROM_ULONG (*color))),
2964 min (0xff, (int) (factor * GREEN_FROM_ULONG (*color))),
2965 min (0xff, (int) (factor * BLUE_FROM_ULONG (*color))));
2966
2967 /* Calculate brightness of COLOR. */
2968 bright = (2 * RED_FROM_ULONG (*color) + 3 * GREEN_FROM_ULONG (*color)
2969 + BLUE_FROM_ULONG (*color)) / 6;
2970
2971 /* We only boost colors that are darker than
2972 HIGHLIGHT_COLOR_DARK_BOOST_LIMIT. */
2973 if (bright < HIGHLIGHT_COLOR_DARK_BOOST_LIMIT)
2974 /* Make an additive adjustment to NEW, because it's dark enough so
2975 that scaling by FACTOR alone isn't enough. */
2976 {
2977 /* How far below the limit this color is (0 - 1, 1 being darker). */
2978 double dimness = 1 - (double)bright / HIGHLIGHT_COLOR_DARK_BOOST_LIMIT;
2979 /* The additive adjustment. */
2980 int min_delta = delta * dimness * factor / 2;
2981
2982 if (factor < 1)
2983 new = RGB_TO_ULONG (max (0, min (0xff, (int) (RED_FROM_ULONG (*color)) - min_delta)),
2984 max (0, min (0xff, (int) (GREEN_FROM_ULONG (*color)) - min_delta)),
2985 max (0, min (0xff, (int) (BLUE_FROM_ULONG (*color)) - min_delta)));
2986 else
2987 new = RGB_TO_ULONG (max (0, min (0xff, (int) (min_delta + RED_FROM_ULONG (*color)))),
2988 max (0, min (0xff, (int) (min_delta + GREEN_FROM_ULONG (*color)))),
2989 max (0, min (0xff, (int) (min_delta + BLUE_FROM_ULONG (*color)))));
2990 }
2991
2992 if (new == *color)
2993 new = RGB_TO_ULONG (max (0, min (0xff, (int) (delta + RED_FROM_ULONG (*color)))),
2994 max (0, min (0xff, (int) (delta + GREEN_FROM_ULONG (*color)))),
2995 max (0, min (0xff, (int) (delta + BLUE_FROM_ULONG (*color)))));
2996
2997 /* MAC_TODO: Map to palette and retry with delta if same? */
2998 /* MAC_TODO: Free colors (if using palette)? */
2999
3000 if (new == *color)
3001 return 0;
3002
3003 *color = new;
3004
3005 return 1;
3006 }
3007
3008
3009 /* Set up the foreground color for drawing relief lines of glyph
3010 string S. RELIEF is a pointer to a struct relief containing the GC
3011 with which lines will be drawn. Use a color that is FACTOR or
3012 DELTA lighter or darker than the relief's background which is found
3013 in S->f->output_data.x->relief_background. If such a color cannot
3014 be allocated, use DEFAULT_PIXEL, instead. */
3015
3016 static void
3017 x_setup_relief_color (f, relief, factor, delta, default_pixel)
3018 struct frame *f;
3019 struct relief *relief;
3020 double factor;
3021 int delta;
3022 unsigned long default_pixel;
3023 {
3024 XGCValues xgcv;
3025 struct mac_output *di = f->output_data.mac;
3026 unsigned long mask = GCForeground;
3027 unsigned long pixel;
3028 unsigned long background = di->relief_background;
3029 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
3030
3031 /* MAC_TODO: Free colors (if using palette)? */
3032
3033 /* Allocate new color. */
3034 xgcv.foreground = default_pixel;
3035 pixel = background;
3036 if (dpyinfo->n_planes != 1
3037 && mac_alloc_lighter_color (f, &pixel, factor, delta))
3038 {
3039 relief->allocated_p = 1;
3040 xgcv.foreground = relief->pixel = pixel;
3041 }
3042
3043 if (relief->gc == 0)
3044 {
3045 #if 0 /* MAC_TODO: stipple */
3046 xgcv.stipple = dpyinfo->gray;
3047 mask |= GCStipple;
3048 #endif
3049 relief->gc = XCreateGC (NULL, FRAME_MAC_WINDOW (f), mask, &xgcv);
3050 }
3051 else
3052 XChangeGC (NULL, relief->gc, mask, &xgcv);
3053 }
3054
3055
3056 /* Set up colors for the relief lines around glyph string S. */
3057
3058 static void
3059 x_setup_relief_colors (s)
3060 struct glyph_string *s;
3061 {
3062 struct mac_output *di = s->f->output_data.mac;
3063 unsigned long color;
3064
3065 if (s->face->use_box_color_for_shadows_p)
3066 color = s->face->box_color;
3067 else if (s->first_glyph->type == IMAGE_GLYPH
3068 && s->img->pixmap
3069 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
3070 color = IMAGE_BACKGROUND (s->img, s->f, 0);
3071 else
3072 {
3073 XGCValues xgcv;
3074
3075 /* Get the background color of the face. */
3076 XGetGCValues (s->display, s->gc, GCBackground, &xgcv);
3077 color = xgcv.background;
3078 }
3079
3080 if (di->white_relief.gc == 0
3081 || color != di->relief_background)
3082 {
3083 di->relief_background = color;
3084 x_setup_relief_color (s->f, &di->white_relief, 1.2, 0x8000,
3085 WHITE_PIX_DEFAULT (s->f));
3086 x_setup_relief_color (s->f, &di->black_relief, 0.6, 0x4000,
3087 BLACK_PIX_DEFAULT (s->f));
3088 }
3089 }
3090
3091
3092 /* Draw a relief on frame F inside the rectangle given by LEFT_X,
3093 TOP_Y, RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the relief
3094 to draw, it must be >= 0. RAISED_P non-zero means draw a raised
3095 relief. LEFT_P non-zero means draw a relief on the left side of
3096 the rectangle. RIGHT_P non-zero means draw a relief on the right
3097 side of the rectangle. CLIP_RECT is the clipping rectangle to use
3098 when drawing. */
3099
3100 static void
3101 x_draw_relief_rect (f, left_x, top_y, right_x, bottom_y, width,
3102 raised_p, top_p, bot_p, left_p, right_p, clip_rect)
3103 struct frame *f;
3104 int left_x, top_y, right_x, bottom_y, width;
3105 int top_p, bot_p, left_p, right_p, raised_p;
3106 Rect *clip_rect;
3107 {
3108 Display *dpy = FRAME_MAC_DISPLAY (f);
3109 int i;
3110 GC gc;
3111
3112 if (raised_p)
3113 gc = f->output_data.mac->white_relief.gc;
3114 else
3115 gc = f->output_data.mac->black_relief.gc;
3116 mac_set_clip_rectangles (dpy, gc, clip_rect, 1);
3117
3118 /* Top. */
3119 if (top_p)
3120 for (i = 0; i < width; ++i)
3121 mac_draw_line (f, gc,
3122 left_x + i * left_p, top_y + i,
3123 right_x - i * right_p, top_y + i);
3124
3125 /* Left. */
3126 if (left_p)
3127 for (i = 0; i < width; ++i)
3128 mac_draw_line (f, gc,
3129 left_x + i, top_y + i, left_x + i, bottom_y - i);
3130
3131 mac_reset_clip_rectangles (dpy, gc);
3132 if (raised_p)
3133 gc = f->output_data.mac->black_relief.gc;
3134 else
3135 gc = f->output_data.mac->white_relief.gc;
3136 mac_set_clip_rectangles (dpy, gc, clip_rect, 1);
3137
3138 /* Bottom. */
3139 if (bot_p)
3140 for (i = 0; i < width; ++i)
3141 mac_draw_line (f, gc,
3142 left_x + i * left_p, bottom_y - i,
3143 right_x - i * right_p, bottom_y - i);
3144
3145 /* Right. */
3146 if (right_p)
3147 for (i = 0; i < width; ++i)
3148 mac_draw_line (f, gc,
3149 right_x - i, top_y + i + 1, right_x - i, bottom_y - i - 1);
3150
3151 mac_reset_clip_rectangles (dpy, gc);
3152 }
3153
3154
3155 /* Draw a box on frame F inside the rectangle given by LEFT_X, TOP_Y,
3156 RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the lines to
3157 draw, it must be >= 0. LEFT_P non-zero means draw a line on the
3158 left side of the rectangle. RIGHT_P non-zero means draw a line
3159 on the right side of the rectangle. CLIP_RECT is the clipping
3160 rectangle to use when drawing. */
3161
3162 static void
3163 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
3164 left_p, right_p, clip_rect)
3165 struct glyph_string *s;
3166 int left_x, top_y, right_x, bottom_y, width, left_p, right_p;
3167 Rect *clip_rect;
3168 {
3169 XGCValues xgcv;
3170
3171 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3172 XSetForeground (s->display, s->gc, s->face->box_color);
3173 mac_set_clip_rectangles (s->display, s->gc, clip_rect, 1);
3174
3175 /* Top. */
3176 mac_fill_rectangle (s->f, s->gc, left_x, top_y,
3177 right_x - left_x + 1, width);
3178
3179 /* Left. */
3180 if (left_p)
3181 mac_fill_rectangle (s->f, s->gc, left_x, top_y,
3182 width, bottom_y - top_y + 1);
3183
3184 /* Bottom. */
3185 mac_fill_rectangle (s->f, s->gc, left_x, bottom_y - width + 1,
3186 right_x - left_x + 1, width);
3187
3188 /* Right. */
3189 if (right_p)
3190 mac_fill_rectangle (s->f, s->gc, right_x - width + 1,
3191 top_y, width, bottom_y - top_y + 1);
3192
3193 XSetForeground (s->display, s->gc, xgcv.foreground);
3194 mac_reset_clip_rectangles (s->display, s->gc);
3195 }
3196
3197
3198 /* Draw a box around glyph string S. */
3199
3200 static void
3201 x_draw_glyph_string_box (s)
3202 struct glyph_string *s;
3203 {
3204 int width, left_x, right_x, top_y, bottom_y, last_x, raised_p;
3205 int left_p, right_p;
3206 struct glyph *last_glyph;
3207 Rect clip_rect;
3208
3209 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
3210 ? WINDOW_RIGHT_EDGE_X (s->w)
3211 : window_box_right (s->w, s->area));
3212
3213 /* The glyph that may have a right box line. */
3214 last_glyph = (s->cmp || s->img
3215 ? s->first_glyph
3216 : s->first_glyph + s->nchars - 1);
3217
3218 width = abs (s->face->box_line_width);
3219 raised_p = s->face->box == FACE_RAISED_BOX;
3220 left_x = s->x;
3221 right_x = (s->row->full_width_p && s->extends_to_end_of_line_p
3222 ? last_x - 1
3223 : min (last_x, s->x + s->background_width) - 1);
3224 top_y = s->y;
3225 bottom_y = top_y + s->height - 1;
3226
3227 left_p = (s->first_glyph->left_box_line_p
3228 || (s->hl == DRAW_MOUSE_FACE
3229 && (s->prev == NULL
3230 || s->prev->hl != s->hl)));
3231 right_p = (last_glyph->right_box_line_p
3232 || (s->hl == DRAW_MOUSE_FACE
3233 && (s->next == NULL
3234 || s->next->hl != s->hl)));
3235
3236 get_glyph_string_clip_rect (s, &clip_rect);
3237
3238 if (s->face->box == FACE_SIMPLE_BOX)
3239 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
3240 left_p, right_p, &clip_rect);
3241 else
3242 {
3243 x_setup_relief_colors (s);
3244 x_draw_relief_rect (s->f, left_x, top_y, right_x, bottom_y,
3245 width, raised_p, 1, 1, left_p, right_p, &clip_rect);
3246 }
3247 }
3248
3249
3250 /* Draw foreground of image glyph string S. */
3251
3252 static void
3253 x_draw_image_foreground (s)
3254 struct glyph_string *s;
3255 {
3256 int x = s->x;
3257 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3258
3259 /* If first glyph of S has a left box line, start drawing it to the
3260 right of that line. */
3261 if (s->face->box != FACE_NO_BOX
3262 && s->first_glyph->left_box_line_p
3263 && s->slice.x == 0)
3264 x += abs (s->face->box_line_width);
3265
3266 /* If there is a margin around the image, adjust x- and y-position
3267 by that margin. */
3268 if (s->slice.x == 0)
3269 x += s->img->hmargin;
3270 if (s->slice.y == 0)
3271 y += s->img->vmargin;
3272
3273 if (s->img->pixmap)
3274 {
3275 x_set_glyph_string_clipping (s);
3276
3277 #if USE_CG_DRAWING
3278 mac_draw_cg_image (s->img->data.ptr_val,
3279 s->f, s->gc, s->slice.x, s->slice.y,
3280 s->slice.width, s->slice.height, x, y, 1);
3281 #endif
3282 if (s->img->mask)
3283 #if !USE_CG_DRAWING
3284 mac_copy_area_with_mask (s->img->pixmap, s->img->mask,
3285 s->f, s->gc, s->slice.x, s->slice.y,
3286 s->slice.width, s->slice.height, x, y);
3287 #else
3288 ;
3289 #endif
3290 else
3291 {
3292 #if !USE_CG_DRAWING
3293 mac_copy_area (s->img->pixmap,
3294 s->f, s->gc, s->slice.x, s->slice.y,
3295 s->slice.width, s->slice.height, x, y);
3296 #endif
3297
3298 /* When the image has a mask, we can expect that at
3299 least part of a mouse highlight or a block cursor will
3300 be visible. If the image doesn't have a mask, make
3301 a block cursor visible by drawing a rectangle around
3302 the image. I believe it's looking better if we do
3303 nothing here for mouse-face. */
3304 if (s->hl == DRAW_CURSOR)
3305 {
3306 int r = s->img->relief;
3307 if (r < 0) r = -r;
3308 mac_draw_rectangle (s->f, s->gc, x - r, y - r,
3309 s->slice.width + r*2 - 1,
3310 s->slice.height + r*2 - 1);
3311 }
3312 }
3313 }
3314 else
3315 /* Draw a rectangle if image could not be loaded. */
3316 mac_draw_rectangle (s->f, s->gc, x, y,
3317 s->slice.width - 1, s->slice.height - 1);
3318 }
3319
3320
3321 /* Draw a relief around the image glyph string S. */
3322
3323 static void
3324 x_draw_image_relief (s)
3325 struct glyph_string *s;
3326 {
3327 int x0, y0, x1, y1, thick, raised_p;
3328 Rect r;
3329 int x = s->x;
3330 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3331
3332 /* If first glyph of S has a left box line, start drawing it to the
3333 right of that line. */
3334 if (s->face->box != FACE_NO_BOX
3335 && s->first_glyph->left_box_line_p
3336 && s->slice.x == 0)
3337 x += abs (s->face->box_line_width);
3338
3339 /* If there is a margin around the image, adjust x- and y-position
3340 by that margin. */
3341 if (s->slice.x == 0)
3342 x += s->img->hmargin;
3343 if (s->slice.y == 0)
3344 y += s->img->vmargin;
3345
3346 if (s->hl == DRAW_IMAGE_SUNKEN
3347 || s->hl == DRAW_IMAGE_RAISED)
3348 {
3349 thick = tool_bar_button_relief >= 0 ? tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3350 raised_p = s->hl == DRAW_IMAGE_RAISED;
3351 }
3352 else
3353 {
3354 thick = abs (s->img->relief);
3355 raised_p = s->img->relief > 0;
3356 }
3357
3358 x0 = x - thick;
3359 y0 = y - thick;
3360 x1 = x + s->slice.width + thick - 1;
3361 y1 = y + s->slice.height + thick - 1;
3362
3363 x_setup_relief_colors (s);
3364 get_glyph_string_clip_rect (s, &r);
3365 x_draw_relief_rect (s->f, x0, y0, x1, y1, thick, raised_p,
3366 s->slice.y == 0,
3367 s->slice.y + s->slice.height == s->img->height,
3368 s->slice.x == 0,
3369 s->slice.x + s->slice.width == s->img->width,
3370 &r);
3371 }
3372
3373
3374 /* Draw part of the background of glyph string S. X, Y, W, and H
3375 give the rectangle to draw. */
3376
3377 static void
3378 x_draw_glyph_string_bg_rect (s, x, y, w, h)
3379 struct glyph_string *s;
3380 int x, y, w, h;
3381 {
3382 #if 0 /* MAC_TODO: stipple */
3383 if (s->stippled_p)
3384 {
3385 /* Fill background with a stipple pattern. */
3386 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
3387 XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
3388 XSetFillStyle (s->display, s->gc, FillSolid);
3389 }
3390 else
3391 #endif /* MAC_TODO */
3392 x_clear_glyph_string_rect (s, x, y, w, h);
3393 }
3394
3395
3396 /* Draw image glyph string S.
3397
3398 s->y
3399 s->x +-------------------------
3400 | s->face->box
3401 |
3402 | +-------------------------
3403 | | s->img->margin
3404 | |
3405 | | +-------------------
3406 | | | the image
3407
3408 */
3409
3410 static void
3411 x_draw_image_glyph_string (s)
3412 struct glyph_string *s;
3413 {
3414 int x, y;
3415 int box_line_hwidth = abs (s->face->box_line_width);
3416 int box_line_vwidth = max (s->face->box_line_width, 0);
3417 int height;
3418
3419 height = s->height - 2 * box_line_vwidth;
3420
3421
3422 /* Fill background with face under the image. Do it only if row is
3423 taller than image or if image has a clip mask to reduce
3424 flickering. */
3425 s->stippled_p = s->face->stipple != 0;
3426 if (height > s->slice.height
3427 || s->img->hmargin
3428 || s->img->vmargin
3429 || s->img->mask
3430 || s->img->pixmap == 0
3431 || s->width != s->background_width)
3432 {
3433 x = s->x;
3434 if (s->first_glyph->left_box_line_p
3435 && s->slice.x == 0)
3436 x += box_line_hwidth;
3437
3438 y = s->y;
3439 if (s->slice.y == 0)
3440 y += box_line_vwidth;
3441
3442 x_draw_glyph_string_bg_rect (s, x, y, s->background_width, height);
3443
3444 s->background_filled_p = 1;
3445 }
3446
3447 /* Draw the foreground. */
3448 x_draw_image_foreground (s);
3449
3450 /* If we must draw a relief around the image, do it. */
3451 if (s->img->relief
3452 || s->hl == DRAW_IMAGE_RAISED
3453 || s->hl == DRAW_IMAGE_SUNKEN)
3454 x_draw_image_relief (s);
3455 }
3456
3457
3458 /* Draw stretch glyph string S. */
3459
3460 static void
3461 x_draw_stretch_glyph_string (s)
3462 struct glyph_string *s;
3463 {
3464 xassert (s->first_glyph->type == STRETCH_GLYPH);
3465 s->stippled_p = s->face->stipple != 0;
3466
3467 if (s->hl == DRAW_CURSOR
3468 && !x_stretch_cursor_p)
3469 {
3470 /* If `x-stretch-block-cursor' is nil, don't draw a block cursor
3471 as wide as the stretch glyph. */
3472 int width = min (FRAME_COLUMN_WIDTH (s->f), s->background_width);
3473
3474 /* Draw cursor. */
3475 x_draw_glyph_string_bg_rect (s, s->x, s->y, width, s->height);
3476
3477 /* Clear rest using the GC of the original non-cursor face. */
3478 if (width < s->background_width)
3479 {
3480 int x = s->x + width, y = s->y;
3481 int w = s->background_width - width, h = s->height;
3482 Rect r;
3483 GC gc;
3484
3485 if (s->row->mouse_face_p
3486 && cursor_in_mouse_face_p (s->w))
3487 {
3488 x_set_mouse_face_gc (s);
3489 gc = s->gc;
3490 }
3491 else
3492 gc = s->face->gc;
3493
3494 get_glyph_string_clip_rect (s, &r);
3495 mac_set_clip_rectangles (s->display, gc, &r, 1);
3496
3497 #if 0 /* MAC_TODO: stipple */
3498 if (s->face->stipple)
3499 {
3500 /* Fill background with a stipple pattern. */
3501 XSetFillStyle (s->display, gc, FillOpaqueStippled);
3502 XFillRectangle (s->display, s->window, gc, x, y, w, h);
3503 XSetFillStyle (s->display, gc, FillSolid);
3504 }
3505 else
3506 #endif /* MAC_TODO */
3507 mac_erase_rectangle (s->f, gc, x, y, w, h);
3508 }
3509 }
3510 else if (!s->background_filled_p)
3511 x_draw_glyph_string_bg_rect (s, s->x, s->y, s->background_width,
3512 s->height);
3513
3514 s->background_filled_p = 1;
3515 }
3516
3517
3518 /* Draw glyph string S. */
3519
3520 static void
3521 x_draw_glyph_string (s)
3522 struct glyph_string *s;
3523 {
3524 int relief_drawn_p = 0;
3525
3526 /* If S draws into the background of its successor that does not
3527 draw a cursor, draw the background of the successor first so that
3528 S can draw into it. This makes S->next use XDrawString instead
3529 of XDrawImageString. */
3530 if (s->next && s->right_overhang && !s->for_overlaps
3531 && s->next->hl != DRAW_CURSOR)
3532 {
3533 xassert (s->next->img == NULL);
3534 x_set_glyph_string_gc (s->next);
3535 x_set_glyph_string_clipping (s->next);
3536 x_draw_glyph_string_background (s->next, 1);
3537 }
3538
3539 /* Set up S->gc, set clipping and draw S. */
3540 x_set_glyph_string_gc (s);
3541
3542 /* Draw relief (if any) in advance for char/composition so that the
3543 glyph string can be drawn over it. */
3544 if (!s->for_overlaps
3545 && s->face->box != FACE_NO_BOX
3546 && (s->first_glyph->type == CHAR_GLYPH
3547 || s->first_glyph->type == COMPOSITE_GLYPH))
3548
3549 {
3550 x_set_glyph_string_clipping (s);
3551 x_draw_glyph_string_background (s, 1);
3552 x_draw_glyph_string_box (s);
3553 x_set_glyph_string_clipping (s);
3554 relief_drawn_p = 1;
3555 }
3556 else
3557 x_set_glyph_string_clipping (s);
3558
3559 switch (s->first_glyph->type)
3560 {
3561 case IMAGE_GLYPH:
3562 x_draw_image_glyph_string (s);
3563 break;
3564
3565 case STRETCH_GLYPH:
3566 x_draw_stretch_glyph_string (s);
3567 break;
3568
3569 case CHAR_GLYPH:
3570 if (s->for_overlaps)
3571 s->background_filled_p = 1;
3572 else
3573 x_draw_glyph_string_background (s, 0);
3574 x_draw_glyph_string_foreground (s);
3575 break;
3576
3577 case COMPOSITE_GLYPH:
3578 if (s->for_overlaps || s->gidx > 0)
3579 s->background_filled_p = 1;
3580 else
3581 x_draw_glyph_string_background (s, 1);
3582 x_draw_composite_glyph_string_foreground (s);
3583 break;
3584
3585 default:
3586 abort ();
3587 }
3588
3589 if (!s->for_overlaps)
3590 {
3591 /* Draw underline. */
3592 if (s->face->underline_p)
3593 {
3594 unsigned long h = 1;
3595 unsigned long dy = s->height - h;
3596
3597 if (s->face->underline_defaulted_p)
3598 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3599 s->width, h);
3600 else
3601 {
3602 XGCValues xgcv;
3603 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3604 XSetForeground (s->display, s->gc, s->face->underline_color);
3605 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3606 s->width, h);
3607 XSetForeground (s->display, s->gc, xgcv.foreground);
3608 }
3609 }
3610
3611 /* Draw overline. */
3612 if (s->face->overline_p)
3613 {
3614 unsigned long dy = 0, h = 1;
3615
3616 if (s->face->overline_color_defaulted_p)
3617 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3618 s->width, h);
3619 else
3620 {
3621 XGCValues xgcv;
3622 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3623 XSetForeground (s->display, s->gc, s->face->overline_color);
3624 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3625 s->width, h);
3626 XSetForeground (s->display, s->gc, xgcv.foreground);
3627 }
3628 }
3629
3630 /* Draw strike-through. */
3631 if (s->face->strike_through_p)
3632 {
3633 unsigned long h = 1;
3634 unsigned long dy = (s->height - h) / 2;
3635
3636 if (s->face->strike_through_color_defaulted_p)
3637 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3638 s->width, h);
3639 else
3640 {
3641 XGCValues xgcv;
3642 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3643 XSetForeground (s->display, s->gc, s->face->strike_through_color);
3644 mac_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3645 s->width, h);
3646 XSetForeground (s->display, s->gc, xgcv.foreground);
3647 }
3648 }
3649
3650 /* Draw relief if not yet drawn. */
3651 if (!relief_drawn_p && s->face->box != FACE_NO_BOX)
3652 x_draw_glyph_string_box (s);
3653 }
3654
3655 /* Reset clipping. */
3656 mac_reset_clip_rectangles (s->display, s->gc);
3657 }
3658
3659 /* Shift display to make room for inserted glyphs. */
3660
3661 void
3662 mac_shift_glyphs_for_insert (f, x, y, width, height, shift_by)
3663 struct frame *f;
3664 int x, y, width, height, shift_by;
3665 {
3666 mac_scroll_area (f, f->output_data.mac->normal_gc,
3667 x, y, width, height,
3668 x + shift_by, y);
3669 }
3670
3671 /* Delete N glyphs at the nominal cursor position. Not implemented
3672 for X frames. */
3673
3674 static void
3675 x_delete_glyphs (n)
3676 register int n;
3677 {
3678 abort ();
3679 }
3680
3681
3682 /* Clear entire frame. If updating_frame is non-null, clear that
3683 frame. Otherwise clear the selected frame. */
3684
3685 static void
3686 x_clear_frame ()
3687 {
3688 struct frame *f;
3689
3690 if (updating_frame)
3691 f = updating_frame;
3692 else
3693 f = SELECTED_FRAME ();
3694
3695 /* Clearing the frame will erase any cursor, so mark them all as no
3696 longer visible. */
3697 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
3698 output_cursor.hpos = output_cursor.vpos = 0;
3699 output_cursor.x = -1;
3700
3701 /* We don't set the output cursor here because there will always
3702 follow an explicit cursor_to. */
3703 BLOCK_INPUT;
3704 mac_clear_window (f);
3705
3706 /* We have to clear the scroll bars, too. If we have changed
3707 colors or something like that, then they should be notified. */
3708 x_scroll_bar_clear (f);
3709
3710 XFlush (FRAME_MAC_DISPLAY (f));
3711 UNBLOCK_INPUT;
3712 }
3713
3714
3715 \f
3716 /* Invert the middle quarter of the frame for .15 sec. */
3717
3718 /* We use the select system call to do the waiting, so we have to make
3719 sure it's available. If it isn't, we just won't do visual bells. */
3720
3721 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
3722
3723
3724 /* Subtract the `struct timeval' values X and Y, storing the result in
3725 *RESULT. Return 1 if the difference is negative, otherwise 0. */
3726
3727 static int
3728 timeval_subtract (result, x, y)
3729 struct timeval *result, x, y;
3730 {
3731 /* Perform the carry for the later subtraction by updating y. This
3732 is safer because on some systems the tv_sec member is unsigned. */
3733 if (x.tv_usec < y.tv_usec)
3734 {
3735 int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
3736 y.tv_usec -= 1000000 * nsec;
3737 y.tv_sec += nsec;
3738 }
3739
3740 if (x.tv_usec - y.tv_usec > 1000000)
3741 {
3742 int nsec = (y.tv_usec - x.tv_usec) / 1000000;
3743 y.tv_usec += 1000000 * nsec;
3744 y.tv_sec -= nsec;
3745 }
3746
3747 /* Compute the time remaining to wait. tv_usec is certainly
3748 positive. */
3749 result->tv_sec = x.tv_sec - y.tv_sec;
3750 result->tv_usec = x.tv_usec - y.tv_usec;
3751
3752 /* Return indication of whether the result should be considered
3753 negative. */
3754 return x.tv_sec < y.tv_sec;
3755 }
3756
3757 void
3758 XTflash (f)
3759 struct frame *f;
3760 {
3761 /* Get the height not including a menu bar widget. */
3762 int height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, FRAME_LINES (f));
3763 /* Height of each line to flash. */
3764 int flash_height = FRAME_LINE_HEIGHT (f);
3765 /* These will be the left and right margins of the rectangles. */
3766 int flash_left = FRAME_INTERNAL_BORDER_WIDTH (f);
3767 int flash_right = FRAME_PIXEL_WIDTH (f) - FRAME_INTERNAL_BORDER_WIDTH (f);
3768
3769 int width;
3770
3771 /* Don't flash the area between a scroll bar and the frame
3772 edge it is next to. */
3773 switch (FRAME_VERTICAL_SCROLL_BAR_TYPE (f))
3774 {
3775 case vertical_scroll_bar_left:
3776 flash_left += VERTICAL_SCROLL_BAR_WIDTH_TRIM;
3777 break;
3778
3779 case vertical_scroll_bar_right:
3780 flash_right -= VERTICAL_SCROLL_BAR_WIDTH_TRIM;
3781 break;
3782
3783 default:
3784 break;
3785 }
3786
3787 width = flash_right - flash_left;
3788
3789 BLOCK_INPUT;
3790
3791 /* If window is tall, flash top and bottom line. */
3792 if (height > 3 * FRAME_LINE_HEIGHT (f))
3793 {
3794 mac_invert_rectangle (f, flash_left,
3795 (FRAME_INTERNAL_BORDER_WIDTH (f)
3796 + FRAME_TOOL_BAR_LINES (f) * FRAME_LINE_HEIGHT (f)),
3797 width, flash_height);
3798 mac_invert_rectangle (f, flash_left,
3799 (height - flash_height
3800 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3801 width, flash_height);
3802 }
3803 else
3804 /* If it is short, flash it all. */
3805 mac_invert_rectangle (f, flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3806 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3807
3808 x_flush (f);
3809
3810 {
3811 struct timeval wakeup;
3812
3813 EMACS_GET_TIME (wakeup);
3814
3815 /* Compute time to wait until, propagating carry from usecs. */
3816 wakeup.tv_usec += 150000;
3817 wakeup.tv_sec += (wakeup.tv_usec / 1000000);
3818 wakeup.tv_usec %= 1000000;
3819
3820 /* Keep waiting until past the time wakeup or any input gets
3821 available. */
3822 while (! detect_input_pending ())
3823 {
3824 struct timeval current;
3825 struct timeval timeout;
3826
3827 EMACS_GET_TIME (current);
3828
3829 /* Break if result would be negative. */
3830 if (timeval_subtract (&current, wakeup, current))
3831 break;
3832
3833 /* How long `select' should wait. */
3834 timeout.tv_sec = 0;
3835 timeout.tv_usec = 10000;
3836
3837 /* Try to wait that long--but we might wake up sooner. */
3838 select (0, NULL, NULL, NULL, &timeout);
3839 }
3840 }
3841
3842 /* If window is tall, flash top and bottom line. */
3843 if (height > 3 * FRAME_LINE_HEIGHT (f))
3844 {
3845 mac_invert_rectangle (f, flash_left,
3846 (FRAME_INTERNAL_BORDER_WIDTH (f)
3847 + FRAME_TOOL_BAR_LINES (f) * FRAME_LINE_HEIGHT (f)),
3848 width, flash_height);
3849 mac_invert_rectangle (f, flash_left,
3850 (height - flash_height
3851 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3852 width, flash_height);
3853 }
3854 else
3855 /* If it is short, flash it all. */
3856 mac_invert_rectangle (f, flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3857 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3858
3859 x_flush (f);
3860
3861 UNBLOCK_INPUT;
3862 }
3863
3864 #endif /* defined (HAVE_TIMEVAL) && defined (HAVE_SELECT) */
3865
3866
3867 /* Make audible bell. */
3868
3869 void
3870 XTring_bell ()
3871 {
3872 struct frame *f = SELECTED_FRAME ();
3873
3874 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
3875 if (visible_bell)
3876 XTflash (f);
3877 else
3878 #endif
3879 {
3880 BLOCK_INPUT;
3881 SysBeep (1);
3882 XFlush (FRAME_MAC_DISPLAY (f));
3883 UNBLOCK_INPUT;
3884 }
3885 }
3886
3887 \f
3888 /* Specify how many text lines, from the top of the window,
3889 should be affected by insert-lines and delete-lines operations.
3890 This, and those operations, are used only within an update
3891 that is bounded by calls to x_update_begin and x_update_end. */
3892
3893 static void
3894 XTset_terminal_window (n)
3895 register int n;
3896 {
3897 /* This function intentionally left blank. */
3898 }
3899
3900
3901 \f
3902 /***********************************************************************
3903 Line Dance
3904 ***********************************************************************/
3905
3906 /* Perform an insert-lines or delete-lines operation, inserting N
3907 lines or deleting -N lines at vertical position VPOS. */
3908
3909 static void
3910 x_ins_del_lines (vpos, n)
3911 int vpos, n;
3912 {
3913 abort ();
3914 }
3915
3916
3917 /* Scroll part of the display as described by RUN. */
3918
3919 static void
3920 x_scroll_run (w, run)
3921 struct window *w;
3922 struct run *run;
3923 {
3924 struct frame *f = XFRAME (w->frame);
3925 int x, y, width, height, from_y, to_y, bottom_y;
3926
3927 /* Get frame-relative bounding box of the text display area of W,
3928 without mode lines. Include in this box the left and right
3929 fringe of W. */
3930 window_box (w, -1, &x, &y, &width, &height);
3931
3932 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
3933 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
3934 bottom_y = y + height;
3935
3936 if (to_y < from_y)
3937 {
3938 /* Scrolling up. Make sure we don't copy part of the mode
3939 line at the bottom. */
3940 if (from_y + run->height > bottom_y)
3941 height = bottom_y - from_y;
3942 else
3943 height = run->height;
3944 }
3945 else
3946 {
3947 /* Scolling down. Make sure we don't copy over the mode line.
3948 at the bottom. */
3949 if (to_y + run->height > bottom_y)
3950 height = bottom_y - to_y;
3951 else
3952 height = run->height;
3953 }
3954
3955 BLOCK_INPUT;
3956
3957 /* Cursor off. Will be switched on again in x_update_window_end. */
3958 updated_window = w;
3959 x_clear_cursor (w);
3960
3961 mac_scroll_area (f, f->output_data.mac->normal_gc,
3962 x, from_y,
3963 width, height,
3964 x, to_y);
3965
3966 UNBLOCK_INPUT;
3967 }
3968
3969
3970 \f
3971 /***********************************************************************
3972 Exposure Events
3973 ***********************************************************************/
3974
3975 \f
3976 static void
3977 frame_highlight (f)
3978 struct frame *f;
3979 {
3980 OSErr err;
3981 ControlRef root_control;
3982
3983 BLOCK_INPUT;
3984 err = GetRootControl (FRAME_MAC_WINDOW (f), &root_control);
3985 if (err == noErr)
3986 ActivateControl (root_control);
3987 UNBLOCK_INPUT;
3988 x_update_cursor (f, 1);
3989 }
3990
3991 static void
3992 frame_unhighlight (f)
3993 struct frame *f;
3994 {
3995 OSErr err;
3996 ControlRef root_control;
3997
3998 BLOCK_INPUT;
3999 err = GetRootControl (FRAME_MAC_WINDOW (f), &root_control);
4000 if (err == noErr)
4001 DeactivateControl (root_control);
4002 UNBLOCK_INPUT;
4003 x_update_cursor (f, 1);
4004 }
4005
4006 /* The focus has changed. Update the frames as necessary to reflect
4007 the new situation. Note that we can't change the selected frame
4008 here, because the Lisp code we are interrupting might become confused.
4009 Each event gets marked with the frame in which it occurred, so the
4010 Lisp code can tell when the switch took place by examining the events. */
4011
4012 static void
4013 x_new_focus_frame (dpyinfo, frame)
4014 struct x_display_info *dpyinfo;
4015 struct frame *frame;
4016 {
4017 struct frame *old_focus = dpyinfo->x_focus_frame;
4018
4019 if (frame != dpyinfo->x_focus_frame)
4020 {
4021 /* Set this before calling other routines, so that they see
4022 the correct value of x_focus_frame. */
4023 dpyinfo->x_focus_frame = frame;
4024
4025 if (old_focus && old_focus->auto_lower)
4026 x_lower_frame (old_focus);
4027
4028 #if 0
4029 selected_frame = frame;
4030 XSETFRAME (XWINDOW (selected_frame->selected_window)->frame,
4031 selected_frame);
4032 Fselect_window (selected_frame->selected_window, Qnil);
4033 choose_minibuf_frame ();
4034 #endif /* ! 0 */
4035
4036 if (dpyinfo->x_focus_frame && dpyinfo->x_focus_frame->auto_raise)
4037 pending_autoraise_frame = dpyinfo->x_focus_frame;
4038 else
4039 pending_autoraise_frame = 0;
4040 }
4041
4042 x_frame_rehighlight (dpyinfo);
4043 }
4044
4045 /* Handle FocusIn and FocusOut state changes for FRAME.
4046 If FRAME has focus and there exists more than one frame, puts
4047 a FOCUS_IN_EVENT into *BUFP. */
4048
4049 static void
4050 mac_focus_changed (type, dpyinfo, frame, bufp)
4051 int type;
4052 struct mac_display_info *dpyinfo;
4053 struct frame *frame;
4054 struct input_event *bufp;
4055 {
4056 if (type == activeFlag)
4057 {
4058 if (dpyinfo->x_focus_event_frame != frame)
4059 {
4060 x_new_focus_frame (dpyinfo, frame);
4061 dpyinfo->x_focus_event_frame = frame;
4062
4063 /* Don't stop displaying the initial startup message
4064 for a switch-frame event we don't need. */
4065 if (GC_NILP (Vterminal_frame)
4066 && GC_CONSP (Vframe_list)
4067 && !GC_NILP (XCDR (Vframe_list)))
4068 {
4069 bufp->kind = FOCUS_IN_EVENT;
4070 XSETFRAME (bufp->frame_or_window, frame);
4071 }
4072 }
4073 }
4074 else
4075 {
4076 if (dpyinfo->x_focus_event_frame == frame)
4077 {
4078 dpyinfo->x_focus_event_frame = 0;
4079 x_new_focus_frame (dpyinfo, 0);
4080 }
4081 }
4082 }
4083
4084 /* The focus may have changed. Figure out if it is a real focus change,
4085 by checking both FocusIn/Out and Enter/LeaveNotify events.
4086
4087 Returns FOCUS_IN_EVENT event in *BUFP. */
4088
4089 static void
4090 x_detect_focus_change (dpyinfo, event, bufp)
4091 struct mac_display_info *dpyinfo;
4092 EventRecord *event;
4093 struct input_event *bufp;
4094 {
4095 struct frame *frame;
4096
4097 frame = mac_window_to_frame ((WindowPtr) event->message);
4098 if (! frame)
4099 return;
4100
4101 /* On Mac, this is only called from focus events, so no switch needed. */
4102 mac_focus_changed ((event->modifiers & activeFlag),
4103 dpyinfo, frame, bufp);
4104 }
4105
4106
4107 /* Handle an event saying the mouse has moved out of an Emacs frame. */
4108
4109 void
4110 x_mouse_leave (dpyinfo)
4111 struct x_display_info *dpyinfo;
4112 {
4113 x_new_focus_frame (dpyinfo, dpyinfo->x_focus_event_frame);
4114 }
4115
4116 /* The focus has changed, or we have redirected a frame's focus to
4117 another frame (this happens when a frame uses a surrogate
4118 mini-buffer frame). Shift the highlight as appropriate.
4119
4120 The FRAME argument doesn't necessarily have anything to do with which
4121 frame is being highlighted or un-highlighted; we only use it to find
4122 the appropriate X display info. */
4123
4124 static void
4125 XTframe_rehighlight (frame)
4126 struct frame *frame;
4127 {
4128 x_frame_rehighlight (FRAME_X_DISPLAY_INFO (frame));
4129 }
4130
4131 static void
4132 x_frame_rehighlight (dpyinfo)
4133 struct x_display_info *dpyinfo;
4134 {
4135 struct frame *old_highlight = dpyinfo->x_highlight_frame;
4136
4137 if (dpyinfo->x_focus_frame)
4138 {
4139 dpyinfo->x_highlight_frame
4140 = ((GC_FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame)))
4141 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
4142 : dpyinfo->x_focus_frame);
4143 if (! FRAME_LIVE_P (dpyinfo->x_highlight_frame))
4144 {
4145 FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
4146 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
4147 }
4148 }
4149 else
4150 dpyinfo->x_highlight_frame = 0;
4151
4152 if (dpyinfo->x_highlight_frame != old_highlight)
4153 {
4154 if (old_highlight)
4155 frame_unhighlight (old_highlight);
4156 if (dpyinfo->x_highlight_frame)
4157 frame_highlight (dpyinfo->x_highlight_frame);
4158 }
4159 }
4160
4161
4162 \f
4163 /* Convert a keysym to its name. */
4164
4165 char *
4166 x_get_keysym_name (keysym)
4167 int keysym;
4168 {
4169 char *value;
4170
4171 BLOCK_INPUT;
4172 #if 0
4173 value = XKeysymToString (keysym);
4174 #else
4175 value = 0;
4176 #endif
4177 UNBLOCK_INPUT;
4178
4179 return value;
4180 }
4181
4182
4183 \f
4184 /* Function to report a mouse movement to the mainstream Emacs code.
4185 The input handler calls this.
4186
4187 We have received a mouse movement event, which is given in *event.
4188 If the mouse is over a different glyph than it was last time, tell
4189 the mainstream emacs code by setting mouse_moved. If not, ask for
4190 another motion event, so we can check again the next time it moves. */
4191
4192 static Point last_mouse_motion_position;
4193 static Lisp_Object last_mouse_motion_frame;
4194
4195 static int
4196 note_mouse_movement (frame, pos)
4197 FRAME_PTR frame;
4198 Point *pos;
4199 {
4200 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (frame);
4201 #if TARGET_API_MAC_CARBON
4202 Rect r;
4203 #endif
4204
4205 last_mouse_movement_time = TickCount () * (1000 / 60); /* to milliseconds */
4206 last_mouse_motion_position = *pos;
4207 XSETFRAME (last_mouse_motion_frame, frame);
4208
4209 #if TARGET_API_MAC_CARBON
4210 if (!PtInRect (*pos, GetWindowPortBounds (FRAME_MAC_WINDOW (frame), &r)))
4211 #else
4212 if (!PtInRect (*pos, &FRAME_MAC_WINDOW (frame)->portRect))
4213 #endif
4214 {
4215 if (frame == dpyinfo->mouse_face_mouse_frame)
4216 /* This case corresponds to LeaveNotify in X11. */
4217 {
4218 /* If we move outside the frame, then we're certainly no
4219 longer on any text in the frame. */
4220 clear_mouse_face (dpyinfo);
4221 dpyinfo->mouse_face_mouse_frame = 0;
4222 if (!dpyinfo->grabbed)
4223 rif->define_frame_cursor (frame,
4224 frame->output_data.mac->nontext_cursor);
4225 }
4226 return 1;
4227 }
4228 /* Has the mouse moved off the glyph it was on at the last sighting? */
4229 if (frame != last_mouse_glyph_frame
4230 || !PtInRect (*pos, &last_mouse_glyph))
4231 {
4232 frame->mouse_moved = 1;
4233 last_mouse_scroll_bar = Qnil;
4234 note_mouse_highlight (frame, pos->h, pos->v);
4235 /* Remember which glyph we're now on. */
4236 remember_mouse_glyph (frame, pos->h, pos->v, &last_mouse_glyph);
4237 last_mouse_glyph_frame = frame;
4238 return 1;
4239 }
4240
4241 return 0;
4242 }
4243
4244 \f
4245 /************************************************************************
4246 Mouse Face
4247 ************************************************************************/
4248
4249 /* MAC TODO: This should be called from somewhere (or removed) ++KFS */
4250
4251 static void
4252 redo_mouse_highlight ()
4253 {
4254 if (!NILP (last_mouse_motion_frame)
4255 && FRAME_LIVE_P (XFRAME (last_mouse_motion_frame)))
4256 note_mouse_highlight (XFRAME (last_mouse_motion_frame),
4257 last_mouse_motion_position.h,
4258 last_mouse_motion_position.v);
4259 }
4260
4261
4262 static struct frame *
4263 mac_focus_frame (dpyinfo)
4264 struct mac_display_info *dpyinfo;
4265 {
4266 if (dpyinfo->x_focus_frame)
4267 return dpyinfo->x_focus_frame;
4268 else
4269 /* Mac version may get events, such as a menu bar click, even when
4270 all the frames are invisible. In this case, we regard the
4271 event came to the selected frame. */
4272 return SELECTED_FRAME ();
4273 }
4274
4275
4276 /* Return the current position of the mouse.
4277 *FP should be a frame which indicates which display to ask about.
4278
4279 If the mouse movement started in a scroll bar, set *FP, *BAR_WINDOW,
4280 and *PART to the frame, window, and scroll bar part that the mouse
4281 is over. Set *X and *Y to the portion and whole of the mouse's
4282 position on the scroll bar.
4283
4284 If the mouse movement started elsewhere, set *FP to the frame the
4285 mouse is on, *BAR_WINDOW to nil, and *X and *Y to the character cell
4286 the mouse is over.
4287
4288 Set *TIME to the server time-stamp for the time at which the mouse
4289 was at this position.
4290
4291 Don't store anything if we don't have a valid set of values to report.
4292
4293 This clears the mouse_moved flag, so we can wait for the next mouse
4294 movement. */
4295
4296 static void
4297 XTmouse_position (fp, insist, bar_window, part, x, y, time)
4298 FRAME_PTR *fp;
4299 int insist;
4300 Lisp_Object *bar_window;
4301 enum scroll_bar_part *part;
4302 Lisp_Object *x, *y;
4303 unsigned long *time;
4304 {
4305 FRAME_PTR f1;
4306
4307 BLOCK_INPUT;
4308
4309 if (! NILP (last_mouse_scroll_bar) && insist == 0)
4310 x_scroll_bar_report_motion (fp, bar_window, part, x, y, time);
4311 else
4312 {
4313 Lisp_Object frame, tail;
4314
4315 /* Clear the mouse-moved flag for every frame on this display. */
4316 FOR_EACH_FRAME (tail, frame)
4317 XFRAME (frame)->mouse_moved = 0;
4318
4319 last_mouse_scroll_bar = Qnil;
4320
4321 if (FRAME_MAC_DISPLAY_INFO (*fp)->grabbed && last_mouse_frame
4322 && FRAME_LIVE_P (last_mouse_frame))
4323 f1 = last_mouse_frame;
4324 else
4325 f1 = mac_focus_frame (FRAME_MAC_DISPLAY_INFO (*fp));
4326
4327 if (f1)
4328 {
4329 /* Ok, we found a frame. Store all the values.
4330 last_mouse_glyph is a rectangle used to reduce the
4331 generation of mouse events. To not miss any motion
4332 events, we must divide the frame into rectangles of the
4333 size of the smallest character that could be displayed
4334 on it, i.e. into the same rectangles that matrices on
4335 the frame are divided into. */
4336 Point mouse_pos;
4337
4338 SetPortWindowPort (FRAME_MAC_WINDOW (f1));
4339 GetMouse (&mouse_pos);
4340 remember_mouse_glyph (f1, mouse_pos.h, mouse_pos.v,
4341 &last_mouse_glyph);
4342 last_mouse_glyph_frame = f1;
4343
4344 *bar_window = Qnil;
4345 *part = 0;
4346 *fp = f1;
4347 XSETINT (*x, mouse_pos.h);
4348 XSETINT (*y, mouse_pos.v);
4349 *time = last_mouse_movement_time;
4350 }
4351 }
4352
4353 UNBLOCK_INPUT;
4354 }
4355
4356 \f
4357 /************************************************************************
4358 Toolkit scroll bars
4359 ************************************************************************/
4360
4361 #ifdef USE_TOOLKIT_SCROLL_BARS
4362
4363 static pascal void scroll_bar_timer_callback P_ ((EventLoopTimerRef, void *));
4364 static OSStatus install_scroll_bar_timer P_ ((void));
4365 static OSStatus set_scroll_bar_timer P_ ((EventTimerInterval));
4366 static int control_part_code_to_scroll_bar_part P_ ((ControlPartCode));
4367 static void construct_scroll_bar_click P_ ((struct scroll_bar *, int,
4368 struct input_event *));
4369 static OSStatus get_control_part_bounds P_ ((ControlHandle, ControlPartCode,
4370 Rect *));
4371 static void x_scroll_bar_handle_press P_ ((struct scroll_bar *,
4372 ControlPartCode,
4373 struct input_event *));
4374 static void x_scroll_bar_handle_release P_ ((struct scroll_bar *,
4375 struct input_event *));
4376 static void x_scroll_bar_handle_drag P_ ((WindowPtr, struct scroll_bar *,
4377 Point, struct input_event *));
4378 static void x_set_toolkit_scroll_bar_thumb P_ ((struct scroll_bar *,
4379 int, int, int));
4380
4381 /* Last scroll bar part sent in x_scroll_bar_handle_*. */
4382
4383 static int last_scroll_bar_part;
4384
4385 static EventLoopTimerRef scroll_bar_timer;
4386
4387 static int scroll_bar_timer_event_posted_p;
4388
4389 #define SCROLL_BAR_FIRST_DELAY 0.5
4390 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
4391
4392 static pascal void
4393 scroll_bar_timer_callback (timer, data)
4394 EventLoopTimerRef timer;
4395 void *data;
4396 {
4397 EventRef event = NULL;
4398 OSErr err;
4399
4400 err = CreateEvent (NULL, kEventClassMouse, kEventMouseMoved, 0,
4401 kEventAttributeNone, &event);
4402 if (err == noErr)
4403 {
4404 Point mouse_pos;
4405
4406 GetMouse (&mouse_pos);
4407 LocalToGlobal (&mouse_pos);
4408 err = SetEventParameter (event, kEventParamMouseLocation, typeQDPoint,
4409 sizeof (Point), &mouse_pos);
4410 }
4411 if (err == noErr)
4412 {
4413 UInt32 modifiers = GetCurrentKeyModifiers ();
4414
4415 err = SetEventParameter (event, kEventParamKeyModifiers, typeUInt32,
4416 sizeof (UInt32), &modifiers);
4417 }
4418 if (err == noErr)
4419 err = PostEventToQueue (GetCurrentEventQueue (), event,
4420 kEventPriorityStandard);
4421 if (err == noErr)
4422 scroll_bar_timer_event_posted_p = 1;
4423
4424 if (event)
4425 ReleaseEvent (event);
4426 }
4427
4428 static OSStatus
4429 install_scroll_bar_timer ()
4430 {
4431 static EventLoopTimerUPP scroll_bar_timer_callbackUPP = NULL;
4432
4433 if (scroll_bar_timer_callbackUPP == NULL)
4434 scroll_bar_timer_callbackUPP =
4435 NewEventLoopTimerUPP (scroll_bar_timer_callback);
4436
4437 if (scroll_bar_timer == NULL)
4438 /* Mac OS X and CarbonLib 1.5 and later allow us to specify
4439 kEventDurationForever as delays. */
4440 return
4441 InstallEventLoopTimer (GetCurrentEventLoop (),
4442 kEventDurationForever, kEventDurationForever,
4443 scroll_bar_timer_callbackUPP, NULL,
4444 &scroll_bar_timer);
4445 }
4446
4447 static OSStatus
4448 set_scroll_bar_timer (delay)
4449 EventTimerInterval delay;
4450 {
4451 if (scroll_bar_timer == NULL)
4452 install_scroll_bar_timer ();
4453
4454 scroll_bar_timer_event_posted_p = 0;
4455
4456 return SetEventLoopTimerNextFireTime (scroll_bar_timer, delay);
4457 }
4458
4459 static int
4460 control_part_code_to_scroll_bar_part (part_code)
4461 ControlPartCode part_code;
4462 {
4463 switch (part_code)
4464 {
4465 case kControlUpButtonPart: return scroll_bar_up_arrow;
4466 case kControlDownButtonPart: return scroll_bar_down_arrow;
4467 case kControlPageUpPart: return scroll_bar_above_handle;
4468 case kControlPageDownPart: return scroll_bar_below_handle;
4469 case kControlIndicatorPart: return scroll_bar_handle;
4470 }
4471
4472 return -1;
4473 }
4474
4475 static void
4476 construct_scroll_bar_click (bar, part, bufp)
4477 struct scroll_bar *bar;
4478 int part;
4479 struct input_event *bufp;
4480 {
4481 bufp->kind = SCROLL_BAR_CLICK_EVENT;
4482 bufp->frame_or_window = bar->window;
4483 bufp->arg = Qnil;
4484 bufp->part = part;
4485 bufp->code = 0;
4486 XSETINT (bufp->x, 0);
4487 XSETINT (bufp->y, 0);
4488 bufp->modifiers = 0;
4489 }
4490
4491 static OSStatus
4492 get_control_part_bounds (ch, part_code, rect)
4493 ControlHandle ch;
4494 ControlPartCode part_code;
4495 Rect *rect;
4496 {
4497 RgnHandle region = NewRgn ();
4498 OSStatus err;
4499
4500 err = GetControlRegion (ch, part_code, region);
4501 if (err == noErr)
4502 GetRegionBounds (region, rect);
4503 DisposeRgn (region);
4504
4505 return err;
4506 }
4507
4508 static void
4509 x_scroll_bar_handle_press (bar, part_code, bufp)
4510 struct scroll_bar *bar;
4511 ControlPartCode part_code;
4512 struct input_event *bufp;
4513 {
4514 int part = control_part_code_to_scroll_bar_part (part_code);
4515
4516 if (part < 0)
4517 return;
4518
4519 if (part != scroll_bar_handle)
4520 {
4521 construct_scroll_bar_click (bar, part, bufp);
4522 HiliteControl (SCROLL_BAR_CONTROL_HANDLE (bar), part_code);
4523 set_scroll_bar_timer (SCROLL_BAR_FIRST_DELAY);
4524 }
4525
4526 last_scroll_bar_part = part;
4527 bar->dragging = Qnil;
4528 tracked_scroll_bar = bar;
4529 }
4530
4531 static void
4532 x_scroll_bar_handle_release (bar, bufp)
4533 struct scroll_bar *bar;
4534 struct input_event *bufp;
4535 {
4536 if (last_scroll_bar_part != scroll_bar_handle
4537 || !GC_NILP (bar->dragging))
4538 construct_scroll_bar_click (bar, scroll_bar_end_scroll, bufp);
4539
4540 HiliteControl (SCROLL_BAR_CONTROL_HANDLE (bar), 0);
4541 set_scroll_bar_timer (kEventDurationForever);
4542
4543 last_scroll_bar_part = -1;
4544 bar->dragging = Qnil;
4545 tracked_scroll_bar = NULL;
4546 }
4547
4548 static void
4549 x_scroll_bar_handle_drag (win, bar, mouse_pos, bufp)
4550 WindowPtr win;
4551 struct scroll_bar *bar;
4552 Point mouse_pos;
4553 struct input_event *bufp;
4554 {
4555 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4556
4557 if (last_scroll_bar_part == scroll_bar_handle)
4558 {
4559 int top, top_range;
4560 Rect r;
4561
4562 get_control_part_bounds (SCROLL_BAR_CONTROL_HANDLE (bar),
4563 kControlIndicatorPart, &r);
4564
4565 if (GC_NILP (bar->dragging))
4566 XSETINT (bar->dragging, mouse_pos.v - r.top);
4567
4568 top = mouse_pos.v - XINT (bar->dragging) - XINT (bar->track_top);
4569 top_range = (XINT (bar->track_height) - (r.bottom - r.top)) *
4570 (1.0 + (float) GetControlViewSize (ch) / GetControl32BitMaximum (ch))
4571 + .5;
4572
4573 if (top < 0)
4574 top = 0;
4575 if (top > top_range)
4576 top = top_range;
4577
4578 construct_scroll_bar_click (bar, scroll_bar_handle, bufp);
4579 XSETINT (bufp->x, top);
4580 XSETINT (bufp->y, top_range);
4581 }
4582 else
4583 {
4584 ControlPartCode part_code;
4585 int unhilite_p = 0, part;
4586
4587 if (ch != FindControlUnderMouse (mouse_pos, win, &part_code))
4588 unhilite_p = 1;
4589 else
4590 {
4591 part = control_part_code_to_scroll_bar_part (part_code);
4592
4593 switch (last_scroll_bar_part)
4594 {
4595 case scroll_bar_above_handle:
4596 case scroll_bar_below_handle:
4597 if (part != scroll_bar_above_handle
4598 && part != scroll_bar_below_handle)
4599 unhilite_p = 1;
4600 break;
4601
4602 case scroll_bar_up_arrow:
4603 case scroll_bar_down_arrow:
4604 if (part != scroll_bar_up_arrow
4605 && part != scroll_bar_down_arrow)
4606 unhilite_p = 1;
4607 break;
4608 }
4609 }
4610
4611 if (unhilite_p)
4612 HiliteControl (SCROLL_BAR_CONTROL_HANDLE (bar), 0);
4613 else if (part != last_scroll_bar_part
4614 || scroll_bar_timer_event_posted_p)
4615 {
4616 construct_scroll_bar_click (bar, part, bufp);
4617 last_scroll_bar_part = part;
4618 HiliteControl (SCROLL_BAR_CONTROL_HANDLE (bar), part_code);
4619 set_scroll_bar_timer (SCROLL_BAR_CONTINUOUS_DELAY);
4620 }
4621 }
4622 }
4623
4624 /* Set the thumb size and position of scroll bar BAR. We are currently
4625 displaying PORTION out of a whole WHOLE, and our position POSITION. */
4626
4627 static void
4628 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole)
4629 struct scroll_bar *bar;
4630 int portion, position, whole;
4631 {
4632 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4633 int value, viewsize, maximum;
4634
4635 if (XINT (bar->track_height) == 0)
4636 return;
4637
4638 if (whole == 0)
4639 value = 0, viewsize = 1, maximum = 0;
4640 else
4641 {
4642 value = position;
4643 viewsize = portion;
4644 maximum = max (0, whole - portion);
4645 }
4646
4647 BLOCK_INPUT;
4648
4649 if (GetControlViewSize (ch) != viewsize
4650 || GetControl32BitValue (ch) != value
4651 || GetControl32BitMaximum (ch) != maximum)
4652 {
4653 /* Temporarily hide the scroll bar to avoid multiple redraws. */
4654 SetControlVisibility (ch, false, false);
4655
4656 SetControl32BitMaximum (ch, maximum);
4657 SetControl32BitValue (ch, value);
4658 SetControlViewSize (ch, viewsize);
4659
4660 SetControlVisibility (ch, true, true);
4661 }
4662
4663 UNBLOCK_INPUT;
4664 }
4665
4666 #endif /* USE_TOOLKIT_SCROLL_BARS */
4667
4668
4669 \f
4670 /************************************************************************
4671 Scroll bars, general
4672 ************************************************************************/
4673
4674 /* Create a scroll bar and return the scroll bar vector for it. W is
4675 the Emacs window on which to create the scroll bar. TOP, LEFT,
4676 WIDTH and HEIGHT are the pixel coordinates and dimensions of the
4677 scroll bar. */
4678
4679 static struct scroll_bar *
4680 x_scroll_bar_create (w, top, left, width, height, disp_top, disp_height)
4681 struct window *w;
4682 int top, left, width, height, disp_top, disp_height;
4683 {
4684 struct frame *f = XFRAME (w->frame);
4685 struct scroll_bar *bar
4686 = XSCROLL_BAR (Fmake_vector (make_number (SCROLL_BAR_VEC_SIZE), Qnil));
4687 Rect r;
4688 ControlHandle ch;
4689
4690 BLOCK_INPUT;
4691
4692 r.left = left;
4693 r.top = disp_top;
4694 r.right = left + width;
4695 r.bottom = disp_top + disp_height;
4696
4697 #if USE_CG_DRAWING
4698 mac_prepare_for_quickdraw (f);
4699 #endif
4700 #if TARGET_API_MAC_CARBON
4701 ch = NewControl (FRAME_MAC_WINDOW (f), &r, "\p",
4702 #if USE_TOOLKIT_SCROLL_BARS
4703 false,
4704 #else
4705 width < disp_height,
4706 #endif
4707 0, 0, 0, kControlScrollBarProc, (long) bar);
4708 #else
4709 ch = NewControl (FRAME_MAC_WINDOW (f), &r, "\p", width < disp_height,
4710 0, 0, 0, scrollBarProc, (long) bar);
4711 #endif
4712 SET_SCROLL_BAR_CONTROL_HANDLE (bar, ch);
4713
4714 XSETWINDOW (bar->window, w);
4715 XSETINT (bar->top, top);
4716 XSETINT (bar->left, left);
4717 XSETINT (bar->width, width);
4718 XSETINT (bar->height, height);
4719 XSETINT (bar->start, 0);
4720 XSETINT (bar->end, 0);
4721 bar->dragging = Qnil;
4722 #ifdef USE_TOOLKIT_SCROLL_BARS
4723 bar->track_top = Qnil;
4724 bar->track_height = Qnil;
4725 #endif
4726
4727 /* Add bar to its frame's list of scroll bars. */
4728 bar->next = FRAME_SCROLL_BARS (f);
4729 bar->prev = Qnil;
4730 XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
4731 if (!NILP (bar->next))
4732 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
4733
4734 UNBLOCK_INPUT;
4735 return bar;
4736 }
4737
4738
4739 /* Draw BAR's handle in the proper position.
4740
4741 If the handle is already drawn from START to END, don't bother
4742 redrawing it, unless REBUILD is non-zero; in that case, always
4743 redraw it. (REBUILD is handy for drawing the handle after expose
4744 events.)
4745
4746 Normally, we want to constrain the start and end of the handle to
4747 fit inside its rectangle, but if the user is dragging the scroll
4748 bar handle, we want to let them drag it down all the way, so that
4749 the bar's top is as far down as it goes; otherwise, there's no way
4750 to move to the very end of the buffer. */
4751
4752 #ifndef USE_TOOLKIT_SCROLL_BARS
4753
4754 static void
4755 x_scroll_bar_set_handle (bar, start, end, rebuild)
4756 struct scroll_bar *bar;
4757 int start, end;
4758 int rebuild;
4759 {
4760 int dragging = ! NILP (bar->dragging);
4761 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4762 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4763 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, XINT (bar->height));
4764 int length = end - start;
4765
4766 /* If the display is already accurate, do nothing. */
4767 if (! rebuild
4768 && start == XINT (bar->start)
4769 && end == XINT (bar->end))
4770 return;
4771
4772 BLOCK_INPUT;
4773
4774 /* Make sure the values are reasonable, and try to preserve the
4775 distance between start and end. */
4776 if (start < 0)
4777 start = 0;
4778 else if (start > top_range)
4779 start = top_range;
4780 end = start + length;
4781
4782 if (end < start)
4783 end = start;
4784 else if (end > top_range && ! dragging)
4785 end = top_range;
4786
4787 /* Store the adjusted setting in the scroll bar. */
4788 XSETINT (bar->start, start);
4789 XSETINT (bar->end, end);
4790
4791 /* Clip the end position, just for display. */
4792 if (end > top_range)
4793 end = top_range;
4794
4795 /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels below
4796 top positions, to make sure the handle is always at least that
4797 many pixels tall. */
4798 end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
4799
4800 SetControlMinimum (ch, 0);
4801 /* Don't inadvertently activate deactivated scroll bars */
4802 if (GetControlMaximum (ch) != -1)
4803 SetControlMaximum (ch, top_range + VERTICAL_SCROLL_BAR_MIN_HANDLE
4804 - (end - start));
4805 SetControlValue (ch, start);
4806 #if TARGET_API_MAC_CARBON
4807 SetControlViewSize (ch, end - start);
4808 #endif
4809
4810 UNBLOCK_INPUT;
4811 }
4812
4813 #endif /* !USE_TOOLKIT_SCROLL_BARS */
4814
4815 /* Destroy scroll bar BAR, and set its Emacs window's scroll bar to
4816 nil. */
4817
4818 static void
4819 x_scroll_bar_remove (bar)
4820 struct scroll_bar *bar;
4821 {
4822 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4823
4824 BLOCK_INPUT;
4825
4826 #if USE_CG_DRAWING
4827 mac_prepare_for_quickdraw (f);
4828 #endif
4829 /* Destroy the Mac scroll bar control */
4830 DisposeControl (SCROLL_BAR_CONTROL_HANDLE (bar));
4831
4832 /* Disassociate this scroll bar from its window. */
4833 XWINDOW (bar->window)->vertical_scroll_bar = Qnil;
4834
4835 UNBLOCK_INPUT;
4836 }
4837
4838
4839 /* Set the handle of the vertical scroll bar for WINDOW to indicate
4840 that we are displaying PORTION characters out of a total of WHOLE
4841 characters, starting at POSITION. If WINDOW has no scroll bar,
4842 create one. */
4843
4844 static void
4845 XTset_vertical_scroll_bar (w, portion, whole, position)
4846 struct window *w;
4847 int portion, whole, position;
4848 {
4849 struct frame *f = XFRAME (w->frame);
4850 struct scroll_bar *bar;
4851 int top, height, left, sb_left, width, sb_width, disp_top, disp_height;
4852 int window_y, window_height;
4853
4854 /* Get window dimensions. */
4855 window_box (w, -1, 0, &window_y, 0, &window_height);
4856 top = window_y;
4857 width = WINDOW_CONFIG_SCROLL_BAR_COLS (w) * FRAME_COLUMN_WIDTH (f);
4858 height = window_height;
4859
4860 /* Compute the left edge of the scroll bar area. */
4861 left = WINDOW_SCROLL_BAR_AREA_X (w);
4862
4863 /* Compute the width of the scroll bar which might be less than
4864 the width of the area reserved for the scroll bar. */
4865 if (WINDOW_CONFIG_SCROLL_BAR_WIDTH (w) > 0)
4866 sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
4867 else
4868 sb_width = width;
4869
4870 /* Compute the left edge of the scroll bar. */
4871 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
4872 sb_left = left;
4873 else
4874 sb_left = left + width - sb_width;
4875
4876 /* Adjustments according to Inside Macintosh to make it look nice */
4877 disp_top = top;
4878 disp_height = height;
4879 #ifdef MAC_OS8
4880 if (disp_top == 0)
4881 {
4882 disp_top = -1;
4883 disp_height++;
4884 }
4885 else if (disp_top == FRAME_PIXEL_HEIGHT (f) - 16)
4886 {
4887 disp_top++;
4888 disp_height--;
4889 }
4890
4891 if (sb_left + sb_width == FRAME_PIXEL_WIDTH (f))
4892 sb_left++;
4893 #endif
4894
4895 /* Does the scroll bar exist yet? */
4896 if (NILP (w->vertical_scroll_bar))
4897 {
4898 BLOCK_INPUT;
4899 mac_clear_area (f, left, top, width, height);
4900 UNBLOCK_INPUT;
4901 bar = x_scroll_bar_create (w, top, sb_left, sb_width, height, disp_top,
4902 disp_height);
4903 XSETVECTOR (w->vertical_scroll_bar, bar);
4904 }
4905 else
4906 {
4907 /* It may just need to be moved and resized. */
4908 ControlHandle ch;
4909
4910 bar = XSCROLL_BAR (w->vertical_scroll_bar);
4911 ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4912
4913 BLOCK_INPUT;
4914
4915 /* If already correctly positioned, do nothing. */
4916 if (!(XINT (bar->left) == sb_left
4917 && XINT (bar->top) == top
4918 && XINT (bar->width) == sb_width
4919 && XINT (bar->height) == height))
4920 {
4921 /* Since toolkit scroll bars are smaller than the space reserved
4922 for them on the frame, we have to clear "under" them. */
4923 mac_clear_area (f, left, top, width, height);
4924
4925 #if USE_CG_DRAWING
4926 mac_prepare_for_quickdraw (f);
4927 #endif
4928 HideControl (ch);
4929 MoveControl (ch, sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM, disp_top);
4930 SizeControl (ch, sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
4931 disp_height);
4932 #ifndef USE_TOOLKIT_SCROLL_BARS
4933 if (sb_width < disp_height)
4934 ShowControl (ch);
4935 #endif
4936
4937 /* Remember new settings. */
4938 XSETINT (bar->left, sb_left);
4939 XSETINT (bar->top, top);
4940 XSETINT (bar->width, sb_width);
4941 XSETINT (bar->height, height);
4942 #ifdef USE_TOOLKIT_SCROLL_BARS
4943 bar->track_top = Qnil;
4944 bar->track_height = Qnil;
4945 #endif
4946 }
4947
4948 UNBLOCK_INPUT;
4949 }
4950
4951 #ifdef USE_TOOLKIT_SCROLL_BARS
4952 if (NILP (bar->track_top))
4953 {
4954 if (sb_width >= disp_height)
4955 {
4956 XSETINT (bar->track_top, 0);
4957 XSETINT (bar->track_height, 0);
4958 }
4959 else
4960 {
4961 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4962 Rect r0, r1;
4963
4964 BLOCK_INPUT;
4965
4966 SetControl32BitMinimum (ch, 0);
4967 SetControl32BitMaximum (ch, 1);
4968 SetControlViewSize (ch, 1);
4969
4970 /* Move the scroll bar thumb to the top. */
4971 SetControl32BitValue (ch, 0);
4972 get_control_part_bounds (ch, kControlIndicatorPart, &r0);
4973
4974 /* Move the scroll bar thumb to the bottom. */
4975 SetControl32BitValue (ch, 1);
4976 get_control_part_bounds (ch, kControlIndicatorPart, &r1);
4977
4978 UnionRect (&r0, &r1, &r0);
4979 XSETINT (bar->track_top, r0.top);
4980 XSETINT (bar->track_height, r0.bottom - r0.top);
4981
4982 /* Don't show the scroll bar if its height is not enough to
4983 display the scroll bar thumb. */
4984 if (r0.bottom - r0.top > 0)
4985 ShowControl (ch);
4986
4987 UNBLOCK_INPUT;
4988 }
4989 }
4990
4991 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
4992 #else /* not USE_TOOLKIT_SCROLL_BARS */
4993 /* Set the scroll bar's current state, unless we're currently being
4994 dragged. */
4995 if (NILP (bar->dragging))
4996 {
4997 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, height);
4998
4999 if (whole == 0)
5000 x_scroll_bar_set_handle (bar, 0, top_range, 0);
5001 else
5002 {
5003 int start = ((double) position * top_range) / whole;
5004 int end = ((double) (position + portion) * top_range) / whole;
5005 x_scroll_bar_set_handle (bar, start, end, 0);
5006 }
5007 }
5008 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5009 }
5010
5011
5012 /* The following three hooks are used when we're doing a thorough
5013 redisplay of the frame. We don't explicitly know which scroll bars
5014 are going to be deleted, because keeping track of when windows go
5015 away is a real pain - "Can you say set-window-configuration, boys
5016 and girls?" Instead, we just assert at the beginning of redisplay
5017 that *all* scroll bars are to be removed, and then save a scroll bar
5018 from the fiery pit when we actually redisplay its window. */
5019
5020 /* Arrange for all scroll bars on FRAME to be removed at the next call
5021 to `*judge_scroll_bars_hook'. A scroll bar may be spared if
5022 `*redeem_scroll_bar_hook' is applied to its window before the judgment. */
5023
5024 static void
5025 XTcondemn_scroll_bars (frame)
5026 FRAME_PTR frame;
5027 {
5028 /* Transfer all the scroll bars to FRAME_CONDEMNED_SCROLL_BARS. */
5029 while (! NILP (FRAME_SCROLL_BARS (frame)))
5030 {
5031 Lisp_Object bar;
5032 bar = FRAME_SCROLL_BARS (frame);
5033 FRAME_SCROLL_BARS (frame) = XSCROLL_BAR (bar)->next;
5034 XSCROLL_BAR (bar)->next = FRAME_CONDEMNED_SCROLL_BARS (frame);
5035 XSCROLL_BAR (bar)->prev = Qnil;
5036 if (! NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
5037 XSCROLL_BAR (FRAME_CONDEMNED_SCROLL_BARS (frame))->prev = bar;
5038 FRAME_CONDEMNED_SCROLL_BARS (frame) = bar;
5039 }
5040 }
5041
5042
5043 /* Un-mark WINDOW's scroll bar for deletion in this judgment cycle.
5044 Note that WINDOW isn't necessarily condemned at all. */
5045
5046 static void
5047 XTredeem_scroll_bar (window)
5048 struct window *window;
5049 {
5050 struct scroll_bar *bar;
5051 struct frame *f;
5052
5053 /* We can't redeem this window's scroll bar if it doesn't have one. */
5054 if (NILP (window->vertical_scroll_bar))
5055 abort ();
5056
5057 bar = XSCROLL_BAR (window->vertical_scroll_bar);
5058
5059 /* Unlink it from the condemned list. */
5060 f = XFRAME (WINDOW_FRAME (window));
5061 if (NILP (bar->prev))
5062 {
5063 /* If the prev pointer is nil, it must be the first in one of
5064 the lists. */
5065 if (EQ (FRAME_SCROLL_BARS (f), window->vertical_scroll_bar))
5066 /* It's not condemned. Everything's fine. */
5067 return;
5068 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
5069 window->vertical_scroll_bar))
5070 FRAME_CONDEMNED_SCROLL_BARS (f) = bar->next;
5071 else
5072 /* If its prev pointer is nil, it must be at the front of
5073 one or the other! */
5074 abort ();
5075 }
5076 else
5077 XSCROLL_BAR (bar->prev)->next = bar->next;
5078
5079 if (! NILP (bar->next))
5080 XSCROLL_BAR (bar->next)->prev = bar->prev;
5081
5082 bar->next = FRAME_SCROLL_BARS (f);
5083 bar->prev = Qnil;
5084 XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
5085 if (! NILP (bar->next))
5086 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
5087 }
5088
5089 /* Remove all scroll bars on FRAME that haven't been saved since the
5090 last call to `*condemn_scroll_bars_hook'. */
5091
5092 static void
5093 XTjudge_scroll_bars (f)
5094 FRAME_PTR f;
5095 {
5096 Lisp_Object bar, next;
5097
5098 bar = FRAME_CONDEMNED_SCROLL_BARS (f);
5099
5100 /* Clear out the condemned list now so we won't try to process any
5101 more events on the hapless scroll bars. */
5102 FRAME_CONDEMNED_SCROLL_BARS (f) = Qnil;
5103
5104 for (; ! NILP (bar); bar = next)
5105 {
5106 struct scroll_bar *b = XSCROLL_BAR (bar);
5107
5108 x_scroll_bar_remove (b);
5109
5110 next = b->next;
5111 b->next = b->prev = Qnil;
5112 }
5113
5114 /* Now there should be no references to the condemned scroll bars,
5115 and they should get garbage-collected. */
5116 }
5117
5118
5119 /* Handle a mouse click on the scroll bar BAR. If *EMACS_EVENT's kind
5120 is set to something other than NO_EVENT, it is enqueued.
5121
5122 This may be called from a signal handler, so we have to ignore GC
5123 mark bits. */
5124
5125 static void
5126 x_scroll_bar_handle_click (bar, part_code, er, bufp)
5127 struct scroll_bar *bar;
5128 ControlPartCode part_code;
5129 EventRecord *er;
5130 struct input_event *bufp;
5131 {
5132 int win_y, top_range;
5133
5134 if (! GC_WINDOWP (bar->window))
5135 abort ();
5136
5137 bufp->kind = SCROLL_BAR_CLICK_EVENT;
5138 bufp->frame_or_window = bar->window;
5139 bufp->arg = Qnil;
5140
5141 bar->dragging = Qnil;
5142
5143 switch (part_code)
5144 {
5145 case kControlUpButtonPart:
5146 bufp->part = scroll_bar_up_arrow;
5147 break;
5148 case kControlDownButtonPart:
5149 bufp->part = scroll_bar_down_arrow;
5150 break;
5151 case kControlPageUpPart:
5152 bufp->part = scroll_bar_above_handle;
5153 break;
5154 case kControlPageDownPart:
5155 bufp->part = scroll_bar_below_handle;
5156 break;
5157 #if TARGET_API_MAC_CARBON
5158 default:
5159 #else
5160 case kControlIndicatorPart:
5161 #endif
5162 if (er->what == mouseDown)
5163 bar->dragging = make_number (0);
5164 XSETVECTOR (last_mouse_scroll_bar, bar);
5165 bufp->part = scroll_bar_handle;
5166 break;
5167 }
5168
5169 win_y = XINT (bufp->y) - XINT (bar->top);
5170 top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (0/*dummy*/, XINT (bar->height));
5171
5172 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
5173
5174 win_y -= 24;
5175
5176 if (! NILP (bar->dragging))
5177 win_y -= XINT (bar->dragging);
5178
5179 if (win_y < 0)
5180 win_y = 0;
5181 if (win_y > top_range)
5182 win_y = top_range;
5183
5184 XSETINT (bufp->x, win_y);
5185 XSETINT (bufp->y, top_range);
5186 }
5187
5188 #ifndef USE_TOOLKIT_SCROLL_BARS
5189
5190 /* Handle some mouse motion while someone is dragging the scroll bar.
5191
5192 This may be called from a signal handler, so we have to ignore GC
5193 mark bits. */
5194
5195 static void
5196 x_scroll_bar_note_movement (bar, y_pos, t)
5197 struct scroll_bar *bar;
5198 int y_pos;
5199 Time t;
5200 {
5201 FRAME_PTR f = XFRAME (XWINDOW (bar->window)->frame);
5202
5203 last_mouse_movement_time = t;
5204
5205 f->mouse_moved = 1;
5206 XSETVECTOR (last_mouse_scroll_bar, bar);
5207
5208 /* If we're dragging the bar, display it. */
5209 if (! GC_NILP (bar->dragging))
5210 {
5211 /* Where should the handle be now? */
5212 int new_start = y_pos - 24;
5213
5214 if (new_start != XINT (bar->start))
5215 {
5216 int new_end = new_start + (XINT (bar->end) - XINT (bar->start));
5217
5218 x_scroll_bar_set_handle (bar, new_start, new_end, 0);
5219 }
5220 }
5221 }
5222
5223 #endif /* !USE_TOOLKIT_SCROLL_BARS */
5224
5225 /* Return information to the user about the current position of the mouse
5226 on the scroll bar. */
5227
5228 static void
5229 x_scroll_bar_report_motion (fp, bar_window, part, x, y, time)
5230 FRAME_PTR *fp;
5231 Lisp_Object *bar_window;
5232 enum scroll_bar_part *part;
5233 Lisp_Object *x, *y;
5234 unsigned long *time;
5235 {
5236 struct scroll_bar *bar = XSCROLL_BAR (last_mouse_scroll_bar);
5237 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
5238 #if TARGET_API_MAC_CARBON
5239 WindowPtr wp = GetControlOwner (ch);
5240 #else
5241 WindowPtr wp = (*ch)->contrlOwner;
5242 #endif
5243 Point mouse_pos;
5244 struct frame *f = mac_window_to_frame (wp);
5245 int win_y, top_range;
5246
5247 SetPortWindowPort (wp);
5248
5249 GetMouse (&mouse_pos);
5250
5251 win_y = mouse_pos.v - XINT (bar->top);
5252 top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, XINT (bar->height));
5253
5254 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
5255
5256 win_y -= 24;
5257
5258 if (! NILP (bar->dragging))
5259 win_y -= XINT (bar->dragging);
5260
5261 if (win_y < 0)
5262 win_y = 0;
5263 if (win_y > top_range)
5264 win_y = top_range;
5265
5266 *fp = f;
5267 *bar_window = bar->window;
5268
5269 if (! NILP (bar->dragging))
5270 *part = scroll_bar_handle;
5271 else if (win_y < XINT (bar->start))
5272 *part = scroll_bar_above_handle;
5273 else if (win_y < XINT (bar->end) + VERTICAL_SCROLL_BAR_MIN_HANDLE)
5274 *part = scroll_bar_handle;
5275 else
5276 *part = scroll_bar_below_handle;
5277
5278 XSETINT (*x, win_y);
5279 XSETINT (*y, top_range);
5280
5281 f->mouse_moved = 0;
5282 last_mouse_scroll_bar = Qnil;
5283
5284 *time = last_mouse_movement_time;
5285 }
5286
5287
5288 /* The screen has been cleared so we may have changed foreground or
5289 background colors, and the scroll bars may need to be redrawn.
5290 Clear out the scroll bars, and ask for expose events, so we can
5291 redraw them. */
5292
5293 void
5294 x_scroll_bar_clear (f)
5295 FRAME_PTR f;
5296 {
5297 XTcondemn_scroll_bars (f);
5298 XTjudge_scroll_bars (f);
5299 }
5300
5301 \f
5302 /***********************************************************************
5303 Text Cursor
5304 ***********************************************************************/
5305
5306 /* Set clipping for output in glyph row ROW. W is the window in which
5307 we operate. GC is the graphics context to set clipping in.
5308
5309 ROW may be a text row or, e.g., a mode line. Text rows must be
5310 clipped to the interior of the window dedicated to text display,
5311 mode lines must be clipped to the whole window. */
5312
5313 static void
5314 x_clip_to_row (w, row, area, gc)
5315 struct window *w;
5316 struct glyph_row *row;
5317 int area;
5318 GC gc;
5319 {
5320 struct frame *f = XFRAME (WINDOW_FRAME (w));
5321 Rect clip_rect;
5322 int window_x, window_y, window_width;
5323
5324 window_box (w, area, &window_x, &window_y, &window_width, 0);
5325
5326 clip_rect.left = window_x;
5327 clip_rect.top = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
5328 clip_rect.top = max (clip_rect.top, window_y);
5329 clip_rect.right = clip_rect.left + window_width;
5330 clip_rect.bottom = clip_rect.top + row->visible_height;
5331
5332 mac_set_clip_rectangles (FRAME_MAC_DISPLAY (f), gc, &clip_rect, 1);
5333 }
5334
5335
5336 /* Draw a hollow box cursor on window W in glyph row ROW. */
5337
5338 static void
5339 x_draw_hollow_cursor (w, row)
5340 struct window *w;
5341 struct glyph_row *row;
5342 {
5343 struct frame *f = XFRAME (WINDOW_FRAME (w));
5344 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
5345 Display *dpy = FRAME_MAC_DISPLAY (f);
5346 int x, y, wd, h;
5347 XGCValues xgcv;
5348 struct glyph *cursor_glyph;
5349 GC gc;
5350
5351 /* Get the glyph the cursor is on. If we can't tell because
5352 the current matrix is invalid or such, give up. */
5353 cursor_glyph = get_phys_cursor_glyph (w);
5354 if (cursor_glyph == NULL)
5355 return;
5356
5357 /* Compute frame-relative coordinates for phys cursor. */
5358 x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
5359 y = get_phys_cursor_geometry (w, row, cursor_glyph, &h);
5360 wd = w->phys_cursor_width;
5361
5362 /* The foreground of cursor_gc is typically the same as the normal
5363 background color, which can cause the cursor box to be invisible. */
5364 xgcv.foreground = f->output_data.mac->cursor_pixel;
5365 if (dpyinfo->scratch_cursor_gc)
5366 XChangeGC (dpy, dpyinfo->scratch_cursor_gc, GCForeground, &xgcv);
5367 else
5368 dpyinfo->scratch_cursor_gc = XCreateGC (dpy, FRAME_MAC_WINDOW (f),
5369 GCForeground, &xgcv);
5370 gc = dpyinfo->scratch_cursor_gc;
5371
5372 /* Set clipping, draw the rectangle, and reset clipping again. */
5373 x_clip_to_row (w, row, TEXT_AREA, gc);
5374 mac_draw_rectangle (f, gc, x, y, wd, h - 1);
5375 mac_reset_clip_rectangles (dpy, gc);
5376 }
5377
5378
5379 /* Draw a bar cursor on window W in glyph row ROW.
5380
5381 Implementation note: One would like to draw a bar cursor with an
5382 angle equal to the one given by the font property XA_ITALIC_ANGLE.
5383 Unfortunately, I didn't find a font yet that has this property set.
5384 --gerd. */
5385
5386 static void
5387 x_draw_bar_cursor (w, row, width, kind)
5388 struct window *w;
5389 struct glyph_row *row;
5390 int width;
5391 enum text_cursor_kinds kind;
5392 {
5393 struct frame *f = XFRAME (w->frame);
5394 struct glyph *cursor_glyph;
5395
5396 /* If cursor is out of bounds, don't draw garbage. This can happen
5397 in mini-buffer windows when switching between echo area glyphs
5398 and mini-buffer. */
5399 cursor_glyph = get_phys_cursor_glyph (w);
5400 if (cursor_glyph == NULL)
5401 return;
5402
5403 /* If on an image, draw like a normal cursor. That's usually better
5404 visible than drawing a bar, esp. if the image is large so that
5405 the bar might not be in the window. */
5406 if (cursor_glyph->type == IMAGE_GLYPH)
5407 {
5408 struct glyph_row *row;
5409 row = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos);
5410 draw_phys_cursor_glyph (w, row, DRAW_CURSOR);
5411 }
5412 else
5413 {
5414 Display *dpy = FRAME_MAC_DISPLAY (f);
5415 Window window = FRAME_MAC_WINDOW (f);
5416 GC gc = FRAME_MAC_DISPLAY_INFO (f)->scratch_cursor_gc;
5417 unsigned long mask = GCForeground | GCBackground;
5418 struct face *face = FACE_FROM_ID (f, cursor_glyph->face_id);
5419 XGCValues xgcv;
5420
5421 /* If the glyph's background equals the color we normally draw
5422 the bar cursor in, the bar cursor in its normal color is
5423 invisible. Use the glyph's foreground color instead in this
5424 case, on the assumption that the glyph's colors are chosen so
5425 that the glyph is legible. */
5426 if (face->background == f->output_data.mac->cursor_pixel)
5427 xgcv.background = xgcv.foreground = face->foreground;
5428 else
5429 xgcv.background = xgcv.foreground = f->output_data.mac->cursor_pixel;
5430
5431 if (gc)
5432 XChangeGC (dpy, gc, mask, &xgcv);
5433 else
5434 {
5435 gc = XCreateGC (dpy, window, mask, &xgcv);
5436 FRAME_MAC_DISPLAY_INFO (f)->scratch_cursor_gc = gc;
5437 }
5438
5439 if (width < 0)
5440 width = FRAME_CURSOR_WIDTH (f);
5441 width = min (cursor_glyph->pixel_width, width);
5442
5443 w->phys_cursor_width = width;
5444 x_clip_to_row (w, row, TEXT_AREA, gc);
5445
5446 if (kind == BAR_CURSOR)
5447 mac_fill_rectangle (f, gc,
5448 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x),
5449 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
5450 width, row->height);
5451 else
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 row->height - width),
5456 cursor_glyph->pixel_width,
5457 width);
5458
5459 mac_reset_clip_rectangles (dpy, gc);
5460 }
5461 }
5462
5463
5464 /* RIF: Define cursor CURSOR on frame F. */
5465
5466 static void
5467 mac_define_frame_cursor (f, cursor)
5468 struct frame *f;
5469 Cursor cursor;
5470 {
5471 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
5472
5473 if (dpyinfo->x_focus_frame == f)
5474 SetThemeCursor (cursor);
5475 }
5476
5477
5478 /* RIF: Clear area on frame F. */
5479
5480 static void
5481 mac_clear_frame_area (f, x, y, width, height)
5482 struct frame *f;
5483 int x, y, width, height;
5484 {
5485 mac_clear_area (f, x, y, width, height);
5486 }
5487
5488
5489 /* RIF: Draw cursor on window W. */
5490
5491 static void
5492 mac_draw_window_cursor (w, glyph_row, x, y, cursor_type, cursor_width, on_p, active_p)
5493 struct window *w;
5494 struct glyph_row *glyph_row;
5495 int x, y;
5496 int cursor_type, cursor_width;
5497 int on_p, active_p;
5498 {
5499 if (on_p)
5500 {
5501 w->phys_cursor_type = cursor_type;
5502 w->phys_cursor_on_p = 1;
5503
5504 if (glyph_row->exact_window_width_line_p
5505 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
5506 {
5507 glyph_row->cursor_in_fringe_p = 1;
5508 draw_fringe_bitmap (w, glyph_row, 0);
5509 }
5510 else
5511 switch (cursor_type)
5512 {
5513 case HOLLOW_BOX_CURSOR:
5514 x_draw_hollow_cursor (w, glyph_row);
5515 break;
5516
5517 case FILLED_BOX_CURSOR:
5518 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
5519 break;
5520
5521 case BAR_CURSOR:
5522 x_draw_bar_cursor (w, glyph_row, cursor_width, BAR_CURSOR);
5523 break;
5524
5525 case HBAR_CURSOR:
5526 x_draw_bar_cursor (w, glyph_row, cursor_width, HBAR_CURSOR);
5527 break;
5528
5529 case NO_CURSOR:
5530 w->phys_cursor_width = 0;
5531 break;
5532
5533 default:
5534 abort ();
5535 }
5536 }
5537 }
5538
5539 \f
5540 /* Icons. */
5541
5542 #if 0 /* MAC_TODO: no icon support yet. */
5543 int
5544 x_bitmap_icon (f, icon)
5545 struct frame *f;
5546 Lisp_Object icon;
5547 {
5548 HANDLE hicon;
5549
5550 if (FRAME_W32_WINDOW (f) == 0)
5551 return 1;
5552
5553 if (NILP (icon))
5554 hicon = LoadIcon (hinst, EMACS_CLASS);
5555 else if (STRINGP (icon))
5556 hicon = LoadImage (NULL, (LPCTSTR) SDATA (icon), IMAGE_ICON, 0, 0,
5557 LR_DEFAULTSIZE | LR_LOADFROMFILE);
5558 else if (SYMBOLP (icon))
5559 {
5560 LPCTSTR name;
5561
5562 if (EQ (icon, intern ("application")))
5563 name = (LPCTSTR) IDI_APPLICATION;
5564 else if (EQ (icon, intern ("hand")))
5565 name = (LPCTSTR) IDI_HAND;
5566 else if (EQ (icon, intern ("question")))
5567 name = (LPCTSTR) IDI_QUESTION;
5568 else if (EQ (icon, intern ("exclamation")))
5569 name = (LPCTSTR) IDI_EXCLAMATION;
5570 else if (EQ (icon, intern ("asterisk")))
5571 name = (LPCTSTR) IDI_ASTERISK;
5572 else if (EQ (icon, intern ("winlogo")))
5573 name = (LPCTSTR) IDI_WINLOGO;
5574 else
5575 return 1;
5576
5577 hicon = LoadIcon (NULL, name);
5578 }
5579 else
5580 return 1;
5581
5582 if (hicon == NULL)
5583 return 1;
5584
5585 PostMessage (FRAME_W32_WINDOW (f), WM_SETICON, (WPARAM) ICON_BIG,
5586 (LPARAM) hicon);
5587
5588 return 0;
5589 }
5590 #endif /* MAC_TODO */
5591 \f
5592 /************************************************************************
5593 Handling X errors
5594 ************************************************************************/
5595
5596 /* Display Error Handling functions not used on W32. Listing them here
5597 helps diff stay in step when comparing w32term.c with xterm.c.
5598
5599 x_error_catcher (display, error)
5600 x_catch_errors (dpy)
5601 x_catch_errors_unwind (old_val)
5602 x_check_errors (dpy, format)
5603 x_had_errors_p (dpy)
5604 x_clear_errors (dpy)
5605 x_uncatch_errors (dpy, count)
5606 x_trace_wire ()
5607 x_connection_signal (signalnum)
5608 x_connection_closed (dpy, error_message)
5609 x_error_quitter (display, error)
5610 x_error_handler (display, error)
5611 x_io_error_quitter (display)
5612
5613 */
5614
5615 \f
5616 /* Changing the font of the frame. */
5617
5618 /* Give frame F the font named FONTNAME as its default font, and
5619 return the full name of that font. FONTNAME may be a wildcard
5620 pattern; in that case, we choose some font that fits the pattern.
5621 The return value shows which font we chose. */
5622
5623 Lisp_Object
5624 x_new_font (f, fontname)
5625 struct frame *f;
5626 register char *fontname;
5627 {
5628 struct font_info *fontp
5629 = FS_LOAD_FONT (f, fontname);
5630
5631 if (!fontp)
5632 return Qnil;
5633
5634 if (FRAME_FONT (f) == (XFontStruct *) (fontp->font))
5635 /* This font is already set in frame F. There's nothing more to
5636 do. */
5637 return build_string (fontp->full_name);
5638
5639 FRAME_FONT (f) = (XFontStruct *) (fontp->font);
5640 FRAME_BASELINE_OFFSET (f) = fontp->baseline_offset;
5641 FRAME_FONTSET (f) = -1;
5642
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));
5646
5647 compute_fringe_widths (f, 1);
5648
5649 /* Compute the scroll bar width in character columns. */
5650 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
5651 {
5652 int wid = FRAME_COLUMN_WIDTH (f);
5653 FRAME_CONFIG_SCROLL_BAR_COLS (f)
5654 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid-1) / wid;
5655 }
5656 else
5657 {
5658 int wid = FRAME_COLUMN_WIDTH (f);
5659 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
5660 }
5661
5662 /* Now make the frame display the given font. */
5663 if (FRAME_MAC_WINDOW (f) != 0)
5664 {
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));
5671
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));
5677 }
5678
5679 return build_string (fontp->full_name);
5680 }
5681 \f
5682 /* Give frame F the fontset named FONTSETNAME as its default fontset,
5683 and return the full name of that fontset. FONTSETNAME may be a
5684 wildcard pattern; in that case, we choose some fontset that fits
5685 the pattern. FONTSETNAME may be a font name for ASCII characters;
5686 in that case, we create a fontset from that font name.
5687
5688 The return value shows which fontset we chose.
5689 If FONTSETNAME specifies the default fontset, return Qt.
5690 If an ASCII font in the specified fontset can't be loaded, return
5691 Qnil. */
5692
5693 Lisp_Object
5694 x_new_fontset (f, fontsetname)
5695 struct frame *f;
5696 Lisp_Object fontsetname;
5697 {
5698 int fontset = fs_query_fontset (fontsetname, 0);
5699 Lisp_Object result;
5700
5701 if (fontset > 0 && FRAME_FONTSET(f) == fontset)
5702 /* This fontset is already set in frame F. There's nothing more
5703 to do. */
5704 return fontset_name (fontset);
5705 else if (fontset == 0)
5706 /* The default fontset can't be the default font. */
5707 return Qt;
5708
5709 if (fontset > 0)
5710 result = x_new_font (f, (SDATA (fontset_ascii (fontset))));
5711 else
5712 result = x_new_font (f, SDATA (fontsetname));
5713
5714 if (!STRINGP (result))
5715 /* Can't load ASCII font. */
5716 return Qnil;
5717
5718 if (fontset < 0)
5719 fontset = new_fontset_from_font_name (result);
5720
5721 /* Since x_new_font doesn't update any fontset information, do it now. */
5722 FRAME_FONTSET (f) = fontset;
5723
5724 return fontset_name (fontset);
5725 }
5726
5727 \f
5728 /***********************************************************************
5729 TODO: W32 Input Methods
5730 ***********************************************************************/
5731 /* Listing missing functions from xterm.c helps diff stay in step.
5732
5733 xim_destroy_callback (xim, client_data, call_data)
5734 xim_open_dpy (dpyinfo, resource_name)
5735 struct xim_inst_t
5736 xim_instantiate_callback (display, client_data, call_data)
5737 xim_initialize (dpyinfo, resource_name)
5738 xim_close_dpy (dpyinfo)
5739
5740 */
5741
5742 \f
5743 void
5744 mac_get_window_bounds (f, inner, outer)
5745 struct frame *f;
5746 Rect *inner, *outer;
5747 {
5748 #if TARGET_API_MAC_CARBON
5749 GetWindowBounds (FRAME_MAC_WINDOW (f), kWindowContentRgn, inner);
5750 GetWindowBounds (FRAME_MAC_WINDOW (f), kWindowStructureRgn, outer);
5751 #else /* not TARGET_API_MAC_CARBON */
5752 RgnHandle region = NewRgn ();
5753
5754 GetWindowRegion (FRAME_MAC_WINDOW (f), kWindowContentRgn, region);
5755 *inner = (*region)->rgnBBox;
5756 GetWindowRegion (FRAME_MAC_WINDOW (f), kWindowStructureRgn, region);
5757 *outer = (*region)->rgnBBox;
5758 DisposeRgn (region);
5759 #endif /* not TARGET_API_MAC_CARBON */
5760 }
5761
5762
5763 \f
5764 /* Calculate the absolute position in frame F
5765 from its current recorded position values and gravity. */
5766
5767 void
5768 x_calc_absolute_position (f)
5769 struct frame *f;
5770 {
5771 int width_diff = 0, height_diff = 0;
5772 int flags = f->size_hint_flags;
5773 Rect inner, outer;
5774
5775 /* We have nothing to do if the current position
5776 is already for the top-left corner. */
5777 if (! ((flags & XNegative) || (flags & YNegative)))
5778 return;
5779
5780 /* Find the offsets of the outside upper-left corner of
5781 the inner window, with respect to the outer window. */
5782 mac_get_window_bounds (f, &inner, &outer);
5783
5784 width_diff = (outer.right - outer.left) - (inner.right - inner.left);
5785 height_diff = (outer.bottom - outer.top) - (inner.bottom - inner.top);
5786
5787 /* Treat negative positions as relative to the leftmost bottommost
5788 position that fits on the screen. */
5789 if (flags & XNegative)
5790 f->left_pos = (FRAME_MAC_DISPLAY_INFO (f)->width
5791 - width_diff
5792 - FRAME_PIXEL_WIDTH (f)
5793 + f->left_pos);
5794
5795 if (flags & YNegative)
5796 f->top_pos = (FRAME_MAC_DISPLAY_INFO (f)->height
5797 - height_diff
5798 - FRAME_PIXEL_HEIGHT (f)
5799 + f->top_pos);
5800
5801 /* The left_pos and top_pos
5802 are now relative to the top and left screen edges,
5803 so the flags should correspond. */
5804 f->size_hint_flags &= ~ (XNegative | YNegative);
5805 }
5806
5807 /* CHANGE_GRAVITY is 1 when calling from Fset_frame_position,
5808 to really change the position, and 0 when calling from
5809 x_make_frame_visible (in that case, XOFF and YOFF are the current
5810 position values). It is -1 when calling from x_set_frame_parameters,
5811 which means, do adjust for borders but don't change the gravity. */
5812
5813 void
5814 x_set_offset (f, xoff, yoff, change_gravity)
5815 struct frame *f;
5816 register int xoff, yoff;
5817 int change_gravity;
5818 {
5819 if (change_gravity > 0)
5820 {
5821 f->top_pos = yoff;
5822 f->left_pos = xoff;
5823 f->size_hint_flags &= ~ (XNegative | YNegative);
5824 if (xoff < 0)
5825 f->size_hint_flags |= XNegative;
5826 if (yoff < 0)
5827 f->size_hint_flags |= YNegative;
5828 f->win_gravity = NorthWestGravity;
5829 }
5830 x_calc_absolute_position (f);
5831
5832 BLOCK_INPUT;
5833 x_wm_set_size_hint (f, (long) 0, 0);
5834
5835 #if TARGET_API_MAC_CARBON
5836 MoveWindowStructure (FRAME_MAC_WINDOW (f), f->left_pos, f->top_pos);
5837 /* If the title bar is completely outside the screen, adjust the
5838 position. */
5839 ConstrainWindowToScreen (FRAME_MAC_WINDOW (f), kWindowTitleBarRgn,
5840 kWindowConstrainMoveRegardlessOfFit
5841 | kWindowConstrainAllowPartial, NULL, NULL);
5842 x_real_positions (f, &f->left_pos, &f->top_pos);
5843 #else
5844 {
5845 Rect inner, outer, screen_rect, dummy;
5846 RgnHandle region = NewRgn ();
5847
5848 mac_get_window_bounds (f, &inner, &outer);
5849 f->x_pixels_diff = inner.left - outer.left;
5850 f->y_pixels_diff = inner.top - outer.top;
5851 MoveWindow (FRAME_MAC_WINDOW (f), f->left_pos + f->x_pixels_diff,
5852 f->top_pos + f->y_pixels_diff, false);
5853
5854 /* If the title bar is completely outside the screen, adjust the
5855 position. The variable `outer' holds the title bar rectangle.
5856 The variable `inner' holds slightly smaller one than `outer',
5857 so that the calculation of overlapping may not become too
5858 strict. */
5859 GetWindowRegion (FRAME_MAC_WINDOW (f), kWindowTitleBarRgn, region);
5860 outer = (*region)->rgnBBox;
5861 DisposeRgn (region);
5862 inner = outer;
5863 InsetRect (&inner, 8, 8);
5864 screen_rect = qd.screenBits.bounds;
5865 screen_rect.top += GetMBarHeight ();
5866
5867 if (!SectRect (&inner, &screen_rect, &dummy))
5868 {
5869 if (inner.right <= screen_rect.left)
5870 f->left_pos = screen_rect.left;
5871 else if (inner.left >= screen_rect.right)
5872 f->left_pos = screen_rect.right - (outer.right - outer.left);
5873
5874 if (inner.bottom <= screen_rect.top)
5875 f->top_pos = screen_rect.top;
5876 else if (inner.top >= screen_rect.bottom)
5877 f->top_pos = screen_rect.bottom - (outer.bottom - outer.top);
5878
5879 MoveWindow (FRAME_MAC_WINDOW (f), f->left_pos + f->x_pixels_diff,
5880 f->top_pos + f->y_pixels_diff, false);
5881 }
5882 }
5883 #endif
5884
5885 UNBLOCK_INPUT;
5886 }
5887
5888 /* Call this to change the size of frame F's x-window.
5889 If CHANGE_GRAVITY is 1, we change to top-left-corner window gravity
5890 for this size change and subsequent size changes.
5891 Otherwise we leave the window gravity unchanged. */
5892
5893 void
5894 x_set_window_size (f, change_gravity, cols, rows)
5895 struct frame *f;
5896 int change_gravity;
5897 int cols, rows;
5898 {
5899 int pixelwidth, pixelheight;
5900
5901 BLOCK_INPUT;
5902
5903 check_frame_size (f, &rows, &cols);
5904 f->scroll_bar_actual_width
5905 = FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f);
5906
5907 compute_fringe_widths (f, 0);
5908
5909 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols);
5910 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
5911
5912 f->win_gravity = NorthWestGravity;
5913 x_wm_set_size_hint (f, (long) 0, 0);
5914
5915 SizeWindow (FRAME_MAC_WINDOW (f), pixelwidth, pixelheight, 0);
5916 #if TARGET_API_MAC_CARBON
5917 if (f->output_data.mac->hourglass_control)
5918 {
5919 #if USE_CG_DRAWING
5920 mac_prepare_for_quickdraw (f);
5921 #endif
5922 MoveControl (f->output_data.mac->hourglass_control,
5923 pixelwidth - HOURGLASS_WIDTH, 0);
5924 }
5925 #endif
5926
5927 /* Now, strictly speaking, we can't be sure that this is accurate,
5928 but the window manager will get around to dealing with the size
5929 change request eventually, and we'll hear how it went when the
5930 ConfigureNotify event gets here.
5931
5932 We could just not bother storing any of this information here,
5933 and let the ConfigureNotify event set everything up, but that
5934 might be kind of confusing to the Lisp code, since size changes
5935 wouldn't be reported in the frame parameters until some random
5936 point in the future when the ConfigureNotify event arrives.
5937
5938 We pass 1 for DELAY since we can't run Lisp code inside of
5939 a BLOCK_INPUT. */
5940 change_frame_size (f, rows, cols, 0, 1, 0);
5941 FRAME_PIXEL_WIDTH (f) = pixelwidth;
5942 FRAME_PIXEL_HEIGHT (f) = pixelheight;
5943
5944 /* We've set {FRAME,PIXEL}_{WIDTH,HEIGHT} to the values we hope to
5945 receive in the ConfigureNotify event; if we get what we asked
5946 for, then the event won't cause the screen to become garbaged, so
5947 we have to make sure to do it here. */
5948 SET_FRAME_GARBAGED (f);
5949
5950 XFlush (FRAME_X_DISPLAY (f));
5951
5952 /* If cursor was outside the new size, mark it as off. */
5953 mark_window_cursors_off (XWINDOW (f->root_window));
5954
5955 /* Clear out any recollection of where the mouse highlighting was,
5956 since it might be in a place that's outside the new frame size.
5957 Actually checking whether it is outside is a pain in the neck,
5958 so don't try--just let the highlighting be done afresh with new size. */
5959 cancel_mouse_face (f);
5960
5961 UNBLOCK_INPUT;
5962 }
5963 \f
5964 /* Mouse warping. */
5965
5966 void x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y);
5967
5968 void
5969 x_set_mouse_position (f, x, y)
5970 struct frame *f;
5971 int x, y;
5972 {
5973 int pix_x, pix_y;
5974
5975 pix_x = FRAME_COL_TO_PIXEL_X (f, x) + FRAME_COLUMN_WIDTH (f) / 2;
5976 pix_y = FRAME_LINE_TO_PIXEL_Y (f, y) + FRAME_LINE_HEIGHT (f) / 2;
5977
5978 if (pix_x < 0) pix_x = 0;
5979 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
5980
5981 if (pix_y < 0) pix_y = 0;
5982 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
5983
5984 x_set_mouse_pixel_position (f, pix_x, pix_y);
5985 }
5986
5987 void
5988 x_set_mouse_pixel_position (f, pix_x, pix_y)
5989 struct frame *f;
5990 int pix_x, pix_y;
5991 {
5992 #if 0 /* MAC_TODO: CursorDeviceMoveTo is non-Carbon */
5993 BLOCK_INPUT;
5994
5995 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
5996 0, 0, 0, 0, pix_x, pix_y);
5997 UNBLOCK_INPUT;
5998 #endif
5999 }
6000 \f
6001 /* focus shifting, raising and lowering. */
6002
6003 void
6004 x_focus_on_frame (f)
6005 struct frame *f;
6006 {
6007 #if 0 /* This proves to be unpleasant. */
6008 x_raise_frame (f);
6009 #endif
6010 #if 0
6011 /* I don't think that the ICCCM allows programs to do things like this
6012 without the interaction of the window manager. Whatever you end up
6013 doing with this code, do it to x_unfocus_frame too. */
6014 XSetInputFocus (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
6015 RevertToPointerRoot, CurrentTime);
6016 #endif /* ! 0 */
6017 }
6018
6019 void
6020 x_unfocus_frame (f)
6021 struct frame *f;
6022 {
6023 }
6024
6025 /* Raise frame F. */
6026
6027 void
6028 x_raise_frame (f)
6029 struct frame *f;
6030 {
6031 if (f->async_visible)
6032 {
6033 BLOCK_INPUT;
6034 BringToFront (FRAME_MAC_WINDOW (f));
6035 UNBLOCK_INPUT;
6036 }
6037 }
6038
6039 /* Lower frame F. */
6040
6041 void
6042 x_lower_frame (f)
6043 struct frame *f;
6044 {
6045 if (f->async_visible)
6046 {
6047 BLOCK_INPUT;
6048 SendBehind (FRAME_MAC_WINDOW (f), NULL);
6049 UNBLOCK_INPUT;
6050 }
6051 }
6052
6053 static void
6054 XTframe_raise_lower (f, raise_flag)
6055 FRAME_PTR f;
6056 int raise_flag;
6057 {
6058 if (raise_flag)
6059 x_raise_frame (f);
6060 else
6061 x_lower_frame (f);
6062 }
6063 \f
6064 /* Change of visibility. */
6065
6066 static void
6067 mac_handle_visibility_change (f)
6068 struct frame *f;
6069 {
6070 WindowPtr wp = FRAME_MAC_WINDOW (f);
6071 int visible = 0, iconified = 0;
6072 struct input_event buf;
6073
6074 if (IsWindowVisible (wp))
6075 {
6076 if (IsWindowCollapsed (wp))
6077 iconified = 1;
6078 else
6079 visible = 1;
6080 }
6081
6082 if (!f->async_visible && visible)
6083 {
6084 if (f->iconified)
6085 {
6086 /* wait_reading_process_output will notice this and update
6087 the frame's display structures. If we were made
6088 invisible, we should not set garbaged, because that stops
6089 redrawing on Update events. */
6090 SET_FRAME_GARBAGED (f);
6091
6092 EVENT_INIT (buf);
6093 buf.kind = DEICONIFY_EVENT;
6094 XSETFRAME (buf.frame_or_window, f);
6095 kbd_buffer_store_event (&buf);
6096 }
6097 else if (! NILP (Vframe_list) && ! NILP (XCDR (Vframe_list)))
6098 /* Force a redisplay sooner or later to update the
6099 frame titles in case this is the second frame. */
6100 record_asynch_buffer_change ();
6101 }
6102 else if (f->async_visible && !visible)
6103 if (iconified)
6104 {
6105 EVENT_INIT (buf);
6106 buf.kind = ICONIFY_EVENT;
6107 XSETFRAME (buf.frame_or_window, f);
6108 kbd_buffer_store_event (&buf);
6109 }
6110
6111 f->async_visible = visible;
6112 f->async_iconified = iconified;
6113 }
6114
6115 /* This tries to wait until the frame is really visible.
6116 However, if the window manager asks the user where to position
6117 the frame, this will return before the user finishes doing that.
6118 The frame will not actually be visible at that time,
6119 but it will become visible later when the window manager
6120 finishes with it. */
6121
6122 void
6123 x_make_frame_visible (f)
6124 struct frame *f;
6125 {
6126 BLOCK_INPUT;
6127
6128 if (! FRAME_VISIBLE_P (f))
6129 {
6130 /* We test FRAME_GARBAGED_P here to make sure we don't
6131 call x_set_offset a second time
6132 if we get to x_make_frame_visible a second time
6133 before the window gets really visible. */
6134 if (! FRAME_ICONIFIED_P (f)
6135 && ! f->output_data.mac->asked_for_visible)
6136 {
6137 #if TARGET_API_MAC_CARBON
6138 if (!(FRAME_SIZE_HINTS (f)->flags & (USPosition | PPosition)))
6139 {
6140 struct frame *sf = SELECTED_FRAME ();
6141 if (!FRAME_MAC_P (sf))
6142 RepositionWindow (FRAME_MAC_WINDOW (f), NULL,
6143 kWindowCenterOnMainScreen);
6144 else
6145 RepositionWindow (FRAME_MAC_WINDOW (f),
6146 FRAME_MAC_WINDOW (sf),
6147 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
6148 kWindowCascadeStartAtParentWindowScreen
6149 #else
6150 kWindowCascadeOnParentWindowScreen
6151 #endif
6152 );
6153 x_real_positions (f, &f->left_pos, &f->top_pos);
6154 }
6155 else
6156 #endif
6157 x_set_offset (f, f->left_pos, f->top_pos, 0);
6158 }
6159
6160 f->output_data.mac->asked_for_visible = 1;
6161
6162 CollapseWindow (FRAME_MAC_WINDOW (f), false);
6163 ShowWindow (FRAME_MAC_WINDOW (f));
6164 }
6165
6166 XFlush (FRAME_MAC_DISPLAY (f));
6167
6168 /* Synchronize to ensure Emacs knows the frame is visible
6169 before we do anything else. We do this loop with input not blocked
6170 so that incoming events are handled. */
6171 {
6172 Lisp_Object frame;
6173 int count;
6174
6175 /* This must come after we set COUNT. */
6176 UNBLOCK_INPUT;
6177
6178 XSETFRAME (frame, f);
6179
6180 /* Wait until the frame is visible. Process X events until a
6181 MapNotify event has been seen, or until we think we won't get a
6182 MapNotify at all.. */
6183 for (count = input_signal_count + 10;
6184 input_signal_count < count && !FRAME_VISIBLE_P (f);)
6185 {
6186 /* Force processing of queued events. */
6187 x_sync (f);
6188
6189 /* Machines that do polling rather than SIGIO have been
6190 observed to go into a busy-wait here. So we'll fake an
6191 alarm signal to let the handler know that there's something
6192 to be read. We used to raise a real alarm, but it seems
6193 that the handler isn't always enabled here. This is
6194 probably a bug. */
6195 if (input_polling_used ())
6196 {
6197 /* It could be confusing if a real alarm arrives while
6198 processing the fake one. Turn it off and let the
6199 handler reset it. */
6200 extern void poll_for_input_1 P_ ((void));
6201 int old_poll_suppress_count = poll_suppress_count;
6202 poll_suppress_count = 1;
6203 poll_for_input_1 ();
6204 poll_suppress_count = old_poll_suppress_count;
6205 }
6206
6207 /* See if a MapNotify event has been processed. */
6208 FRAME_SAMPLE_VISIBILITY (f);
6209 }
6210 }
6211 }
6212
6213 /* Change from mapped state to withdrawn state. */
6214
6215 /* Make the frame visible (mapped and not iconified). */
6216
6217 void
6218 x_make_frame_invisible (f)
6219 struct frame *f;
6220 {
6221 /* A deactivate event does not occur when the last visible frame is
6222 made invisible. So if we clear the highlight here, it will not
6223 be rehighlighted when it is made visible. */
6224 #if 0
6225 /* Don't keep the highlight on an invisible frame. */
6226 if (FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame == f)
6227 FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame = 0;
6228 #endif
6229
6230 BLOCK_INPUT;
6231
6232 /* Before unmapping the window, update the WM_SIZE_HINTS property to claim
6233 that the current position of the window is user-specified, rather than
6234 program-specified, so that when the window is mapped again, it will be
6235 placed at the same location, without forcing the user to position it
6236 by hand again (they have already done that once for this window.) */
6237 x_wm_set_size_hint (f, (long) 0, 1);
6238
6239 HideWindow (FRAME_MAC_WINDOW (f));
6240
6241 UNBLOCK_INPUT;
6242
6243 #if !USE_CARBON_EVENTS
6244 mac_handle_visibility_change (f);
6245 #endif
6246 }
6247
6248 /* Change window state from mapped to iconified. */
6249
6250 void
6251 x_iconify_frame (f)
6252 struct frame *f;
6253 {
6254 OSErr err;
6255
6256 /* A deactivate event does not occur when the last visible frame is
6257 iconified. So if we clear the highlight here, it will not be
6258 rehighlighted when it is deiconified. */
6259 #if 0
6260 /* Don't keep the highlight on an invisible frame. */
6261 if (FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame == f)
6262 FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame = 0;
6263 #endif
6264
6265 if (f->async_iconified)
6266 return;
6267
6268 BLOCK_INPUT;
6269
6270 FRAME_SAMPLE_VISIBILITY (f);
6271
6272 if (! FRAME_VISIBLE_P (f))
6273 ShowWindow (FRAME_MAC_WINDOW (f));
6274
6275 err = CollapseWindow (FRAME_MAC_WINDOW (f), true);
6276
6277 UNBLOCK_INPUT;
6278
6279 if (err != noErr)
6280 error ("Can't notify window manager of iconification");
6281
6282 #if !USE_CARBON_EVENTS
6283 mac_handle_visibility_change (f);
6284 #endif
6285 }
6286
6287 \f
6288 /* Free X resources of frame F. */
6289
6290 void
6291 x_free_frame_resources (f)
6292 struct frame *f;
6293 {
6294 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
6295 WindowPtr wp = FRAME_MAC_WINDOW (f);
6296
6297 BLOCK_INPUT;
6298
6299 if (wp != tip_window)
6300 remove_window_handler (wp);
6301
6302 DisposeWindow (wp);
6303 if (wp == tip_window)
6304 /* Neither WaitNextEvent nor ReceiveNextEvent receives `window
6305 closed' event. So we reset tip_window here. */
6306 tip_window = NULL;
6307
6308 free_frame_menubar (f);
6309
6310 if (FRAME_FACE_CACHE (f))
6311 free_frame_faces (f);
6312
6313 x_free_gcs (f);
6314
6315 if (FRAME_SIZE_HINTS (f))
6316 xfree (FRAME_SIZE_HINTS (f));
6317
6318 xfree (f->output_data.mac);
6319 f->output_data.mac = NULL;
6320
6321 if (f == dpyinfo->x_focus_frame)
6322 dpyinfo->x_focus_frame = 0;
6323 if (f == dpyinfo->x_focus_event_frame)
6324 dpyinfo->x_focus_event_frame = 0;
6325 if (f == dpyinfo->x_highlight_frame)
6326 dpyinfo->x_highlight_frame = 0;
6327
6328 if (f == dpyinfo->mouse_face_mouse_frame)
6329 {
6330 dpyinfo->mouse_face_beg_row
6331 = dpyinfo->mouse_face_beg_col = -1;
6332 dpyinfo->mouse_face_end_row
6333 = dpyinfo->mouse_face_end_col = -1;
6334 dpyinfo->mouse_face_window = Qnil;
6335 dpyinfo->mouse_face_deferred_gc = 0;
6336 dpyinfo->mouse_face_mouse_frame = 0;
6337 }
6338
6339 UNBLOCK_INPUT;
6340 }
6341
6342
6343 /* Destroy the X window of frame F. */
6344
6345 void
6346 x_destroy_window (f)
6347 struct frame *f;
6348 {
6349 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
6350
6351 x_free_frame_resources (f);
6352
6353 dpyinfo->reference_count--;
6354 }
6355
6356 \f
6357 /* Setting window manager hints. */
6358
6359 /* Set the normal size hints for the window manager, for frame F.
6360 FLAGS is the flags word to use--or 0 meaning preserve the flags
6361 that the window now has.
6362 If USER_POSITION is nonzero, we set the USPosition
6363 flag (this is useful when FLAGS is 0). */
6364 void
6365 x_wm_set_size_hint (f, flags, user_position)
6366 struct frame *f;
6367 long flags;
6368 int user_position;
6369 {
6370 int base_width, base_height, width_inc, height_inc;
6371 int min_rows = 0, min_cols = 0;
6372 XSizeHints *size_hints;
6373
6374 base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
6375 base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
6376 width_inc = FRAME_COLUMN_WIDTH (f);
6377 height_inc = FRAME_LINE_HEIGHT (f);
6378
6379 check_frame_size (f, &min_rows, &min_cols);
6380
6381 size_hints = FRAME_SIZE_HINTS (f);
6382 if (size_hints == NULL)
6383 {
6384 size_hints = FRAME_SIZE_HINTS (f) = xmalloc (sizeof (XSizeHints));
6385 bzero (size_hints, sizeof (XSizeHints));
6386 }
6387
6388 size_hints->flags |= PResizeInc | PMinSize | PBaseSize ;
6389 size_hints->width_inc = width_inc;
6390 size_hints->height_inc = height_inc;
6391 size_hints->min_width = base_width + min_cols * width_inc;
6392 size_hints->min_height = base_height + min_rows * height_inc;
6393 size_hints->base_width = base_width;
6394 size_hints->base_height = base_height;
6395
6396 if (flags)
6397 size_hints->flags = flags;
6398 else if (user_position)
6399 {
6400 size_hints->flags &= ~ PPosition;
6401 size_hints->flags |= USPosition;
6402 }
6403 }
6404
6405 #if 0 /* MAC_TODO: hide application instead of iconify? */
6406 /* Used for IconicState or NormalState */
6407
6408 void
6409 x_wm_set_window_state (f, state)
6410 struct frame *f;
6411 int state;
6412 {
6413 #ifdef USE_X_TOOLKIT
6414 Arg al[1];
6415
6416 XtSetArg (al[0], XtNinitialState, state);
6417 XtSetValues (f->output_data.x->widget, al, 1);
6418 #else /* not USE_X_TOOLKIT */
6419 Window window = FRAME_X_WINDOW (f);
6420
6421 f->output_data.x->wm_hints.flags |= StateHint;
6422 f->output_data.x->wm_hints.initial_state = state;
6423
6424 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
6425 #endif /* not USE_X_TOOLKIT */
6426 }
6427
6428 void
6429 x_wm_set_icon_pixmap (f, pixmap_id)
6430 struct frame *f;
6431 int pixmap_id;
6432 {
6433 Pixmap icon_pixmap;
6434
6435 #ifndef USE_X_TOOLKIT
6436 Window window = FRAME_X_WINDOW (f);
6437 #endif
6438
6439 if (pixmap_id > 0)
6440 {
6441 icon_pixmap = x_bitmap_pixmap (f, pixmap_id);
6442 f->output_data.x->wm_hints.icon_pixmap = icon_pixmap;
6443 }
6444 else
6445 {
6446 /* It seems there is no way to turn off use of an icon pixmap.
6447 The following line does it, only if no icon has yet been created,
6448 for some window managers. But with mwm it crashes.
6449 Some people say it should clear the IconPixmapHint bit in this case,
6450 but that doesn't work, and the X consortium said it isn't the
6451 right thing at all. Since there is no way to win,
6452 best to explicitly give up. */
6453 #if 0
6454 f->output_data.x->wm_hints.icon_pixmap = None;
6455 #else
6456 return;
6457 #endif
6458 }
6459
6460 #ifdef USE_X_TOOLKIT /* same as in x_wm_set_window_state. */
6461
6462 {
6463 Arg al[1];
6464 XtSetArg (al[0], XtNiconPixmap, icon_pixmap);
6465 XtSetValues (f->output_data.x->widget, al, 1);
6466 }
6467
6468 #else /* not USE_X_TOOLKIT */
6469
6470 f->output_data.x->wm_hints.flags |= IconPixmapHint;
6471 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
6472
6473 #endif /* not USE_X_TOOLKIT */
6474 }
6475
6476 #endif /* MAC_TODO */
6477
6478 void
6479 x_wm_set_icon_position (f, icon_x, icon_y)
6480 struct frame *f;
6481 int icon_x, icon_y;
6482 {
6483 #if 0 /* MAC_TODO: no icons on Mac */
6484 #ifdef USE_X_TOOLKIT
6485 Window window = XtWindow (f->output_data.x->widget);
6486 #else
6487 Window window = FRAME_X_WINDOW (f);
6488 #endif
6489
6490 f->output_data.x->wm_hints.flags |= IconPositionHint;
6491 f->output_data.x->wm_hints.icon_x = icon_x;
6492 f->output_data.x->wm_hints.icon_y = icon_y;
6493
6494 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
6495 #endif /* MAC_TODO */
6496 }
6497
6498 \f
6499 /***********************************************************************
6500 XLFD Pattern Match
6501 ***********************************************************************/
6502
6503 /* An XLFD pattern is divided into blocks delimited by '*'. This
6504 structure holds information for each block. */
6505 struct xlfdpat_block
6506 {
6507 /* Length of the pattern string in this block. Non-zero except for
6508 the first and the last blocks. */
6509 int len;
6510
6511 /* Pattern string except the last character in this block. The last
6512 character is replaced with NUL in order to use it as a
6513 sentinel. */
6514 unsigned char *pattern;
6515
6516 /* Last character of the pattern string. Must not be '?'. */
6517 unsigned char last_char;
6518
6519 /* One of the tables for the Boyer-Moore string search. It
6520 specifies the number of positions to proceed for each character
6521 with which the match fails. */
6522 int skip[256];
6523
6524 /* The skip value for the last character in the above `skip' is
6525 assigned to `infinity' in order to simplify a loop condition.
6526 The original value is saved here. */
6527 int last_char_skip;
6528 };
6529
6530 struct xlfdpat
6531 {
6532 /* Normalized pattern string. "Normalized" means that capital
6533 letters are lowered, blocks are not empty except the first and
6534 the last ones, and trailing '?'s in a block that is not the last
6535 one are moved to the next one. The last character in each block
6536 is replaced with NUL. */
6537 unsigned char *buf;
6538
6539 /* Number of characters except '*'s and trailing '?'s in the
6540 normalized pattern string. */
6541 int nchars;
6542
6543 /* Number of trailing '?'s in the normalized pattern string. */
6544 int trailing_anychars;
6545
6546 /* Number of blocks and information for each block. The latter is
6547 NULL if the pattern is exact (no '*' or '?' in it). */
6548 int nblocks;
6549 struct xlfdpat_block *blocks;
6550 };
6551
6552 static void
6553 xlfdpat_destroy (pat)
6554 struct xlfdpat *pat;
6555 {
6556 if (pat)
6557 {
6558 if (pat->buf)
6559 {
6560 if (pat->blocks)
6561 xfree (pat->blocks);
6562 xfree (pat->buf);
6563 }
6564 xfree (pat);
6565 }
6566 }
6567
6568 static struct xlfdpat *
6569 xlfdpat_create (pattern)
6570 char *pattern;
6571 {
6572 struct xlfdpat *pat;
6573 int nblocks, i, skip;
6574 unsigned char last_char, *p, *q, *anychar_head;
6575 struct xlfdpat_block *blk;
6576
6577 pat = xmalloc (sizeof (struct xlfdpat));
6578 pat->buf = xmalloc (strlen (pattern) + 1);
6579
6580 /* Normalize the pattern string and store it to `pat->buf'. */
6581 nblocks = 0;
6582 anychar_head = NULL;
6583 q = pat->buf;
6584 last_char = '\0';
6585 for (p = pattern; *p; p++)
6586 {
6587 unsigned char c = *p;
6588
6589 if (c == '*')
6590 if (last_char == '*')
6591 /* ...a** -> ...a* */
6592 continue;
6593 else
6594 {
6595 if (last_char == '?')
6596 {
6597 if (anychar_head > pat->buf && *(anychar_head - 1) == '*')
6598 /* ...*??* -> ...*?? */
6599 continue;
6600 else
6601 /* ...a??* -> ...a*?? */
6602 {
6603 *anychar_head++ = '*';
6604 c = '?';
6605 }
6606 }
6607 nblocks++;
6608 }
6609 else if (c == '?')
6610 {
6611 if (last_char != '?')
6612 anychar_head = q;
6613 }
6614 else
6615 /* On Mac OS X 10.3, tolower also converts non-ASCII
6616 characters for some locales. */
6617 if (isascii (c))
6618 c = tolower (c);
6619
6620 *q++ = last_char = c;
6621 }
6622 *q = '\0';
6623 nblocks++;
6624 pat->nblocks = nblocks;
6625 if (last_char != '?')
6626 pat->trailing_anychars = 0;
6627 else
6628 {
6629 pat->trailing_anychars = q - anychar_head;
6630 q = anychar_head;
6631 }
6632 pat->nchars = q - pat->buf - (nblocks - 1);
6633
6634 if (anychar_head == NULL && nblocks == 1)
6635 {
6636 /* The pattern is exact. */
6637 pat->blocks = NULL;
6638 return pat;
6639 }
6640
6641 pat->blocks = xmalloc (sizeof (struct xlfdpat_block) * nblocks);
6642
6643 /* Divide the normalized pattern into blocks. */
6644 p = pat->buf;
6645 for (blk = pat->blocks; blk < pat->blocks + nblocks - 1; blk++)
6646 {
6647 blk->pattern = p;
6648 while (*p != '*')
6649 p++;
6650 blk->len = p - blk->pattern;
6651 p++;
6652 }
6653 blk->pattern = p;
6654 blk->len = q - blk->pattern;
6655
6656 /* Setup a table for the Boyer-Moore string search. */
6657 for (blk = pat->blocks; blk < pat->blocks + nblocks; blk++)
6658 if (blk->len != 0)
6659 {
6660 blk->last_char = blk->pattern[blk->len - 1];
6661 blk->pattern[blk->len - 1] = '\0';
6662
6663 for (skip = 1; skip < blk->len; skip++)
6664 if (blk->pattern[blk->len - skip - 1] == '?')
6665 break;
6666
6667 for (i = 0; i < 256; i++)
6668 blk->skip[i] = skip;
6669
6670 p = blk->pattern + (blk->len - skip);
6671 while (--skip > 0)
6672 blk->skip[*p++] = skip;
6673
6674 blk->last_char_skip = blk->skip[blk->last_char];
6675 }
6676
6677 return pat;
6678
6679 error:
6680 xlfdpat_destroy (pat);
6681 return NULL;
6682 }
6683
6684 static INLINE int
6685 xlfdpat_exact_p (pat)
6686 struct xlfdpat *pat;
6687 {
6688 return pat->blocks == NULL;
6689 }
6690
6691 /* Return the first string in STRING + 0, ..., STRING + START_MAX such
6692 that the pattern in *BLK matches with its prefix. Return NULL
6693 there is no such strings. STRING must be lowered in advance. */
6694
6695 static char *
6696 xlfdpat_block_match_1 (blk, string, start_max)
6697 struct xlfdpat_block *blk;
6698 unsigned char *string;
6699 int start_max;
6700 {
6701 int start, infinity;
6702 unsigned char *p, *s;
6703
6704 xassert (blk->len > 0);
6705 xassert (start_max + blk->len <= strlen (string));
6706 xassert (blk->last_char != '?');
6707
6708 /* See the comments in the function `boyer_moore' (search.c) for the
6709 use of `infinity'. */
6710 infinity = start_max + blk->len + 1;
6711 blk->skip[blk->last_char] = infinity;
6712
6713 start = 0;
6714 do
6715 {
6716 /* Check the last character of the pattern. */
6717 s = string + blk->len - 1;
6718 do
6719 {
6720 start += blk->skip[*(s + start)];
6721 }
6722 while (start <= start_max);
6723
6724 if (start < infinity)
6725 /* Couldn't find the last character. */
6726 return NULL;
6727
6728 /* No less than `infinity' means we could find the last
6729 character at `s[start - infinity]'. */
6730 start -= infinity;
6731
6732 /* Check the remaining characters. We prefer making no-'?'
6733 cases faster because the use of '?' is really rare. */
6734 p = blk->pattern;
6735 s = string + start;
6736 do
6737 {
6738 while (*p++ == *s++)
6739 ;
6740 }
6741 while (*(p - 1) == '?');
6742
6743 if (*(p - 1) == '\0')
6744 /* Matched. */
6745 return string + start;
6746
6747 /* Didn't match. */
6748 start += blk->last_char_skip;
6749 }
6750 while (start <= start_max);
6751
6752 return NULL;
6753 }
6754
6755 #define xlfdpat_block_match(b, s, m) \
6756 ((b)->len == 1 ? memchr ((s), (b)->last_char, (m) + 1) \
6757 : xlfdpat_block_match_1 (b, s, m))
6758
6759 /* Check if XLFD pattern PAT, which is generated by `xfldpat_create',
6760 matches with STRING. STRING must be lowered in advance. */
6761
6762 static int
6763 xlfdpat_match (pat, string)
6764 struct xlfdpat *pat;
6765 unsigned char *string;
6766 {
6767 int str_len, nblocks, i, start_max;
6768 struct xlfdpat_block *blk;
6769 unsigned char *s;
6770
6771 xassert (pat->nblocks > 0);
6772
6773 if (xlfdpat_exact_p (pat))
6774 return strcmp (pat->buf, string) == 0;
6775
6776 /* The number of the characters in the string must not be smaller
6777 than that in the pattern. */
6778 str_len = strlen (string);
6779 if (str_len < pat->nchars + pat->trailing_anychars)
6780 return 0;
6781
6782 /* Chop off the trailing '?'s. */
6783 str_len -= pat->trailing_anychars;
6784
6785 /* The last block. When it is non-empty, it must match at the end
6786 of the string. */
6787 nblocks = pat->nblocks;
6788 blk = pat->blocks + (nblocks - 1);
6789 if (nblocks == 1)
6790 /* The last block is also the first one. */
6791 return (str_len == blk->len
6792 && (blk->len == 0 || xlfdpat_block_match (blk, string, 0)));
6793 else if (blk->len != 0)
6794 if (!xlfdpat_block_match (blk, string + (str_len - blk->len), 0))
6795 return 0;
6796
6797 /* The first block. When it is non-empty, it must match at the
6798 beginning of the string. */
6799 blk = pat->blocks;
6800 if (blk->len != 0)
6801 {
6802 s = xlfdpat_block_match (blk, string, 0);
6803 if (s == NULL)
6804 return 0;
6805 string = s + blk->len;
6806 }
6807
6808 /* The rest of the blocks. */
6809 start_max = str_len - pat->nchars;
6810 for (i = 1, blk++; i < nblocks - 1; i++, blk++)
6811 {
6812 s = xlfdpat_block_match (blk, string, start_max);
6813 if (s == NULL)
6814 return 0;
6815 start_max -= s - string;
6816 string = s + blk->len;
6817 }
6818
6819 return 1;
6820 }
6821
6822 \f
6823 /***********************************************************************
6824 Fonts
6825 ***********************************************************************/
6826
6827 /* Return a pointer to struct font_info of font FONT_IDX of frame F. */
6828
6829 struct font_info *
6830 x_get_font_info (f, font_idx)
6831 FRAME_PTR f;
6832 int font_idx;
6833 {
6834 return (FRAME_MAC_FONT_TABLE (f) + font_idx);
6835 }
6836
6837 /* the global font name table */
6838 static char **font_name_table = NULL;
6839 static int font_name_table_size = 0;
6840 static int font_name_count = 0;
6841
6842 /* Alist linking font family names to Font Manager font family
6843 references (which can also be used as QuickDraw font IDs). We use
6844 an alist because hash tables are not ready when the terminal frame
6845 for Mac OS Classic is created. */
6846 static Lisp_Object fm_font_family_alist;
6847 #if USE_ATSUI
6848 /* Hash table linking font family names to ATSU font IDs. */
6849 static Lisp_Object atsu_font_id_hash;
6850 #endif
6851
6852 /* Alist linking character set strings to Mac text encoding and Emacs
6853 coding system. */
6854 static Lisp_Object Vmac_charset_info_alist;
6855
6856 static Lisp_Object
6857 create_text_encoding_info_alist ()
6858 {
6859 Lisp_Object result = Qnil, rest;
6860
6861 for (rest = Vmac_charset_info_alist; CONSP (rest); rest = XCDR (rest))
6862 {
6863 Lisp_Object charset_info = XCAR (rest);
6864 Lisp_Object charset, coding_system, text_encoding;
6865 Lisp_Object existing_info;
6866
6867 if (!(CONSP (charset_info)
6868 && STRINGP (charset = XCAR (charset_info))
6869 && CONSP (XCDR (charset_info))
6870 && INTEGERP (text_encoding = XCAR (XCDR (charset_info)))
6871 && CONSP (XCDR (XCDR (charset_info)))
6872 && SYMBOLP (coding_system = XCAR (XCDR (XCDR (charset_info))))))
6873 continue;
6874
6875 existing_info = assq_no_quit (text_encoding, result);
6876 if (NILP (existing_info))
6877 result = Fcons (list3 (text_encoding, coding_system, charset),
6878 result);
6879 else
6880 if (NILP (Fmember (charset, XCDR (XCDR (existing_info)))))
6881 XSETCDR (XCDR (existing_info),
6882 Fcons (charset, XCDR (XCDR (existing_info))));
6883 }
6884
6885 return result;
6886 }
6887
6888
6889 static void
6890 decode_mac_font_name (name, size, coding_system)
6891 char *name;
6892 int size;
6893 Lisp_Object coding_system;
6894 {
6895 struct coding_system coding;
6896 char *buf, *p;
6897
6898 if (!NILP (coding_system) && !NILP (Fcoding_system_p (coding_system)))
6899 {
6900 for (p = name; *p; p++)
6901 if (!isascii (*p) || iscntrl (*p))
6902 break;
6903
6904 if (*p)
6905 {
6906 setup_coding_system (coding_system, &coding);
6907 coding.src_multibyte = 0;
6908 coding.dst_multibyte = 1;
6909 coding.mode |= CODING_MODE_LAST_BLOCK;
6910 coding.dst_bytes = size;
6911 coding.destination = (unsigned char *) alloca (coding.dst_bytes);
6912
6913 decode_coding_c_string (&coding, name, strlen (name), Qnil);
6914 bcopy (coding.destination, name, min (coding.produced, size));
6915 name[min (coding.produced, size)] = '\0';
6916 }
6917 }
6918
6919 /* If there's just one occurrence of '-' in the family name, it is
6920 replaced with '_'. (More than one occurrence of '-' means a
6921 "FOUNDRY-FAMILY-CHARSET"-style name.) */
6922 p = strchr (name, '-');
6923 if (p && strchr (p + 1, '-') == NULL)
6924 *p = '_';
6925
6926 for (p = name; *p; p++)
6927 /* On Mac OS X 10.3, tolower also converts non-ASCII characters
6928 for some locales. */
6929 if (isascii (*p))
6930 *p = tolower (*p);
6931 }
6932
6933
6934 static char *
6935 mac_to_x_fontname (name, size, style, charset)
6936 char *name;
6937 int size;
6938 Style style;
6939 char *charset;
6940 {
6941 Str31 foundry, cs;
6942 Str255 family;
6943 char xf[256], *result;
6944 unsigned char *p;
6945
6946 if (sscanf (name, "%31[^-]-%255[^-]-%31s", foundry, family, cs) == 3)
6947 charset = cs;
6948 else
6949 {
6950 strcpy(foundry, "Apple");
6951 strcpy(family, name);
6952 }
6953
6954 sprintf (xf, "%s-%c-normal--%d-%d-%d-%d-m-%d-%s",
6955 style & bold ? "bold" : "medium", style & italic ? 'i' : 'r',
6956 size, size * 10, size ? 72 : 0, size ? 72 : 0, size * 10, charset);
6957
6958 result = xmalloc (strlen (foundry) + strlen (family) + strlen (xf) + 3 + 1);
6959 sprintf (result, "-%s-%s-%s", foundry, family, xf);
6960 for (p = result; *p; p++)
6961 /* On Mac OS X 10.3, tolower also converts non-ASCII characters
6962 for some locales. */
6963 if (isascii (*p))
6964 *p = tolower (*p);
6965 return result;
6966 }
6967
6968
6969 /* Parse fully-specified and instantiated X11 font spec XF, and store
6970 the results to FAMILY, *SIZE, *STYLE, and CHARSET. Return 1 if the
6971 parsing succeeded, and 0 otherwise. For FAMILY and CHARSET, the
6972 caller must allocate at least 256 and 32 bytes respectively. For
6973 ordinary Mac fonts, the value stored to FAMILY should just be their
6974 names, like "monaco", "Taipei", etc. Fonts converted from the GNU
6975 intlfonts collection contain their charset designation in their
6976 names, like "ETL-Fixed-iso8859-1", "ETL-Fixed-koi8-r", etc. Both
6977 types of font names are handled accordingly. */
6978
6979 const int kDefaultFontSize = 12;
6980
6981 static int
6982 parse_x_font_name (xf, family, size, style, charset)
6983 char *xf, *family;
6984 int *size;
6985 Style *style;
6986 char *charset;
6987 {
6988 Str31 foundry, weight;
6989 int point_size, avgwidth;
6990 char slant[2], *p;
6991
6992 if (sscanf (xf, "-%31[^-]-%255[^-]-%31[^-]-%1[^-]-%*[^-]-%*[^-]-%d-%d-%*[^-]-%*[^-]-%*c-%d-%31s",
6993 foundry, family, weight, slant, size,
6994 &point_size, &avgwidth, charset) != 8
6995 && sscanf (xf, "-%31[^-]-%255[^-]-%31[^-]-%1[^-]-%*[^-]--%d-%d-%*[^-]-%*[^-]-%*c-%d-%31s",
6996 foundry, family, weight, slant, size,
6997 &point_size, &avgwidth, charset) != 8)
6998 return 0;
6999
7000 if (*size == 0)
7001 {
7002 if (point_size > 0)
7003 *size = point_size / 10;
7004 else if (avgwidth > 0)
7005 *size = avgwidth / 10;
7006 }
7007 if (*size == 0)
7008 *size = kDefaultFontSize;
7009
7010 *style = normal;
7011 if (strcmp (weight, "bold") == 0)
7012 *style |= bold;
7013 if (*slant == 'i')
7014 *style |= italic;
7015
7016 if (NILP (Fassoc (build_string (charset), Vmac_charset_info_alist)))
7017 {
7018 int foundry_len = strlen (foundry), family_len = strlen (family);
7019
7020 if (foundry_len + family_len + strlen (charset) + 2 < sizeof (Str255))
7021 {
7022 /* Like sprintf (family, "%s-%s-%s", foundry, family, charset),
7023 but take overlap into account. */
7024 memmove (family + foundry_len + 1, family, family_len);
7025 memcpy (family, foundry, foundry_len);
7026 family[foundry_len] = '-';
7027 family[foundry_len + 1 + family_len] = '-';
7028 strcpy (family + foundry_len + 1 + family_len + 1, charset);
7029 }
7030 else
7031 return 0;
7032 }
7033
7034 for (p = family; *p; p++)
7035 /* On Mac OS X 10.3, tolower also converts non-ASCII characters
7036 for some locales. */
7037 if (isascii (*p))
7038 *p = tolower (*p);
7039
7040 return 1;
7041 }
7042
7043
7044 static void
7045 add_font_name_table_entry (char *font_name)
7046 {
7047 if (font_name_table_size == 0)
7048 {
7049 font_name_table_size = 256;
7050 font_name_table = (char **)
7051 xmalloc (font_name_table_size * sizeof (char *));
7052 }
7053 else if (font_name_count + 1 >= font_name_table_size)
7054 {
7055 font_name_table_size *= 2;
7056 font_name_table = (char **)
7057 xrealloc (font_name_table,
7058 font_name_table_size * sizeof (char *));
7059 }
7060
7061 font_name_table[font_name_count++] = font_name;
7062 }
7063
7064 /* Sets up the table font_name_table to contain the list of all fonts
7065 in the system the first time the table is used so that the Resource
7066 Manager need not be accessed every time this information is
7067 needed. */
7068
7069 static void
7070 init_font_name_table ()
7071 {
7072 #if TARGET_API_MAC_CARBON
7073 FMFontFamilyIterator ffi;
7074 FMFontFamilyInstanceIterator ffii;
7075 FMFontFamily ff;
7076 Lisp_Object text_encoding_info_alist;
7077 struct gcpro gcpro1;
7078
7079 text_encoding_info_alist = create_text_encoding_info_alist ();
7080
7081 #if USE_ATSUI
7082 #if USE_CG_TEXT_DRAWING
7083 init_cg_text_anti_aliasing_threshold ();
7084 #endif
7085 if (!NILP (assq_no_quit (make_number (kTextEncodingMacUnicode),
7086 text_encoding_info_alist)))
7087 {
7088 OSErr err;
7089 ItemCount nfonts, i;
7090 ATSUFontID *font_ids = NULL;
7091 Ptr name, prev_name = NULL;
7092 ByteCount name_len;
7093
7094 atsu_font_id_hash =
7095 make_hash_table (Qequal, make_number (DEFAULT_HASH_SIZE),
7096 make_float (DEFAULT_REHASH_SIZE),
7097 make_float (DEFAULT_REHASH_THRESHOLD),
7098 Qnil, Qnil, Qnil);;
7099 err = ATSUFontCount (&nfonts);
7100 if (err == noErr)
7101 {
7102 font_ids = xmalloc (sizeof (ATSUFontID) * nfonts);
7103 err = ATSUGetFontIDs (font_ids, nfonts, NULL);
7104 }
7105 if (err == noErr)
7106 for (i = 0; i < nfonts; i++)
7107 {
7108 err = ATSUFindFontName (font_ids[i], kFontFamilyName,
7109 kFontMacintoshPlatform, kFontNoScript,
7110 kFontNoLanguage, 0, NULL, &name_len, NULL);
7111 if (err != noErr)
7112 continue;
7113 name = xmalloc (name_len + 1);
7114 name[name_len] = '\0';
7115 err = ATSUFindFontName (font_ids[i], kFontFamilyName,
7116 kFontMacintoshPlatform, kFontNoScript,
7117 kFontNoLanguage, name_len, name,
7118 NULL, NULL);
7119 if (err == noErr)
7120 decode_mac_font_name (name, name_len + 1, Qnil);
7121 if (err == noErr
7122 && *name != '.'
7123 && (prev_name == NULL
7124 || strcmp (name, prev_name) != 0))
7125 {
7126 static char *cs = "iso10646-1";
7127
7128 add_font_name_table_entry (mac_to_x_fontname (name, 0,
7129 normal, cs));
7130 add_font_name_table_entry (mac_to_x_fontname (name, 0,
7131 italic, cs));
7132 add_font_name_table_entry (mac_to_x_fontname (name, 0,
7133 bold, cs));
7134 add_font_name_table_entry (mac_to_x_fontname (name, 0,
7135 italic | bold, cs));
7136 Fputhash (make_unibyte_string (name, name_len),
7137 long_to_cons (font_ids[i]), atsu_font_id_hash);
7138 xfree (prev_name);
7139 prev_name = name;
7140 }
7141 else
7142 xfree (name);
7143 }
7144 if (prev_name)
7145 xfree (prev_name);
7146 if (font_ids)
7147 xfree (font_ids);
7148 }
7149 #endif
7150
7151 /* Create a dummy instance iterator here to avoid creating and
7152 destroying it in the loop. */
7153 if (FMCreateFontFamilyInstanceIterator (0, &ffii) != noErr)
7154 return;
7155 /* Create an iterator to enumerate the font families. */
7156 if (FMCreateFontFamilyIterator (NULL, NULL, kFMDefaultOptions, &ffi)
7157 != noErr)
7158 {
7159 FMDisposeFontFamilyInstanceIterator (&ffii);
7160 return;
7161 }
7162
7163 GCPRO1 (text_encoding_info_alist);
7164
7165 while (FMGetNextFontFamily (&ffi, &ff) == noErr)
7166 {
7167 Str255 name;
7168 FMFont font;
7169 FMFontStyle style;
7170 FMFontSize size;
7171 TextEncoding encoding;
7172 TextEncodingBase sc;
7173 Lisp_Object text_encoding_info;
7174
7175 if (FMGetFontFamilyName (ff, name) != noErr)
7176 break;
7177 p2cstr (name);
7178 if (*name == '.')
7179 continue;
7180
7181 if (FMGetFontFamilyTextEncoding (ff, &encoding) != noErr)
7182 break;
7183 sc = GetTextEncodingBase (encoding);
7184 text_encoding_info = assq_no_quit (make_number (sc),
7185 text_encoding_info_alist);
7186 if (NILP (text_encoding_info))
7187 text_encoding_info = assq_no_quit (make_number (kTextEncodingMacRoman),
7188 text_encoding_info_alist);
7189 decode_mac_font_name (name, sizeof (name),
7190 XCAR (XCDR (text_encoding_info)));
7191 fm_font_family_alist = Fcons (Fcons (build_string (name),
7192 make_number (ff)),
7193 fm_font_family_alist);
7194
7195 /* Point the instance iterator at the current font family. */
7196 if (FMResetFontFamilyInstanceIterator (ff, &ffii) != noErr)
7197 break;
7198
7199 while (FMGetNextFontFamilyInstance (&ffii, &font, &style, &size)
7200 == noErr)
7201 {
7202 Lisp_Object rest = XCDR (XCDR (text_encoding_info));
7203
7204 if (size > 0 || style == normal)
7205 for (; !NILP (rest); rest = XCDR (rest))
7206 {
7207 char *cs = SDATA (XCAR (rest));
7208
7209 if (size == 0)
7210 {
7211 add_font_name_table_entry (mac_to_x_fontname (name, size,
7212 style, cs));
7213 add_font_name_table_entry (mac_to_x_fontname (name, size,
7214 italic, cs));
7215 add_font_name_table_entry (mac_to_x_fontname (name, size,
7216 bold, cs));
7217 add_font_name_table_entry (mac_to_x_fontname (name, size,
7218 italic | bold,
7219 cs));
7220 }
7221 else
7222 {
7223 add_font_name_table_entry (mac_to_x_fontname (name, size,
7224 style, cs));
7225 }
7226 }
7227 }
7228 }
7229
7230 UNGCPRO;
7231
7232 /* Dispose of the iterators. */
7233 FMDisposeFontFamilyIterator (&ffi);
7234 FMDisposeFontFamilyInstanceIterator (&ffii);
7235 #else /* !TARGET_API_MAC_CARBON */
7236 GrafPtr port;
7237 SInt16 fontnum, old_fontnum;
7238 int num_mac_fonts = CountResources('FOND');
7239 int i, j;
7240 Handle font_handle, font_handle_2;
7241 short id, scriptcode;
7242 ResType type;
7243 Str255 name;
7244 struct FontAssoc *fat;
7245 struct AsscEntry *assc_entry;
7246 Lisp_Object text_encoding_info_alist, text_encoding_info;
7247 struct gcpro gcpro1;
7248
7249 GetPort (&port); /* save the current font number used */
7250 old_fontnum = port->txFont;
7251
7252 text_encoding_info_alist = create_text_encoding_info_alist ();
7253
7254 GCPRO1 (text_encoding_info_alist);
7255
7256 for (i = 1; i <= num_mac_fonts; i++) /* get all available fonts */
7257 {
7258 font_handle = GetIndResource ('FOND', i);
7259 if (!font_handle)
7260 continue;
7261
7262 GetResInfo (font_handle, &id, &type, name);
7263 GetFNum (name, &fontnum);
7264 p2cstr (name);
7265 if (fontnum == 0)
7266 continue;
7267
7268 TextFont (fontnum);
7269 scriptcode = FontToScript (fontnum);
7270 text_encoding_info = assq_no_quit (make_number (scriptcode),
7271 text_encoding_info_alist);
7272 if (NILP (text_encoding_info))
7273 text_encoding_info = assq_no_quit (make_number (smRoman),
7274 text_encoding_info_alist);
7275 decode_mac_font_name (name, sizeof (name),
7276 XCAR (XCDR (text_encoding_info)));
7277 fm_font_family_alist = Fcons (Fcons (build_string (name),
7278 make_number (fontnum)),
7279 fm_font_family_alist);
7280 do
7281 {
7282 HLock (font_handle);
7283
7284 if (GetResourceSizeOnDisk (font_handle)
7285 >= sizeof (struct FamRec))
7286 {
7287 fat = (struct FontAssoc *) (*font_handle
7288 + sizeof (struct FamRec));
7289 assc_entry
7290 = (struct AsscEntry *) (*font_handle
7291 + sizeof (struct FamRec)
7292 + sizeof (struct FontAssoc));
7293
7294 for (j = 0; j <= fat->numAssoc; j++, assc_entry++)
7295 {
7296 Lisp_Object rest = XCDR (XCDR (text_encoding_info));
7297
7298 for (; !NILP (rest); rest = XCDR (rest))
7299 {
7300 char *cs = SDATA (XCAR (rest));
7301
7302 add_font_name_table_entry (mac_to_x_fontname (name,
7303 assc_entry->fontSize,
7304 assc_entry->fontStyle,
7305 cs));
7306 }
7307 }
7308 }
7309
7310 HUnlock (font_handle);
7311 font_handle_2 = GetNextFOND (font_handle);
7312 ReleaseResource (font_handle);
7313 font_handle = font_handle_2;
7314 }
7315 while (ResError () == noErr && font_handle);
7316 }
7317
7318 UNGCPRO;
7319
7320 TextFont (old_fontnum);
7321 #endif /* !TARGET_API_MAC_CARBON */
7322 }
7323
7324
7325 void
7326 mac_clear_font_name_table ()
7327 {
7328 int i;
7329
7330 for (i = 0; i < font_name_count; i++)
7331 xfree (font_name_table[i]);
7332 xfree (font_name_table);
7333 font_name_table = NULL;
7334 font_name_table_size = font_name_count = 0;
7335 fm_font_family_alist = Qnil;
7336 }
7337
7338
7339 enum xlfd_scalable_field_index
7340 {
7341 XLFD_SCL_PIXEL_SIZE,
7342 XLFD_SCL_POINT_SIZE,
7343 XLFD_SCL_AVGWIDTH,
7344 XLFD_SCL_LAST
7345 };
7346
7347 static int xlfd_scalable_fields[] =
7348 {
7349 6, /* PIXEL_SIZE */
7350 7, /* POINT_SIZE */
7351 11, /* AVGWIDTH */
7352 -1
7353 };
7354
7355 static Lisp_Object
7356 mac_do_list_fonts (pattern, maxnames)
7357 char *pattern;
7358 int maxnames;
7359 {
7360 int i, n_fonts = 0;
7361 Lisp_Object font_list = Qnil;
7362 struct xlfdpat *pat;
7363 char *scaled, *ptr;
7364 int scl_val[XLFD_SCL_LAST], *field, *val;
7365 int exact;
7366
7367 if (font_name_table == NULL) /* Initialize when first used. */
7368 init_font_name_table ();
7369
7370 for (i = 0; i < XLFD_SCL_LAST; i++)
7371 scl_val[i] = -1;
7372
7373 /* If the pattern contains 14 dashes and one of PIXEL_SIZE,
7374 POINT_SIZE, and AVGWIDTH fields is explicitly specified, scalable
7375 fonts are scaled according to the specified size. */
7376 ptr = pattern;
7377 i = 0;
7378 field = xlfd_scalable_fields;
7379 val = scl_val;
7380 if (*ptr == '-')
7381 do
7382 {
7383 ptr++;
7384 if (i == *field)
7385 {
7386 if ('0' <= *ptr && *ptr <= '9')
7387 {
7388 *val = *ptr++ - '0';
7389 while ('0' <= *ptr && *ptr <= '9' && *val < 10000)
7390 *val = *val * 10 + *ptr++ - '0';
7391 if (*ptr != '-')
7392 *val = -1;
7393 }
7394 field++;
7395 val++;
7396 }
7397 ptr = strchr (ptr, '-');
7398 i++;
7399 }
7400 while (ptr && i < 14);
7401
7402 if (i == 14 && ptr == NULL)
7403 {
7404 if (scl_val[XLFD_SCL_PIXEL_SIZE] < 0)
7405 scl_val[XLFD_SCL_PIXEL_SIZE] =
7406 (scl_val[XLFD_SCL_POINT_SIZE] > 0 ? scl_val[XLFD_SCL_POINT_SIZE] / 10
7407 : (scl_val[XLFD_SCL_AVGWIDTH] > 0 ? scl_val[XLFD_SCL_AVGWIDTH] / 10
7408 : -1));
7409 if (scl_val[XLFD_SCL_POINT_SIZE] < 0)
7410 scl_val[XLFD_SCL_POINT_SIZE] =
7411 (scl_val[XLFD_SCL_PIXEL_SIZE] > 0 ? scl_val[XLFD_SCL_PIXEL_SIZE] * 10
7412 : (scl_val[XLFD_SCL_AVGWIDTH] > 0 ? scl_val[XLFD_SCL_AVGWIDTH]
7413 : -1));
7414 if (scl_val[XLFD_SCL_AVGWIDTH] < 0)
7415 scl_val[XLFD_SCL_AVGWIDTH] =
7416 (scl_val[XLFD_SCL_PIXEL_SIZE] > 0 ? scl_val[XLFD_SCL_PIXEL_SIZE] * 10
7417 : (scl_val[XLFD_SCL_POINT_SIZE] > 0 ? scl_val[XLFD_SCL_POINT_SIZE]
7418 : -1));
7419 }
7420 else
7421 scl_val[XLFD_SCL_PIXEL_SIZE] = -1;
7422
7423 pat = xlfdpat_create (pattern);
7424 if (pat == NULL)
7425 return Qnil;
7426
7427 exact = xlfdpat_exact_p (pat);
7428
7429 for (i = 0; i < font_name_count; i++)
7430 {
7431 if (xlfdpat_match (pat, font_name_table[i]))
7432 {
7433 font_list = Fcons (build_string (font_name_table[i]), font_list);
7434 if (exact || (maxnames > 0 && ++n_fonts >= maxnames))
7435 break;
7436 }
7437 else if (scl_val[XLFD_SCL_PIXEL_SIZE] > 0
7438 && (ptr = strstr (font_name_table[i], "-0-0-0-0-m-0-")))
7439 {
7440 int former_len = ptr - font_name_table[i];
7441
7442 scaled = xmalloc (strlen (font_name_table[i]) + 20 + 1);
7443 memcpy (scaled, font_name_table[i], former_len);
7444 sprintf (scaled + former_len,
7445 "-%d-%d-72-72-m-%d-%s",
7446 scl_val[XLFD_SCL_PIXEL_SIZE],
7447 scl_val[XLFD_SCL_POINT_SIZE],
7448 scl_val[XLFD_SCL_AVGWIDTH],
7449 ptr + sizeof ("-0-0-0-0-m-0-") - 1);
7450
7451 if (xlfdpat_match (pat, scaled))
7452 {
7453 font_list = Fcons (build_string (scaled), font_list);
7454 xfree (scaled);
7455 if (exact || (maxnames > 0 && ++n_fonts >= maxnames))
7456 break;
7457 }
7458 else
7459 xfree (scaled);
7460 }
7461 }
7462
7463 xlfdpat_destroy (pat);
7464
7465 return font_list;
7466 }
7467
7468 /* Return a list of names of available fonts matching PATTERN on frame F.
7469
7470 Frame F null means we have not yet created any frame on Mac, and
7471 consult the first display in x_display_list. MAXNAMES sets a limit
7472 on how many fonts to match. */
7473
7474 Lisp_Object
7475 x_list_fonts (f, pattern, size, maxnames)
7476 struct frame *f;
7477 Lisp_Object pattern;
7478 int size, maxnames;
7479 {
7480 Lisp_Object list = Qnil, patterns, tem, key;
7481 struct mac_display_info *dpyinfo
7482 = f ? FRAME_MAC_DISPLAY_INFO (f) : x_display_list;
7483
7484 xassert (size <= 0);
7485
7486 patterns = Fassoc (pattern, Valternate_fontname_alist);
7487 if (NILP (patterns))
7488 patterns = Fcons (pattern, Qnil);
7489
7490 for (; CONSP (patterns); patterns = XCDR (patterns))
7491 {
7492 pattern = XCAR (patterns);
7493
7494 if (!STRINGP (pattern))
7495 continue;
7496
7497 tem = XCAR (XCDR (dpyinfo->name_list_element));
7498 key = Fcons (pattern, make_number (maxnames));
7499
7500 list = Fassoc (key, tem);
7501 if (!NILP (list))
7502 {
7503 list = Fcdr_safe (list);
7504 /* We have a cashed list. Don't have to get the list again. */
7505 goto label_cached;
7506 }
7507
7508 BLOCK_INPUT;
7509 list = mac_do_list_fonts (SDATA (pattern), maxnames);
7510 UNBLOCK_INPUT;
7511
7512 /* MAC_TODO: add code for matching outline fonts here */
7513
7514 /* Now store the result in the cache. */
7515 XSETCAR (XCDR (dpyinfo->name_list_element),
7516 Fcons (Fcons (key, list),
7517 XCAR (XCDR (dpyinfo->name_list_element))));
7518
7519 label_cached:
7520 if (NILP (list)) continue; /* Try the remaining alternatives. */
7521 }
7522
7523 return list;
7524 }
7525
7526
7527 #if GLYPH_DEBUG
7528
7529 /* Check that FONT is valid on frame F. It is if it can be found in F's
7530 font table. */
7531
7532 static void
7533 x_check_font (f, font)
7534 struct frame *f;
7535 XFontStruct *font;
7536 {
7537 int i;
7538 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
7539
7540 xassert (font != NULL);
7541
7542 for (i = 0; i < dpyinfo->n_fonts; i++)
7543 if (dpyinfo->font_table[i].name
7544 && font == dpyinfo->font_table[i].font)
7545 break;
7546
7547 xassert (i < dpyinfo->n_fonts);
7548 }
7549
7550 #endif /* GLYPH_DEBUG != 0 */
7551
7552 /* Set *W to the minimum width, *H to the minimum font height of FONT.
7553 Note: There are (broken) X fonts out there with invalid XFontStruct
7554 min_bounds contents. For example, handa@etl.go.jp reports that
7555 "-adobe-courier-medium-r-normal--*-180-*-*-m-*-iso8859-1" fonts
7556 have font->min_bounds.width == 0. */
7557
7558 static INLINE void
7559 x_font_min_bounds (font, w, h)
7560 MacFontStruct *font;
7561 int *w, *h;
7562 {
7563 *h = FONT_HEIGHT (font);
7564 *w = font->min_bounds.width;
7565 }
7566
7567
7568 /* Compute the smallest character width and smallest font height over
7569 all fonts available on frame F. Set the members smallest_char_width
7570 and smallest_font_height in F's x_display_info structure to
7571 the values computed. Value is non-zero if smallest_font_height or
7572 smallest_char_width become smaller than they were before. */
7573
7574 static int
7575 x_compute_min_glyph_bounds (f)
7576 struct frame *f;
7577 {
7578 int i;
7579 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
7580 MacFontStruct *font;
7581 int old_width = dpyinfo->smallest_char_width;
7582 int old_height = dpyinfo->smallest_font_height;
7583
7584 dpyinfo->smallest_font_height = 100000;
7585 dpyinfo->smallest_char_width = 100000;
7586
7587 for (i = 0; i < dpyinfo->n_fonts; ++i)
7588 if (dpyinfo->font_table[i].name)
7589 {
7590 struct font_info *fontp = dpyinfo->font_table + i;
7591 int w, h;
7592
7593 font = (MacFontStruct *) fontp->font;
7594 xassert (font != (MacFontStruct *) ~0);
7595 x_font_min_bounds (font, &w, &h);
7596
7597 dpyinfo->smallest_font_height = min (dpyinfo->smallest_font_height, h);
7598 dpyinfo->smallest_char_width = min (dpyinfo->smallest_char_width, w);
7599 }
7600
7601 xassert (dpyinfo->smallest_char_width > 0
7602 && dpyinfo->smallest_font_height > 0);
7603
7604 return (dpyinfo->n_fonts == 1
7605 || dpyinfo->smallest_char_width < old_width
7606 || dpyinfo->smallest_font_height < old_height);
7607 }
7608
7609
7610 /* Determine whether given string is a fully-specified XLFD: all 14
7611 fields are present, none is '*'. */
7612
7613 static int
7614 is_fully_specified_xlfd (char *p)
7615 {
7616 int i;
7617 char *q;
7618
7619 if (*p != '-')
7620 return 0;
7621
7622 for (i = 0; i < 13; i++)
7623 {
7624 q = strchr (p + 1, '-');
7625 if (q == NULL)
7626 return 0;
7627 if (q - p == 2 && *(p + 1) == '*')
7628 return 0;
7629 p = q;
7630 }
7631
7632 if (strchr (p + 1, '-') != NULL)
7633 return 0;
7634
7635 if (*(p + 1) == '*' && *(p + 2) == '\0')
7636 return 0;
7637
7638 return 1;
7639 }
7640
7641
7642 /* XLoadQueryFont creates and returns an internal representation for a
7643 font in a MacFontStruct struct. There is really no concept
7644 corresponding to "loading" a font on the Mac. But we check its
7645 existence and find the font number and all other information for it
7646 and store them in the returned MacFontStruct. */
7647
7648 static MacFontStruct *
7649 XLoadQueryFont (Display *dpy, char *fontname)
7650 {
7651 int size;
7652 char *name;
7653 Str255 family;
7654 Str31 charset;
7655 SInt16 fontnum;
7656 #if USE_ATSUI
7657 static ATSUFontID font_id;
7658 ATSUStyle mac_style = NULL;
7659 #endif
7660 Style fontface;
7661 #if TARGET_API_MAC_CARBON
7662 TextEncoding encoding;
7663 int scriptcode;
7664 #else
7665 short scriptcode;
7666 #endif
7667 MacFontStruct *font;
7668 XCharStruct *space_bounds = NULL, *pcm;
7669
7670 if (is_fully_specified_xlfd (fontname))
7671 name = fontname;
7672 else
7673 {
7674 Lisp_Object matched_fonts;
7675
7676 matched_fonts = mac_do_list_fonts (fontname, 1);
7677 if (NILP (matched_fonts))
7678 return NULL;
7679 name = SDATA (XCAR (matched_fonts));
7680 }
7681
7682 if (parse_x_font_name (name, family, &size, &fontface, charset) == 0)
7683 return NULL;
7684
7685 #if USE_ATSUI
7686 if (strcmp (charset, "iso10646-1") == 0) /* XXX */
7687 {
7688 OSErr err;
7689 ATSUAttributeTag tags[] = {kATSUFontTag, kATSUSizeTag,
7690 kATSUQDBoldfaceTag, kATSUQDItalicTag};
7691 ByteCount sizes[] = {sizeof (ATSUFontID), sizeof (Fixed),
7692 sizeof (Boolean), sizeof (Boolean)};
7693 static Fixed size_fixed;
7694 static Boolean bold_p, italic_p;
7695 ATSUAttributeValuePtr values[] = {&font_id, &size_fixed,
7696 &bold_p, &italic_p};
7697 ATSUFontFeatureType types[] = {kAllTypographicFeaturesType,
7698 kDiacriticsType};
7699 ATSUFontFeatureSelector selectors[] = {kAllTypeFeaturesOffSelector,
7700 kDecomposeDiacriticsSelector};
7701 Lisp_Object font_id_cons;
7702
7703 font_id_cons = Fgethash (make_unibyte_string (family, strlen (family)),
7704 atsu_font_id_hash, Qnil);
7705 if (NILP (font_id_cons))
7706 return NULL;
7707 font_id = cons_to_long (font_id_cons);
7708 size_fixed = Long2Fix (size);
7709 bold_p = (fontface & bold) != 0;
7710 italic_p = (fontface & italic) != 0;
7711 err = ATSUCreateStyle (&mac_style);
7712 if (err != noErr)
7713 return NULL;
7714 err = ATSUSetFontFeatures (mac_style, sizeof (types) / sizeof (types[0]),
7715 types, selectors);
7716 if (err != noErr)
7717 return NULL;
7718 err = ATSUSetAttributes (mac_style, sizeof (tags) / sizeof (tags[0]),
7719 tags, sizes, values);
7720 fontnum = -1;
7721 scriptcode = kTextEncodingMacUnicode;
7722 }
7723 else
7724 #endif
7725 {
7726 Lisp_Object tmp = Fassoc (build_string (family), fm_font_family_alist);
7727
7728 if (NILP (tmp))
7729 return NULL;
7730 fontnum = XINT (XCDR (tmp));
7731 #if TARGET_API_MAC_CARBON
7732 if (FMGetFontFamilyTextEncoding (fontnum, &encoding) != noErr)
7733 return NULL;
7734 scriptcode = GetTextEncodingBase (encoding);
7735 #else
7736 scriptcode = FontToScript (fontnum);
7737 #endif
7738 }
7739
7740 font = (MacFontStruct *) xmalloc (sizeof (struct MacFontStruct));
7741
7742 font->mac_fontnum = fontnum;
7743 font->mac_fontsize = size;
7744 font->mac_fontface = fontface;
7745 font->mac_scriptcode = scriptcode;
7746 #if USE_ATSUI
7747 font->mac_style = mac_style;
7748 #if USE_CG_TEXT_DRAWING
7749 font->cg_font = NULL;
7750 font->cg_glyphs = NULL;
7751 #endif
7752 #endif
7753
7754 /* Apple Japanese (SJIS) font is listed as both
7755 "*-jisx0208.1983-sjis" (Japanese script) and "*-jisx0201.1976-0"
7756 (Roman script) in init_font_name_table (). The latter should be
7757 treated as a one-byte font. */
7758 if (scriptcode == smJapanese && strcmp (charset, "jisx0201.1976-0") == 0)
7759 font->mac_scriptcode = smRoman;
7760
7761 font->full_name = mac_to_x_fontname (family, size, fontface, charset);
7762
7763 #if USE_ATSUI
7764 if (font->mac_style)
7765 {
7766 OSErr err;
7767 UniChar c;
7768
7769 font->min_byte1 = 0;
7770 font->max_byte1 = 0xff;
7771 font->min_char_or_byte2 = 0;
7772 font->max_char_or_byte2 = 0xff;
7773
7774 font->bounds.rows = xmalloc (sizeof (XCharStructRow *) * 0x100);
7775 bzero (font->bounds.rows, sizeof (XCharStructRow *) * 0x100);
7776 font->bounds.rows[0] = xmalloc (sizeof (XCharStructRow));
7777 bzero (font->bounds.rows[0], sizeof (XCharStructRow));
7778
7779 #if USE_CG_TEXT_DRAWING
7780 {
7781 FMFontFamily font_family;
7782 FMFontStyle style;
7783 ATSFontRef ats_font;
7784
7785 err = FMGetFontFamilyInstanceFromFont (font_id, &font_family, &style);
7786 if (err == noErr)
7787 err = FMGetFontFromFontFamilyInstance (font_family, fontface,
7788 &font_id, &style);
7789 /* Use CG text drawing if italic/bold is not synthesized. */
7790 if (err == noErr && style == fontface)
7791 {
7792 ats_font = FMGetATSFontRefFromFont (font_id);
7793 font->cg_font = CGFontCreateWithPlatformFont (&ats_font);
7794 }
7795 }
7796
7797 if (font->cg_font)
7798 {
7799 font->cg_glyphs = xmalloc (sizeof (CGGlyph) * 0x100);
7800 bzero (font->cg_glyphs, sizeof (CGGlyph) * 0x100);
7801 }
7802 #endif
7803 space_bounds = font->bounds.rows[0]->per_char + 0x20;
7804 err = mac_query_char_extents (font->mac_style, 0x20,
7805 &font->ascent, &font->descent,
7806 space_bounds,
7807 #if USE_CG_TEXT_DRAWING
7808 (font->cg_glyphs ? font->cg_glyphs + 0x20
7809 : NULL)
7810 #else
7811 NULL
7812 #endif
7813 );
7814 if (err != noErr)
7815 {
7816 mac_unload_font (&one_mac_display_info, font);
7817 return NULL;
7818 }
7819 XCHARSTRUCTROW_SET_CHAR_VALID (font->bounds.rows[0], 0x20);
7820
7821 pcm = font->bounds.rows[0]->per_char;
7822 for (c = 0x21; c <= 0xff; c++)
7823 {
7824 if (c == 0xad)
7825 /* Soft hyphen is not supported in ATSUI. */
7826 continue;
7827 else if (c == 0x7f)
7828 {
7829 c = 0x9f;
7830 continue;
7831 }
7832
7833 mac_query_char_extents (font->mac_style, c, NULL, NULL, pcm + c,
7834 #if USE_CG_TEXT_DRAWING
7835 (font->cg_glyphs ? font->cg_glyphs + c
7836 : NULL)
7837 #else
7838 NULL
7839 #endif
7840 );
7841 XCHARSTRUCTROW_SET_CHAR_VALID (font->bounds.rows[0], c);
7842
7843 #if USE_CG_TEXT_DRAWING
7844 if (font->cg_glyphs && font->cg_glyphs[c] == 0)
7845 {
7846 /* Don't use CG text drawing if font substitution occurs in
7847 ASCII or Latin-1 characters. */
7848 CGFontRelease (font->cg_font);
7849 font->cg_font = NULL;
7850 xfree (font->cg_glyphs);
7851 font->cg_glyphs = NULL;
7852 }
7853 #endif
7854 }
7855 }
7856 else
7857 #endif
7858 {
7859 GrafPtr port;
7860 SInt16 old_fontnum, old_fontsize;
7861 Style old_fontface;
7862 FontInfo the_fontinfo;
7863 int is_two_byte_font;
7864
7865 /* Save the current font number used. */
7866 GetPort (&port);
7867 #if TARGET_API_MAC_CARBON
7868 old_fontnum = GetPortTextFont (port);
7869 old_fontsize = GetPortTextSize (port);
7870 old_fontface = GetPortTextFace (port);
7871 #else
7872 old_fontnum = port->txFont;
7873 old_fontsize = port->txSize;
7874 old_fontface = port->txFace;
7875 #endif
7876
7877 TextFont (fontnum);
7878 TextSize (size);
7879 TextFace (fontface);
7880
7881 GetFontInfo (&the_fontinfo);
7882
7883 font->ascent = the_fontinfo.ascent;
7884 font->descent = the_fontinfo.descent;
7885
7886 is_two_byte_font = (font->mac_scriptcode == smJapanese
7887 || font->mac_scriptcode == smTradChinese
7888 || font->mac_scriptcode == smSimpChinese
7889 || font->mac_scriptcode == smKorean);
7890
7891 if (is_two_byte_font)
7892 {
7893 int char_width;
7894
7895 font->min_byte1 = 0xa1;
7896 font->max_byte1 = 0xfe;
7897 font->min_char_or_byte2 = 0xa1;
7898 font->max_char_or_byte2 = 0xfe;
7899
7900 /* Use the width of an "ideographic space" of that font
7901 because the_fontinfo.widMax returns the wrong width for
7902 some fonts. */
7903 switch (font->mac_scriptcode)
7904 {
7905 case smJapanese:
7906 font->min_byte1 = 0x81;
7907 font->max_byte1 = 0xfc;
7908 font->min_char_or_byte2 = 0x40;
7909 font->max_char_or_byte2 = 0xfc;
7910 char_width = StringWidth("\p\x81\x40");
7911 break;
7912 case smTradChinese:
7913 font->min_char_or_byte2 = 0x40;
7914 char_width = StringWidth("\p\xa1\x40");
7915 break;
7916 case smSimpChinese:
7917 char_width = StringWidth("\p\xa1\xa1");
7918 break;
7919 case smKorean:
7920 char_width = StringWidth("\p\xa1\xa1");
7921 break;
7922 }
7923
7924 font->bounds.per_char = NULL;
7925
7926 if (fontface & italic)
7927 font->max_bounds.rbearing = char_width + 1;
7928 else
7929 font->max_bounds.rbearing = char_width;
7930 font->max_bounds.lbearing = 0;
7931 font->max_bounds.width = char_width;
7932 font->max_bounds.ascent = the_fontinfo.ascent;
7933 font->max_bounds.descent = the_fontinfo.descent;
7934
7935 font->min_bounds = font->max_bounds;
7936 }
7937 else
7938 {
7939 int c;
7940
7941 font->min_byte1 = font->max_byte1 = 0;
7942 font->min_char_or_byte2 = 0x20;
7943 font->max_char_or_byte2 = 0xff;
7944
7945 font->bounds.per_char =
7946 xmalloc (sizeof (XCharStruct) * (0xff - 0x20 + 1));
7947 bzero (font->bounds.per_char,
7948 sizeof (XCharStruct) * (0xff - 0x20 + 1));
7949
7950 space_bounds = font->bounds.per_char;
7951 mac_query_char_extents (NULL, 0x20, &font->ascent, &font->descent,
7952 space_bounds, NULL);
7953
7954 for (c = 0x21, pcm = space_bounds + 1; c <= 0xff; c++, pcm++)
7955 mac_query_char_extents (NULL, c, NULL, NULL, pcm, NULL);
7956 }
7957
7958 /* Restore previous font number, size and face. */
7959 TextFont (old_fontnum);
7960 TextSize (old_fontsize);
7961 TextFace (old_fontface);
7962 }
7963
7964 if (space_bounds)
7965 {
7966 int c;
7967
7968 font->min_bounds = font->max_bounds = *space_bounds;
7969 for (c = 0x21, pcm = space_bounds + 1; c <= 0x7f; c++, pcm++)
7970 if (pcm->width > 0)
7971 {
7972 font->min_bounds.lbearing = min (font->min_bounds.lbearing,
7973 pcm->lbearing);
7974 font->min_bounds.rbearing = min (font->min_bounds.rbearing,
7975 pcm->rbearing);
7976 font->min_bounds.width = min (font->min_bounds.width,
7977 pcm->width);
7978 font->min_bounds.ascent = min (font->min_bounds.ascent,
7979 pcm->ascent);
7980
7981 font->max_bounds.lbearing = max (font->max_bounds.lbearing,
7982 pcm->lbearing);
7983 font->max_bounds.rbearing = max (font->max_bounds.rbearing,
7984 pcm->rbearing);
7985 font->max_bounds.width = max (font->max_bounds.width,
7986 pcm->width);
7987 font->max_bounds.ascent = max (font->max_bounds.ascent,
7988 pcm->ascent);
7989 }
7990 if (
7991 #if USE_ATSUI
7992 font->mac_style == NULL &&
7993 #endif
7994 font->max_bounds.width == font->min_bounds.width
7995 && font->min_bounds.lbearing >= 0
7996 && font->max_bounds.rbearing <= font->max_bounds.width)
7997 {
7998 /* Fixed width and no overhangs. */
7999 xfree (font->bounds.per_char);
8000 font->bounds.per_char = NULL;
8001 }
8002 }
8003
8004 #if !defined (MAC_OS8) || USE_ATSUI
8005 /* AppKit and WebKit do some adjustment to the heights of Courier,
8006 Helvetica, and Times. This only works on the environments where
8007 srcCopy text transfer mode is never used. */
8008 if (
8009 #ifdef MAC_OS8 /* implies USE_ATSUI */
8010 font->mac_style &&
8011 #endif
8012 (strcmp (family, "courier") == 0 || strcmp (family, "helvetica") == 0
8013 || strcmp (family, "times") == 0))
8014 font->ascent += (font->ascent + font->descent) * .15 + 0.5;
8015 #endif
8016
8017 return font;
8018 }
8019
8020
8021 void
8022 mac_unload_font (dpyinfo, font)
8023 struct mac_display_info *dpyinfo;
8024 XFontStruct *font;
8025 {
8026 xfree (font->full_name);
8027 #if USE_ATSUI
8028 if (font->mac_style)
8029 {
8030 int i;
8031
8032 for (i = font->min_byte1; i <= font->max_byte1; i++)
8033 if (font->bounds.rows[i])
8034 xfree (font->bounds.rows[i]);
8035 xfree (font->bounds.rows);
8036 ATSUDisposeStyle (font->mac_style);
8037 }
8038 else
8039 #endif
8040 if (font->bounds.per_char)
8041 xfree (font->bounds.per_char);
8042 #if USE_CG_TEXT_DRAWING
8043 if (font->cg_font)
8044 CGFontRelease (font->cg_font);
8045 if (font->cg_glyphs)
8046 xfree (font->cg_glyphs);
8047 #endif
8048 xfree (font);
8049 }
8050
8051
8052 /* Load font named FONTNAME of the size SIZE for frame F, and return a
8053 pointer to the structure font_info while allocating it dynamically.
8054 If SIZE is 0, load any size of font.
8055 If loading is failed, return NULL. */
8056
8057 struct font_info *
8058 x_load_font (f, fontname, size)
8059 struct frame *f;
8060 register char *fontname;
8061 int size;
8062 {
8063 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
8064 Lisp_Object font_names;
8065
8066 /* Get a list of all the fonts that match this name. Once we
8067 have a list of matching fonts, we compare them against the fonts
8068 we already have by comparing names. */
8069 font_names = x_list_fonts (f, build_string (fontname), size, 1);
8070
8071 if (!NILP (font_names))
8072 {
8073 Lisp_Object tail;
8074 int i;
8075
8076 for (i = 0; i < dpyinfo->n_fonts; i++)
8077 for (tail = font_names; CONSP (tail); tail = XCDR (tail))
8078 if (dpyinfo->font_table[i].name
8079 && (!strcmp (dpyinfo->font_table[i].name,
8080 SDATA (XCAR (tail)))
8081 || !strcmp (dpyinfo->font_table[i].full_name,
8082 SDATA (XCAR (tail)))))
8083 return (dpyinfo->font_table + i);
8084 }
8085 else
8086 return NULL;
8087
8088 /* Load the font and add it to the table. */
8089 {
8090 struct MacFontStruct *font;
8091 struct font_info *fontp;
8092 int i;
8093
8094 fontname = (char *) SDATA (XCAR (font_names));
8095
8096 BLOCK_INPUT;
8097 font = (MacFontStruct *) XLoadQueryFont (FRAME_MAC_DISPLAY (f), fontname);
8098 UNBLOCK_INPUT;
8099 if (!font)
8100 return NULL;
8101
8102 /* Find a free slot in the font table. */
8103 for (i = 0; i < dpyinfo->n_fonts; ++i)
8104 if (dpyinfo->font_table[i].name == NULL)
8105 break;
8106
8107 /* If no free slot found, maybe enlarge the font table. */
8108 if (i == dpyinfo->n_fonts
8109 && dpyinfo->n_fonts == dpyinfo->font_table_size)
8110 {
8111 int sz;
8112 dpyinfo->font_table_size = max (16, 2 * dpyinfo->font_table_size);
8113 sz = dpyinfo->font_table_size * sizeof *dpyinfo->font_table;
8114 dpyinfo->font_table
8115 = (struct font_info *) xrealloc (dpyinfo->font_table, sz);
8116 }
8117
8118 fontp = dpyinfo->font_table + i;
8119 if (i == dpyinfo->n_fonts)
8120 ++dpyinfo->n_fonts;
8121
8122 /* Now fill in the slots of *FONTP. */
8123 BLOCK_INPUT;
8124 bzero (fontp, sizeof (*fontp));
8125 fontp->font = font;
8126 fontp->font_idx = i;
8127 fontp->charset = -1; /* fs_load_font sets it. */
8128 fontp->name = (char *) xmalloc (strlen (fontname) + 1);
8129 bcopy (fontname, fontp->name, strlen (fontname) + 1);
8130
8131 if (font->min_bounds.width == font->max_bounds.width)
8132 {
8133 /* Fixed width font. */
8134 fontp->average_width = fontp->space_width = font->min_bounds.width;
8135 }
8136 else
8137 {
8138 XChar2b char2b;
8139 XCharStruct *pcm;
8140
8141 char2b.byte1 = 0x00, char2b.byte2 = 0x20;
8142 pcm = mac_per_char_metric (font, &char2b, 0);
8143 if (pcm)
8144 fontp->space_width = pcm->width;
8145 else
8146 fontp->space_width = FONT_WIDTH (font);
8147
8148 if (pcm)
8149 {
8150 int width = pcm->width;
8151 for (char2b.byte2 = 33; char2b.byte2 <= 126; char2b.byte2++)
8152 if ((pcm = mac_per_char_metric (font, &char2b, 0)) != NULL)
8153 width += pcm->width;
8154 fontp->average_width = width / 95;
8155 }
8156 else
8157 fontp->average_width = FONT_WIDTH (font);
8158 }
8159
8160 fontp->full_name = (char *) xmalloc (strlen (font->full_name) + 1);
8161 bcopy (font->full_name, fontp->full_name, strlen (font->full_name) + 1);
8162
8163 fontp->size = font->max_bounds.width;
8164 fontp->height = FONT_HEIGHT (font);
8165 {
8166 /* For some font, ascent and descent in max_bounds field is
8167 larger than the above value. */
8168 int max_height = font->max_bounds.ascent + font->max_bounds.descent;
8169 if (max_height > fontp->height)
8170 fontp->height = max_height;
8171 }
8172
8173 /* MAC_TODO: The script encoding is irrelevant in unicode? */
8174 /* The slot `encoding' specifies how to map a character
8175 code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
8176 the font code-points (0:0x20..0x7F, 1:0xA0..0xFF), or
8177 (0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF,
8178 2:0xA020..0xFF7F). For the moment, we don't know which charset
8179 uses this font. So, we set information in fontp->encoding_type
8180 which is never used by any charset. If mapping can't be
8181 decided, set FONT_ENCODING_NOT_DECIDED. */
8182 if (font->mac_scriptcode == smJapanese)
8183 fontp->encoding_type = 4;
8184 else
8185 {
8186 fontp->encoding_type
8187 = (font->max_byte1 == 0
8188 /* 1-byte font */
8189 ? (font->min_char_or_byte2 < 0x80
8190 ? (font->max_char_or_byte2 < 0x80
8191 ? 0 /* 0x20..0x7F */
8192 : FONT_ENCODING_NOT_DECIDED) /* 0x20..0xFF */
8193 : 1) /* 0xA0..0xFF */
8194 /* 2-byte font */
8195 : (font->min_byte1 < 0x80
8196 ? (font->max_byte1 < 0x80
8197 ? (font->min_char_or_byte2 < 0x80
8198 ? (font->max_char_or_byte2 < 0x80
8199 ? 0 /* 0x2020..0x7F7F */
8200 : FONT_ENCODING_NOT_DECIDED) /* 0x2020..0x7FFF */
8201 : 3) /* 0x20A0..0x7FFF */
8202 : FONT_ENCODING_NOT_DECIDED) /* 0x20??..0xA0?? */
8203 : (font->min_char_or_byte2 < 0x80
8204 ? (font->max_char_or_byte2 < 0x80
8205 ? 2 /* 0xA020..0xFF7F */
8206 : FONT_ENCODING_NOT_DECIDED) /* 0xA020..0xFFFF */
8207 : 1))); /* 0xA0A0..0xFFFF */
8208 }
8209
8210 #if 0 /* MAC_TODO: fill these out with more reasonably values */
8211 fontp->baseline_offset
8212 = (XGetFontProperty (font, dpyinfo->Xatom_MULE_BASELINE_OFFSET, &value)
8213 ? (long) value : 0);
8214 fontp->relative_compose
8215 = (XGetFontProperty (font, dpyinfo->Xatom_MULE_RELATIVE_COMPOSE, &value)
8216 ? (long) value : 0);
8217 fontp->default_ascent
8218 = (XGetFontProperty (font, dpyinfo->Xatom_MULE_DEFAULT_ASCENT, &value)
8219 ? (long) value : 0);
8220 #else
8221 fontp->baseline_offset = 0;
8222 fontp->relative_compose = 0;
8223 fontp->default_ascent = 0;
8224 #endif
8225
8226 /* Set global flag fonts_changed_p to non-zero if the font loaded
8227 has a character with a smaller width than any other character
8228 before, or if the font loaded has a smaller height than any
8229 other font loaded before. If this happens, it will make a
8230 glyph matrix reallocation necessary. */
8231 fonts_changed_p |= x_compute_min_glyph_bounds (f);
8232 UNBLOCK_INPUT;
8233 return fontp;
8234 }
8235 }
8236
8237
8238 /* Return a pointer to struct font_info of a font named FONTNAME for
8239 frame F. If no such font is loaded, return NULL. */
8240
8241 struct font_info *
8242 x_query_font (f, fontname)
8243 struct frame *f;
8244 register char *fontname;
8245 {
8246 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
8247 int i;
8248
8249 for (i = 0; i < dpyinfo->n_fonts; i++)
8250 if (dpyinfo->font_table[i].name
8251 && (!strcmp (dpyinfo->font_table[i].name, fontname)
8252 || !strcmp (dpyinfo->font_table[i].full_name, fontname)))
8253 return (dpyinfo->font_table + i);
8254 return NULL;
8255 }
8256
8257
8258 /* Find a CCL program for a font specified by FONTP, and set the member
8259 `encoder' of the structure. */
8260
8261 void
8262 x_find_ccl_program (fontp)
8263 struct font_info *fontp;
8264 {
8265 Lisp_Object list, elt;
8266
8267 for (list = Vfont_ccl_encoder_alist; CONSP (list); list = XCDR (list))
8268 {
8269 elt = XCAR (list);
8270 if (CONSP (elt)
8271 && STRINGP (XCAR (elt))
8272 && (fast_c_string_match_ignore_case (XCAR (elt), fontp->name)
8273 >= 0))
8274 break;
8275 }
8276 if (! NILP (list))
8277 {
8278 struct ccl_program *ccl
8279 = (struct ccl_program *) xmalloc (sizeof (struct ccl_program));
8280
8281 if (setup_ccl_program (ccl, XCDR (elt)) < 0)
8282 xfree (ccl);
8283 else
8284 fontp->font_encoder = ccl;
8285 }
8286 }
8287
8288
8289 \f
8290 /* The Mac Event loop code */
8291
8292 #if !TARGET_API_MAC_CARBON
8293 #include <Events.h>
8294 #include <Quickdraw.h>
8295 #include <Balloons.h>
8296 #include <Devices.h>
8297 #include <Fonts.h>
8298 #include <Gestalt.h>
8299 #include <Menus.h>
8300 #include <Processes.h>
8301 #include <Sound.h>
8302 #include <ToolUtils.h>
8303 #include <TextUtils.h>
8304 #include <Dialogs.h>
8305 #include <Script.h>
8306 #include <Types.h>
8307 #include <Resources.h>
8308
8309 #if __MWERKS__
8310 #include <unix.h>
8311 #endif
8312 #endif /* ! TARGET_API_MAC_CARBON */
8313
8314 #define M_APPLE 128
8315 #define I_ABOUT 1
8316
8317 #define WINDOW_RESOURCE 128
8318 #define TERM_WINDOW_RESOURCE 129
8319
8320 #define DEFAULT_NUM_COLS 80
8321
8322 #define MIN_DOC_SIZE 64
8323 #define MAX_DOC_SIZE 32767
8324
8325 #define EXTRA_STACK_ALLOC (256 * 1024)
8326
8327 #define ARGV_STRING_LIST_ID 129
8328 #define ABOUT_ALERT_ID 128
8329 #define RAM_TOO_LARGE_ALERT_ID 129
8330
8331 /* Contains the string "reverse", which is a constant for mouse button emu.*/
8332 Lisp_Object Qreverse;
8333
8334
8335 /* Modifier associated with the control key, or nil to ignore. */
8336 Lisp_Object Vmac_control_modifier;
8337
8338 /* Modifier associated with the option key, or nil to ignore. */
8339 Lisp_Object Vmac_option_modifier;
8340
8341 /* Modifier associated with the command key, or nil to ignore. */
8342 Lisp_Object Vmac_command_modifier;
8343
8344 /* Modifier associated with the function key, or nil to ignore. */
8345 Lisp_Object Vmac_function_modifier;
8346
8347 /* True if the option and command modifiers should be used to emulate
8348 a three button mouse */
8349 Lisp_Object Vmac_emulate_three_button_mouse;
8350
8351 #if USE_CARBON_EVENTS
8352 /* Non-zero if the mouse wheel button (i.e. button 4) should map to
8353 mouse-2, instead of mouse-3. */
8354 int mac_wheel_button_is_mouse_2;
8355
8356 /* If non-zero, the Mac "Command" key is passed on to the Mac Toolbox
8357 for processing before Emacs sees it. */
8358 int mac_pass_command_to_system;
8359
8360 /* If non-zero, the Mac "Control" key is passed on to the Mac Toolbox
8361 for processing before Emacs sees it. */
8362 int mac_pass_control_to_system;
8363 #endif
8364
8365 /* Points to the variable `inev' in the function XTread_socket. It is
8366 used for passing an input event to the function back from
8367 Carbon/Apple event handlers. */
8368 static struct input_event *read_socket_inev = NULL;
8369
8370 Point saved_menu_event_location;
8371
8372 /* Apple Events */
8373 #if USE_CARBON_EVENTS
8374 static Lisp_Object Qhicommand;
8375 #endif
8376 extern int mac_ready_for_apple_events;
8377 extern Lisp_Object Qundefined;
8378 extern void init_apple_event_handler P_ ((void));
8379 extern void mac_find_apple_event_spec P_ ((AEEventClass, AEEventID,
8380 Lisp_Object *, Lisp_Object *,
8381 Lisp_Object *));
8382 extern OSErr init_coercion_handler P_ ((void));
8383
8384 #if TARGET_API_MAC_CARBON
8385 /* Drag and Drop */
8386 static pascal OSErr mac_do_track_drag (DragTrackingMessage, WindowPtr, void*, DragReference);
8387 static pascal OSErr mac_do_receive_drag (WindowPtr, void*, DragReference);
8388 static DragTrackingHandlerUPP mac_do_track_dragUPP = NULL;
8389 static DragReceiveHandlerUPP mac_do_receive_dragUPP = NULL;
8390 #endif
8391
8392 #if USE_CARBON_EVENTS
8393 #ifdef MAC_OSX
8394 extern void init_service_handler ();
8395 static Lisp_Object Qservices, Qpaste, Qperform;
8396 #endif
8397 /* Window Event Handler */
8398 static pascal OSStatus mac_handle_window_event (EventHandlerCallRef,
8399 EventRef, void *);
8400 #endif
8401 OSErr install_window_handler (WindowPtr);
8402
8403 extern void init_emacs_passwd_dir ();
8404 extern int emacs_main (int, char **, char **);
8405
8406 extern void initialize_applescript();
8407 extern void terminate_applescript();
8408
8409 static unsigned int
8410 #if USE_CARBON_EVENTS
8411 mac_to_emacs_modifiers (UInt32 mods)
8412 #else
8413 mac_to_emacs_modifiers (EventModifiers mods)
8414 #endif
8415 {
8416 unsigned int result = 0;
8417 if (mods & shiftKey)
8418 result |= shift_modifier;
8419
8420 /* Deactivated to simplify configuration:
8421 if Vmac_option_modifier is non-NIL, we fully process the Option
8422 key. Otherwise, we only process it if an additional Ctrl or Command
8423 is pressed. That way the system may convert the character to a
8424 composed one.
8425 if ((mods & optionKey) &&
8426 (( !NILP(Vmac_option_modifier) ||
8427 ((mods & cmdKey) || (mods & controlKey))))) */
8428
8429 if (!NILP (Vmac_option_modifier) && (mods & optionKey)) {
8430 Lisp_Object val = Fget(Vmac_option_modifier, Qmodifier_value);
8431 if (INTEGERP(val))
8432 result |= XUINT(val);
8433 }
8434 if (!NILP (Vmac_command_modifier) && (mods & cmdKey)) {
8435 Lisp_Object val = Fget(Vmac_command_modifier, Qmodifier_value);
8436 if (INTEGERP(val))
8437 result |= XUINT(val);
8438 }
8439 if (!NILP (Vmac_control_modifier) && (mods & controlKey)) {
8440 Lisp_Object val = Fget(Vmac_control_modifier, Qmodifier_value);
8441 if (INTEGERP(val))
8442 result |= XUINT(val);
8443 }
8444
8445 #ifdef MAC_OSX
8446 if (!NILP (Vmac_function_modifier) && (mods & kEventKeyModifierFnMask)) {
8447 Lisp_Object val = Fget(Vmac_function_modifier, Qmodifier_value);
8448 if (INTEGERP(val))
8449 result |= XUINT(val);
8450 }
8451 #endif
8452
8453 return result;
8454 }
8455
8456 static int
8457 mac_get_emulated_btn ( UInt32 modifiers )
8458 {
8459 int result = 0;
8460 if (!NILP (Vmac_emulate_three_button_mouse)) {
8461 int cmdIs3 = !EQ (Vmac_emulate_three_button_mouse, Qreverse);
8462 if (modifiers & cmdKey)
8463 result = cmdIs3 ? 2 : 1;
8464 else if (modifiers & optionKey)
8465 result = cmdIs3 ? 1 : 2;
8466 }
8467 return result;
8468 }
8469
8470 #if USE_CARBON_EVENTS
8471 /* Obtains the event modifiers from the event ref and then calls
8472 mac_to_emacs_modifiers. */
8473 static UInt32
8474 mac_event_to_emacs_modifiers (EventRef eventRef)
8475 {
8476 UInt32 mods = 0;
8477 GetEventParameter (eventRef, kEventParamKeyModifiers, typeUInt32, NULL,
8478 sizeof (UInt32), NULL, &mods);
8479 if (!NILP (Vmac_emulate_three_button_mouse) &&
8480 GetEventClass(eventRef) == kEventClassMouse)
8481 {
8482 mods &= ~(optionKey | cmdKey);
8483 }
8484 return mac_to_emacs_modifiers (mods);
8485 }
8486
8487 /* Given an event ref, return the code to use for the mouse button
8488 code in the emacs input_event. */
8489 static int
8490 mac_get_mouse_btn (EventRef ref)
8491 {
8492 EventMouseButton result = kEventMouseButtonPrimary;
8493 GetEventParameter (ref, kEventParamMouseButton, typeMouseButton, NULL,
8494 sizeof (EventMouseButton), NULL, &result);
8495 switch (result)
8496 {
8497 case kEventMouseButtonPrimary:
8498 if (NILP (Vmac_emulate_three_button_mouse))
8499 return 0;
8500 else {
8501 UInt32 mods = 0;
8502 GetEventParameter (ref, kEventParamKeyModifiers, typeUInt32, NULL,
8503 sizeof (UInt32), NULL, &mods);
8504 return mac_get_emulated_btn(mods);
8505 }
8506 case kEventMouseButtonSecondary:
8507 return mac_wheel_button_is_mouse_2 ? 2 : 1;
8508 case kEventMouseButtonTertiary:
8509 case 4: /* 4 is the number for the mouse wheel button */
8510 return mac_wheel_button_is_mouse_2 ? 1 : 2;
8511 default:
8512 return 0;
8513 }
8514 }
8515
8516 /* Normally, ConvertEventRefToEventRecord will correctly handle all
8517 events. However the click of the mouse wheel is not converted to a
8518 mouseDown or mouseUp event. Likewise for dead key down events.
8519 This calls ConvertEventRef, but then checks to see if it is a mouse
8520 up/down, or a dead key down carbon event that has not been
8521 converted, and if so, converts it by hand (to be picked up in the
8522 XTread_socket loop). */
8523 static Boolean mac_convert_event_ref (EventRef eventRef, EventRecord *eventRec)
8524 {
8525 OSStatus err;
8526 Boolean result = ConvertEventRefToEventRecord (eventRef, eventRec);
8527
8528 if (result)
8529 return result;
8530
8531 switch (GetEventClass (eventRef))
8532 {
8533 case kEventClassMouse:
8534 switch (GetEventKind (eventRef))
8535 {
8536 case kEventMouseDown:
8537 eventRec->what = mouseDown;
8538 result = 1;
8539 break;
8540
8541 case kEventMouseUp:
8542 eventRec->what = mouseUp;
8543 result = 1;
8544 break;
8545
8546 default:
8547 break;
8548 }
8549 break;
8550
8551 case kEventClassKeyboard:
8552 switch (GetEventKind (eventRef))
8553 {
8554 case kEventRawKeyDown:
8555 {
8556 unsigned char char_codes;
8557 UInt32 key_code;
8558
8559 err = GetEventParameter (eventRef, kEventParamKeyMacCharCodes,
8560 typeChar, NULL, sizeof (char),
8561 NULL, &char_codes);
8562 if (err == noErr)
8563 err = GetEventParameter (eventRef, kEventParamKeyCode,
8564 typeUInt32, NULL, sizeof (UInt32),
8565 NULL, &key_code);
8566 if (err == noErr)
8567 {
8568 eventRec->what = keyDown;
8569 eventRec->message = char_codes | ((key_code & 0xff) << 8);
8570 result = 1;
8571 }
8572 }
8573 break;
8574
8575 default:
8576 break;
8577 }
8578 break;
8579
8580 default:
8581 break;
8582 }
8583
8584 if (result)
8585 {
8586 /* Need where and when. */
8587 UInt32 mods = 0;
8588
8589 GetEventParameter (eventRef, kEventParamMouseLocation, typeQDPoint,
8590 NULL, sizeof (Point), NULL, &eventRec->where);
8591 /* Use two step process because new event modifiers are 32-bit
8592 and old are 16-bit. Currently, only loss is NumLock & Fn. */
8593 GetEventParameter (eventRef, kEventParamKeyModifiers, typeUInt32,
8594 NULL, sizeof (UInt32), NULL, &mods);
8595 eventRec->modifiers = mods;
8596
8597 eventRec->when = EventTimeToTicks (GetEventTime (eventRef));
8598 }
8599
8600 return result;
8601 }
8602
8603 #endif
8604
8605 #ifdef MAC_OS8
8606 static void
8607 do_get_menus (void)
8608 {
8609 Handle menubar_handle;
8610 MenuHandle menu_handle;
8611
8612 menubar_handle = GetNewMBar (128);
8613 if(menubar_handle == NULL)
8614 abort ();
8615 SetMenuBar (menubar_handle);
8616 DrawMenuBar ();
8617
8618 #if !TARGET_API_MAC_CARBON
8619 menu_handle = GetMenuHandle (M_APPLE);
8620 if(menu_handle != NULL)
8621 AppendResMenu (menu_handle,'DRVR');
8622 else
8623 abort ();
8624 #endif
8625 }
8626
8627
8628 static void
8629 do_init_managers (void)
8630 {
8631 #if !TARGET_API_MAC_CARBON
8632 InitGraf (&qd.thePort);
8633 InitFonts ();
8634 FlushEvents (everyEvent, 0);
8635 InitWindows ();
8636 InitMenus ();
8637 TEInit ();
8638 InitDialogs (NULL);
8639 #endif /* !TARGET_API_MAC_CARBON */
8640 InitCursor ();
8641
8642 #if !TARGET_API_MAC_CARBON
8643 /* set up some extra stack space for use by emacs */
8644 SetApplLimit ((Ptr) ((long) GetApplLimit () - EXTRA_STACK_ALLOC));
8645
8646 /* MaxApplZone must be called for AppleScript to execute more
8647 complicated scripts */
8648 MaxApplZone ();
8649 MoreMasters ();
8650 #endif /* !TARGET_API_MAC_CARBON */
8651 }
8652
8653 static void
8654 do_check_ram_size (void)
8655 {
8656 SInt32 physical_ram_size, logical_ram_size;
8657
8658 if (Gestalt (gestaltPhysicalRAMSize, &physical_ram_size) != noErr
8659 || Gestalt (gestaltLogicalRAMSize, &logical_ram_size) != noErr
8660 || physical_ram_size > (1 << VALBITS)
8661 || logical_ram_size > (1 << VALBITS))
8662 {
8663 StopAlert (RAM_TOO_LARGE_ALERT_ID, NULL);
8664 exit (1);
8665 }
8666 }
8667 #endif /* MAC_OS8 */
8668
8669 static void
8670 do_window_update (WindowPtr win)
8671 {
8672 struct frame *f = mac_window_to_frame (win);
8673
8674 BeginUpdate (win);
8675
8676 /* The tooltip has been drawn already. Avoid the SET_FRAME_GARBAGED
8677 below. */
8678 if (win != tip_window)
8679 {
8680 if (f->async_visible == 0)
8681 {
8682 /* Update events may occur when a frame gets iconified. */
8683 #if 0
8684 f->async_visible = 1;
8685 f->async_iconified = 0;
8686 SET_FRAME_GARBAGED (f);
8687 #endif
8688 }
8689 else
8690 {
8691 Rect r;
8692 #if TARGET_API_MAC_CARBON
8693 RgnHandle region = NewRgn ();
8694
8695 GetPortVisibleRegion (GetWindowPort (win), region);
8696 GetRegionBounds (region, &r);
8697 expose_frame (f, r.left, r.top, r.right - r.left, r.bottom - r.top);
8698 UpdateControls (win, region);
8699 DisposeRgn (region);
8700 #else
8701 r = (*win->visRgn)->rgnBBox;
8702 expose_frame (f, r.left, r.top, r.right - r.left, r.bottom - r.top);
8703 UpdateControls (win, win->visRgn);
8704 #endif
8705 }
8706 }
8707
8708 EndUpdate (win);
8709 }
8710
8711 static int
8712 is_emacs_window (WindowPtr win)
8713 {
8714 Lisp_Object tail, frame;
8715
8716 if (!win)
8717 return 0;
8718
8719 FOR_EACH_FRAME (tail, frame)
8720 if (FRAME_MAC_P (XFRAME (frame)))
8721 if (FRAME_MAC_WINDOW (XFRAME (frame)) == win)
8722 return 1;
8723
8724 return 0;
8725 }
8726
8727 static void
8728 do_app_resume ()
8729 {
8730 /* Window-activate events will do the job. */
8731 }
8732
8733 static void
8734 do_app_suspend ()
8735 {
8736 /* Window-deactivate events will do the job. */
8737 }
8738
8739
8740 static void
8741 do_apple_menu (SInt16 menu_item)
8742 {
8743 #if !TARGET_API_MAC_CARBON
8744 Str255 item_name;
8745 SInt16 da_driver_refnum;
8746
8747 if (menu_item == I_ABOUT)
8748 NoteAlert (ABOUT_ALERT_ID, NULL);
8749 else
8750 {
8751 GetMenuItemText (GetMenuHandle (M_APPLE), menu_item, item_name);
8752 da_driver_refnum = OpenDeskAcc (item_name);
8753 }
8754 #endif /* !TARGET_API_MAC_CARBON */
8755 }
8756
8757 void
8758 do_menu_choice (SInt32 menu_choice)
8759 {
8760 SInt16 menu_id, menu_item;
8761
8762 menu_id = HiWord (menu_choice);
8763 menu_item = LoWord (menu_choice);
8764
8765 switch (menu_id)
8766 {
8767 case 0:
8768 break;
8769
8770 case M_APPLE:
8771 do_apple_menu (menu_item);
8772 break;
8773
8774 default:
8775 {
8776 struct frame *f = mac_focus_frame (&one_mac_display_info);
8777 MenuHandle menu = GetMenuHandle (menu_id);
8778 if (menu)
8779 {
8780 UInt32 refcon;
8781
8782 GetMenuItemRefCon (menu, menu_item, &refcon);
8783 menubar_selection_callback (f, refcon);
8784 }
8785 }
8786 }
8787
8788 HiliteMenu (0);
8789 }
8790
8791
8792 /* Handle drags in size box. Based on code contributed by Ben
8793 Mesander and IM - Window Manager A. */
8794
8795 static void
8796 do_grow_window (WindowPtr w, EventRecord *e)
8797 {
8798 Rect limit_rect;
8799 int rows, columns, width, height;
8800 struct frame *f = mac_window_to_frame (w);
8801 XSizeHints *size_hints = FRAME_SIZE_HINTS (f);
8802 int min_width = MIN_DOC_SIZE, min_height = MIN_DOC_SIZE;
8803 #if TARGET_API_MAC_CARBON
8804 Rect new_rect;
8805 #else
8806 long grow_size;
8807 #endif
8808
8809 if (size_hints->flags & PMinSize)
8810 {
8811 min_width = size_hints->min_width;
8812 min_height = size_hints->min_height;
8813 }
8814 SetRect (&limit_rect, min_width, min_height, MAX_DOC_SIZE, MAX_DOC_SIZE);
8815
8816 #if TARGET_API_MAC_CARBON
8817 if (!ResizeWindow (w, e->where, &limit_rect, &new_rect))
8818 return;
8819 height = new_rect.bottom - new_rect.top;
8820 width = new_rect.right - new_rect.left;
8821 #else
8822 grow_size = GrowWindow (w, e->where, &limit_rect);
8823 /* see if it really changed size */
8824 if (grow_size == 0)
8825 return;
8826 height = HiWord (grow_size);
8827 width = LoWord (grow_size);
8828 #endif
8829
8830 if (width != FRAME_PIXEL_WIDTH (f)
8831 || height != FRAME_PIXEL_HEIGHT (f))
8832 {
8833 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, height);
8834 columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, width);
8835
8836 x_set_window_size (f, 0, columns, rows);
8837 }
8838 }
8839
8840
8841 /* Handle clicks in zoom box. Calculation of "standard state" based
8842 on code in IM - Window Manager A and code contributed by Ben
8843 Mesander. The standard state of an Emacs window is 80-characters
8844 wide (DEFAULT_NUM_COLS) and as tall as will fit on the screen. */
8845
8846 static void
8847 do_zoom_window (WindowPtr w, int zoom_in_or_out)
8848 {
8849 Rect zoom_rect, port_rect;
8850 int columns, rows, width, height;
8851 struct frame *f = mac_window_to_frame (w);
8852 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
8853 #if TARGET_API_MAC_CARBON
8854 Point standard_size;
8855
8856 standard_size.h = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, DEFAULT_NUM_COLS);
8857 standard_size.v = dpyinfo->height;
8858
8859 if (IsWindowInStandardState (w, &standard_size, &zoom_rect))
8860 zoom_in_or_out = inZoomIn;
8861 else
8862 {
8863 /* Adjust the standard size according to character boundaries. */
8864
8865 columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, zoom_rect.right - zoom_rect.left);
8866 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, zoom_rect.bottom - zoom_rect.top);
8867 standard_size.h = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, columns);
8868 standard_size.v = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
8869 GetWindowBounds (w, kWindowContentRgn, &port_rect);
8870 if (IsWindowInStandardState (w, &standard_size, &zoom_rect)
8871 && port_rect.left == zoom_rect.left
8872 && port_rect.top == zoom_rect.top)
8873 zoom_in_or_out = inZoomIn;
8874 else
8875 zoom_in_or_out = inZoomOut;
8876 }
8877
8878 ZoomWindowIdeal (w, zoom_in_or_out, &standard_size);
8879 #else /* not TARGET_API_MAC_CARBON */
8880 GrafPtr save_port;
8881 Point top_left;
8882 int w_title_height;
8883
8884 GetPort (&save_port);
8885
8886 SetPortWindowPort (w);
8887
8888 /* Clear window to avoid flicker. */
8889 EraseRect (&(w->portRect));
8890 if (zoom_in_or_out == inZoomOut)
8891 {
8892 SetPt (&top_left, w->portRect.left, w->portRect.top);
8893 LocalToGlobal (&top_left);
8894
8895 /* calculate height of window's title bar */
8896 w_title_height = top_left.v - 1
8897 - (**((WindowPeek) w)->strucRgn).rgnBBox.top + GetMBarHeight ();
8898
8899 /* get maximum height of window into zoom_rect.bottom - zoom_rect.top */
8900 zoom_rect = qd.screenBits.bounds;
8901 zoom_rect.top += w_title_height;
8902 InsetRect (&zoom_rect, 8, 4); /* not too tight */
8903
8904 zoom_rect.right = zoom_rect.left
8905 + FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, DEFAULT_NUM_COLS);
8906
8907 /* Adjust the standard size according to character boundaries. */
8908 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, zoom_rect.bottom - zoom_rect.top);
8909 zoom_rect.bottom =
8910 zoom_rect.top + FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
8911
8912 (**((WStateDataHandle) ((WindowPeek) w)->dataHandle)).stdState
8913 = zoom_rect;
8914 }
8915
8916 ZoomWindow (w, zoom_in_or_out, f == mac_focus_frame (dpyinfo));
8917
8918 SetPort (save_port);
8919 #endif /* not TARGET_API_MAC_CARBON */
8920
8921 /* retrieve window size and update application values */
8922 #if TARGET_API_MAC_CARBON
8923 GetWindowPortBounds (w, &port_rect);
8924 #else
8925 port_rect = w->portRect;
8926 #endif
8927 height = port_rect.bottom - port_rect.top;
8928 width = port_rect.right - port_rect.left;
8929
8930 if (width != FRAME_PIXEL_WIDTH (f)
8931 || height != FRAME_PIXEL_HEIGHT (f))
8932 {
8933 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, height);
8934 columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, width);
8935
8936 change_frame_size (f, rows, columns, 0, 1, 0);
8937 SET_FRAME_GARBAGED (f);
8938 cancel_mouse_face (f);
8939
8940 FRAME_PIXEL_WIDTH (f) = width;
8941 FRAME_PIXEL_HEIGHT (f) = height;
8942 }
8943 x_real_positions (f, &f->left_pos, &f->top_pos);
8944 }
8945
8946 OSErr
8947 mac_store_apple_event (class, id, desc)
8948 Lisp_Object class, id;
8949 const AEDesc *desc;
8950 {
8951 OSErr err;
8952 struct input_event buf;
8953 AEDesc *desc_copy;
8954
8955 desc_copy = xmalloc (sizeof (AEDesc));
8956 err = AEDuplicateDesc (desc, desc_copy);
8957 if (err == noErr)
8958 {
8959 EVENT_INIT (buf);
8960
8961 buf.kind = MAC_APPLE_EVENT;
8962 buf.x = class;
8963 buf.y = id;
8964 buf.code = (int)desc_copy;
8965 XSETFRAME (buf.frame_or_window,
8966 mac_focus_frame (&one_mac_display_info));
8967 buf.arg = Qnil;
8968 kbd_buffer_store_event (&buf);
8969 }
8970
8971 return err;
8972 }
8973
8974 Lisp_Object
8975 mac_make_lispy_event_code (code)
8976 int code;
8977 {
8978 AEDesc *desc = (AEDesc *)code;
8979 Lisp_Object obj;
8980
8981 obj = mac_aedesc_to_lisp (desc);
8982 AEDisposeDesc (desc);
8983 xfree (desc);
8984
8985 return obj;
8986 }
8987
8988 #if USE_CARBON_EVENTS
8989 static pascal OSStatus
8990 mac_handle_command_event (next_handler, event, data)
8991 EventHandlerCallRef next_handler;
8992 EventRef event;
8993 void *data;
8994 {
8995 OSStatus result, err;
8996 HICommand command;
8997 Lisp_Object class_key, id_key, binding;
8998
8999 result = CallNextEventHandler (next_handler, event);
9000 if (result != eventNotHandledErr)
9001 return result;
9002
9003 err = GetEventParameter (event, kEventParamDirectObject, typeHICommand,
9004 NULL, sizeof (HICommand), NULL, &command);
9005
9006 if (err != noErr || command.commandID == 0)
9007 return eventNotHandledErr;
9008
9009 /* A HICommand event is mapped to an Apple event whose event class
9010 symbol is `hicommand' and event ID is its command ID. */
9011 class_key = Qhicommand;
9012 mac_find_apple_event_spec (0, command.commandID,
9013 &class_key, &id_key, &binding);
9014 if (!NILP (binding) && !EQ (binding, Qundefined))
9015 {
9016 if (INTEGERP (binding))
9017 return XINT (binding);
9018 else
9019 {
9020 AppleEvent apple_event;
9021 static EventParamName names[] = {kEventParamDirectObject,
9022 kEventParamKeyModifiers};
9023 static EventParamType types[] = {typeHICommand,
9024 typeUInt32};
9025 err = create_apple_event_from_event_ref (event, 2, names, types,
9026 &apple_event);
9027 if (err == noErr)
9028 {
9029 err = mac_store_apple_event (class_key, id_key, &apple_event);
9030 AEDisposeDesc (&apple_event);
9031 }
9032 if (err == noErr)
9033 return noErr;
9034 }
9035 }
9036
9037 return eventNotHandledErr;
9038 }
9039
9040 static OSErr
9041 init_command_handler ()
9042 {
9043 EventTypeSpec specs[] = {{kEventClassCommand, kEventCommandProcess}};
9044 static EventHandlerUPP handle_command_eventUPP = NULL;
9045
9046 if (handle_command_eventUPP == NULL)
9047 handle_command_eventUPP = NewEventHandlerUPP (mac_handle_command_event);
9048 return InstallApplicationEventHandler (handle_command_eventUPP,
9049 GetEventTypeCount (specs), specs,
9050 NULL, NULL);
9051 }
9052
9053 static pascal OSStatus
9054 mac_handle_window_event (next_handler, event, data)
9055 EventHandlerCallRef next_handler;
9056 EventRef event;
9057 void *data;
9058 {
9059 WindowPtr wp;
9060 OSStatus result, err;
9061 UInt32 attributes;
9062 XSizeHints *size_hints;
9063
9064 err = GetEventParameter (event, kEventParamDirectObject, typeWindowRef,
9065 NULL, sizeof (WindowPtr), NULL, &wp);
9066 if (err != noErr)
9067 return eventNotHandledErr;
9068
9069 switch (GetEventKind (event))
9070 {
9071 case kEventWindowUpdate:
9072 result = CallNextEventHandler (next_handler, event);
9073 if (result != eventNotHandledErr)
9074 return result;
9075
9076 do_window_update (wp);
9077 return noErr;
9078
9079 case kEventWindowBoundsChanging:
9080 result = CallNextEventHandler (next_handler, event);
9081 if (result != eventNotHandledErr)
9082 return result;
9083
9084 err = GetEventParameter (event, kEventParamAttributes, typeUInt32,
9085 NULL, sizeof (UInt32), NULL, &attributes);
9086 if (err != noErr)
9087 break;
9088
9089 size_hints = FRAME_SIZE_HINTS (mac_window_to_frame (wp));
9090 if ((attributes & kWindowBoundsChangeUserResize)
9091 && ((size_hints->flags & (PResizeInc | PBaseSize | PMinSize))
9092 == (PResizeInc | PBaseSize | PMinSize)))
9093 {
9094 Rect bounds;
9095 int width, height;
9096
9097 err = GetEventParameter (event, kEventParamCurrentBounds,
9098 typeQDRectangle, NULL, sizeof (Rect),
9099 NULL, &bounds);
9100 if (err != noErr)
9101 break;
9102
9103 width = bounds.right - bounds.left;
9104 height = bounds.bottom - bounds.top;
9105
9106 if (width < size_hints->min_width)
9107 width = size_hints->min_width;
9108 else
9109 width = size_hints->base_width
9110 + (int) ((width - size_hints->base_width)
9111 / (float) size_hints->width_inc + .5)
9112 * size_hints->width_inc;
9113
9114 if (height < size_hints->min_height)
9115 height = size_hints->min_height;
9116 else
9117 height = size_hints->base_height
9118 + (int) ((height - size_hints->base_height)
9119 / (float) size_hints->height_inc + .5)
9120 * size_hints->height_inc;
9121
9122 bounds.right = bounds.left + width;
9123 bounds.bottom = bounds.top + height;
9124 SetEventParameter (event, kEventParamCurrentBounds,
9125 typeQDRectangle, sizeof (Rect), &bounds);
9126 return noErr;
9127 }
9128 break;
9129
9130 case kEventWindowShown:
9131 case kEventWindowHidden:
9132 case kEventWindowExpanded:
9133 case kEventWindowCollapsed:
9134 result = CallNextEventHandler (next_handler, event);
9135
9136 mac_handle_visibility_change (mac_window_to_frame (wp));
9137 return noErr;
9138
9139 break;
9140 }
9141
9142 return eventNotHandledErr;
9143 }
9144
9145 static pascal OSStatus
9146 mac_handle_mouse_event (next_handler, event, data)
9147 EventHandlerCallRef next_handler;
9148 EventRef event;
9149 void *data;
9150 {
9151 OSStatus result, err;
9152
9153 switch (GetEventKind (event))
9154 {
9155 case kEventMouseWheelMoved:
9156 {
9157 WindowPtr wp;
9158 struct frame *f;
9159 EventMouseWheelAxis axis;
9160 SInt32 delta;
9161 Point point;
9162
9163 result = CallNextEventHandler (next_handler, event);
9164 if (result != eventNotHandledErr || read_socket_inev == NULL)
9165 return result;
9166
9167 err = GetEventParameter (event, kEventParamWindowRef, typeWindowRef,
9168 NULL, sizeof (WindowRef), NULL, &wp);
9169 if (err != noErr)
9170 break;
9171
9172 f = mac_window_to_frame (wp);
9173 if (f != mac_focus_frame (&one_mac_display_info))
9174 break;
9175
9176 err = GetEventParameter (event, kEventParamMouseWheelAxis,
9177 typeMouseWheelAxis, NULL,
9178 sizeof (EventMouseWheelAxis), NULL, &axis);
9179 if (err != noErr || axis != kEventMouseWheelAxisY)
9180 break;
9181
9182 err = GetEventParameter (event, kEventParamMouseWheelDelta,
9183 typeSInt32, NULL, sizeof (SInt32),
9184 NULL, &delta);
9185 if (err != noErr)
9186 break;
9187 err = GetEventParameter (event, kEventParamMouseLocation,
9188 typeQDPoint, NULL, sizeof (Point),
9189 NULL, &point);
9190 if (err != noErr)
9191 break;
9192 read_socket_inev->kind = WHEEL_EVENT;
9193 read_socket_inev->code = 0;
9194 read_socket_inev->modifiers =
9195 (mac_event_to_emacs_modifiers (event)
9196 | ((delta < 0) ? down_modifier : up_modifier));
9197 SetPortWindowPort (wp);
9198 GlobalToLocal (&point);
9199 XSETINT (read_socket_inev->x, point.h);
9200 XSETINT (read_socket_inev->y, point.v);
9201 XSETFRAME (read_socket_inev->frame_or_window, f);
9202
9203 return noErr;
9204 }
9205 break;
9206
9207 default:
9208 break;
9209 }
9210
9211 return eventNotHandledErr;
9212 }
9213
9214 #ifdef MAC_OSX
9215 OSErr
9216 mac_store_services_event (event)
9217 EventRef event;
9218 {
9219 OSErr err;
9220 AppleEvent apple_event;
9221 Lisp_Object id_key;
9222
9223 switch (GetEventKind (event))
9224 {
9225 case kEventServicePaste:
9226 id_key = Qpaste;
9227 err = create_apple_event_from_event_ref (event, 0, NULL, NULL,
9228 &apple_event);
9229 break;
9230
9231 case kEventServicePerform:
9232 {
9233 static EventParamName names[] = {kEventParamServiceMessageName,
9234 kEventParamServiceUserData};
9235 static EventParamType types[] = {typeCFStringRef,
9236 typeCFStringRef};
9237
9238 id_key = Qperform;
9239 err = create_apple_event_from_event_ref (event, 2, names, types,
9240 &apple_event);
9241 }
9242 break;
9243
9244 default:
9245 abort ();
9246 }
9247
9248 if (err == noErr)
9249 {
9250 err = mac_store_apple_event (Qservices, id_key, &apple_event);
9251 AEDisposeDesc (&apple_event);
9252 }
9253
9254 return err;
9255 }
9256 #endif /* MAC_OSX */
9257 #endif /* USE_CARBON_EVENTS */
9258
9259
9260 OSErr
9261 install_window_handler (window)
9262 WindowPtr window;
9263 {
9264 OSErr err = noErr;
9265 #if USE_CARBON_EVENTS
9266 EventTypeSpec specs_window[] =
9267 {{kEventClassWindow, kEventWindowUpdate},
9268 {kEventClassWindow, kEventWindowBoundsChanging},
9269 {kEventClassWindow, kEventWindowShown},
9270 {kEventClassWindow, kEventWindowHidden},
9271 {kEventClassWindow, kEventWindowExpanded},
9272 {kEventClassWindow, kEventWindowCollapsed}};
9273 EventTypeSpec specs_mouse[] = {{kEventClassMouse, kEventMouseWheelMoved}};
9274 static EventHandlerUPP handle_window_eventUPP = NULL;
9275 static EventHandlerUPP handle_mouse_eventUPP = NULL;
9276
9277 if (handle_window_eventUPP == NULL)
9278 handle_window_eventUPP = NewEventHandlerUPP (mac_handle_window_event);
9279 if (handle_mouse_eventUPP == NULL)
9280 handle_mouse_eventUPP = NewEventHandlerUPP (mac_handle_mouse_event);
9281 err = InstallWindowEventHandler (window, handle_window_eventUPP,
9282 GetEventTypeCount (specs_window),
9283 specs_window, NULL, NULL);
9284 if (err == noErr)
9285 err = InstallWindowEventHandler (window, handle_mouse_eventUPP,
9286 GetEventTypeCount (specs_mouse),
9287 specs_mouse, NULL, NULL);
9288 #endif
9289 #if TARGET_API_MAC_CARBON
9290 if (mac_do_track_dragUPP == NULL)
9291 mac_do_track_dragUPP = NewDragTrackingHandlerUPP (mac_do_track_drag);
9292 if (mac_do_receive_dragUPP == NULL)
9293 mac_do_receive_dragUPP = NewDragReceiveHandlerUPP (mac_do_receive_drag);
9294
9295 if (err == noErr)
9296 err = InstallTrackingHandler (mac_do_track_dragUPP, window, NULL);
9297 if (err == noErr)
9298 err = InstallReceiveHandler (mac_do_receive_dragUPP, window, NULL);
9299 #endif
9300 return err;
9301 }
9302
9303 void
9304 remove_window_handler (window)
9305 WindowPtr window;
9306 {
9307 #if TARGET_API_MAC_CARBON
9308 if (mac_do_track_dragUPP)
9309 RemoveTrackingHandler (mac_do_track_dragUPP, window);
9310 if (mac_do_receive_dragUPP)
9311 RemoveReceiveHandler (mac_do_receive_dragUPP, window);
9312 #endif
9313 }
9314
9315 #if TARGET_API_MAC_CARBON
9316 static pascal OSErr
9317 mac_do_track_drag (DragTrackingMessage message, WindowPtr window,
9318 void *handlerRefCon, DragReference theDrag)
9319 {
9320 static int can_accept;
9321 short items;
9322 short index;
9323 ItemReference theItem;
9324 FlavorFlags theFlags;
9325 OSErr result;
9326
9327 if (GetFrontWindowOfClass (kMovableModalWindowClass, false))
9328 return dragNotAcceptedErr;
9329
9330 switch (message)
9331 {
9332 case kDragTrackingEnterHandler:
9333 CountDragItems (theDrag, &items);
9334 can_accept = 0;
9335 for (index = 1; index <= items; index++)
9336 {
9337 GetDragItemReferenceNumber (theDrag, index, &theItem);
9338 result = GetFlavorFlags (theDrag, theItem, flavorTypeHFS, &theFlags);
9339 if (result == noErr)
9340 {
9341 can_accept = 1;
9342 break;
9343 }
9344 }
9345 break;
9346
9347 case kDragTrackingEnterWindow:
9348 if (can_accept)
9349 {
9350 RgnHandle hilite_rgn = NewRgn ();
9351 Rect r;
9352 struct frame *f = mac_window_to_frame (window);
9353
9354 GetWindowPortBounds (window, &r);
9355 OffsetRect (&r, -r.left, -r.top);
9356 RectRgn (hilite_rgn, &r);
9357 ShowDragHilite (theDrag, hilite_rgn, true);
9358 DisposeRgn (hilite_rgn);
9359 SetThemeCursor (kThemeCopyArrowCursor);
9360 }
9361 break;
9362
9363 case kDragTrackingInWindow:
9364 break;
9365
9366 case kDragTrackingLeaveWindow:
9367 if (can_accept)
9368 {
9369 struct frame *f = mac_window_to_frame (window);
9370
9371 HideDragHilite (theDrag);
9372 SetThemeCursor (kThemeArrowCursor);
9373 }
9374 break;
9375
9376 case kDragTrackingLeaveHandler:
9377 break;
9378 }
9379
9380 return noErr;
9381 }
9382
9383 static pascal OSErr
9384 mac_do_receive_drag (WindowPtr window, void *handlerRefCon,
9385 DragReference theDrag)
9386 {
9387 short items;
9388 short index;
9389 FlavorFlags theFlags;
9390 Point mouse;
9391 OSErr result;
9392 ItemReference theItem;
9393 HFSFlavor data;
9394 Size size = sizeof (HFSFlavor);
9395 Lisp_Object file_list;
9396
9397 if (GetFrontWindowOfClass (kMovableModalWindowClass, false))
9398 return dragNotAcceptedErr;
9399
9400 file_list = Qnil;
9401 GetDragMouse (theDrag, &mouse, 0L);
9402 CountDragItems (theDrag, &items);
9403 for (index = 1; index <= items; index++)
9404 {
9405 /* Only handle file references. */
9406 GetDragItemReferenceNumber (theDrag, index, &theItem);
9407 result = GetFlavorFlags (theDrag, theItem, flavorTypeHFS, &theFlags);
9408 if (result == noErr)
9409 {
9410 OSErr err;
9411 AEDesc desc;
9412
9413 err = GetFlavorData (theDrag, theItem, flavorTypeHFS,
9414 &data, &size, 0L);
9415 if (err == noErr)
9416 err = AECoercePtr (typeFSS, &data.fileSpec, sizeof (FSSpec),
9417 TYPE_FILE_NAME, &desc);
9418 if (err == noErr)
9419 {
9420 Lisp_Object file;
9421
9422 /* x-dnd functions expect undecoded filenames. */
9423 file = make_uninit_string (AEGetDescDataSize (&desc));
9424 err = AEGetDescData (&desc, SDATA (file), SBYTES (file));
9425 if (err == noErr)
9426 file_list = Fcons (file, file_list);
9427 AEDisposeDesc (&desc);
9428 }
9429 }
9430 }
9431 /* If there are items in the list, construct an event and post it to
9432 the queue like an interrupt using kbd_buffer_store_event. */
9433 if (!NILP (file_list))
9434 {
9435 struct input_event event;
9436 Lisp_Object frame;
9437 struct frame *f = mac_window_to_frame (window);
9438 SInt16 modifiers;
9439
9440 GlobalToLocal (&mouse);
9441 GetDragModifiers (theDrag, NULL, NULL, &modifiers);
9442
9443 event.kind = DRAG_N_DROP_EVENT;
9444 event.code = 0;
9445 event.modifiers = mac_to_emacs_modifiers (modifiers);
9446 event.timestamp = TickCount () * (1000 / 60);
9447 XSETINT (event.x, mouse.h);
9448 XSETINT (event.y, mouse.v);
9449 XSETFRAME (frame, f);
9450 event.frame_or_window = frame;
9451 event.arg = file_list;
9452 /* Post to the interrupt queue */
9453 kbd_buffer_store_event (&event);
9454 /* MAC_TODO: Mimic behavior of windows by switching contexts to Emacs */
9455 {
9456 ProcessSerialNumber psn;
9457 GetCurrentProcess (&psn);
9458 SetFrontProcess (&psn);
9459 }
9460
9461 return noErr;
9462 }
9463 else
9464 return dragNotAcceptedErr;
9465 }
9466 #endif
9467
9468
9469 #if __profile__
9470 void
9471 profiler_exit_proc ()
9472 {
9473 ProfilerDump ("\pEmacs.prof");
9474 ProfilerTerm ();
9475 }
9476 #endif
9477
9478 /* These few functions implement Emacs as a normal Mac application
9479 (almost): set up the heap and the Toolbox, handle necessary system
9480 events plus a few simple menu events. They also set up Emacs's
9481 access to functions defined in the rest of this file. Emacs uses
9482 function hooks to perform all its terminal I/O. A complete list of
9483 these functions appear in termhooks.h. For what they do, read the
9484 comments there and see also w32term.c and xterm.c. What's
9485 noticeably missing here is the event loop, which is normally
9486 present in most Mac application. After performing the necessary
9487 Mac initializations, main passes off control to emacs_main
9488 (corresponding to main in emacs.c). Emacs_main calls XTread_socket
9489 (defined further below) to read input. This is where
9490 WaitNextEvent/ReceiveNextEvent is called to process Mac events. */
9491
9492 #ifdef MAC_OS8
9493 #undef main
9494 int
9495 main (void)
9496 {
9497 #if __profile__ /* is the profiler on? */
9498 if (ProfilerInit(collectDetailed, bestTimeBase, 5000, 200))
9499 exit(1);
9500 #endif
9501
9502 #if __MWERKS__
9503 /* set creator and type for files created by MSL */
9504 _fcreator = 'EMAx';
9505 _ftype = 'TEXT';
9506 #endif
9507
9508 do_init_managers ();
9509
9510 do_get_menus ();
9511
9512 #ifndef USE_LSB_TAG
9513 do_check_ram_size ();
9514 #endif
9515
9516 init_emacs_passwd_dir ();
9517
9518 init_environ ();
9519
9520 init_coercion_handler ();
9521
9522 initialize_applescript ();
9523
9524 init_apple_event_handler ();
9525
9526 {
9527 char **argv;
9528 int argc = 0;
9529
9530 /* set up argv array from STR# resource */
9531 get_string_list (&argv, ARGV_STRING_LIST_ID);
9532 while (argv[argc])
9533 argc++;
9534
9535 /* free up AppleScript resources on exit */
9536 atexit (terminate_applescript);
9537
9538 #if __profile__ /* is the profiler on? */
9539 atexit (profiler_exit_proc);
9540 #endif
9541
9542 /* 3rd param "envp" never used in emacs_main */
9543 (void) emacs_main (argc, argv, 0);
9544 }
9545
9546 /* Never reached - real exit in Fkill_emacs */
9547 return 0;
9548 }
9549 #endif
9550
9551 /* Table for translating Mac keycode to X keysym values. Contributed
9552 by Sudhir Shenoy.
9553 Mapping for special keys is now identical to that in Apple X11
9554 except `clear' (-> <clear>) on the KeyPad, `enter' (-> <kp-enter>)
9555 on the right of the Cmd key on laptops, and fn + `enter' (->
9556 <linefeed>). */
9557 static unsigned char keycode_to_xkeysym_table[] = {
9558 /*0x00*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9559 /*0x10*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9560 /*0x20*/ 0, 0, 0, 0, 0x0d /*return*/, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9561
9562 /*0x30*/ 0x09 /*tab*/, 0 /*0x0020 space*/, 0, 0x08 /*backspace*/,
9563 /*0x34*/ 0x8d /*enter on laptops*/, 0x1b /*escape*/, 0, 0,
9564 /*0x38*/ 0, 0, 0, 0,
9565 /*0x3C*/ 0, 0, 0, 0,
9566
9567 /*0x40*/ 0, 0xae /*kp-.*/, 0, 0xaa /*kp-**/,
9568 /*0x44*/ 0, 0xab /*kp-+*/, 0, 0x0b /*clear*/,
9569 /*0x48*/ 0, 0, 0, 0xaf /*kp-/*/,
9570 /*0x4C*/ 0x8d /*kp-enter*/, 0, 0xad /*kp--*/, 0,
9571
9572 /*0x50*/ 0, 0xbd /*kp-=*/, 0xb0 /*kp-0*/, 0xb1 /*kp-1*/,
9573 /*0x54*/ 0xb2 /*kp-2*/, 0xb3 /*kp-3*/, 0xb4 /*kp-4*/, 0xb5 /*kp-5*/,
9574 /*0x58*/ 0xb6 /*kp-6*/, 0xb7 /*kp-7*/, 0, 0xb8 /*kp-8*/,
9575 /*0x5C*/ 0xb9 /*kp-9*/, 0, 0, 0,
9576
9577 /*0x60*/ 0xc2 /*f5*/, 0xc3 /*f6*/, 0xc4 /*f7*/, 0xc0 /*f3*/,
9578 /*0x64*/ 0xc5 /*f8*/, 0xc6 /*f9*/, 0, 0xc8 /*f11*/,
9579 /*0x68*/ 0, 0xca /*f13*/, 0, 0xcb /*f14*/,
9580 /*0x6C*/ 0, 0xc7 /*f10*/, 0x0a /*fn+enter on laptops*/, 0xc9 /*f12*/,
9581
9582 /*0x70*/ 0, 0xcc /*f15*/, 0x6a /*help*/, 0x50 /*home*/,
9583 /*0x74*/ 0x55 /*pgup*/, 0xff /*delete*/, 0xc1 /*f4*/, 0x57 /*end*/,
9584 /*0x78*/ 0xbf /*f2*/, 0x56 /*pgdown*/, 0xbe /*f1*/, 0x51 /*left*/,
9585 /*0x7C*/ 0x53 /*right*/, 0x54 /*down*/, 0x52 /*up*/, 0
9586 };
9587
9588
9589 static int
9590 keycode_to_xkeysym (int keyCode, int *xKeySym)
9591 {
9592 *xKeySym = keycode_to_xkeysym_table [keyCode & 0x7f];
9593 return *xKeySym != 0;
9594 }
9595
9596 static unsigned char fn_keycode_to_xkeysym_table[] = {
9597 /*0x00*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9598 /*0x10*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9599 /*0x20*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9600
9601 /*0x30*/ 0, 0, 0, 0,
9602 /*0x34*/ 0, 0, 0, 0,
9603 /*0x38*/ 0, 0, 0, 0,
9604 /*0x3C*/ 0, 0, 0, 0,
9605
9606 /*0x40*/ 0, 0x2e /*kp-. = .*/, 0, 0x50 /*kp-* = 'p'*/,
9607 /*0x44*/ 0, '/' /*kp-+*/, 0, 0,
9608 /*0x48*/ 0, 0, 0, 0x30 /*kp-/ = '0'*/,
9609 /*0x4C*/ 0, 0, 0x3b /*kp-- = ';'*/, 0,
9610
9611 /*0x50*/ 0, 0x2d /*kp-= = '-'*/, 0x6d /*kp-0 = 'm'*/, 0x6a /*kp-1 = 'j'*/,
9612 /*0x54*/ 0x6b /*kp-2 = 'k'*/, 0x6c /*kp-3 = 'l'*/, 'u' /*kp-4*/, 'i' /*kp-5*/,
9613 /*0x58*/ 'o' /*kp-6*/, '7' /*kp-7*/, 0, '8' /*kp-8*/,
9614 /*0x5C*/ '9' /*kp-9*/, 0, 0, 0,
9615
9616 /*0x60*/ 0, 0, 0, 0,
9617 /*0x64*/ 0, 0, 0, 0,
9618 /*0x68*/ 0, 0, 0, 0,
9619 /*0x6C*/ 0, 0, 0, 0,
9620
9621 /*0x70*/ 0, 0, 0, 0,
9622 /*0x74*/ 0, 0, 0, 0,
9623 /*0x78*/ 0, 0, 0, 0,
9624 /*0x7C*/ 0, 0, 0, 0
9625 };
9626 static int
9627 convert_fn_keycode (EventRef eventRef, int keyCode, int *newCode)
9628 {
9629 #ifdef MAC_OSX
9630 /* Use the special map to translate keys when function modifier is
9631 to be caught. KeyTranslate can't be used in that case.
9632 We can't detect the function key using the input_event.modifiers,
9633 because this uses the high word of an UInt32. Therefore,
9634 we'll just read it out of the original eventRef.
9635 */
9636
9637
9638 /* TODO / known issues
9639
9640 - Fn-Shift-j is regonized as Fn-j and not Fn-J.
9641 The above table always translates to lower characters. We need to use
9642 the KCHR keyboard resource (KeyTranslate() ) to map k->K and 8->*.
9643
9644 - The table is meant for English language keyboards, and it will work
9645 for many others with the exception of key combinations like Fn-ö on
9646 a German keyboard, which is currently mapped to Fn-;.
9647 How to solve this without keeping separate tables for all keyboards
9648 around? KeyTranslate isn't of much help here, as it only takes a 16-bit
9649 value for keycode with the modifiers in he high byte, i.e. no room for the
9650 Fn modifier. That's why we need the table.
9651
9652 */
9653 OSStatus err;
9654 UInt32 mods = 0;
9655 if (!NILP(Vmac_function_modifier))
9656 {
9657 err = GetEventParameter (eventRef, kEventParamKeyModifiers, typeUInt32,
9658 NULL, sizeof (UInt32), NULL, &mods);
9659 if (err != noErr && mods & kEventKeyModifierFnMask)
9660 { *newCode = fn_keycode_to_xkeysym_table [keyCode & 0x7f];
9661
9662 return (*newCode != 0);
9663 }
9664 }
9665 #endif
9666 return false;
9667 }
9668
9669 static int
9670 backtranslate_modified_keycode(int mods, int keycode, int def)
9671 {
9672 EventModifiers mapped_modifiers =
9673 (NILP (Vmac_control_modifier) ? 0 : controlKey)
9674 | (NILP (Vmac_option_modifier) ? 0 : optionKey)
9675 | (NILP (Vmac_command_modifier) ? 0 : cmdKey);
9676
9677 if (mods & mapped_modifiers)
9678 {
9679 /* This code comes from Keyboard Resource,
9680 Appendix C of IM - Text. This is necessary
9681 since shift is ignored in KCHR table
9682 translation when option or command is pressed.
9683 It also does not translate correctly
9684 control-shift chars like C-% so mask off shift
9685 here also.
9686
9687 Not done for combinations with the option key (alt)
9688 unless it is to be caught by Emacs: this is
9689 to preserve key combinations translated by the OS
9690 such as Alt-3.
9691 */
9692 /* Mask off modifier keys that are mapped to some Emacs
9693 modifiers. */
9694 int new_modifiers = mods & ~mapped_modifiers;
9695 /* set high byte of keycode to modifier high byte*/
9696 int new_keycode = keycode | new_modifiers;
9697 Ptr kchr_ptr = (Ptr) GetScriptManagerVariable (smKCHRCache);
9698 unsigned long some_state = 0;
9699 return (int) KeyTranslate (kchr_ptr, new_keycode,
9700 &some_state) & 0xff;
9701 /* TO DO: Recognize two separate resulting characters, "for
9702 example, when the user presses Option-E followed by N, you
9703 can map this through the KeyTranslate function using the
9704 U.S. 'KCHR' resource to produce ´n, which KeyTranslate
9705 returns as two characters in the bytes labeled Character code
9706 1 and Character code 2." (from Carbon API doc) */
9707
9708 }
9709 else
9710 return def;
9711 }
9712
9713
9714 #if !USE_CARBON_EVENTS
9715 static RgnHandle mouse_region = NULL;
9716
9717 Boolean
9718 mac_wait_next_event (er, sleep_time, dequeue)
9719 EventRecord *er;
9720 UInt32 sleep_time;
9721 Boolean dequeue;
9722 {
9723 static EventRecord er_buf = {nullEvent};
9724 UInt32 target_tick, current_tick;
9725 EventMask event_mask;
9726
9727 if (mouse_region == NULL)
9728 mouse_region = NewRgn ();
9729
9730 event_mask = everyEvent;
9731 if (!mac_ready_for_apple_events)
9732 event_mask -= highLevelEventMask;
9733
9734 current_tick = TickCount ();
9735 target_tick = current_tick + sleep_time;
9736
9737 if (er_buf.what == nullEvent)
9738 while (!WaitNextEvent (event_mask, &er_buf,
9739 target_tick - current_tick, mouse_region))
9740 {
9741 current_tick = TickCount ();
9742 if (target_tick <= current_tick)
9743 return false;
9744 }
9745
9746 *er = er_buf;
9747 if (dequeue)
9748 er_buf.what = nullEvent;
9749 return true;
9750 }
9751 #endif /* not USE_CARBON_EVENTS */
9752
9753 /* Emacs calls this whenever it wants to read an input event from the
9754 user. */
9755 int
9756 XTread_socket (sd, expected, hold_quit)
9757 int sd, expected;
9758 struct input_event *hold_quit;
9759 {
9760 struct input_event inev;
9761 int count = 0;
9762 #if USE_CARBON_EVENTS
9763 EventRef eventRef;
9764 EventTargetRef toolbox_dispatcher;
9765 #endif
9766 EventRecord er;
9767 struct mac_display_info *dpyinfo = &one_mac_display_info;
9768
9769 if (interrupt_input_blocked)
9770 {
9771 interrupt_input_pending = 1;
9772 return -1;
9773 }
9774
9775 interrupt_input_pending = 0;
9776 BLOCK_INPUT;
9777
9778 /* So people can tell when we have read the available input. */
9779 input_signal_count++;
9780
9781 ++handling_signal;
9782
9783 #if USE_CARBON_EVENTS
9784 toolbox_dispatcher = GetEventDispatcherTarget ();
9785
9786 while (
9787 #if USE_CG_DRAWING
9788 mac_prepare_for_quickdraw (NULL),
9789 #endif
9790 !ReceiveNextEvent (0, NULL, kEventDurationNoWait,
9791 kEventRemoveFromQueue, &eventRef))
9792 #else /* !USE_CARBON_EVENTS */
9793 while (mac_wait_next_event (&er, 0, true))
9794 #endif /* !USE_CARBON_EVENTS */
9795 {
9796 int do_help = 0;
9797 struct frame *f;
9798 unsigned long timestamp;
9799
9800 /* It is necessary to set this (additional) argument slot of an
9801 event to nil because keyboard.c protects incompletely
9802 processed event from being garbage collected by placing them
9803 in the kbd_buffer_gcpro vector. */
9804 EVENT_INIT (inev);
9805 inev.kind = NO_EVENT;
9806 inev.arg = Qnil;
9807
9808 #if USE_CARBON_EVENTS
9809 timestamp = GetEventTime (eventRef) / kEventDurationMillisecond;
9810 #else
9811 timestamp = er.when * (1000 / 60); /* ticks to milliseconds */
9812 #endif
9813
9814 #if USE_CARBON_EVENTS
9815 /* Handle new events */
9816 if (!mac_convert_event_ref (eventRef, &er))
9817 {
9818 /* There used to be a handler for the kEventMouseWheelMoved
9819 event here. But as of Mac OS X 10.4, this kind of event
9820 is not directly posted to the main event queue by
9821 two-finger scrolling on the trackpad. Instead, some
9822 private event is posted and it is converted to a wheel
9823 event by the default handler for the application target.
9824 The converted one can be received by a Carbon event
9825 handler installed on a window target. */
9826 read_socket_inev = &inev;
9827 SendEventToEventTarget (eventRef, toolbox_dispatcher);
9828 read_socket_inev = NULL;
9829 }
9830 else
9831 #endif /* USE_CARBON_EVENTS */
9832 switch (er.what)
9833 {
9834 case mouseDown:
9835 case mouseUp:
9836 {
9837 WindowPtr window_ptr;
9838 ControlPartCode part_code;
9839 int tool_bar_p = 0;
9840
9841 #if USE_CARBON_EVENTS
9842 /* This is needed to send mouse events like aqua window
9843 buttons to the correct handler. */
9844 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
9845 != eventNotHandledErr)
9846 break;
9847 #endif
9848 last_mouse_glyph_frame = 0;
9849
9850 if (dpyinfo->grabbed && last_mouse_frame
9851 && FRAME_LIVE_P (last_mouse_frame))
9852 {
9853 window_ptr = FRAME_MAC_WINDOW (last_mouse_frame);
9854 part_code = inContent;
9855 }
9856 else
9857 {
9858 part_code = FindWindow (er.where, &window_ptr);
9859 if (tip_window && window_ptr == tip_window)
9860 {
9861 HideWindow (tip_window);
9862 part_code = FindWindow (er.where, &window_ptr);
9863 }
9864 }
9865
9866 if (er.what != mouseDown &&
9867 (part_code != inContent || dpyinfo->grabbed == 0))
9868 break;
9869
9870 switch (part_code)
9871 {
9872 case inMenuBar:
9873 f = mac_focus_frame (dpyinfo);
9874 saved_menu_event_location = er.where;
9875 inev.kind = MENU_BAR_ACTIVATE_EVENT;
9876 XSETFRAME (inev.frame_or_window, f);
9877 break;
9878
9879 case inContent:
9880 if (window_ptr != FRAME_MAC_WINDOW (mac_focus_frame (dpyinfo)))
9881 SelectWindow (window_ptr);
9882 else
9883 {
9884 ControlPartCode control_part_code;
9885 ControlHandle ch;
9886 Point mouse_loc = er.where;
9887 #ifdef MAC_OSX
9888 ControlKind control_kind;
9889 #endif
9890
9891 f = mac_window_to_frame (window_ptr);
9892 /* convert to local coordinates of new window */
9893 SetPortWindowPort (window_ptr);
9894
9895 GlobalToLocal (&mouse_loc);
9896 #if TARGET_API_MAC_CARBON
9897 ch = FindControlUnderMouse (mouse_loc, window_ptr,
9898 &control_part_code);
9899 #ifdef MAC_OSX
9900 if (ch)
9901 GetControlKind (ch, &control_kind);
9902 #endif
9903 #else
9904 control_part_code = FindControl (mouse_loc, window_ptr,
9905 &ch);
9906 #endif
9907
9908 #if USE_CARBON_EVENTS
9909 inev.code = mac_get_mouse_btn (eventRef);
9910 inev.modifiers = mac_event_to_emacs_modifiers (eventRef);
9911 #else
9912 inev.code = mac_get_emulated_btn (er.modifiers);
9913 inev.modifiers = mac_to_emacs_modifiers (er.modifiers);
9914 #endif
9915 XSETINT (inev.x, mouse_loc.h);
9916 XSETINT (inev.y, mouse_loc.v);
9917
9918 if ((dpyinfo->grabbed && tracked_scroll_bar)
9919 || (ch != 0
9920 #ifndef USE_TOOLKIT_SCROLL_BARS
9921 /* control_part_code becomes kControlNoPart if
9922 a progress indicator is clicked. */
9923 && control_part_code != kControlNoPart
9924 #else /* USE_TOOLKIT_SCROLL_BARS */
9925 #ifdef MAC_OSX
9926 && control_kind.kind == kControlKindScrollBar
9927 #endif /* MAC_OSX */
9928 #endif /* USE_TOOLKIT_SCROLL_BARS */
9929 ))
9930 {
9931 struct scroll_bar *bar;
9932
9933 if (dpyinfo->grabbed && tracked_scroll_bar)
9934 {
9935 bar = tracked_scroll_bar;
9936 #ifndef USE_TOOLKIT_SCROLL_BARS
9937 control_part_code = kControlIndicatorPart;
9938 #endif
9939 }
9940 else
9941 bar = (struct scroll_bar *) GetControlReference (ch);
9942 #ifdef USE_TOOLKIT_SCROLL_BARS
9943 /* Make the "Ctrl-Mouse-2 splits window" work
9944 for toolkit scroll bars. */
9945 if (er.modifiers & controlKey)
9946 x_scroll_bar_handle_click (bar, control_part_code,
9947 &er, &inev);
9948 else if (er.what == mouseDown)
9949 x_scroll_bar_handle_press (bar, control_part_code,
9950 &inev);
9951 else
9952 x_scroll_bar_handle_release (bar, &inev);
9953 #else /* not USE_TOOLKIT_SCROLL_BARS */
9954 x_scroll_bar_handle_click (bar, control_part_code,
9955 &er, &inev);
9956 if (er.what == mouseDown
9957 && control_part_code == kControlIndicatorPart)
9958 tracked_scroll_bar = bar;
9959 else
9960 tracked_scroll_bar = NULL;
9961 #endif /* not USE_TOOLKIT_SCROLL_BARS */
9962 }
9963 else
9964 {
9965 Lisp_Object window;
9966 int x = mouse_loc.h;
9967 int y = mouse_loc.v;
9968
9969 window = window_from_coordinates (f, x, y, 0, 0, 0, 1);
9970 if (EQ (window, f->tool_bar_window))
9971 {
9972 if (er.what == mouseDown)
9973 handle_tool_bar_click (f, x, y, 1, 0);
9974 else
9975 handle_tool_bar_click (f, x, y, 0,
9976 inev.modifiers);
9977 tool_bar_p = 1;
9978 }
9979 else
9980 {
9981 XSETFRAME (inev.frame_or_window, f);
9982 inev.kind = MOUSE_CLICK_EVENT;
9983 }
9984 }
9985
9986 if (er.what == mouseDown)
9987 {
9988 dpyinfo->grabbed |= (1 << inev.code);
9989 last_mouse_frame = f;
9990
9991 if (!tool_bar_p)
9992 last_tool_bar_item = -1;
9993 }
9994 else
9995 {
9996 if ((dpyinfo->grabbed & (1 << inev.code)) == 0)
9997 /* If a button is released though it was not
9998 previously pressed, that would be because
9999 of multi-button emulation. */
10000 dpyinfo->grabbed = 0;
10001 else
10002 dpyinfo->grabbed &= ~(1 << inev.code);
10003 }
10004
10005 /* Ignore any mouse motion that happened before
10006 this event; any subsequent mouse-movement Emacs
10007 events should reflect only motion after the
10008 ButtonPress. */
10009 if (f != 0)
10010 f->mouse_moved = 0;
10011
10012 #ifdef USE_TOOLKIT_SCROLL_BARS
10013 if (inev.kind == MOUSE_CLICK_EVENT)
10014 #endif
10015 switch (er.what)
10016 {
10017 case mouseDown:
10018 inev.modifiers |= down_modifier;
10019 break;
10020 case mouseUp:
10021 inev.modifiers |= up_modifier;
10022 break;
10023 }
10024 }
10025 break;
10026
10027 case inDrag:
10028 #if TARGET_API_MAC_CARBON
10029 DragWindow (window_ptr, er.where, NULL);
10030 #else /* not TARGET_API_MAC_CARBON */
10031 DragWindow (window_ptr, er.where, &qd.screenBits.bounds);
10032 #endif /* not TARGET_API_MAC_CARBON */
10033 /* Update the frame parameters. */
10034 {
10035 struct frame *f = mac_window_to_frame (window_ptr);
10036
10037 if (f && !f->async_iconified)
10038 x_real_positions (f, &f->left_pos, &f->top_pos);
10039 }
10040 break;
10041
10042 case inGoAway:
10043 if (TrackGoAway (window_ptr, er.where))
10044 {
10045 inev.kind = DELETE_WINDOW_EVENT;
10046 XSETFRAME (inev.frame_or_window,
10047 mac_window_to_frame (window_ptr));
10048 }
10049 break;
10050
10051 /* window resize handling added --ben */
10052 case inGrow:
10053 do_grow_window (window_ptr, &er);
10054 break;
10055
10056 /* window zoom handling added --ben */
10057 case inZoomIn:
10058 case inZoomOut:
10059 if (TrackBox (window_ptr, er.where, part_code))
10060 do_zoom_window (window_ptr, part_code);
10061 break;
10062
10063 default:
10064 break;
10065 }
10066 }
10067 break;
10068
10069 case updateEvt:
10070 #if USE_CARBON_EVENTS
10071 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
10072 != eventNotHandledErr)
10073 break;
10074 #else
10075 do_window_update ((WindowPtr) er.message);
10076 #endif
10077 break;
10078
10079 case osEvt:
10080 #if USE_CARBON_EVENTS
10081 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
10082 != eventNotHandledErr)
10083 break;
10084 #endif
10085 switch ((er.message >> 24) & 0x000000FF)
10086 {
10087 case suspendResumeMessage:
10088 if ((er.message & resumeFlag) == 1)
10089 do_app_resume ();
10090 else
10091 do_app_suspend ();
10092 break;
10093
10094 case mouseMovedMessage:
10095 #if !USE_CARBON_EVENTS
10096 SetRectRgn (mouse_region, er.where.h, er.where.v,
10097 er.where.h + 1, er.where.v + 1);
10098 #endif
10099 previous_help_echo_string = help_echo_string;
10100 help_echo_string = Qnil;
10101
10102 if (dpyinfo->grabbed && last_mouse_frame
10103 && FRAME_LIVE_P (last_mouse_frame))
10104 f = last_mouse_frame;
10105 else
10106 f = dpyinfo->x_focus_frame;
10107
10108 if (dpyinfo->mouse_face_hidden)
10109 {
10110 dpyinfo->mouse_face_hidden = 0;
10111 clear_mouse_face (dpyinfo);
10112 }
10113
10114 if (f)
10115 {
10116 WindowPtr wp = FRAME_MAC_WINDOW (f);
10117 Point mouse_pos = er.where;
10118
10119 SetPortWindowPort (wp);
10120
10121 GlobalToLocal (&mouse_pos);
10122
10123 if (dpyinfo->grabbed && tracked_scroll_bar)
10124 #ifdef USE_TOOLKIT_SCROLL_BARS
10125 x_scroll_bar_handle_drag (wp, tracked_scroll_bar,
10126 mouse_pos, &inev);
10127 #else /* not USE_TOOLKIT_SCROLL_BARS */
10128 x_scroll_bar_note_movement (tracked_scroll_bar,
10129 mouse_pos.v
10130 - XINT (tracked_scroll_bar->top),
10131 er.when * (1000 / 60));
10132 #endif /* not USE_TOOLKIT_SCROLL_BARS */
10133 else
10134 {
10135 /* Generate SELECT_WINDOW_EVENTs when needed. */
10136 if (mouse_autoselect_window)
10137 {
10138 Lisp_Object window;
10139
10140 window = window_from_coordinates (f,
10141 mouse_pos.h,
10142 mouse_pos.v,
10143 0, 0, 0, 0);
10144
10145 /* Window will be selected only when it is
10146 not selected now and last mouse movement
10147 event was not in it. Minibuffer window
10148 will be selected iff it is active. */
10149 if (WINDOWP (window)
10150 && !EQ (window, last_window)
10151 && !EQ (window, selected_window))
10152 {
10153 inev.kind = SELECT_WINDOW_EVENT;
10154 inev.frame_or_window = window;
10155 }
10156
10157 last_window=window;
10158 }
10159 if (!note_mouse_movement (f, &mouse_pos))
10160 help_echo_string = previous_help_echo_string;
10161 }
10162 }
10163
10164 /* If the contents of the global variable
10165 help_echo_string has changed, generate a
10166 HELP_EVENT. */
10167 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
10168 do_help = 1;
10169 break;
10170 }
10171 break;
10172
10173 case activateEvt:
10174 {
10175 WindowPtr window_ptr = (WindowPtr) er.message;
10176
10177 #if USE_CARBON_EVENTS
10178 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
10179 != eventNotHandledErr)
10180 break;
10181 #endif
10182 if (window_ptr == tip_window)
10183 {
10184 HideWindow (tip_window);
10185 break;
10186 }
10187
10188 if (!is_emacs_window (window_ptr))
10189 break;
10190
10191 if ((er.modifiers & activeFlag) != 0)
10192 {
10193 /* A window has been activated */
10194 Point mouse_loc = er.where;
10195
10196 x_detect_focus_change (dpyinfo, &er, &inev);
10197
10198 SetPortWindowPort (window_ptr);
10199 GlobalToLocal (&mouse_loc);
10200 /* Window-activated event counts as mouse movement,
10201 so update things that depend on mouse position. */
10202 note_mouse_movement (mac_window_to_frame (window_ptr),
10203 &mouse_loc);
10204 }
10205 else
10206 {
10207 /* A window has been deactivated */
10208 #if USE_TOOLKIT_SCROLL_BARS
10209 if (dpyinfo->grabbed && tracked_scroll_bar)
10210 {
10211 struct input_event event;
10212
10213 EVENT_INIT (event);
10214 event.kind = NO_EVENT;
10215 x_scroll_bar_handle_release (tracked_scroll_bar, &event);
10216 if (event.kind != NO_EVENT)
10217 {
10218 event.timestamp = timestamp;
10219 kbd_buffer_store_event_hold (&event, hold_quit);
10220 count++;
10221 }
10222 }
10223 #endif
10224 dpyinfo->grabbed = 0;
10225
10226 x_detect_focus_change (dpyinfo, &er, &inev);
10227
10228 f = mac_window_to_frame (window_ptr);
10229 if (f == dpyinfo->mouse_face_mouse_frame)
10230 {
10231 /* If we move outside the frame, then we're
10232 certainly no longer on any text in the
10233 frame. */
10234 clear_mouse_face (dpyinfo);
10235 dpyinfo->mouse_face_mouse_frame = 0;
10236 }
10237
10238 /* Generate a nil HELP_EVENT to cancel a help-echo.
10239 Do it only if there's something to cancel.
10240 Otherwise, the startup message is cleared when the
10241 mouse leaves the frame. */
10242 if (any_help_event_p)
10243 do_help = -1;
10244 }
10245 }
10246 break;
10247
10248 case keyDown:
10249 case autoKey:
10250 {
10251 int keycode = (er.message & keyCodeMask) >> 8;
10252 int xkeysym;
10253
10254 #if USE_CARBON_EVENTS && defined (MAC_OSX)
10255 /* When using Carbon Events, we need to pass raw keyboard
10256 events to the TSM ourselves. If TSM handles it, it
10257 will pass back noErr, otherwise it will pass back
10258 "eventNotHandledErr" and we can process it
10259 normally. */
10260 if ((mac_pass_command_to_system
10261 || !(er.modifiers & cmdKey))
10262 && (mac_pass_control_to_system
10263 || !(er.modifiers & controlKey))
10264 && (NILP (Vmac_option_modifier)
10265 || !(er.modifiers & optionKey)))
10266 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
10267 != eventNotHandledErr)
10268 break;
10269 #endif
10270
10271 #if 0
10272 if (dpyinfo->x_focus_frame == NULL)
10273 {
10274 /* Beep if keyboard input occurs when all the frames
10275 are invisible. */
10276 SysBeep (1);
10277 break;
10278 }
10279 #endif
10280
10281 {
10282 static SInt16 last_key_script = -1;
10283 SInt16 current_key_script = GetScriptManagerVariable (smKeyScript);
10284
10285 if (last_key_script != current_key_script)
10286 {
10287 struct input_event event;
10288
10289 EVENT_INIT (event);
10290 event.kind = LANGUAGE_CHANGE_EVENT;
10291 event.arg = Qnil;
10292 event.code = current_key_script;
10293 event.timestamp = timestamp;
10294 kbd_buffer_store_event (&event);
10295 count++;
10296 }
10297 last_key_script = current_key_script;
10298 }
10299
10300 ObscureCursor ();
10301
10302 f = mac_focus_frame (dpyinfo);
10303
10304 if (!dpyinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight)
10305 && !EQ (f->tool_bar_window, dpyinfo->mouse_face_window))
10306 {
10307 clear_mouse_face (dpyinfo);
10308 dpyinfo->mouse_face_hidden = 1;
10309 }
10310
10311 /* translate the keycode back to determine the original key */
10312 /* Convert key code if function key is pressed.
10313 Otherwise, if non-ASCII-event, take care of that
10314 without re-translating the key code. */
10315 #if USE_CARBON_EVENTS
10316 if (convert_fn_keycode (eventRef, keycode, &xkeysym))
10317 {
10318 inev.code = xkeysym;
10319 /* this doesn't work - tried to add shift modifiers */
10320 inev.code =
10321 backtranslate_modified_keycode(er.modifiers & (~0x2200),
10322 xkeysym | 0x80, xkeysym);
10323 inev.kind = ASCII_KEYSTROKE_EVENT;
10324 }
10325 else
10326 #endif
10327 if (keycode_to_xkeysym (keycode, &xkeysym))
10328 {
10329 inev.code = 0xff00 | xkeysym;
10330 inev.kind = NON_ASCII_KEYSTROKE_EVENT;
10331 }
10332 else
10333 {
10334 inev.code =
10335 backtranslate_modified_keycode(er.modifiers, keycode,
10336 er.message & charCodeMask);
10337 inev.kind = ASCII_KEYSTROKE_EVENT;
10338 }
10339 }
10340
10341 #if USE_CARBON_EVENTS
10342 inev.modifiers = mac_event_to_emacs_modifiers (eventRef);
10343 #else
10344 inev.modifiers = mac_to_emacs_modifiers (er.modifiers);
10345 #endif
10346 inev.modifiers |= (extra_keyboard_modifiers
10347 & (meta_modifier | alt_modifier
10348 | hyper_modifier | super_modifier));
10349 XSETFRAME (inev.frame_or_window, f);
10350 break;
10351
10352 case kHighLevelEvent:
10353 read_socket_inev = &inev;
10354 AEProcessAppleEvent (&er);
10355 read_socket_inev = NULL;
10356 break;
10357
10358 default:
10359 break;
10360 }
10361 #if USE_CARBON_EVENTS
10362 ReleaseEvent (eventRef);
10363 #endif
10364
10365 if (inev.kind != NO_EVENT)
10366 {
10367 inev.timestamp = timestamp;
10368 kbd_buffer_store_event_hold (&inev, hold_quit);
10369 count++;
10370 }
10371
10372 if (do_help
10373 && !(hold_quit && hold_quit->kind != NO_EVENT))
10374 {
10375 Lisp_Object frame;
10376
10377 if (f)
10378 XSETFRAME (frame, f);
10379 else
10380 frame = Qnil;
10381
10382 if (do_help > 0)
10383 {
10384 any_help_event_p = 1;
10385 gen_help_event (help_echo_string, frame, help_echo_window,
10386 help_echo_object, help_echo_pos);
10387 }
10388 else
10389 {
10390 help_echo_string = Qnil;
10391 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
10392 }
10393 count++;
10394 }
10395
10396 }
10397
10398 /* If the focus was just given to an autoraising frame,
10399 raise it now. */
10400 /* ??? This ought to be able to handle more than one such frame. */
10401 if (pending_autoraise_frame)
10402 {
10403 x_raise_frame (pending_autoraise_frame);
10404 pending_autoraise_frame = 0;
10405 }
10406
10407 #if !USE_CARBON_EVENTS
10408 /* Check which frames are still visible. We do this here because
10409 there doesn't seem to be any direct notification from the Window
10410 Manager that the visibility of a window has changed (at least,
10411 not in all cases). */
10412 {
10413 Lisp_Object tail, frame;
10414
10415 FOR_EACH_FRAME (tail, frame)
10416 {
10417 struct frame *f = XFRAME (frame);
10418
10419 /* The tooltip has been drawn already. Avoid the
10420 SET_FRAME_GARBAGED in mac_handle_visibility_change. */
10421 if (EQ (frame, tip_frame))
10422 continue;
10423
10424 if (FRAME_MAC_P (f))
10425 mac_handle_visibility_change (f);
10426 }
10427 }
10428 #endif
10429
10430 --handling_signal;
10431 UNBLOCK_INPUT;
10432 return count;
10433 }
10434
10435
10436 /* Need to override CodeWarrior's input function so no conversion is
10437 done on newlines Otherwise compiled functions in .elc files will be
10438 read incorrectly. Defined in ...:MSL C:MSL
10439 Common:Source:buffer_io.c. */
10440 #ifdef __MWERKS__
10441 void
10442 __convert_to_newlines (unsigned char * p, size_t * n)
10443 {
10444 #pragma unused(p,n)
10445 }
10446
10447 void
10448 __convert_from_newlines (unsigned char * p, size_t * n)
10449 {
10450 #pragma unused(p,n)
10451 }
10452 #endif
10453
10454 #ifdef MAC_OS8
10455 void
10456 make_mac_terminal_frame (struct frame *f)
10457 {
10458 Lisp_Object frame;
10459 Rect r;
10460
10461 XSETFRAME (frame, f);
10462
10463 f->output_method = output_mac;
10464 f->output_data.mac = (struct mac_output *)
10465 xmalloc (sizeof (struct mac_output));
10466 bzero (f->output_data.mac, sizeof (struct mac_output));
10467
10468 XSETFRAME (FRAME_KBOARD (f)->Vdefault_minibuffer_frame, f);
10469
10470 FRAME_COLS (f) = 96;
10471 FRAME_LINES (f) = 4;
10472
10473 FRAME_CAN_HAVE_SCROLL_BARS (f) = 1;
10474 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = vertical_scroll_bar_right;
10475
10476 FRAME_DESIRED_CURSOR (f) = FILLED_BOX_CURSOR;
10477
10478 f->output_data.mac->cursor_pixel = 0;
10479 f->output_data.mac->border_pixel = 0x00ff00;
10480 f->output_data.mac->mouse_pixel = 0xff00ff;
10481 f->output_data.mac->cursor_foreground_pixel = 0x0000ff;
10482
10483 f->output_data.mac->text_cursor = kThemeIBeamCursor;
10484 f->output_data.mac->nontext_cursor = kThemeArrowCursor;
10485 f->output_data.mac->modeline_cursor = kThemeArrowCursor;
10486 f->output_data.mac->hand_cursor = kThemePointingHandCursor;
10487 f->output_data.mac->hourglass_cursor = kThemeWatchCursor;
10488 f->output_data.mac->horizontal_drag_cursor = kThemeResizeLeftRightCursor;
10489
10490 FRAME_FONTSET (f) = -1;
10491 f->output_data.mac->explicit_parent = 0;
10492 f->left_pos = 8;
10493 f->top_pos = 32;
10494 f->border_width = 0;
10495
10496 f->internal_border_width = 0;
10497
10498 f->auto_raise = 1;
10499 f->auto_lower = 1;
10500
10501 f->new_text_cols = 0;
10502 f->new_text_lines = 0;
10503
10504 SetRect (&r, f->left_pos, f->top_pos,
10505 f->left_pos + FRAME_PIXEL_WIDTH (f),
10506 f->top_pos + FRAME_PIXEL_HEIGHT (f));
10507
10508 BLOCK_INPUT;
10509
10510 if (!(FRAME_MAC_WINDOW (f) =
10511 NewCWindow (NULL, &r, "\p", true, dBoxProc,
10512 (WindowPtr) -1, 1, (long) f->output_data.mac)))
10513 abort ();
10514 /* so that update events can find this mac_output struct */
10515 f->output_data.mac->mFP = f; /* point back to emacs frame */
10516
10517 UNBLOCK_INPUT;
10518
10519 x_make_gc (f);
10520
10521 /* Need to be initialized for unshow_buffer in window.c. */
10522 selected_window = f->selected_window;
10523
10524 Fmodify_frame_parameters (frame,
10525 Fcons (Fcons (Qfont,
10526 build_string ("-*-monaco-medium-r-*--*-90-*-*-*-*-mac-roman")), Qnil));
10527 Fmodify_frame_parameters (frame,
10528 Fcons (Fcons (Qforeground_color,
10529 build_string ("black")), Qnil));
10530 Fmodify_frame_parameters (frame,
10531 Fcons (Fcons (Qbackground_color,
10532 build_string ("white")), Qnil));
10533 }
10534 #endif
10535
10536 \f
10537 /***********************************************************************
10538 Initialization
10539 ***********************************************************************/
10540
10541 int mac_initialized = 0;
10542
10543 void
10544 mac_initialize_display_info ()
10545 {
10546 struct mac_display_info *dpyinfo = &one_mac_display_info;
10547 GDHandle main_device_handle;
10548
10549 bzero (dpyinfo, sizeof (*dpyinfo));
10550
10551 #ifdef MAC_OSX
10552 dpyinfo->mac_id_name
10553 = (char *) xmalloc (SCHARS (Vinvocation_name)
10554 + SCHARS (Vsystem_name)
10555 + 2);
10556 sprintf (dpyinfo->mac_id_name, "%s@%s",
10557 SDATA (Vinvocation_name), SDATA (Vsystem_name));
10558 #else
10559 dpyinfo->mac_id_name = (char *) xmalloc (strlen ("Mac Display") + 1);
10560 strcpy (dpyinfo->mac_id_name, "Mac Display");
10561 #endif
10562
10563 main_device_handle = LMGetMainDevice();
10564
10565 dpyinfo->reference_count = 0;
10566 dpyinfo->resx = 72.0;
10567 dpyinfo->resy = 72.0;
10568 dpyinfo->color_p = TestDeviceAttribute (main_device_handle, gdDevType);
10569 #ifdef MAC_OSX
10570 /* HasDepth returns true if it is possible to have a 32 bit display,
10571 but this may not be what is actually used. Mac OSX can do better.
10572 CGMainDisplayID is only available on OSX 10.2 and higher, but the
10573 header for CGGetActiveDisplayList says that the first display returned
10574 is the active one, so we use that. */
10575 {
10576 CGDirectDisplayID disp_id[1];
10577 CGDisplayCount disp_count;
10578 CGDisplayErr error_code;
10579
10580 error_code = CGGetActiveDisplayList (1, disp_id, &disp_count);
10581 if (error_code != 0)
10582 error ("No display found, CGGetActiveDisplayList error %d", error_code);
10583
10584 dpyinfo->n_planes = CGDisplayBitsPerPixel (disp_id[0]);
10585 }
10586 #else
10587 for (dpyinfo->n_planes = 32; dpyinfo->n_planes > 0; dpyinfo->n_planes >>= 1)
10588 if (HasDepth (main_device_handle, dpyinfo->n_planes,
10589 gdDevType, dpyinfo->color_p))
10590 break;
10591 #endif
10592 dpyinfo->height = (**main_device_handle).gdRect.bottom;
10593 dpyinfo->width = (**main_device_handle).gdRect.right;
10594 dpyinfo->grabbed = 0;
10595 dpyinfo->root_window = NULL;
10596 dpyinfo->image_cache = make_image_cache ();
10597
10598 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
10599 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
10600 dpyinfo->mouse_face_face_id = DEFAULT_FACE_ID;
10601 dpyinfo->mouse_face_window = Qnil;
10602 dpyinfo->mouse_face_overlay = Qnil;
10603 dpyinfo->mouse_face_hidden = 0;
10604 }
10605
10606
10607 static XrmDatabase
10608 mac_make_rdb (xrm_option)
10609 char *xrm_option;
10610 {
10611 XrmDatabase database;
10612
10613 database = xrm_get_preference_database (NULL);
10614 if (xrm_option)
10615 xrm_merge_string_database (database, xrm_option);
10616
10617 return database;
10618 }
10619
10620 struct mac_display_info *
10621 mac_term_init (display_name, xrm_option, resource_name)
10622 Lisp_Object display_name;
10623 char *xrm_option;
10624 char *resource_name;
10625 {
10626 struct mac_display_info *dpyinfo;
10627
10628 BLOCK_INPUT;
10629
10630 if (!mac_initialized)
10631 {
10632 mac_initialize ();
10633 mac_initialized = 1;
10634 }
10635
10636 if (x_display_list)
10637 error ("Sorry, this version can only handle one display");
10638
10639 mac_initialize_display_info ();
10640
10641 dpyinfo = &one_mac_display_info;
10642
10643 dpyinfo->xrdb = mac_make_rdb (xrm_option);
10644
10645 /* Put this display on the chain. */
10646 dpyinfo->next = x_display_list;
10647 x_display_list = dpyinfo;
10648
10649 /* Put it on x_display_name_list. */
10650 x_display_name_list = Fcons (Fcons (display_name,
10651 Fcons (Qnil, dpyinfo->xrdb)),
10652 x_display_name_list);
10653 dpyinfo->name_list_element = XCAR (x_display_name_list);
10654
10655 UNBLOCK_INPUT;
10656
10657 return dpyinfo;
10658 }
10659 /* Get rid of display DPYINFO, assuming all frames are already gone. */
10660
10661 void
10662 x_delete_display (dpyinfo)
10663 struct mac_display_info *dpyinfo;
10664 {
10665 int i;
10666
10667 /* Discard this display from x_display_name_list and x_display_list.
10668 We can't use Fdelq because that can quit. */
10669 if (! NILP (x_display_name_list)
10670 && EQ (XCAR (x_display_name_list), dpyinfo->name_list_element))
10671 x_display_name_list = XCDR (x_display_name_list);
10672 else
10673 {
10674 Lisp_Object tail;
10675
10676 tail = x_display_name_list;
10677 while (CONSP (tail) && CONSP (XCDR (tail)))
10678 {
10679 if (EQ (XCAR (XCDR (tail)), dpyinfo->name_list_element))
10680 {
10681 XSETCDR (tail, XCDR (XCDR (tail)));
10682 break;
10683 }
10684 tail = XCDR (tail);
10685 }
10686 }
10687
10688 if (x_display_list == dpyinfo)
10689 x_display_list = dpyinfo->next;
10690 else
10691 {
10692 struct x_display_info *tail;
10693
10694 for (tail = x_display_list; tail; tail = tail->next)
10695 if (tail->next == dpyinfo)
10696 tail->next = tail->next->next;
10697 }
10698
10699 /* Free the font names in the font table. */
10700 for (i = 0; i < dpyinfo->n_fonts; i++)
10701 if (dpyinfo->font_table[i].name)
10702 {
10703 if (dpyinfo->font_table[i].name != dpyinfo->font_table[i].full_name)
10704 xfree (dpyinfo->font_table[i].full_name);
10705 xfree (dpyinfo->font_table[i].name);
10706 }
10707
10708 if (dpyinfo->font_table->font_encoder)
10709 xfree (dpyinfo->font_table->font_encoder);
10710
10711 xfree (dpyinfo->font_table);
10712 xfree (dpyinfo->mac_id_name);
10713
10714 if (x_display_list == 0)
10715 {
10716 mac_clear_font_name_table ();
10717 bzero (dpyinfo, sizeof (*dpyinfo));
10718 }
10719 }
10720
10721 \f
10722 #ifdef MAC_OSX
10723 void
10724 mac_check_bundle()
10725 {
10726 extern int inhibit_window_system;
10727 extern int noninteractive;
10728 CFBundleRef appsBundle;
10729
10730 /* No need to test if already -nw*/
10731 if (inhibit_window_system || noninteractive)
10732 return;
10733
10734 appsBundle = CFBundleGetMainBundle();
10735 if (appsBundle != NULL)
10736 {
10737 CFStringRef cfBI = CFSTR("CFBundleIdentifier");
10738 CFTypeRef res = CFBundleGetValueForInfoDictionaryKey(appsBundle, cfBI);
10739 /* We found the bundle identifier, now we know we are valid. */
10740 if (res != NULL)
10741 {
10742 CFRelease(res);
10743 return;
10744 }
10745 }
10746 /* MAC_TODO: Have this start the bundled executable */
10747
10748 /* For now, prevent the fatal error by bringing it up in the terminal */
10749 inhibit_window_system = 1;
10750 }
10751
10752 void
10753 MakeMeTheFrontProcess ()
10754 {
10755 ProcessSerialNumber psn;
10756 OSErr err;
10757
10758 err = GetCurrentProcess (&psn);
10759 if (err == noErr)
10760 (void) SetFrontProcess (&psn);
10761 }
10762
10763 /***** Code to handle C-g testing *****/
10764
10765 /* Contains the Mac modifier formed from quit_char */
10766 int mac_quit_char_modifiers = 0;
10767 int mac_quit_char_keycode;
10768 extern int quit_char;
10769
10770 static void
10771 mac_determine_quit_char_modifiers()
10772 {
10773 /* Todo: Determine modifiers from quit_char. */
10774 UInt32 qc_modifiers = ctrl_modifier;
10775
10776 /* Map modifiers */
10777 mac_quit_char_modifiers = 0;
10778 if (qc_modifiers & ctrl_modifier) mac_quit_char_modifiers |= controlKey;
10779 if (qc_modifiers & shift_modifier) mac_quit_char_modifiers |= shiftKey;
10780 if (qc_modifiers & alt_modifier) mac_quit_char_modifiers |= optionKey;
10781 }
10782
10783 static void
10784 init_quit_char_handler ()
10785 {
10786 /* TODO: Let this support keys other the 'g' */
10787 mac_quit_char_keycode = 5;
10788 /* Look at <architecture/adb_kb_map.h> for details */
10789 /* http://gemma.apple.com/techpubs/mac/Toolbox/Toolbox-40.html#MARKER-9-184*/
10790
10791 mac_determine_quit_char_modifiers();
10792 }
10793 #endif /* MAC_OSX */
10794
10795 static void
10796 init_menu_bar ()
10797 {
10798 #ifdef MAC_OSX
10799 OSErr err;
10800 MenuRef menu;
10801 MenuItemIndex menu_index;
10802
10803 err = GetIndMenuItemWithCommandID (NULL, kHICommandQuit, 1,
10804 &menu, &menu_index);
10805 if (err == noErr)
10806 SetMenuItemCommandKey (menu, menu_index, false, 0);
10807 #if USE_CARBON_EVENTS
10808 EnableMenuCommand (NULL, kHICommandPreferences);
10809 err = GetIndMenuItemWithCommandID (NULL, kHICommandPreferences, 1,
10810 &menu, &menu_index);
10811 if (err == noErr)
10812 {
10813 SetMenuItemCommandKey (menu, menu_index, false, 0);
10814 InsertMenuItemTextWithCFString (menu, NULL,
10815 0, kMenuItemAttrSeparator, 0);
10816 InsertMenuItemTextWithCFString (menu, CFSTR ("About Emacs"),
10817 0, 0, kHICommandAbout);
10818 }
10819 #endif /* USE_CARBON_EVENTS */
10820 #else /* !MAC_OSX */
10821 #if USE_CARBON_EVENTS
10822 SetMenuItemCommandID (GetMenuHandle (M_APPLE), I_ABOUT, kHICommandAbout);
10823 #endif
10824 #endif
10825 }
10826
10827
10828 /* Set up use of X before we make the first connection. */
10829
10830 extern frame_parm_handler mac_frame_parm_handlers[];
10831
10832 static struct redisplay_interface x_redisplay_interface =
10833 {
10834 mac_frame_parm_handlers,
10835 x_produce_glyphs,
10836 x_write_glyphs,
10837 x_insert_glyphs,
10838 x_clear_end_of_line,
10839 x_scroll_run,
10840 x_after_update_window_line,
10841 x_update_window_begin,
10842 x_update_window_end,
10843 x_cursor_to,
10844 x_flush,
10845 0, /* flush_display_optional */
10846 x_clear_window_mouse_face,
10847 x_get_glyph_overhangs,
10848 x_fix_overlapping_area,
10849 x_draw_fringe_bitmap,
10850 #if USE_CG_DRAWING
10851 mac_define_fringe_bitmap,
10852 mac_destroy_fringe_bitmap,
10853 #else
10854 0, /* define_fringe_bitmap */
10855 0, /* destroy_fringe_bitmap */
10856 #endif
10857 mac_per_char_metric,
10858 mac_encode_char,
10859 mac_compute_glyph_string_overhangs,
10860 x_draw_glyph_string,
10861 mac_define_frame_cursor,
10862 mac_clear_frame_area,
10863 mac_draw_window_cursor,
10864 mac_draw_vertical_window_border,
10865 mac_shift_glyphs_for_insert
10866 };
10867
10868 void
10869 mac_initialize ()
10870 {
10871 rif = &x_redisplay_interface;
10872
10873 clear_frame_hook = x_clear_frame;
10874 ins_del_lines_hook = x_ins_del_lines;
10875 delete_glyphs_hook = x_delete_glyphs;
10876 ring_bell_hook = XTring_bell;
10877 reset_terminal_modes_hook = XTreset_terminal_modes;
10878 set_terminal_modes_hook = XTset_terminal_modes;
10879 update_begin_hook = x_update_begin;
10880 update_end_hook = x_update_end;
10881 set_terminal_window_hook = XTset_terminal_window;
10882 read_socket_hook = XTread_socket;
10883 frame_up_to_date_hook = XTframe_up_to_date;
10884 mouse_position_hook = XTmouse_position;
10885 frame_rehighlight_hook = XTframe_rehighlight;
10886 frame_raise_lower_hook = XTframe_raise_lower;
10887
10888 set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
10889 condemn_scroll_bars_hook = XTcondemn_scroll_bars;
10890 redeem_scroll_bar_hook = XTredeem_scroll_bar;
10891 judge_scroll_bars_hook = XTjudge_scroll_bars;
10892
10893 scroll_region_ok = 1; /* we'll scroll partial frames */
10894 char_ins_del_ok = 1;
10895 line_ins_del_ok = 1; /* we'll just blt 'em */
10896 fast_clear_end_of_line = 1; /* X does this well */
10897 memory_below_frame = 0; /* we don't remember what scrolls
10898 off the bottom */
10899 baud_rate = 19200;
10900
10901 last_tool_bar_item = -1;
10902 any_help_event_p = 0;
10903
10904 /* Try to use interrupt input; if we can't, then start polling. */
10905 Fset_input_mode (Qt, Qnil, Qt, Qnil);
10906
10907 BLOCK_INPUT;
10908
10909 #if TARGET_API_MAC_CARBON
10910
10911 #if USE_CARBON_EVENTS
10912 #ifdef MAC_OSX
10913 init_service_handler ();
10914
10915 init_quit_char_handler ();
10916 #endif /* MAC_OSX */
10917
10918 init_command_handler ();
10919
10920 init_menu_bar ();
10921 #endif /* USE_CARBON_EVENTS */
10922
10923 #ifdef MAC_OSX
10924 init_coercion_handler ();
10925
10926 init_apple_event_handler ();
10927
10928 if (!inhibit_window_system)
10929 MakeMeTheFrontProcess ();
10930 #endif
10931 #endif
10932
10933 #if USE_CG_DRAWING
10934 mac_init_fringe ();
10935 #endif
10936
10937 UNBLOCK_INPUT;
10938 }
10939
10940
10941 void
10942 syms_of_macterm ()
10943 {
10944 #if 0
10945 staticpro (&x_error_message_string);
10946 x_error_message_string = Qnil;
10947 #endif
10948
10949 Qcontrol = intern ("control"); staticpro (&Qcontrol);
10950 Qmeta = intern ("meta"); staticpro (&Qmeta);
10951 Qalt = intern ("alt"); staticpro (&Qalt);
10952 Qhyper = intern ("hyper"); staticpro (&Qhyper);
10953 Qsuper = intern ("super"); staticpro (&Qsuper);
10954 Qmodifier_value = intern ("modifier-value");
10955 staticpro (&Qmodifier_value);
10956
10957 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
10958 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
10959 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
10960 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
10961 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
10962
10963 #if USE_CARBON_EVENTS
10964 Qhicommand = intern ("hicommand"); staticpro (&Qhicommand);
10965 #ifdef MAC_OSX
10966 Qservices = intern ("services"); staticpro (&Qservices);
10967 Qpaste = intern ("paste"); staticpro (&Qpaste);
10968 Qperform = intern ("perform"); staticpro (&Qperform);
10969 #endif
10970 #endif
10971
10972 #ifdef MAC_OSX
10973 Fprovide (intern ("mac-carbon"), Qnil);
10974 #endif
10975
10976 staticpro (&Qreverse);
10977 Qreverse = intern ("reverse");
10978
10979 staticpro (&x_display_name_list);
10980 x_display_name_list = Qnil;
10981
10982 staticpro (&last_mouse_scroll_bar);
10983 last_mouse_scroll_bar = Qnil;
10984
10985 staticpro (&fm_font_family_alist);
10986 fm_font_family_alist = Qnil;
10987
10988 #if USE_ATSUI
10989 staticpro (&atsu_font_id_hash);
10990 atsu_font_id_hash = Qnil;
10991 #endif
10992
10993 /* We don't yet support this, but defining this here avoids whining
10994 from cus-start.el and other places, like "M-x set-variable". */
10995 DEFVAR_BOOL ("x-use-underline-position-properties",
10996 &x_use_underline_position_properties,
10997 doc: /* *Non-nil means make use of UNDERLINE_POSITION font properties.
10998 nil means ignore them. If you encounter fonts with bogus
10999 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
11000 to 4.1, set this to nil.
11001
11002 NOTE: Not supported on Mac yet. */);
11003 x_use_underline_position_properties = 0;
11004
11005 DEFVAR_LISP ("x-toolkit-scroll-bars", &Vx_toolkit_scroll_bars,
11006 doc: /* If not nil, Emacs uses toolkit scroll bars. */);
11007 #ifdef USE_TOOLKIT_SCROLL_BARS
11008 Vx_toolkit_scroll_bars = Qt;
11009 #else
11010 Vx_toolkit_scroll_bars = Qnil;
11011 #endif
11012
11013 staticpro (&last_mouse_motion_frame);
11014 last_mouse_motion_frame = Qnil;
11015
11016 /* Variables to configure modifier key assignment. */
11017
11018 DEFVAR_LISP ("mac-control-modifier", &Vmac_control_modifier,
11019 doc: /* *Modifier key assumed when the Mac control key is pressed.
11020 The value can be `control', `meta', `alt', `hyper', or `super' for the
11021 respective modifier. The default is `control'. */);
11022 Vmac_control_modifier = Qcontrol;
11023
11024 DEFVAR_LISP ("mac-option-modifier", &Vmac_option_modifier,
11025 doc: /* *Modifier key assumed when the Mac alt/option key is pressed.
11026 The value can be `control', `meta', `alt', `hyper', or `super' for the
11027 respective modifier. If the value is nil then the key will act as the
11028 normal Mac control modifier, and the option key can be used to compose
11029 characters depending on the chosen Mac keyboard setting. */);
11030 Vmac_option_modifier = Qnil;
11031
11032 DEFVAR_LISP ("mac-command-modifier", &Vmac_command_modifier,
11033 doc: /* *Modifier key assumed when the Mac command key is pressed.
11034 The value can be `control', `meta', `alt', `hyper', or `super' for the
11035 respective modifier. The default is `meta'. */);
11036 Vmac_command_modifier = Qmeta;
11037
11038 DEFVAR_LISP ("mac-function-modifier", &Vmac_function_modifier,
11039 doc: /* *Modifier key assumed when the Mac function key is pressed.
11040 The value can be `control', `meta', `alt', `hyper', or `super' for the
11041 respective modifier. Note that remapping the function key may lead to
11042 unexpected results for some keys on non-US/GB keyboards. */);
11043 Vmac_function_modifier = Qnil;
11044
11045 DEFVAR_LISP ("mac-emulate-three-button-mouse",
11046 &Vmac_emulate_three_button_mouse,
11047 doc: /* *Specify a way of three button mouse emulation.
11048 The value can be nil, t, or the symbol `reverse'.
11049 nil means that no emulation should be done and the modifiers should be
11050 placed on the mouse-1 event.
11051 t means that when the option-key is held down while pressing the mouse
11052 button, the click will register as mouse-2 and while the command-key
11053 is held down, the click will register as mouse-3.
11054 The symbol `reverse' means that the option-key will register for
11055 mouse-3 and the command-key will register for mouse-2. */);
11056 Vmac_emulate_three_button_mouse = Qnil;
11057
11058 #if USE_CARBON_EVENTS
11059 DEFVAR_BOOL ("mac-wheel-button-is-mouse-2", &mac_wheel_button_is_mouse_2,
11060 doc: /* *Non-nil if the wheel button is mouse-2 and the right click mouse-3.
11061 Otherwise, the right click will be treated as mouse-2 and the wheel
11062 button will be mouse-3. */);
11063 mac_wheel_button_is_mouse_2 = 1;
11064
11065 DEFVAR_BOOL ("mac-pass-command-to-system", &mac_pass_command_to_system,
11066 doc: /* *Non-nil if command key presses are passed on to the Mac Toolbox. */);
11067 mac_pass_command_to_system = 1;
11068
11069 DEFVAR_BOOL ("mac-pass-control-to-system", &mac_pass_control_to_system,
11070 doc: /* *Non-nil if control key presses are passed on to the Mac Toolbox. */);
11071 mac_pass_control_to_system = 1;
11072
11073 #endif
11074
11075 DEFVAR_BOOL ("mac-allow-anti-aliasing", &mac_use_core_graphics,
11076 doc: /* *If non-nil, allow anti-aliasing.
11077 The text will be rendered using Core Graphics text rendering which
11078 may anti-alias the text. */);
11079 mac_use_core_graphics = 0;
11080
11081 /* Register an entry for `mac-roman' so that it can be used when
11082 creating the terminal frame on Mac OS 9 before loading
11083 term/mac-win.elc. */
11084 DEFVAR_LISP ("mac-charset-info-alist", &Vmac_charset_info_alist,
11085 doc: /* Alist of Emacs character sets vs text encodings and coding systems.
11086 Each entry should be of the form:
11087
11088 (CHARSET-NAME TEXT-ENCODING CODING-SYSTEM)
11089
11090 where CHARSET-NAME is a string used in font names to identify the
11091 charset, TEXT-ENCODING is a TextEncodingBase value in Mac, and
11092 CODING_SYSTEM is a coding system corresponding to TEXT-ENCODING. */);
11093 Vmac_charset_info_alist =
11094 Fcons (list3 (build_string ("mac-roman"),
11095 make_number (smRoman), Qnil), Qnil);
11096 }
11097
11098 /* arch-tag: f2259165-4454-4c04-a029-a133c8af7b5b
11099 (do not change this comment) */