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