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