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