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