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