(comment-search-forward, comment-search-backward): Fix typos.
[emacs.git] / src / macterm.c
blob54a2fce792d048ae849230d810eafa6928eabbd9
1 /* Implementation of GUI terminal on the Mac OS.
2 Copyright (C) 2000, 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
4 This file is part of GNU Emacs.
6 GNU Emacs is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs; see the file COPYING. If not, write to
18 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
21 /* Contributed by Andrew Choi (akochoi@mac.com). */
23 #include <config.h>
24 #include <signal.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include "lisp.h"
28 #include "charset.h"
29 #include "blockinput.h"
31 #include "macterm.h"
33 #ifndef MAC_OSX
34 #include <alloca.h>
35 #endif
37 #ifdef MAC_OSX
38 /* USE_CARBON_EVENTS determines if the Carbon Event Manager is used to
39 obtain events from the event queue. If set to 0, WaitNextEvent is
40 used instead. */
41 #define USE_CARBON_EVENTS 1
42 #else /* not MAC_OSX */
43 #include <Quickdraw.h>
44 #include <ToolUtils.h>
45 #include <Sound.h>
46 #include <Events.h>
47 #include <Script.h>
48 #include <Resources.h>
49 #include <Fonts.h>
50 #include <TextUtils.h>
51 #include <LowMem.h>
52 #include <Controls.h>
53 #if defined (__MRC__) || (__MSL__ >= 0x6000)
54 #include <ControlDefinitions.h>
55 #endif
57 #if __profile__
58 #include <profiler.h>
59 #endif
60 #endif /* not MAC_OSX */
62 #include "systty.h"
63 #include "systime.h"
64 #include "atimer.h"
65 #include "keymap.h"
67 #include <ctype.h>
68 #include <errno.h>
69 #include <setjmp.h>
70 #include <sys/stat.h>
72 #include "keyboard.h"
73 #include "frame.h"
74 #include "dispextern.h"
75 #include "fontset.h"
76 #include "termhooks.h"
77 #include "termopts.h"
78 #include "termchar.h"
79 #include "gnu.h"
80 #include "disptab.h"
81 #include "buffer.h"
82 #include "window.h"
83 #include "intervals.h"
84 #include "composite.h"
85 #include "coding.h"
87 /* Set of macros that handle mapping of Mac modifier keys to emacs. */
88 #define macCtrlKey (NILP (Vmac_reverse_ctrl_meta) ? controlKey : \
89 (NILP (Vmac_command_key_is_meta) ? optionKey : cmdKey))
90 #define macShiftKey (shiftKey)
91 #define macMetaKey (NILP (Vmac_reverse_ctrl_meta) ? \
92 (NILP (Vmac_command_key_is_meta) ? optionKey : cmdKey) \
93 : controlKey)
94 #define macAltKey (NILP (Vmac_command_key_is_meta) ? cmdKey : optionKey)
98 /* Non-nil means Emacs uses toolkit scroll bars. */
100 Lisp_Object Vx_toolkit_scroll_bars;
102 /* Non-zero means that a HELP_EVENT has been generated since Emacs
103 start. */
105 static int any_help_event_p;
107 /* Non-zero means autoselect window with the mouse cursor. */
109 int x_autoselect_window_p;
111 /* Non-zero means make use of UNDERLINE_POSITION font properties. */
113 int x_use_underline_position_properties;
115 /* Non-zero means draw block and hollow cursor as wide as the glyph
116 under it. For example, if a block cursor is over a tab, it will be
117 drawn as wide as that tab on the display. */
120 /* This is a chain of structures for all the X displays currently in
121 use. */
123 struct x_display_info *x_display_list;
125 /* This is a list of cons cells, each of the form (NAME
126 . FONT-LIST-CACHE), one for each element of x_display_list and in
127 the same order. NAME is the name of the frame. FONT-LIST-CACHE
128 records previous values returned by x-list-fonts. */
130 Lisp_Object x_display_name_list;
132 /* This is display since Mac does not support multiple ones. */
133 struct mac_display_info one_mac_display_info;
135 /* Frame being updated by update_frame. This is declared in term.c.
136 This is set by update_begin and looked at by all the XT functions.
137 It is zero while not inside an update. In that case, the XT
138 functions assume that `selected_frame' is the frame to apply to. */
140 extern struct frame *updating_frame;
142 extern int waiting_for_input;
144 /* This is a frame waiting to be auto-raised, within XTread_socket. */
146 struct frame *pending_autoraise_frame;
148 /* Non-zero means user is interacting with a toolkit scroll bar. */
150 static int toolkit_scroll_bar_interaction;
152 /* Mouse movement.
154 Formerly, we used PointerMotionHintMask (in standard_event_mask)
155 so that we would have to call XQueryPointer after each MotionNotify
156 event to ask for another such event. However, this made mouse tracking
157 slow, and there was a bug that made it eventually stop.
159 Simply asking for MotionNotify all the time seems to work better.
161 In order to avoid asking for motion events and then throwing most
162 of them away or busy-polling the server for mouse positions, we ask
163 the server for pointer motion hints. This means that we get only
164 one event per group of mouse movements. "Groups" are delimited by
165 other kinds of events (focus changes and button clicks, for
166 example), or by XQueryPointer calls; when one of these happens, we
167 get another MotionNotify event the next time the mouse moves. This
168 is at least as efficient as getting motion events when mouse
169 tracking is on, and I suspect only negligibly worse when tracking
170 is off. */
172 /* Where the mouse was last time we reported a mouse event. */
174 static Rect last_mouse_glyph;
175 static Lisp_Object last_mouse_press_frame;
177 /* The scroll bar in which the last X motion event occurred.
179 If the last X motion event occurred in a scroll bar, we set this so
180 XTmouse_position can know whether to report a scroll bar motion or
181 an ordinary motion.
183 If the last X motion event didn't occur in a scroll bar, we set
184 this to Qnil, to tell XTmouse_position to return an ordinary motion
185 event. */
187 static Lisp_Object last_mouse_scroll_bar;
189 /* This is a hack. We would really prefer that XTmouse_position would
190 return the time associated with the position it returns, but there
191 doesn't seem to be any way to wrest the time-stamp from the server
192 along with the position query. So, we just keep track of the time
193 of the last movement we received, and return that in hopes that
194 it's somewhat accurate. */
196 static Time last_mouse_movement_time;
198 struct scroll_bar *tracked_scroll_bar = NULL;
200 /* Incremented by XTread_socket whenever it really tries to read
201 events. */
203 #ifdef __STDC__
204 static int volatile input_signal_count;
205 #else
206 static int input_signal_count;
207 #endif
209 /* Used locally within XTread_socket. */
211 static int x_noop_count;
213 /* Initial values of argv and argc. */
215 extern char **initial_argv;
216 extern int initial_argc;
218 extern Lisp_Object Vcommand_line_args, Vsystem_name;
220 /* Tells if a window manager is present or not. */
222 extern Lisp_Object Vx_no_window_manager;
224 extern int errno;
226 /* A mask of extra modifier bits to put into every keyboard char. */
228 extern int extra_keyboard_modifiers;
230 static Lisp_Object Qvendor_specific_keysyms;
232 #if 0
233 extern XrmDatabase x_load_resources P_ ((Display *, char *, char *, char *));
234 #endif
236 extern int inhibit_window_system;
238 #if __MRC__
239 QDGlobals qd; /* QuickDraw global information structure. */
240 #endif
243 struct frame * x_window_to_frame (struct mac_display_info *, WindowPtr);
244 struct mac_display_info *mac_display_info_for_display (Display *);
245 static void x_update_window_end P_ ((struct window *, int, int));
246 static void mac_handle_tool_bar_click P_ ((struct frame *, EventRecord *));
247 static int x_io_error_quitter P_ ((Display *));
248 int x_catch_errors P_ ((Display *));
249 void x_uncatch_errors P_ ((Display *, int));
250 void x_lower_frame P_ ((struct frame *));
251 void x_scroll_bar_clear P_ ((struct frame *));
252 int x_had_errors_p P_ ((Display *));
253 void x_wm_set_size_hint P_ ((struct frame *, long, int));
254 void x_raise_frame P_ ((struct frame *));
255 void x_set_window_size P_ ((struct frame *, int, int, int));
256 void x_wm_set_window_state P_ ((struct frame *, int));
257 void x_wm_set_icon_pixmap P_ ((struct frame *, int));
258 void mac_initialize P_ ((void));
259 static void x_font_min_bounds P_ ((XFontStruct *, int *, int *));
260 static int x_compute_min_glyph_bounds P_ ((struct frame *));
261 static void x_update_end P_ ((struct frame *));
262 static void XTframe_up_to_date P_ ((struct frame *));
263 static void XTreassert_line_highlight P_ ((int, int));
264 static void x_change_line_highlight P_ ((int, int, int, int));
265 static void XTset_terminal_modes P_ ((void));
266 static void XTreset_terminal_modes P_ ((void));
267 static void x_clear_frame P_ ((void));
268 static void frame_highlight P_ ((struct frame *));
269 static void frame_unhighlight P_ ((struct frame *));
270 static void x_new_focus_frame P_ ((struct x_display_info *, struct frame *));
271 static void XTframe_rehighlight P_ ((struct frame *));
272 static void x_frame_rehighlight P_ ((struct x_display_info *));
273 static void x_draw_hollow_cursor P_ ((struct window *, struct glyph_row *));
274 static void x_draw_bar_cursor P_ ((struct window *, struct glyph_row *, int,
275 enum text_cursor_kinds));
277 static void x_clip_to_row P_ ((struct window *, struct glyph_row *, GC));
278 static void x_flush P_ ((struct frame *f));
279 static void x_update_begin P_ ((struct frame *));
280 static void x_update_window_begin P_ ((struct window *));
281 static void x_after_update_window_line P_ ((struct glyph_row *));
283 void activate_scroll_bars (FRAME_PTR);
284 void deactivate_scroll_bars (FRAME_PTR);
286 static int is_emacs_window (WindowPtr);
288 int x_bitmap_icon (struct frame *, Lisp_Object);
289 void x_make_frame_visible (struct frame *);
291 extern void window_scroll (Lisp_Object, int, int, int);
293 /* Defined in macmenu.h. */
294 extern void menubar_selection_callback (FRAME_PTR, int);
295 extern void set_frame_menubar (FRAME_PTR, int, int);
297 /* X display function emulation */
299 void
300 XFreePixmap (display, pixmap)
301 Display *display; /* not used */
302 Pixmap pixmap;
304 DisposeGWorld (pixmap);
308 /* Set foreground color for subsequent QuickDraw commands. Assume
309 graphic port has already been set. */
311 static void
312 mac_set_forecolor (unsigned long color)
314 RGBColor fg_color;
316 fg_color.red = RED16_FROM_ULONG (color);
317 fg_color.green = GREEN16_FROM_ULONG (color);
318 fg_color.blue = BLUE16_FROM_ULONG (color);
320 RGBForeColor (&fg_color);
324 /* Set background color for subsequent QuickDraw commands. Assume
325 graphic port has already been set. */
327 static void
328 mac_set_backcolor (unsigned long color)
330 RGBColor bg_color;
332 bg_color.red = RED16_FROM_ULONG (color);
333 bg_color.green = GREEN16_FROM_ULONG (color);
334 bg_color.blue = BLUE16_FROM_ULONG (color);
336 RGBBackColor (&bg_color);
339 /* Set foreground and background color for subsequent QuickDraw
340 commands. Assume that the graphic port has already been set. */
342 static void
343 mac_set_colors (GC gc)
345 mac_set_forecolor (gc->foreground);
346 mac_set_backcolor (gc->background);
349 /* Mac version of XDrawLine. */
351 static void
352 XDrawLine (display, w, gc, x1, y1, x2, y2)
353 Display *display;
354 WindowPtr w;
355 GC gc;
356 int x1, y1, x2, y2;
358 SetPortWindowPort (w);
360 mac_set_colors (gc);
362 MoveTo (x1, y1);
363 LineTo (x2, y2);
366 void
367 mac_draw_line_to_pixmap (display, p, gc, x1, y1, x2, y2)
368 Display *display;
369 Pixmap p;
370 GC gc;
371 int x1, y1, x2, y2;
373 CGrafPtr old_port;
374 GDHandle old_gdh;
376 GetGWorld (&old_port, &old_gdh);
377 SetGWorld (p, NULL);
379 mac_set_colors (gc);
381 LockPixels (GetGWorldPixMap (p));
382 MoveTo (x1, y1);
383 LineTo (x2, y2);
384 UnlockPixels (GetGWorldPixMap (p));
386 SetGWorld (old_port, old_gdh);
389 /* Mac version of XClearArea. */
391 void
392 XClearArea (display, w, x, y, width, height, exposures)
393 Display *display;
394 WindowPtr w;
395 int x, y;
396 unsigned int width, height;
397 int exposures;
399 struct mac_output *mwp = (mac_output *) GetWRefCon (w);
400 Rect r;
401 XGCValues xgc;
403 xgc.foreground = mwp->x_compatible.foreground_pixel;
404 xgc.background = mwp->x_compatible.background_pixel;
406 SetPortWindowPort (w);
408 mac_set_colors (&xgc);
409 SetRect (&r, x, y, x + width, y + height);
411 EraseRect (&r);
414 /* Mac version of XClearWindow. */
416 static void
417 XClearWindow (display, w)
418 Display *display;
419 WindowPtr w;
421 struct mac_output *mwp = (mac_output *) GetWRefCon (w);
422 XGCValues xgc;
424 xgc.foreground = mwp->x_compatible.foreground_pixel;
425 xgc.background = mwp->x_compatible.background_pixel;
427 SetPortWindowPort (w);
429 mac_set_colors (&xgc);
431 #if TARGET_API_MAC_CARBON
433 Rect r;
435 GetWindowPortBounds (w, &r);
436 EraseRect (&r);
438 #else /* not TARGET_API_MAC_CARBON */
439 EraseRect (&(w->portRect));
440 #endif /* not TARGET_API_MAC_CARBON */
444 /* Mac replacement for XCopyArea. */
446 static void
447 mac_draw_bitmap (display, w, gc, x, y, width, height, bits, overlay_p)
448 Display *display;
449 WindowPtr w;
450 GC gc;
451 int x, y, width, height;
452 unsigned short *bits;
453 int overlay_p;
455 BitMap bitmap;
456 Rect r;
458 bitmap.rowBytes = sizeof(unsigned short);
459 bitmap.baseAddr = (char *)bits;
460 SetRect (&(bitmap.bounds), 0, 0, width, height);
462 SetPortWindowPort (w);
464 mac_set_colors (gc);
465 SetRect (&r, x, y, x + width, y + height);
467 #if TARGET_API_MAC_CARBON
468 LockPortBits (GetWindowPort (w));
469 CopyBits (&bitmap, GetPortBitMapForCopyBits (GetWindowPort (w)),
470 &(bitmap.bounds), &r, overlay_p ? srcOr : srcCopy, 0);
471 UnlockPortBits (GetWindowPort (w));
472 #else /* not TARGET_API_MAC_CARBON */
473 CopyBits (&bitmap, &(w->portBits), &(bitmap.bounds), &r,
474 overlay_p ? srcOr : srcCopy, 0);
475 #endif /* not TARGET_API_MAC_CARBON */
479 /* Mac replacement for XSetClipRectangles. */
481 static void
482 mac_set_clip_rectangle (display, w, r)
483 Display *display;
484 WindowPtr w;
485 Rect *r;
487 SetPortWindowPort (w);
489 ClipRect (r);
493 /* Mac replacement for XSetClipMask. */
495 static void
496 mac_reset_clipping (display, w)
497 Display *display;
498 WindowPtr w;
500 Rect r;
502 SetPortWindowPort (w);
504 SetRect (&r, -32767, -32767, 32767, 32767);
505 ClipRect (&r);
509 /* XBM bits seem to be backward within bytes compared with how
510 Mac does things. */
511 static unsigned char
512 reflect_byte (orig)
513 unsigned char orig;
515 int i;
516 unsigned char reflected = 0x00;
517 for (i = 0; i < 8; i++)
519 if (orig & (0x01 << i))
520 reflected |= 0x80 >> i;
522 return reflected;
526 /* Mac replacement for XCreateBitmapFromBitmapData. */
528 static void
529 mac_create_bitmap_from_bitmap_data (bitmap, bits, w, h)
530 BitMap *bitmap;
531 char *bits;
532 int w, h;
534 int i, j, w1;
535 char *p;
537 w1 = (w + 7) / 8; /* nb of 8bits elt in X bitmap */
538 bitmap->rowBytes = ((w + 15) / 16) * 2; /* nb of 16bits elt in Mac bitmap */
539 bitmap->baseAddr = xmalloc (bitmap->rowBytes * h);
540 bzero (bitmap->baseAddr, bitmap->rowBytes * h);
541 for (i = 0; i < h; i++)
543 p = bitmap->baseAddr + i * bitmap->rowBytes;
544 for (j = 0; j < w1; j++)
545 *p++ = reflect_byte (*bits++);
548 SetRect (&(bitmap->bounds), 0, 0, w, h);
552 static void
553 mac_free_bitmap (bitmap)
554 BitMap *bitmap;
556 xfree (bitmap->baseAddr);
560 Pixmap
561 XCreatePixmap (display, w, width, height, depth)
562 Display *display; /* not used */
563 WindowPtr w;
564 unsigned int width, height;
565 unsigned int depth; /* not used */
567 Pixmap pixmap;
568 Rect r;
569 QDErr err;
571 SetPortWindowPort (w);
573 SetRect (&r, 0, 0, width, height);
574 err = NewGWorld (&pixmap, depth, &r, NULL, NULL, 0);
575 if (err != noErr)
576 return NULL;
577 return pixmap;
581 Pixmap
582 XCreatePixmapFromBitmapData (display, w, data, width, height, fg, bg, depth)
583 Display *display; /* not used */
584 WindowPtr w;
585 char *data;
586 unsigned int width, height;
587 unsigned long fg, bg;
588 unsigned int depth; /* not used */
590 Pixmap pixmap;
591 BitMap bitmap;
592 CGrafPtr old_port;
593 GDHandle old_gdh;
595 pixmap = XCreatePixmap (display, w, width, height, depth);
596 if (pixmap == NULL)
597 return NULL;
599 GetGWorld (&old_port, &old_gdh);
600 SetGWorld (pixmap, NULL);
601 mac_create_bitmap_from_bitmap_data (&bitmap, data, width, height);
602 mac_set_forecolor (fg);
603 mac_set_backcolor (bg);
604 LockPixels (GetGWorldPixMap (pixmap));
605 #if TARGET_API_MAC_CARBON
606 CopyBits (&bitmap, GetPortBitMapForCopyBits (pixmap),
607 &bitmap.bounds, &bitmap.bounds, srcCopy, 0);
608 #else /* not TARGET_API_MAC_CARBON */
609 CopyBits (&bitmap, &(((GrafPtr)pixmap)->portBits),
610 &bitmap.bounds, &bitmap.bounds, srcCopy, 0);
611 #endif /* not TARGET_API_MAC_CARBON */
612 UnlockPixels (GetGWorldPixMap (pixmap));
613 SetGWorld (old_port, old_gdh);
614 mac_free_bitmap (&bitmap);
616 return pixmap;
620 /* Mac replacement for XFillRectangle. */
622 static void
623 XFillRectangle (display, w, gc, x, y, width, height)
624 Display *display;
625 WindowPtr w;
626 GC gc;
627 int x, y;
628 unsigned int width, height;
630 Rect r;
632 SetPortWindowPort (w);
634 mac_set_colors (gc);
635 SetRect (&r, x, y, x + width, y + height);
637 PaintRect (&r); /* using foreground color of gc */
641 static void
642 mac_fill_rectangle_to_pixmap (display, p, gc, x, y, width, height)
643 Display *display;
644 Pixmap p;
645 GC gc;
646 int x, y;
647 unsigned int width, height;
649 CGrafPtr old_port;
650 GDHandle old_gdh;
651 Rect r;
653 GetGWorld (&old_port, &old_gdh);
654 SetGWorld (p, NULL);
655 mac_set_colors (gc);
656 SetRect (&r, x, y, x + width, y + height);
658 LockPixels (GetGWorldPixMap (p));
659 PaintRect (&r); /* using foreground color of gc */
660 UnlockPixels (GetGWorldPixMap (p));
662 SetGWorld (old_port, old_gdh);
666 /* Mac replacement for XDrawRectangle: dest is a window. */
668 static void
669 mac_draw_rectangle (display, w, gc, x, y, width, height)
670 Display *display;
671 WindowPtr w;
672 GC gc;
673 int x, y;
674 unsigned int width, height;
676 Rect r;
678 SetPortWindowPort (w);
680 mac_set_colors (gc);
681 SetRect (&r, x, y, x + width + 1, y + height + 1);
683 FrameRect (&r); /* using foreground color of gc */
687 /* Mac replacement for XDrawRectangle: dest is a Pixmap. */
689 static void
690 mac_draw_rectangle_to_pixmap (display, p, gc, x, y, width, height)
691 Display *display;
692 Pixmap p;
693 GC gc;
694 int x, y;
695 unsigned int width, height;
697 CGrafPtr old_port;
698 GDHandle old_gdh;
699 Rect r;
701 GetGWorld (&old_port, &old_gdh);
702 SetGWorld (p, NULL);
703 mac_set_colors (gc);
704 SetRect (&r, x, y, x + width + 1, y + height + 1);
706 LockPixels (GetGWorldPixMap (p));
707 FrameRect (&r); /* using foreground color of gc */
708 UnlockPixels (GetGWorldPixMap (p));
710 SetGWorld (old_port, old_gdh);
714 static void
715 mac_draw_string_common (display, w, gc, x, y, buf, nchars, mode,
716 bytes_per_char)
717 Display *display;
718 WindowPtr w;
719 GC gc;
720 int x, y;
721 char *buf;
722 int nchars, mode, bytes_per_char;
724 SetPortWindowPort (w);
726 mac_set_colors (gc);
728 TextFont (gc->font->mac_fontnum);
729 TextSize (gc->font->mac_fontsize);
730 TextFace (gc->font->mac_fontface);
731 TextMode (mode);
733 MoveTo (x, y);
734 DrawText (buf, 0, nchars * bytes_per_char);
738 /* Mac replacement for XDrawString. */
740 static void
741 XDrawString (display, w, gc, x, y, buf, nchars)
742 Display *display;
743 WindowPtr w;
744 GC gc;
745 int x, y;
746 char *buf;
747 int nchars;
749 mac_draw_string_common (display, w, gc, x, y, buf, nchars, srcOr, 1);
753 /* Mac replacement for XDrawString16. */
755 static void
756 XDrawString16 (display, w, gc, x, y, buf, nchars)
757 Display *display;
758 WindowPtr w;
759 GC gc;
760 int x, y;
761 XChar2b *buf;
762 int nchars;
764 mac_draw_string_common (display, w, gc, x, y, (char *) buf, nchars, srcOr,
769 /* Mac replacement for XDrawImageString. */
771 static void
772 XDrawImageString (display, w, gc, x, y, buf, nchars)
773 Display *display;
774 WindowPtr w;
775 GC gc;
776 int x, y;
777 char *buf;
778 int nchars;
780 mac_draw_string_common (display, w, gc, x, y, buf, nchars, srcCopy, 1);
784 /* Mac replacement for XDrawString16. */
786 static void
787 XDrawImageString16 (display, w, gc, x, y, buf, nchars)
788 Display *display;
789 WindowPtr w;
790 GC gc;
791 int x, y;
792 XChar2b *buf;
793 int nchars;
795 mac_draw_string_common (display, w, gc, x, y, (char *) buf, nchars, srcCopy,
800 /* Mac replacement for XCopyArea: dest must be window. */
802 static void
803 mac_copy_area (display, src, dest, gc, src_x, src_y, width, height, dest_x,
804 dest_y)
805 Display *display;
806 Pixmap src;
807 WindowPtr dest;
808 GC gc;
809 int src_x, src_y;
810 unsigned int width, height;
811 int dest_x, dest_y;
813 Rect src_r, dest_r;
815 SetPortWindowPort (dest);
817 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
818 SetRect (&dest_r, dest_x, dest_y, dest_x + width, dest_y + height);
820 ForeColor (blackColor);
821 BackColor (whiteColor);
823 LockPixels (GetGWorldPixMap (src));
824 #if TARGET_API_MAC_CARBON
825 LockPortBits (GetWindowPort (dest));
826 CopyBits (GetPortBitMapForCopyBits (src),
827 GetPortBitMapForCopyBits (GetWindowPort (dest)),
828 &src_r, &dest_r, srcCopy, 0);
829 UnlockPortBits (GetWindowPort (dest));
830 #else /* not TARGET_API_MAC_CARBON */
831 CopyBits (&(((GrafPtr)src)->portBits), &(dest->portBits),
832 &src_r, &dest_r, srcCopy, 0);
833 #endif /* not TARGET_API_MAC_CARBON */
834 UnlockPixels (GetGWorldPixMap (src));
838 static void
839 mac_copy_area_with_mask (display, src, mask, dest, gc, src_x, src_y,
840 width, height, dest_x, dest_y)
841 Display *display;
842 Pixmap src, mask;
843 WindowPtr dest;
844 GC gc;
845 int src_x, src_y;
846 unsigned int width, height;
847 int dest_x, dest_y;
849 Rect src_r, dest_r;
851 SetPortWindowPort (dest);
853 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
854 SetRect (&dest_r, dest_x, dest_y, dest_x + width, dest_y + height);
856 ForeColor (blackColor);
857 BackColor (whiteColor);
859 LockPixels (GetGWorldPixMap (src));
860 LockPixels (GetGWorldPixMap (mask));
861 #if TARGET_API_MAC_CARBON
862 LockPortBits (GetWindowPort (dest));
863 CopyMask (GetPortBitMapForCopyBits (src), GetPortBitMapForCopyBits (mask),
864 GetPortBitMapForCopyBits (GetWindowPort (dest)),
865 &src_r, &src_r, &dest_r);
866 UnlockPortBits (GetWindowPort (dest));
867 #else /* not TARGET_API_MAC_CARBON */
868 CopyMask (&(((GrafPtr)src)->portBits), &(((GrafPtr)mask)->portBits),
869 &(dest->portBits), &src_r, &src_r, &dest_r);
870 #endif /* not TARGET_API_MAC_CARBON */
871 UnlockPixels (GetGWorldPixMap (mask));
872 UnlockPixels (GetGWorldPixMap (src));
876 #if 0
877 /* Convert a pair of local coordinates to global (screen) coordinates.
878 Assume graphic port has been properly set. */
879 static void
880 local_to_global_coord (short *h, short *v)
882 Point p;
884 p.h = *h;
885 p.v = *v;
887 LocalToGlobal (&p);
889 *h = p.h;
890 *v = p.v;
892 #endif
894 /* Mac replacement for XCopyArea: used only for scrolling. */
896 static void
897 mac_scroll_area (display, w, gc, src_x, src_y, width, height, dest_x, dest_y)
898 Display *display;
899 WindowPtr w;
900 GC gc;
901 int src_x, src_y;
902 unsigned int width, height;
903 int dest_x, dest_y;
905 #if TARGET_API_MAC_CARBON
906 Rect gw_r, src_r, dest_r;
908 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
909 SetRect (&dest_r, dest_x, dest_y, dest_x + width, dest_y + height);
911 SetPortWindowPort (w);
913 ForeColor (blackColor);
914 BackColor (whiteColor);
916 LockPortBits (GetWindowPort (w));
918 const BitMap *bitmap = GetPortBitMapForCopyBits (GetWindowPort (w));
919 CopyBits (bitmap, bitmap, &src_r, &dest_r, srcCopy, 0);
921 UnlockPortBits (GetWindowPort (w));
923 mac_set_colors (gc);
924 #else /* not TARGET_API_MAC_CARBON */
925 Rect src_r, dest_r;
927 SetPort (w);
928 #if 0
929 mac_set_colors (gc);
930 #endif
932 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
933 SetRect (&dest_r, dest_x, dest_y, dest_x + width, dest_y + height);
935 #if 0
936 /* Need to use global coordinates and screenBits since src and dest
937 areas overlap in general. */
938 local_to_global_coord (&src_r.left, &src_r.top);
939 local_to_global_coord (&src_r.right, &src_r.bottom);
940 local_to_global_coord (&dest_r.left, &dest_r.top);
941 local_to_global_coord (&dest_r.right, &dest_r.bottom);
943 CopyBits (&qd.screenBits, &qd.screenBits, &src_r, &dest_r, srcCopy, 0);
944 #else
945 /* In Color QuickDraw, set ForeColor and BackColor as follows to avoid
946 color mapping in CopyBits. Otherwise, it will be slow. */
947 ForeColor (blackColor);
948 BackColor (whiteColor);
949 CopyBits (&(w->portBits), &(w->portBits), &src_r, &dest_r, srcCopy, 0);
951 mac_set_colors (gc);
952 #endif
953 #endif /* not TARGET_API_MAC_CARBON */
957 /* Mac replacement for XCopyArea: dest must be Pixmap. */
959 static void
960 mac_copy_area_to_pixmap (display, src, dest, gc, src_x, src_y, width, height,
961 dest_x, dest_y)
962 Display *display;
963 Pixmap src, dest;
964 GC gc;
965 int src_x, src_y;
966 unsigned int width, height;
967 int dest_x, dest_y;
969 CGrafPtr old_port;
970 GDHandle old_gdh;
971 Rect src_r, dest_r;
973 GetGWorld (&old_port, &old_gdh);
974 SetGWorld (dest, NULL);
975 ForeColor (blackColor);
976 BackColor (whiteColor);
978 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
979 SetRect (&dest_r, dest_x, dest_y, dest_x + width, dest_y + height);
981 LockPixels (GetGWorldPixMap (src));
982 LockPixels (GetGWorldPixMap (dest));
983 #if TARGET_API_MAC_CARBON
984 CopyBits (GetPortBitMapForCopyBits (src), GetPortBitMapForCopyBits (dest),
985 &src_r, &dest_r, srcCopy, 0);
986 #else /* not TARGET_API_MAC_CARBON */
987 CopyBits (&(((GrafPtr)src)->portBits), &(((GrafPtr)dest)->portBits),
988 &src_r, &dest_r, srcCopy, 0);
989 #endif /* not TARGET_API_MAC_CARBON */
990 UnlockPixels (GetGWorldPixMap (dest));
991 UnlockPixels (GetGWorldPixMap (src));
993 SetGWorld (old_port, old_gdh);
997 static void
998 mac_copy_area_with_mask_to_pixmap (display, src, mask, dest, gc, src_x, src_y,
999 width, height, dest_x, dest_y)
1000 Display *display;
1001 Pixmap src, mask, dest;
1002 GC gc;
1003 int src_x, src_y;
1004 unsigned int width, height;
1005 int dest_x, dest_y;
1007 CGrafPtr old_port;
1008 GDHandle old_gdh;
1009 Rect src_r, dest_r;
1011 GetGWorld (&old_port, &old_gdh);
1012 SetGWorld (dest, NULL);
1013 ForeColor (blackColor);
1014 BackColor (whiteColor);
1016 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
1017 SetRect (&dest_r, dest_x, dest_y, dest_x + width, dest_y + height);
1019 LockPixels (GetGWorldPixMap (src));
1020 LockPixels (GetGWorldPixMap (mask));
1021 LockPixels (GetGWorldPixMap (dest));
1022 #if TARGET_API_MAC_CARBON
1023 CopyMask (GetPortBitMapForCopyBits (src), GetPortBitMapForCopyBits (mask),
1024 GetPortBitMapForCopyBits (dest), &src_r, &src_r, &dest_r);
1025 #else /* not TARGET_API_MAC_CARBON */
1026 CopyMask (&(((GrafPtr)src)->portBits), &(((GrafPtr)mask)->portBits),
1027 &(((GrafPtr)dest)->portBits), &src_r, &src_r, &dest_r);
1028 #endif /* not TARGET_API_MAC_CARBON */
1029 UnlockPixels (GetGWorldPixMap (dest));
1030 UnlockPixels (GetGWorldPixMap (mask));
1031 UnlockPixels (GetGWorldPixMap (src));
1033 SetGWorld (old_port, old_gdh);
1037 /* Mac replacement for XChangeGC. */
1039 static void
1040 XChangeGC (void * ignore, XGCValues* gc, unsigned long mask,
1041 XGCValues *xgcv)
1043 if (mask & GCForeground)
1044 gc->foreground = xgcv->foreground;
1045 if (mask & GCBackground)
1046 gc->background = xgcv->background;
1047 if (mask & GCFont)
1048 gc->font = xgcv->font;
1052 /* Mac replacement for XCreateGC. */
1054 XGCValues *
1055 XCreateGC (void * ignore, Window window, unsigned long mask,
1056 XGCValues *xgcv)
1058 XGCValues *gc = (XGCValues *) xmalloc (sizeof (XGCValues));
1059 bzero (gc, sizeof (XGCValues));
1061 XChangeGC (ignore, gc, mask, xgcv);
1063 return gc;
1067 /* Used in xfaces.c. */
1069 void
1070 XFreeGC (display, gc)
1071 Display *display;
1072 GC gc;
1074 xfree (gc);
1078 /* Mac replacement for XGetGCValues. */
1080 static void
1081 XGetGCValues (void* ignore, XGCValues *gc,
1082 unsigned long mask, XGCValues *xgcv)
1084 XChangeGC (ignore, xgcv, mask, gc);
1088 /* Mac replacement for XSetForeground. */
1090 void
1091 XSetForeground (display, gc, color)
1092 Display *display;
1093 GC gc;
1094 unsigned long color;
1096 gc->foreground = color;
1100 /* Mac replacement for XSetFont. */
1102 static void
1103 XSetFont (display, gc, font)
1104 Display *display;
1105 GC gc;
1106 XFontStruct *font;
1108 gc->font = font;
1112 static void
1113 XTextExtents16 (XFontStruct *font, XChar2b *text, int nchars,
1114 int *direction,int *font_ascent,
1115 int *font_descent, XCharStruct *cs)
1117 /* MAC_TODO: Use GetTextMetrics to do this and inline it below. */
1121 /* x_sync is a no-op on Mac. */
1122 void
1123 x_sync (f)
1124 void *f;
1129 /* Remove calls to XFlush by defining XFlush to an empty replacement.
1130 Calls to XFlush should be unnecessary because the X output buffer
1131 is flushed automatically as needed by calls to XPending,
1132 XNextEvent, or XWindowEvent according to the XFlush man page.
1133 XTread_socket calls XPending. Removing XFlush improves
1134 performance. */
1136 #if TARGET_API_MAC_CARBON
1137 #define XFlush(DISPLAY) QDFlushPortBuffer (GetQDGlobalsThePort (), NULL)
1138 #else
1139 #define XFlush(DISPLAY) (void) 0
1140 #endif
1142 /* Flush display of frame F, or of all frames if F is null. */
1144 void
1145 x_flush (f)
1146 struct frame *f;
1148 #if TARGET_API_MAC_CARBON
1149 BLOCK_INPUT;
1150 if (f == NULL)
1152 Lisp_Object rest, frame;
1153 FOR_EACH_FRAME (rest, frame)
1154 x_flush (XFRAME (frame));
1156 else if (FRAME_MAC_P (f))
1157 XFlush (FRAME_MAC_DISPLAY (f));
1158 UNBLOCK_INPUT;
1159 #endif /* TARGET_API_MAC_CARBON */
1164 /* Return the struct mac_display_info corresponding to DPY. There's
1165 only one. */
1167 struct mac_display_info *
1168 mac_display_info_for_display (dpy)
1169 Display *dpy;
1171 return &one_mac_display_info;
1176 /***********************************************************************
1177 Starting and ending an update
1178 ***********************************************************************/
1180 /* Start an update of frame F. This function is installed as a hook
1181 for update_begin, i.e. it is called when update_begin is called.
1182 This function is called prior to calls to x_update_window_begin for
1183 each window being updated. */
1185 static void
1186 x_update_begin (f)
1187 struct frame *f;
1189 /* Nothing to do. */
1193 /* Start update of window W. Set the global variable updated_window
1194 to the window being updated and set output_cursor to the cursor
1195 position of W. */
1197 static void
1198 x_update_window_begin (w)
1199 struct window *w;
1201 struct frame *f = XFRAME (WINDOW_FRAME (w));
1202 struct mac_display_info *display_info = FRAME_MAC_DISPLAY_INFO (f);
1204 updated_window = w;
1205 set_output_cursor (&w->cursor);
1207 BLOCK_INPUT;
1209 if (f == display_info->mouse_face_mouse_frame)
1211 /* Don't do highlighting for mouse motion during the update. */
1212 display_info->mouse_face_defer = 1;
1214 /* If F needs to be redrawn, simply forget about any prior mouse
1215 highlighting. */
1216 if (FRAME_GARBAGED_P (f))
1217 display_info->mouse_face_window = Qnil;
1219 #if 0 /* Rows in a current matrix containing glyphs in mouse-face have
1220 their mouse_face_p flag set, which means that they are always
1221 unequal to rows in a desired matrix which never have that
1222 flag set. So, rows containing mouse-face glyphs are never
1223 scrolled, and we don't have to switch the mouse highlight off
1224 here to prevent it from being scrolled. */
1226 /* Can we tell that this update does not affect the window
1227 where the mouse highlight is? If so, no need to turn off.
1228 Likewise, don't do anything if the frame is garbaged;
1229 in that case, the frame's current matrix that we would use
1230 is all wrong, and we will redisplay that line anyway. */
1231 if (!NILP (display_info->mouse_face_window)
1232 && w == XWINDOW (display_info->mouse_face_window))
1234 int i;
1236 for (i = 0; i < w->desired_matrix->nrows; ++i)
1237 if (MATRIX_ROW_ENABLED_P (w->desired_matrix, i))
1238 break;
1240 if (i < w->desired_matrix->nrows)
1241 clear_mouse_face (display_info);
1243 #endif /* 0 */
1246 UNBLOCK_INPUT;
1250 /* Draw a vertical window border from (x,y0) to (x,y1) */
1252 static void
1253 mac_draw_vertical_window_border (w, x, y0, y1)
1254 struct window *w;
1255 int x, y0, y1;
1257 struct frame *f = XFRAME (WINDOW_FRAME (w));
1259 XDrawLine (FRAME_MAC_DISPLAY (f), FRAME_MAC_WINDOW (f),
1260 f->output_data.mac->normal_gc, x, y0, x, y1);
1264 /* End update of window W (which is equal to updated_window).
1266 Draw vertical borders between horizontally adjacent windows, and
1267 display W's cursor if CURSOR_ON_P is non-zero.
1269 MOUSE_FACE_OVERWRITTEN_P non-zero means that some row containing
1270 glyphs in mouse-face were overwritten. In that case we have to
1271 make sure that the mouse-highlight is properly redrawn.
1273 W may be a menu bar pseudo-window in case we don't have X toolkit
1274 support. Such windows don't have a cursor, so don't display it
1275 here. */
1277 static void
1278 x_update_window_end (w, cursor_on_p, mouse_face_overwritten_p)
1279 struct window *w;
1280 int cursor_on_p, mouse_face_overwritten_p;
1282 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (XFRAME (w->frame));
1284 if (!w->pseudo_window_p)
1286 BLOCK_INPUT;
1288 if (cursor_on_p)
1289 display_and_set_cursor (w, 1, output_cursor.hpos,
1290 output_cursor.vpos,
1291 output_cursor.x, output_cursor.y);
1293 x_draw_vertical_border (w);
1295 draw_window_fringes (w);
1297 UNBLOCK_INPUT;
1300 /* If a row with mouse-face was overwritten, arrange for
1301 XTframe_up_to_date to redisplay the mouse highlight. */
1302 if (mouse_face_overwritten_p)
1304 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
1305 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
1306 dpyinfo->mouse_face_window = Qnil;
1309 #if 0
1310 /* Unhide the caret. This won't actually show the cursor, unless it
1311 was visible before the corresponding call to HideCaret in
1312 x_update_window_begin. */
1313 if (w32_use_visible_system_caret)
1314 SendMessage (w32_system_caret_hwnd, WM_EMACS_SHOW_CARET, 0, 0);
1315 #endif
1317 updated_window = NULL;
1321 /* End update of frame F. This function is installed as a hook in
1322 update_end. */
1324 static void
1325 x_update_end (f)
1326 struct frame *f;
1328 /* Reset the background color of Mac OS Window to that of the frame after
1329 update so that it is used by Mac Toolbox to clear the update region before
1330 an update event is generated. */
1331 SetPortWindowPort (FRAME_MAC_WINDOW (f));
1333 mac_set_backcolor (FRAME_BACKGROUND_PIXEL (f));
1335 /* Mouse highlight may be displayed again. */
1336 FRAME_MAC_DISPLAY_INFO (f)->mouse_face_defer = 0;
1338 BLOCK_INPUT;
1339 XFlush (FRAME_MAC_DISPLAY (f));
1340 UNBLOCK_INPUT;
1344 /* This function is called from various places in xdisp.c whenever a
1345 complete update has been performed. The global variable
1346 updated_window is not available here. */
1348 static void
1349 XTframe_up_to_date (f)
1350 struct frame *f;
1352 if (FRAME_MAC_P (f))
1354 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
1356 if (dpyinfo->mouse_face_deferred_gc
1357 || f == dpyinfo->mouse_face_mouse_frame)
1359 BLOCK_INPUT;
1360 if (dpyinfo->mouse_face_mouse_frame)
1361 note_mouse_highlight (dpyinfo->mouse_face_mouse_frame,
1362 dpyinfo->mouse_face_mouse_x,
1363 dpyinfo->mouse_face_mouse_y);
1364 dpyinfo->mouse_face_deferred_gc = 0;
1365 UNBLOCK_INPUT;
1371 /* Draw truncation mark bitmaps, continuation mark bitmaps, overlay
1372 arrow bitmaps, or clear the fringes if no bitmaps are required
1373 before DESIRED_ROW is made current. The window being updated is
1374 found in updated_window. This function is called from
1375 update_window_line only if it is known that there are differences
1376 between bitmaps to be drawn between current row and DESIRED_ROW. */
1378 static void
1379 x_after_update_window_line (desired_row)
1380 struct glyph_row *desired_row;
1382 struct window *w = updated_window;
1383 struct frame *f;
1384 int width, height;
1386 xassert (w);
1388 if (!desired_row->mode_line_p && !w->pseudo_window_p)
1389 desired_row->redraw_fringe_bitmaps_p = 1;
1391 /* When a window has disappeared, make sure that no rest of
1392 full-width rows stays visible in the internal border. Could
1393 check here if updated_window is the leftmost/rightmost window,
1394 but I guess it's not worth doing since vertically split windows
1395 are almost never used, internal border is rarely set, and the
1396 overhead is very small. */
1397 if (windows_or_buffers_changed
1398 && desired_row->full_width_p
1399 && (f = XFRAME (w->frame),
1400 width = FRAME_INTERNAL_BORDER_WIDTH (f),
1401 width != 0)
1402 && (height = desired_row->visible_height,
1403 height > 0))
1405 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
1406 /* Internal border is drawn below the tool bar. */
1407 if (WINDOWP (f->tool_bar_window)
1408 && w == XWINDOW (f->tool_bar_window))
1409 y -= width;
1411 BLOCK_INPUT;
1413 XClearArea (FRAME_MAC_DISPLAY (f), FRAME_MAC_WINDOW (f),
1414 0, y, width, height, 0);
1415 XClearArea (FRAME_MAC_DISPLAY (f), FRAME_MAC_WINDOW (f),
1416 FRAME_PIXEL_WIDTH (f) - width, y,
1417 width, height, 0);
1419 UNBLOCK_INPUT;
1424 /* Draw the bitmap WHICH in one of the left or right fringes of
1425 window W. ROW is the glyph row for which to display the bitmap; it
1426 determines the vertical position at which the bitmap has to be
1427 drawn. */
1429 static void
1430 x_draw_fringe_bitmap (w, row, p)
1431 struct window *w;
1432 struct glyph_row *row;
1433 struct draw_fringe_bitmap_params *p;
1435 struct frame *f = XFRAME (WINDOW_FRAME (w));
1436 Display *display = FRAME_MAC_DISPLAY (f);
1437 WindowPtr window = FRAME_MAC_WINDOW (f);
1438 XGCValues gcv;
1439 GC gc = f->output_data.mac->normal_gc;
1440 struct face *face = p->face;
1441 int rowY;
1443 /* Must clip because of partially visible lines. */
1444 rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
1445 if (p->y < rowY)
1447 /* Adjust position of "bottom aligned" bitmap on partially
1448 visible last row. */
1449 int oldY = row->y;
1450 int oldVH = row->visible_height;
1451 row->visible_height = p->h;
1452 row->y -= rowY - p->y;
1453 x_clip_to_row (w, row, gc);
1454 row->y = oldY;
1455 row->visible_height = oldVH;
1457 else
1458 x_clip_to_row (w, row, gc);
1460 if (p->bx >= 0 && !p->overlay_p)
1462 XGCValues gcv;
1463 gcv.foreground = face->background;
1465 #if 0 /* MAC_TODO: stipple */
1466 /* In case the same realized face is used for fringes and
1467 for something displayed in the text (e.g. face `region' on
1468 mono-displays, the fill style may have been changed to
1469 FillSolid in x_draw_glyph_string_background. */
1470 if (face->stipple)
1471 XSetFillStyle (FRAME_X_DISPLAY (f), face->gc, FillOpaqueStippled);
1472 else
1473 XSetForeground (FRAME_X_DISPLAY (f), face->gc, face->background);
1474 #endif
1476 XFillRectangle (FRAME_MAC_DISPLAY (f), FRAME_MAC_WINDOW (f),
1477 &gcv,
1478 p->bx, p->by, p->nx, p->ny);
1480 #if 0 /* MAC_TODO: stipple */
1481 if (!face->stipple)
1482 XSetForeground (FRAME_X_DISPLAY (f), face->gc, face->foreground);
1483 #endif
1486 if (p->which)
1488 unsigned short *bits = p->bits + p->dh;
1490 gcv.foreground = (p->cursor_p
1491 ? (p->overlay_p ? face->background
1492 : f->output_data.mac->cursor_pixel)
1493 : face->foreground);
1494 gcv.background = face->background;
1496 mac_draw_bitmap (display, window, &gcv, p->x, p->y,
1497 p->wd, p->h, bits, p->overlay_p);
1500 mac_reset_clipping (display, window);
1504 /* This is called when starting Emacs and when restarting after
1505 suspend. When starting Emacs, no window is mapped. And nothing
1506 must be done to Emacs's own window if it is suspended (though that
1507 rarely happens). */
1509 static void
1510 XTset_terminal_modes ()
1514 /* This is called when exiting or suspending Emacs. Exiting will make
1515 the windows go away, and suspending requires no action. */
1517 static void
1518 XTreset_terminal_modes ()
1523 /***********************************************************************
1524 Display Iterator
1525 ***********************************************************************/
1527 /* Function prototypes of this page. */
1529 static XCharStruct *x_per_char_metric P_ ((XFontStruct *, XChar2b *));
1530 static int mac_encode_char P_ ((int, XChar2b *, struct font_info *, int *));
1533 /* Return a pointer to per-char metric information in FONT of a
1534 character pointed by B which is a pointer to an XChar2b. */
1536 #define PER_CHAR_METRIC(font, b) \
1537 ((font)->per_char \
1538 ? ((font)->per_char + (b)->byte2 - (font)->min_char_or_byte2 \
1539 + (((font)->min_byte1 || (font)->max_byte1) \
1540 ? (((b)->byte1 - (font)->min_byte1) \
1541 * ((font)->max_char_or_byte2 - (font)->min_char_or_byte2 + 1)) \
1542 : 0)) \
1543 : &((font)->max_bounds))
1546 /* Get metrics of character CHAR2B in FONT. Value is null if CHAR2B
1547 is not contained in the font. */
1549 static INLINE XCharStruct *
1550 x_per_char_metric (font, char2b)
1551 XFontStruct *font;
1552 XChar2b *char2b;
1554 /* The result metric information. */
1555 XCharStruct *pcm = NULL;
1557 xassert (font && char2b);
1559 if (font->per_char != NULL)
1561 if (font->min_byte1 == 0 && font->max_byte1 == 0)
1563 /* min_char_or_byte2 specifies the linear character index
1564 corresponding to the first element of the per_char array,
1565 max_char_or_byte2 is the index of the last character. A
1566 character with non-zero CHAR2B->byte1 is not in the font.
1567 A character with byte2 less than min_char_or_byte2 or
1568 greater max_char_or_byte2 is not in the font. */
1569 if (char2b->byte1 == 0
1570 && char2b->byte2 >= font->min_char_or_byte2
1571 && char2b->byte2 <= font->max_char_or_byte2)
1572 pcm = font->per_char + char2b->byte2 - font->min_char_or_byte2;
1574 else
1576 /* If either min_byte1 or max_byte1 are nonzero, both
1577 min_char_or_byte2 and max_char_or_byte2 are less than
1578 256, and the 2-byte character index values corresponding
1579 to the per_char array element N (counting from 0) are:
1581 byte1 = N/D + min_byte1
1582 byte2 = N\D + min_char_or_byte2
1584 where:
1586 D = max_char_or_byte2 - min_char_or_byte2 + 1
1587 / = integer division
1588 \ = integer modulus */
1589 if (char2b->byte1 >= font->min_byte1
1590 && char2b->byte1 <= font->max_byte1
1591 && char2b->byte2 >= font->min_char_or_byte2
1592 && char2b->byte2 <= font->max_char_or_byte2)
1594 pcm = (font->per_char
1595 + ((font->max_char_or_byte2 - font->min_char_or_byte2 + 1)
1596 * (char2b->byte1 - font->min_byte1))
1597 + (char2b->byte2 - font->min_char_or_byte2));
1601 else
1603 /* If the per_char pointer is null, all glyphs between the first
1604 and last character indexes inclusive have the same
1605 information, as given by both min_bounds and max_bounds. */
1606 if (char2b->byte2 >= font->min_char_or_byte2
1607 && char2b->byte2 <= font->max_char_or_byte2)
1608 pcm = &font->max_bounds;
1611 return ((pcm == NULL
1612 || (pcm->width == 0 && (pcm->rbearing - pcm->lbearing) == 0))
1613 ? NULL : pcm);
1616 /* RIF:
1619 static XCharStruct *
1620 mac_per_char_metric (font, char2b, font_type)
1621 XFontStruct *font;
1622 XChar2b *char2b;
1623 int font_type;
1625 return x_per_char_metric (font, char2b);
1628 /* RIF:
1629 Encode CHAR2B using encoding information from FONT_INFO. CHAR2B is
1630 the two-byte form of C. Encoding is returned in *CHAR2B. */
1632 static int
1633 mac_encode_char (c, char2b, font_info, two_byte_p)
1634 int c;
1635 XChar2b *char2b;
1636 struct font_info *font_info;
1637 int *two_byte_p;
1639 int charset = CHAR_CHARSET (c);
1640 XFontStruct *font = font_info->font;
1642 /* FONT_INFO may define a scheme by which to encode byte1 and byte2.
1643 This may be either a program in a special encoder language or a
1644 fixed encoding. */
1645 if (font_info->font_encoder)
1647 /* It's a program. */
1648 struct ccl_program *ccl = font_info->font_encoder;
1650 if (CHARSET_DIMENSION (charset) == 1)
1652 ccl->reg[0] = charset;
1653 ccl->reg[1] = char2b->byte2;
1655 else
1657 ccl->reg[0] = charset;
1658 ccl->reg[1] = char2b->byte1;
1659 ccl->reg[2] = char2b->byte2;
1662 ccl_driver (ccl, NULL, NULL, 0, 0, NULL);
1664 /* We assume that MSBs are appropriately set/reset by CCL
1665 program. */
1666 if (font->max_byte1 == 0) /* 1-byte font */
1667 char2b->byte1 = 0, char2b->byte2 = ccl->reg[1];
1668 else
1669 char2b->byte1 = ccl->reg[1], char2b->byte2 = ccl->reg[2];
1671 else if (font_info->encoding[charset])
1673 /* Fixed encoding scheme. See fontset.h for the meaning of the
1674 encoding numbers. */
1675 int enc = font_info->encoding[charset];
1677 if ((enc == 1 || enc == 2)
1678 && CHARSET_DIMENSION (charset) == 2)
1679 char2b->byte1 |= 0x80;
1681 if (enc == 1 || enc == 3)
1682 char2b->byte2 |= 0x80;
1684 if (enc == 4)
1686 int sjis1, sjis2;
1688 ENCODE_SJIS (char2b->byte1, char2b->byte2, sjis1, sjis2);
1689 char2b->byte1 = sjis1;
1690 char2b->byte2 = sjis2;
1694 if (two_byte_p)
1695 *two_byte_p = ((XFontStruct *) (font_info->font))->max_byte1 > 0;
1697 return FONT_TYPE_UNKNOWN;
1702 /***********************************************************************
1703 Glyph display
1704 ***********************************************************************/
1707 static void x_set_glyph_string_clipping P_ ((struct glyph_string *));
1708 static void x_set_glyph_string_gc P_ ((struct glyph_string *));
1709 static void x_draw_glyph_string_background P_ ((struct glyph_string *,
1710 int));
1711 static void x_draw_glyph_string_foreground P_ ((struct glyph_string *));
1712 static void x_draw_composite_glyph_string_foreground P_ ((struct glyph_string *));
1713 static void x_draw_glyph_string_box P_ ((struct glyph_string *));
1714 static void x_draw_glyph_string P_ ((struct glyph_string *));
1715 static void x_set_cursor_gc P_ ((struct glyph_string *));
1716 static void x_set_mode_line_face_gc P_ ((struct glyph_string *));
1717 static void x_set_mouse_face_gc P_ ((struct glyph_string *));
1718 /*static int x_alloc_lighter_color P_ ((struct frame *, Display *, Colormap,
1719 unsigned long *, double, int));*/
1720 static void x_setup_relief_color P_ ((struct frame *, struct relief *,
1721 double, int, unsigned long));
1722 static void x_setup_relief_colors P_ ((struct glyph_string *));
1723 static void x_draw_image_glyph_string P_ ((struct glyph_string *));
1724 static void x_draw_image_relief P_ ((struct glyph_string *));
1725 static void x_draw_image_foreground P_ ((struct glyph_string *));
1726 static void x_draw_image_foreground_1 P_ ((struct glyph_string *, Pixmap));
1727 static void x_clear_glyph_string_rect P_ ((struct glyph_string *, int,
1728 int, int, int));
1729 static void x_draw_relief_rect P_ ((struct frame *, int, int, int, int,
1730 int, int, int, int, int, int,
1731 Rect *));
1732 static void x_draw_box_rect P_ ((struct glyph_string *, int, int, int, int,
1733 int, int, int, Rect *));
1735 #if GLYPH_DEBUG
1736 static void x_check_font P_ ((struct frame *, XFontStruct *));
1737 #endif
1740 /* Set S->gc to a suitable GC for drawing glyph string S in cursor
1741 face. */
1743 static void
1744 x_set_cursor_gc (s)
1745 struct glyph_string *s;
1747 if (s->font == FRAME_FONT (s->f)
1748 && s->face->background == FRAME_BACKGROUND_PIXEL (s->f)
1749 && s->face->foreground == FRAME_FOREGROUND_PIXEL (s->f)
1750 && !s->cmp)
1751 s->gc = s->f->output_data.mac->cursor_gc;
1752 else
1754 /* Cursor on non-default face: must merge. */
1755 XGCValues xgcv;
1756 unsigned long mask;
1758 xgcv.background = s->f->output_data.mac->cursor_pixel;
1759 xgcv.foreground = s->face->background;
1761 /* If the glyph would be invisible, try a different foreground. */
1762 if (xgcv.foreground == xgcv.background)
1763 xgcv.foreground = s->face->foreground;
1764 if (xgcv.foreground == xgcv.background)
1765 xgcv.foreground = s->f->output_data.mac->cursor_foreground_pixel;
1766 if (xgcv.foreground == xgcv.background)
1767 xgcv.foreground = s->face->foreground;
1769 /* Make sure the cursor is distinct from text in this face. */
1770 if (xgcv.background == s->face->background
1771 && xgcv.foreground == s->face->foreground)
1773 xgcv.background = s->face->foreground;
1774 xgcv.foreground = s->face->background;
1777 IF_DEBUG (x_check_font (s->f, s->font));
1778 xgcv.font = s->font;
1779 mask = GCForeground | GCBackground | GCFont;
1781 if (FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc)
1782 XChangeGC (s->display, FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc,
1783 mask, &xgcv);
1784 else
1785 FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc
1786 = XCreateGC (s->display, s->window, mask, &xgcv);
1788 s->gc = FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc;
1793 /* Set up S->gc of glyph string S for drawing text in mouse face. */
1795 static void
1796 x_set_mouse_face_gc (s)
1797 struct glyph_string *s;
1799 int face_id;
1800 struct face *face;
1802 /* What face has to be used last for the mouse face? */
1803 face_id = FRAME_X_DISPLAY_INFO (s->f)->mouse_face_face_id;
1804 face = FACE_FROM_ID (s->f, face_id);
1805 if (face == NULL)
1806 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
1808 if (s->first_glyph->type == CHAR_GLYPH)
1809 face_id = FACE_FOR_CHAR (s->f, face, s->first_glyph->u.ch);
1810 else
1811 face_id = FACE_FOR_CHAR (s->f, face, 0);
1812 s->face = FACE_FROM_ID (s->f, face_id);
1813 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
1815 /* If font in this face is same as S->font, use it. */
1816 if (s->font == s->face->font)
1817 s->gc = s->face->gc;
1818 else
1820 /* Otherwise construct scratch_cursor_gc with values from FACE
1821 but font FONT. */
1822 XGCValues xgcv;
1823 unsigned long mask;
1825 xgcv.background = s->face->background;
1826 xgcv.foreground = s->face->foreground;
1827 IF_DEBUG (x_check_font (s->f, s->font));
1828 xgcv.font = s->font;
1829 mask = GCForeground | GCBackground | GCFont;
1831 if (FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc)
1832 XChangeGC (s->display, FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc,
1833 mask, &xgcv);
1834 else
1835 FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc
1836 = XCreateGC (s->display, s->window, mask, &xgcv);
1838 s->gc = FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc;
1841 xassert (s->gc != 0);
1845 /* Set S->gc of glyph string S to a GC suitable for drawing a mode line.
1846 Faces to use in the mode line have already been computed when the
1847 matrix was built, so there isn't much to do, here. */
1849 static INLINE void
1850 x_set_mode_line_face_gc (s)
1851 struct glyph_string *s;
1853 s->gc = s->face->gc;
1857 /* Set S->gc of glyph string S for drawing that glyph string. Set
1858 S->stippled_p to a non-zero value if the face of S has a stipple
1859 pattern. */
1861 static INLINE void
1862 x_set_glyph_string_gc (s)
1863 struct glyph_string *s;
1865 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
1867 if (s->hl == DRAW_NORMAL_TEXT)
1869 s->gc = s->face->gc;
1870 s->stippled_p = s->face->stipple != 0;
1872 else if (s->hl == DRAW_INVERSE_VIDEO)
1874 x_set_mode_line_face_gc (s);
1875 s->stippled_p = s->face->stipple != 0;
1877 else if (s->hl == DRAW_CURSOR)
1879 x_set_cursor_gc (s);
1880 s->stippled_p = 0;
1882 else if (s->hl == DRAW_MOUSE_FACE)
1884 x_set_mouse_face_gc (s);
1885 s->stippled_p = s->face->stipple != 0;
1887 else if (s->hl == DRAW_IMAGE_RAISED
1888 || s->hl == DRAW_IMAGE_SUNKEN)
1890 s->gc = s->face->gc;
1891 s->stippled_p = s->face->stipple != 0;
1893 else
1895 s->gc = s->face->gc;
1896 s->stippled_p = s->face->stipple != 0;
1899 /* GC must have been set. */
1900 xassert (s->gc != 0);
1904 /* Set clipping for output of glyph string S. S may be part of a mode
1905 line or menu if we don't have X toolkit support. */
1907 static INLINE void
1908 x_set_glyph_string_clipping (s)
1909 struct glyph_string *s;
1911 Rect r;
1912 get_glyph_string_clip_rect (s, &r);
1913 mac_set_clip_rectangle (s->display, s->window, &r);
1917 /* RIF:
1918 Compute left and right overhang of glyph string S. If S is a glyph
1919 string for a composition, assume overhangs don't exist. */
1921 static void
1922 mac_compute_glyph_string_overhangs (s)
1923 struct glyph_string *s;
1925 #if 0
1926 /* MAC_TODO: XTextExtents16 does nothing yet... */
1928 if (s->cmp == NULL
1929 && s->first_glyph->type == CHAR_GLYPH)
1931 XCharStruct cs;
1932 int direction, font_ascent, font_descent;
1933 XTextExtents16 (s->font, s->char2b, s->nchars, &direction,
1934 &font_ascent, &font_descent, &cs);
1935 s->right_overhang = cs.rbearing > cs.width ? cs.rbearing - cs.width : 0;
1936 s->left_overhang = cs.lbearing < 0 ? -cs.lbearing : 0;
1938 #endif
1942 /* Fill rectangle X, Y, W, H with background color of glyph string S. */
1944 static INLINE void
1945 x_clear_glyph_string_rect (s, x, y, w, h)
1946 struct glyph_string *s;
1947 int x, y, w, h;
1949 XGCValues xgcv;
1951 xgcv.foreground = s->gc->background;
1952 XFillRectangle (s->display, s->window, &xgcv, x, y, w, h);
1956 /* Draw the background of glyph_string S. If S->background_filled_p
1957 is non-zero don't draw it. FORCE_P non-zero means draw the
1958 background even if it wouldn't be drawn normally. This is used
1959 when a string preceding S draws into the background of S, or S
1960 contains the first component of a composition. */
1962 static void
1963 x_draw_glyph_string_background (s, force_p)
1964 struct glyph_string *s;
1965 int force_p;
1967 /* Nothing to do if background has already been drawn or if it
1968 shouldn't be drawn in the first place. */
1969 if (!s->background_filled_p)
1971 int box_line_width = max (s->face->box_line_width, 0);
1973 #if 0 /* MAC_TODO: stipple */
1974 if (s->stippled_p)
1976 /* Fill background with a stipple pattern. */
1977 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
1978 XFillRectangle (s->display, s->window, s->gc, s->x,
1979 s->y + box_line_width,
1980 s->background_width,
1981 s->height - 2 * box_line_width);
1982 XSetFillStyle (s->display, s->gc, FillSolid);
1983 s->background_filled_p = 1;
1985 else
1986 #endif
1987 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
1988 || s->font_not_found_p
1989 || s->extends_to_end_of_line_p
1990 || force_p)
1992 x_clear_glyph_string_rect (s, s->x, s->y + box_line_width,
1993 s->background_width,
1994 s->height - 2 * box_line_width);
1995 s->background_filled_p = 1;
2001 /* Draw the foreground of glyph string S. */
2003 static void
2004 x_draw_glyph_string_foreground (s)
2005 struct glyph_string *s;
2007 int i, x;
2009 /* If first glyph of S has a left box line, start drawing the text
2010 of S to the right of that box line. */
2011 if (s->face->box != FACE_NO_BOX
2012 && s->first_glyph->left_box_line_p)
2013 x = s->x + abs (s->face->box_line_width);
2014 else
2015 x = s->x;
2017 /* Draw characters of S as rectangles if S's font could not be
2018 loaded. */
2019 if (s->font_not_found_p)
2021 for (i = 0; i < s->nchars; ++i)
2023 struct glyph *g = s->first_glyph + i;
2024 mac_draw_rectangle (s->display, s->window,
2025 s->gc, x, s->y, g->pixel_width - 1,
2026 s->height - 1);
2027 x += g->pixel_width;
2030 else
2032 char *char1b = (char *) s->char2b;
2033 int boff = s->font_info->baseline_offset;
2035 if (s->font_info->vertical_centering)
2036 boff = VCENTER_BASELINE_OFFSET (s->font, s->f) - boff;
2038 /* If we can use 8-bit functions, condense S->char2b. */
2039 if (!s->two_byte_p)
2040 for (i = 0; i < s->nchars; ++i)
2041 char1b[i] = s->char2b[i].byte2;
2043 /* Draw text with XDrawString if background has already been
2044 filled. Otherwise, use XDrawImageString. (Note that
2045 XDrawImageString is usually faster than XDrawString.) Always
2046 use XDrawImageString when drawing the cursor so that there is
2047 no chance that characters under a box cursor are invisible. */
2048 if (s->for_overlaps_p
2049 || (s->background_filled_p && s->hl != DRAW_CURSOR))
2051 /* Draw characters with 16-bit or 8-bit functions. */
2052 if (s->two_byte_p)
2053 XDrawString16 (s->display, s->window, s->gc, x,
2054 s->ybase - boff, s->char2b, s->nchars);
2055 else
2056 XDrawString (s->display, s->window, s->gc, x,
2057 s->ybase - boff, char1b, s->nchars);
2059 else
2061 if (s->two_byte_p)
2062 XDrawImageString16 (s->display, s->window, s->gc, x,
2063 s->ybase - boff, s->char2b, s->nchars);
2064 else
2065 XDrawImageString (s->display, s->window, s->gc, x,
2066 s->ybase - boff, char1b, s->nchars);
2071 /* Draw the foreground of composite glyph string S. */
2073 static void
2074 x_draw_composite_glyph_string_foreground (s)
2075 struct glyph_string *s;
2077 int i, x;
2079 /* If first glyph of S has a left box line, start drawing the text
2080 of S to the right of that box line. */
2081 if (s->face->box != FACE_NO_BOX
2082 && s->first_glyph->left_box_line_p)
2083 x = s->x + abs (s->face->box_line_width);
2084 else
2085 x = s->x;
2087 /* S is a glyph string for a composition. S->gidx is the index of
2088 the first character drawn for glyphs of this composition.
2089 S->gidx == 0 means we are drawing the very first character of
2090 this composition. */
2092 /* Draw a rectangle for the composition if the font for the very
2093 first character of the composition could not be loaded. */
2094 if (s->font_not_found_p)
2096 if (s->gidx == 0)
2097 mac_draw_rectangle (s->display, s->window, s->gc, x, s->y,
2098 s->width - 1, s->height - 1);
2100 else
2102 for (i = 0; i < s->nchars; i++, ++s->gidx)
2103 XDrawString16 (s->display, s->window, s->gc,
2104 x + s->cmp->offsets[s->gidx * 2],
2105 s->ybase - s->cmp->offsets[s->gidx * 2 + 1],
2106 s->char2b + i, 1);
2111 #ifdef USE_X_TOOLKIT
2113 static struct frame *x_frame_of_widget P_ ((Widget));
2116 /* Return the frame on which widget WIDGET is used.. Abort if frame
2117 cannot be determined. */
2119 static struct frame *
2120 x_frame_of_widget (widget)
2121 Widget widget;
2123 struct x_display_info *dpyinfo;
2124 Lisp_Object tail;
2125 struct frame *f;
2127 dpyinfo = x_display_info_for_display (XtDisplay (widget));
2129 /* Find the top-level shell of the widget. Note that this function
2130 can be called when the widget is not yet realized, so XtWindow
2131 (widget) == 0. That's the reason we can't simply use
2132 x_any_window_to_frame. */
2133 while (!XtIsTopLevelShell (widget))
2134 widget = XtParent (widget);
2136 /* Look for a frame with that top-level widget. Allocate the color
2137 on that frame to get the right gamma correction value. */
2138 for (tail = Vframe_list; GC_CONSP (tail); tail = XCDR (tail))
2139 if (GC_FRAMEP (XCAR (tail))
2140 && (f = XFRAME (XCAR (tail)),
2141 (f->output_data.nothing != 1
2142 && FRAME_X_DISPLAY_INFO (f) == dpyinfo))
2143 && f->output_data.x->widget == widget)
2144 return f;
2146 abort ();
2150 /* Allocate the color COLOR->pixel on the screen and display of
2151 widget WIDGET in colormap CMAP. If an exact match cannot be
2152 allocated, try the nearest color available. Value is non-zero
2153 if successful. This is called from lwlib. */
2156 x_alloc_nearest_color_for_widget (widget, cmap, color)
2157 Widget widget;
2158 Colormap cmap;
2159 XColor *color;
2161 struct frame *f = x_frame_of_widget (widget);
2162 return x_alloc_nearest_color (f, cmap, color);
2166 #endif /* USE_X_TOOLKIT */
2168 #if 0 /* MAC_TODO */
2170 /* Allocate the color COLOR->pixel on SCREEN of DISPLAY, colormap
2171 CMAP. If an exact match can't be allocated, try the nearest color
2172 available. Value is non-zero if successful. Set *COLOR to the
2173 color allocated. */
2176 x_alloc_nearest_color (f, cmap, color)
2177 struct frame *f;
2178 Colormap cmap;
2179 XColor *color;
2181 Display *display = FRAME_X_DISPLAY (f);
2182 Screen *screen = FRAME_X_SCREEN (f);
2183 int rc;
2185 gamma_correct (f, color);
2186 rc = XAllocColor (display, cmap, color);
2187 if (rc == 0)
2189 /* If we got to this point, the colormap is full, so we're going
2190 to try to get the next closest color. The algorithm used is
2191 a least-squares matching, which is what X uses for closest
2192 color matching with StaticColor visuals. */
2193 int nearest, i;
2194 unsigned long nearest_delta = ~0;
2195 int ncells = XDisplayCells (display, XScreenNumberOfScreen (screen));
2196 XColor *cells = (XColor *) alloca (ncells * sizeof *cells);
2198 for (i = 0; i < ncells; ++i)
2199 cells[i].pixel = i;
2200 XQueryColors (display, cmap, cells, ncells);
2202 for (nearest = i = 0; i < ncells; ++i)
2204 long dred = (color->red >> 8) - (cells[i].red >> 8);
2205 long dgreen = (color->green >> 8) - (cells[i].green >> 8);
2206 long dblue = (color->blue >> 8) - (cells[i].blue >> 8);
2207 unsigned long delta = dred * dred + dgreen * dgreen + dblue * dblue;
2209 if (delta < nearest_delta)
2211 nearest = i;
2212 nearest_delta = delta;
2216 color->red = cells[nearest].red;
2217 color->green = cells[nearest].green;
2218 color->blue = cells[nearest].blue;
2219 rc = XAllocColor (display, cmap, color);
2222 #ifdef DEBUG_X_COLORS
2223 if (rc)
2224 register_color (color->pixel);
2225 #endif /* DEBUG_X_COLORS */
2227 return rc;
2231 /* Allocate color PIXEL on frame F. PIXEL must already be allocated.
2232 It's necessary to do this instead of just using PIXEL directly to
2233 get color reference counts right. */
2235 unsigned long
2236 x_copy_color (f, pixel)
2237 struct frame *f;
2238 unsigned long pixel;
2240 XColor color;
2242 color.pixel = pixel;
2243 BLOCK_INPUT;
2244 XQueryColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
2245 XAllocColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
2246 UNBLOCK_INPUT;
2247 #ifdef DEBUG_X_COLORS
2248 register_color (pixel);
2249 #endif
2250 return color.pixel;
2254 /* Allocate color PIXEL on display DPY. PIXEL must already be allocated.
2255 It's necessary to do this instead of just using PIXEL directly to
2256 get color reference counts right. */
2258 unsigned long
2259 x_copy_dpy_color (dpy, cmap, pixel)
2260 Display *dpy;
2261 Colormap cmap;
2262 unsigned long pixel;
2264 XColor color;
2266 color.pixel = pixel;
2267 BLOCK_INPUT;
2268 XQueryColor (dpy, cmap, &color);
2269 XAllocColor (dpy, cmap, &color);
2270 UNBLOCK_INPUT;
2271 #ifdef DEBUG_X_COLORS
2272 register_color (pixel);
2273 #endif
2274 return color.pixel;
2277 #endif /* MAC_TODO */
2280 /* Brightness beyond which a color won't have its highlight brightness
2281 boosted.
2283 Nominally, highlight colors for `3d' faces are calculated by
2284 brightening an object's color by a constant scale factor, but this
2285 doesn't yield good results for dark colors, so for colors who's
2286 brightness is less than this value (on a scale of 0-255) have to
2287 use an additional additive factor.
2289 The value here is set so that the default menu-bar/mode-line color
2290 (grey75) will not have its highlights changed at all. */
2291 #define HIGHLIGHT_COLOR_DARK_BOOST_LIMIT 187
2294 /* Allocate a color which is lighter or darker than *COLOR by FACTOR
2295 or DELTA. Try a color with RGB values multiplied by FACTOR first.
2296 If this produces the same color as COLOR, try a color where all RGB
2297 values have DELTA added. Return the allocated color in *COLOR.
2298 DISPLAY is the X display, CMAP is the colormap to operate on.
2299 Value is non-zero if successful. */
2301 static int
2302 mac_alloc_lighter_color (f, color, factor, delta)
2303 struct frame *f;
2304 unsigned long *color;
2305 double factor;
2306 int delta;
2308 unsigned long new;
2309 long bright;
2311 /* On Mac, RGB values are 0-255, not 0-65535, so scale delta. */
2312 delta /= 256;
2314 /* Change RGB values by specified FACTOR. Avoid overflow! */
2315 xassert (factor >= 0);
2316 new = RGB_TO_ULONG (min (0xff, (int) (factor * RED_FROM_ULONG (*color))),
2317 min (0xff, (int) (factor * GREEN_FROM_ULONG (*color))),
2318 min (0xff, (int) (factor * BLUE_FROM_ULONG (*color))));
2320 /* Calculate brightness of COLOR. */
2321 bright = (2 * RED_FROM_ULONG (*color) + 3 * GREEN_FROM_ULONG (*color)
2322 + BLUE_FROM_ULONG (*color)) / 6;
2324 /* We only boost colors that are darker than
2325 HIGHLIGHT_COLOR_DARK_BOOST_LIMIT. */
2326 if (bright < HIGHLIGHT_COLOR_DARK_BOOST_LIMIT)
2327 /* Make an additive adjustment to NEW, because it's dark enough so
2328 that scaling by FACTOR alone isn't enough. */
2330 /* How far below the limit this color is (0 - 1, 1 being darker). */
2331 double dimness = 1 - (double)bright / HIGHLIGHT_COLOR_DARK_BOOST_LIMIT;
2332 /* The additive adjustment. */
2333 int min_delta = delta * dimness * factor / 2;
2335 if (factor < 1)
2336 new = RGB_TO_ULONG (max (0, min (0xff, (int) (RED_FROM_ULONG (*color)) - min_delta)),
2337 max (0, min (0xff, (int) (GREEN_FROM_ULONG (*color)) - min_delta)),
2338 max (0, min (0xff, (int) (BLUE_FROM_ULONG (*color)) - min_delta)));
2339 else
2340 new = RGB_TO_ULONG (max (0, min (0xff, (int) (min_delta + RED_FROM_ULONG (*color)))),
2341 max (0, min (0xff, (int) (min_delta + GREEN_FROM_ULONG (*color)))),
2342 max (0, min (0xff, (int) (min_delta + BLUE_FROM_ULONG (*color)))));
2345 if (new == *color)
2346 new = RGB_TO_ULONG (max (0, min (0xff, (int) (delta + RED_FROM_ULONG (*color)))),
2347 max (0, min (0xff, (int) (delta + GREEN_FROM_ULONG (*color)))),
2348 max (0, min (0xff, (int) (delta + BLUE_FROM_ULONG (*color)))));
2350 /* MAC_TODO: Map to palette and retry with delta if same? */
2351 /* MAC_TODO: Free colors (if using palette)? */
2353 if (new == *color)
2354 return 0;
2356 *color = new;
2358 return 1;
2362 /* Set up the foreground color for drawing relief lines of glyph
2363 string S. RELIEF is a pointer to a struct relief containing the GC
2364 with which lines will be drawn. Use a color that is FACTOR or
2365 DELTA lighter or darker than the relief's background which is found
2366 in S->f->output_data.x->relief_background. If such a color cannot
2367 be allocated, use DEFAULT_PIXEL, instead. */
2369 static void
2370 x_setup_relief_color (f, relief, factor, delta, default_pixel)
2371 struct frame *f;
2372 struct relief *relief;
2373 double factor;
2374 int delta;
2375 unsigned long default_pixel;
2377 XGCValues xgcv;
2378 struct mac_output *di = f->output_data.mac;
2379 unsigned long mask = GCForeground;
2380 unsigned long pixel;
2381 unsigned long background = di->relief_background;
2382 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
2384 /* MAC_TODO: Free colors (if using palette)? */
2386 /* Allocate new color. */
2387 xgcv.foreground = default_pixel;
2388 pixel = background;
2389 if (dpyinfo->n_planes != 1
2390 && mac_alloc_lighter_color (f, &pixel, factor, delta))
2392 relief->allocated_p = 1;
2393 xgcv.foreground = relief->pixel = pixel;
2396 if (relief->gc == 0)
2398 #if 0 /* MAC_TODO: stipple */
2399 xgcv.stipple = dpyinfo->gray;
2400 mask |= GCStipple;
2401 #endif
2402 relief->gc = XCreateGC (NULL, FRAME_MAC_WINDOW (f), mask, &xgcv);
2404 else
2405 XChangeGC (NULL, relief->gc, mask, &xgcv);
2409 /* Set up colors for the relief lines around glyph string S. */
2411 static void
2412 x_setup_relief_colors (s)
2413 struct glyph_string *s;
2415 struct mac_output *di = s->f->output_data.mac;
2416 unsigned long color;
2418 if (s->face->use_box_color_for_shadows_p)
2419 color = s->face->box_color;
2420 else if (s->first_glyph->type == IMAGE_GLYPH
2421 && s->img->pixmap
2422 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2423 color = IMAGE_BACKGROUND (s->img, s->f, 0);
2424 else
2426 XGCValues xgcv;
2428 /* Get the background color of the face. */
2429 XGetGCValues (s->display, s->gc, GCBackground, &xgcv);
2430 color = xgcv.background;
2433 if (di->white_relief.gc == 0
2434 || color != di->relief_background)
2436 di->relief_background = color;
2437 x_setup_relief_color (s->f, &di->white_relief, 1.2, 0x8000,
2438 WHITE_PIX_DEFAULT (s->f));
2439 x_setup_relief_color (s->f, &di->black_relief, 0.6, 0x4000,
2440 BLACK_PIX_DEFAULT (s->f));
2445 /* Draw a relief on frame F inside the rectangle given by LEFT_X,
2446 TOP_Y, RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the relief
2447 to draw, it must be >= 0. RAISED_P non-zero means draw a raised
2448 relief. LEFT_P non-zero means draw a relief on the left side of
2449 the rectangle. RIGHT_P non-zero means draw a relief on the right
2450 side of the rectangle. CLIP_RECT is the clipping rectangle to use
2451 when drawing. */
2453 static void
2454 x_draw_relief_rect (f, left_x, top_y, right_x, bottom_y, width,
2455 raised_p, top_p, bot_p, left_p, right_p, clip_rect)
2456 struct frame *f;
2457 int left_x, top_y, right_x, bottom_y, width;
2458 int top_p, bot_p, left_p, right_p, raised_p;
2459 Rect *clip_rect;
2461 Display *dpy = FRAME_MAC_DISPLAY (f);
2462 Window window = FRAME_MAC_WINDOW (f);
2463 int i;
2464 GC gc;
2466 if (raised_p)
2467 gc = f->output_data.mac->white_relief.gc;
2468 else
2469 gc = f->output_data.mac->black_relief.gc;
2470 mac_set_clip_rectangle (dpy, window, clip_rect);
2472 /* Top. */
2473 if (top_p)
2474 for (i = 0; i < width; ++i)
2475 XDrawLine (dpy, window, gc,
2476 left_x + i * left_p, top_y + i,
2477 right_x - i * right_p, top_y + i);
2479 /* Left. */
2480 if (left_p)
2481 for (i = 0; i < width; ++i)
2482 XDrawLine (dpy, window, gc,
2483 left_x + i, top_y + i, left_x + i, bottom_y - i);
2485 mac_reset_clipping (dpy, window);
2486 if (raised_p)
2487 gc = f->output_data.mac->black_relief.gc;
2488 else
2489 gc = f->output_data.mac->white_relief.gc;
2490 mac_set_clip_rectangle (dpy, window,
2491 clip_rect);
2493 /* Bottom. */
2494 if (bot_p)
2495 for (i = 0; i < width; ++i)
2496 XDrawLine (dpy, window, gc,
2497 left_x + i * left_p, bottom_y - i,
2498 right_x - i * right_p, bottom_y - i);
2500 /* Right. */
2501 if (right_p)
2502 for (i = 0; i < width; ++i)
2503 XDrawLine (dpy, window, gc,
2504 right_x - i, top_y + i + 1, right_x - i, bottom_y - i - 1);
2506 mac_reset_clipping (dpy, window);
2510 /* Draw a box on frame F inside the rectangle given by LEFT_X, TOP_Y,
2511 RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the lines to
2512 draw, it must be >= 0. LEFT_P non-zero means draw a line on the
2513 left side of the rectangle. RIGHT_P non-zero means draw a line
2514 on the right side of the rectangle. CLIP_RECT is the clipping
2515 rectangle to use when drawing. */
2517 static void
2518 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
2519 left_p, right_p, clip_rect)
2520 struct glyph_string *s;
2521 int left_x, top_y, right_x, bottom_y, width, left_p, right_p;
2522 Rect *clip_rect;
2524 XGCValues xgcv;
2526 xgcv.foreground = s->face->box_color;
2527 mac_set_clip_rectangle (s->display, s->window, clip_rect);
2529 /* Top. */
2530 XFillRectangle (s->display, s->window, &xgcv,
2531 left_x, top_y, right_x - left_x + 1, width);
2533 /* Left. */
2534 if (left_p)
2535 XFillRectangle (s->display, s->window, &xgcv,
2536 left_x, top_y, width, bottom_y - top_y + 1);
2538 /* Bottom. */
2539 XFillRectangle (s->display, s->window, &xgcv,
2540 left_x, bottom_y - width + 1, right_x - left_x + 1, width);
2542 /* Right. */
2543 if (right_p)
2544 XFillRectangle (s->display, s->window, &xgcv,
2545 right_x - width + 1, top_y, width, bottom_y - top_y + 1);
2547 mac_reset_clipping (s->display, s->window);
2551 /* Draw a box around glyph string S. */
2553 static void
2554 x_draw_glyph_string_box (s)
2555 struct glyph_string *s;
2557 int width, left_x, right_x, top_y, bottom_y, last_x, raised_p;
2558 int left_p, right_p;
2559 struct glyph *last_glyph;
2560 Rect clip_rect;
2562 last_x = window_box_right (s->w, s->area);
2563 if (s->row->full_width_p
2564 && !s->w->pseudo_window_p)
2566 last_x += WINDOW_RIGHT_SCROLL_BAR_AREA_WIDTH (s->w);
2567 if (s->area != RIGHT_MARGIN_AREA
2568 || WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (s->w))
2569 last_x += WINDOW_RIGHT_FRINGE_WIDTH (s->w);
2572 /* The glyph that may have a right box line. */
2573 last_glyph = (s->cmp || s->img
2574 ? s->first_glyph
2575 : s->first_glyph + s->nchars - 1);
2577 width = abs (s->face->box_line_width);
2578 raised_p = s->face->box == FACE_RAISED_BOX;
2579 left_x = s->x;
2580 right_x = (s->row->full_width_p && s->extends_to_end_of_line_p
2581 ? last_x - 1
2582 : min (last_x, s->x + s->background_width) - 1);
2583 top_y = s->y;
2584 bottom_y = top_y + s->height - 1;
2586 left_p = (s->first_glyph->left_box_line_p
2587 || (s->hl == DRAW_MOUSE_FACE
2588 && (s->prev == NULL
2589 || s->prev->hl != s->hl)));
2590 right_p = (last_glyph->right_box_line_p
2591 || (s->hl == DRAW_MOUSE_FACE
2592 && (s->next == NULL
2593 || s->next->hl != s->hl)));
2595 get_glyph_string_clip_rect (s, &clip_rect);
2597 if (s->face->box == FACE_SIMPLE_BOX)
2598 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
2599 left_p, right_p, &clip_rect);
2600 else
2602 x_setup_relief_colors (s);
2603 x_draw_relief_rect (s->f, left_x, top_y, right_x, bottom_y,
2604 width, raised_p, 1, 1, left_p, right_p, &clip_rect);
2609 /* Draw foreground of image glyph string S. */
2611 static void
2612 x_draw_image_foreground (s)
2613 struct glyph_string *s;
2615 int x = s->x;
2616 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2618 /* If first glyph of S has a left box line, start drawing it to the
2619 right of that line. */
2620 if (s->face->box != FACE_NO_BOX
2621 && s->first_glyph->left_box_line_p
2622 && s->slice.x == 0)
2623 x += abs (s->face->box_line_width);
2625 /* If there is a margin around the image, adjust x- and y-position
2626 by that margin. */
2627 if (s->slice.x == 0)
2628 x += s->img->hmargin;
2629 if (s->slice.y == 0)
2630 y += s->img->vmargin;
2632 if (s->img->pixmap)
2634 if (s->img->mask)
2636 Rect nr;
2637 XRectangle clip_rect, image_rect, r;
2639 get_glyph_string_clip_rect (s, &nr);
2640 CONVERT_TO_XRECT (clip_rect, nr);
2641 image_rect.x = x;
2642 image_rect.y = y;
2643 image_rect.width = s->slice.width;
2644 image_rect.height = s->slice.height;
2645 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2646 mac_copy_area_with_mask (s->display, s->img->pixmap, s->img->mask,
2647 s->window, s->gc,
2648 s->slice.x + r.x - x, s->slice.y + r.y - y,
2649 r.width, r.height, r.x, r.y);
2651 else
2653 Rect nr;
2654 XRectangle clip_rect, image_rect, r;
2656 get_glyph_string_clip_rect (s, &nr);
2657 CONVERT_TO_XRECT (clip_rect, nr);
2658 image_rect.x = x;
2659 image_rect.y = y;
2660 image_rect.width = s->slice.width;
2661 image_rect.height = s->slice.height;
2662 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2663 mac_copy_area (s->display, s->img->pixmap, s->window, s->gc,
2664 s->slice.x + r.x - x, s->slice.y + r.y - y,
2665 r.width, r.height, r.x, r.y);
2667 /* When the image has a mask, we can expect that at
2668 least part of a mouse highlight or a block cursor will
2669 be visible. If the image doesn't have a mask, make
2670 a block cursor visible by drawing a rectangle around
2671 the image. I believe it's looking better if we do
2672 nothing here for mouse-face. */
2673 if (s->hl == DRAW_CURSOR)
2675 int r = s->img->relief;
2676 if (r < 0) r = -r;
2677 mac_draw_rectangle (s->display, s->window, s->gc,
2678 x - r, y - r,
2679 s->slice.width + r*2 - 1,
2680 s->slice.height + r*2 - 1);
2684 else
2685 /* Draw a rectangle if image could not be loaded. */
2686 mac_draw_rectangle (s->display, s->window, s->gc, x, y,
2687 s->slice.width - 1, s->slice.height - 1);
2691 /* Draw a relief around the image glyph string S. */
2693 static void
2694 x_draw_image_relief (s)
2695 struct glyph_string *s;
2697 int x0, y0, x1, y1, thick, raised_p;
2698 Rect r;
2699 int x = s->x;
2700 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2702 /* If first glyph of S has a left box line, start drawing it to the
2703 right of that line. */
2704 if (s->face->box != FACE_NO_BOX
2705 && s->first_glyph->left_box_line_p
2706 && s->slice.x == 0)
2707 x += abs (s->face->box_line_width);
2709 /* If there is a margin around the image, adjust x- and y-position
2710 by that margin. */
2711 if (s->slice.x == 0)
2712 x += s->img->hmargin;
2713 if (s->slice.y == 0)
2714 y += s->img->vmargin;
2716 if (s->hl == DRAW_IMAGE_SUNKEN
2717 || s->hl == DRAW_IMAGE_RAISED)
2719 thick = tool_bar_button_relief >= 0 ? tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2720 raised_p = s->hl == DRAW_IMAGE_RAISED;
2722 else
2724 thick = abs (s->img->relief);
2725 raised_p = s->img->relief > 0;
2728 x0 = x - thick;
2729 y0 = y - thick;
2730 x1 = x + s->slice.width + thick - 1;
2731 y1 = y + s->slice.height + thick - 1;
2733 x_setup_relief_colors (s);
2734 get_glyph_string_clip_rect (s, &r);
2735 x_draw_relief_rect (s->f, x0, y0, x1, y1, thick, raised_p,
2736 s->slice.y == 0,
2737 s->slice.y + s->slice.height == s->img->height,
2738 s->slice.x == 0,
2739 s->slice.x + s->slice.width == s->img->width,
2740 &r);
2744 /* Draw the foreground of image glyph string S to PIXMAP. */
2746 static void
2747 x_draw_image_foreground_1 (s, pixmap)
2748 struct glyph_string *s;
2749 Pixmap pixmap;
2751 int x = 0;
2752 int y = s->ybase - s->y - image_ascent (s->img, s->face, &s->slice);
2754 /* If first glyph of S has a left box line, start drawing it to the
2755 right of that line. */
2756 if (s->face->box != FACE_NO_BOX
2757 && s->first_glyph->left_box_line_p
2758 && s->slice.x == 0)
2759 x += abs (s->face->box_line_width);
2761 /* If there is a margin around the image, adjust x- and y-position
2762 by that margin. */
2763 if (s->slice.x == 0)
2764 x += s->img->hmargin;
2765 if (s->slice.y == 0)
2766 y += s->img->vmargin;
2768 if (s->img->pixmap)
2770 if (s->img->mask)
2771 mac_copy_area_with_mask_to_pixmap (s->display, s->img->pixmap,
2772 s->img->mask, pixmap, s->gc,
2773 s->slice.x, s->slice.y,
2774 s->slice.width, s->slice.height,
2775 x, y);
2776 else
2778 mac_copy_area_to_pixmap (s->display, s->img->pixmap, pixmap, s->gc,
2779 s->slice.x, s->slice.y,
2780 s->slice.width, s->slice.height,
2781 x, y);
2783 /* When the image has a mask, we can expect that at
2784 least part of a mouse highlight or a block cursor will
2785 be visible. If the image doesn't have a mask, make
2786 a block cursor visible by drawing a rectangle around
2787 the image. I believe it's looking better if we do
2788 nothing here for mouse-face. */
2789 if (s->hl == DRAW_CURSOR)
2791 int r = s->img->relief;
2792 if (r < 0) r = -r;
2793 mac_draw_rectangle (s->display, s->window, s->gc, x - r, y - r,
2794 s->slice.width + r*2 - 1,
2795 s->slice.height + r*2 - 1);
2799 else
2800 /* Draw a rectangle if image could not be loaded. */
2801 mac_draw_rectangle_to_pixmap (s->display, pixmap, s->gc, x, y,
2802 s->slice.width - 1, s->slice.height - 1);
2806 /* Draw part of the background of glyph string S. X, Y, W, and H
2807 give the rectangle to draw. */
2809 static void
2810 x_draw_glyph_string_bg_rect (s, x, y, w, h)
2811 struct glyph_string *s;
2812 int x, y, w, h;
2814 #if 0 /* MAC_TODO: stipple */
2815 if (s->stippled_p)
2817 /* Fill background with a stipple pattern. */
2818 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2819 XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
2820 XSetFillStyle (s->display, s->gc, FillSolid);
2822 else
2823 #endif /* MAC_TODO */
2824 x_clear_glyph_string_rect (s, x, y, w, h);
2828 /* Draw image glyph string S.
2830 s->y
2831 s->x +-------------------------
2832 | s->face->box
2834 | +-------------------------
2835 | | s->img->margin
2837 | | +-------------------
2838 | | | the image
2842 static void
2843 x_draw_image_glyph_string (s)
2844 struct glyph_string *s;
2846 int x, y;
2847 int box_line_hwidth = abs (s->face->box_line_width);
2848 int box_line_vwidth = max (s->face->box_line_width, 0);
2849 int height;
2850 Pixmap pixmap = 0;
2852 height = s->height - 2 * box_line_vwidth;
2855 /* Fill background with face under the image. Do it only if row is
2856 taller than image or if image has a clip mask to reduce
2857 flickering. */
2858 s->stippled_p = s->face->stipple != 0;
2859 if (height > s->slice.height
2860 || s->img->hmargin
2861 || s->img->vmargin
2862 || s->img->mask
2863 || s->img->pixmap == 0
2864 || s->width != s->background_width)
2866 x = s->x;
2867 if (s->first_glyph->left_box_line_p
2868 && s->slice.x == 0)
2869 x += box_line_hwidth;
2871 y = s->y;
2872 if (s->slice.y == 0)
2873 y += box_line_vwidth;
2875 if (s->img->mask)
2877 /* Create a pixmap as large as the glyph string. Fill it
2878 with the background color. Copy the image to it, using
2879 its mask. Copy the temporary pixmap to the display. */
2880 int depth = one_mac_display_info.n_planes;
2882 /* Create a pixmap as large as the glyph string. */
2883 pixmap = XCreatePixmap (s->display, s->window,
2884 s->background_width,
2885 s->height, depth);
2887 /* Fill the pixmap with the background color/stipple. */
2888 #if 0 /* TODO: stipple */
2889 if (s->stippled_p)
2891 /* Fill background with a stipple pattern. */
2892 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2893 XFillRectangle (s->display, pixmap, s->gc,
2894 0, 0, s->background_width, s->height);
2895 XSetFillStyle (s->display, s->gc, FillSolid);
2897 else
2898 #endif
2900 XGCValues xgcv;
2901 XGetGCValues (s->display, s->gc, GCForeground | GCBackground,
2902 &xgcv);
2903 XSetForeground (s->display, s->gc, xgcv.background);
2904 mac_fill_rectangle_to_pixmap (s->display, pixmap, s->gc,
2905 0, 0, s->background_width,
2906 s->height);
2907 XSetForeground (s->display, s->gc, xgcv.foreground);
2910 else
2911 x_draw_glyph_string_bg_rect (s, x, y, s->background_width, height);
2913 s->background_filled_p = 1;
2916 /* Draw the foreground. */
2917 if (pixmap != 0)
2919 x_draw_image_foreground_1 (s, pixmap);
2920 x_set_glyph_string_clipping (s);
2921 mac_copy_area (s->display, pixmap, s->window, s->gc,
2922 0, 0, s->background_width, s->height, s->x, s->y);
2923 mac_reset_clipping (s->display, s->window);
2924 XFreePixmap (s->display, pixmap);
2926 else
2927 x_draw_image_foreground (s);
2929 /* If we must draw a relief around the image, do it. */
2930 if (s->img->relief
2931 || s->hl == DRAW_IMAGE_RAISED
2932 || s->hl == DRAW_IMAGE_SUNKEN)
2933 x_draw_image_relief (s);
2937 /* Draw stretch glyph string S. */
2939 static void
2940 x_draw_stretch_glyph_string (s)
2941 struct glyph_string *s;
2943 xassert (s->first_glyph->type == STRETCH_GLYPH);
2944 s->stippled_p = s->face->stipple != 0;
2946 if (s->hl == DRAW_CURSOR
2947 && !x_stretch_cursor_p)
2949 /* If `x-stretch-block-cursor' is nil, don't draw a block cursor
2950 as wide as the stretch glyph. */
2951 int width = min (FRAME_COLUMN_WIDTH (s->f), s->background_width);
2953 /* Draw cursor. */
2954 x_draw_glyph_string_bg_rect (s, s->x, s->y, width, s->height);
2956 /* Clear rest using the GC of the original non-cursor face. */
2957 if (width < s->background_width)
2959 int x = s->x + width, y = s->y;
2960 int w = s->background_width - width, h = s->height;
2961 Rect r;
2962 GC gc;
2964 if (s->row->mouse_face_p
2965 && cursor_in_mouse_face_p (s->w))
2967 x_set_mouse_face_gc (s);
2968 gc = s->gc;
2970 else
2971 gc = s->face->gc;
2973 get_glyph_string_clip_rect (s, &r);
2974 mac_set_clip_rectangle (s->display, s->window, &r);
2976 #if 0 /* MAC_TODO: stipple */
2977 if (s->face->stipple)
2979 /* Fill background with a stipple pattern. */
2980 XSetFillStyle (s->display, gc, FillOpaqueStippled);
2981 XFillRectangle (s->display, s->window, gc, x, y, w, h);
2982 XSetFillStyle (s->display, gc, FillSolid);
2984 else
2985 #endif /* MAC_TODO */
2987 XGCValues xgcv;
2988 XGetGCValues (s->display, gc, GCForeground | GCBackground, &xgcv);
2989 XSetForeground (s->display, gc, xgcv.background);
2990 XFillRectangle (s->display, s->window, gc, x, y, w, h);
2991 XSetForeground (s->display, gc, xgcv.foreground);
2994 mac_reset_clipping (s->display, s->window);
2997 else if (!s->background_filled_p)
2998 x_draw_glyph_string_bg_rect (s, s->x, s->y, s->background_width,
2999 s->height);
3001 s->background_filled_p = 1;
3005 /* Draw glyph string S. */
3007 static void
3008 x_draw_glyph_string (s)
3009 struct glyph_string *s;
3011 int relief_drawn_p = 0;
3013 /* If S draws into the background of its successor, draw the
3014 background of the successor first so that S can draw into it.
3015 This makes S->next use XDrawString instead of XDrawImageString. */
3016 if (s->next && s->right_overhang && !s->for_overlaps_p)
3018 xassert (s->next->img == NULL);
3019 x_set_glyph_string_gc (s->next);
3020 x_set_glyph_string_clipping (s->next);
3021 x_draw_glyph_string_background (s->next, 1);
3024 /* Set up S->gc, set clipping and draw S. */
3025 x_set_glyph_string_gc (s);
3027 /* Draw relief (if any) in advance for char/composition so that the
3028 glyph string can be drawn over it. */
3029 if (!s->for_overlaps_p
3030 && s->face->box != FACE_NO_BOX
3031 && (s->first_glyph->type == CHAR_GLYPH
3032 || s->first_glyph->type == COMPOSITE_GLYPH))
3035 x_set_glyph_string_clipping (s);
3036 x_draw_glyph_string_background (s, 1);
3037 x_draw_glyph_string_box (s);
3038 x_set_glyph_string_clipping (s);
3039 relief_drawn_p = 1;
3041 else
3042 x_set_glyph_string_clipping (s);
3044 switch (s->first_glyph->type)
3046 case IMAGE_GLYPH:
3047 x_draw_image_glyph_string (s);
3048 break;
3050 case STRETCH_GLYPH:
3051 x_draw_stretch_glyph_string (s);
3052 break;
3054 case CHAR_GLYPH:
3055 if (s->for_overlaps_p)
3056 s->background_filled_p = 1;
3057 else
3058 x_draw_glyph_string_background (s, 0);
3059 x_draw_glyph_string_foreground (s);
3060 break;
3062 case COMPOSITE_GLYPH:
3063 if (s->for_overlaps_p || s->gidx > 0)
3064 s->background_filled_p = 1;
3065 else
3066 x_draw_glyph_string_background (s, 1);
3067 x_draw_composite_glyph_string_foreground (s);
3068 break;
3070 default:
3071 abort ();
3074 if (!s->for_overlaps_p)
3076 /* Draw underline. */
3077 if (s->face->underline_p)
3079 unsigned long h = 1;
3080 unsigned long dy = s->height - h;
3082 if (s->face->underline_defaulted_p)
3083 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
3084 s->width, h);
3085 else
3087 XGCValues xgcv;
3088 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3089 XSetForeground (s->display, s->gc, s->face->underline_color);
3090 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
3091 s->width, h);
3092 XSetForeground (s->display, s->gc, xgcv.foreground);
3096 /* Draw overline. */
3097 if (s->face->overline_p)
3099 unsigned long dy = 0, h = 1;
3101 if (s->face->overline_color_defaulted_p)
3102 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
3103 s->width, h);
3104 else
3106 XGCValues xgcv;
3107 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3108 XSetForeground (s->display, s->gc, s->face->overline_color);
3109 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
3110 s->width, h);
3111 XSetForeground (s->display, s->gc, xgcv.foreground);
3115 /* Draw strike-through. */
3116 if (s->face->strike_through_p)
3118 unsigned long h = 1;
3119 unsigned long dy = (s->height - h) / 2;
3121 if (s->face->strike_through_color_defaulted_p)
3122 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
3123 s->width, h);
3124 else
3126 XGCValues xgcv;
3127 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3128 XSetForeground (s->display, s->gc, s->face->strike_through_color);
3129 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
3130 s->width, h);
3131 XSetForeground (s->display, s->gc, xgcv.foreground);
3135 /* Draw relief if not yet drawn. */
3136 if (!relief_drawn_p && s->face->box != FACE_NO_BOX)
3137 x_draw_glyph_string_box (s);
3140 /* Reset clipping. */
3141 mac_reset_clipping (s->display, s->window);
3144 /* Shift display to make room for inserted glyphs. */
3146 void
3147 mac_shift_glyphs_for_insert (f, x, y, width, height, shift_by)
3148 struct frame *f;
3149 int x, y, width, height, shift_by;
3151 mac_scroll_area (FRAME_MAC_DISPLAY (f), FRAME_MAC_WINDOW (f),
3152 f->output_data.mac->normal_gc,
3153 x, y, width, height,
3154 x + shift_by, y);
3157 /* Delete N glyphs at the nominal cursor position. Not implemented
3158 for X frames. */
3160 static void
3161 x_delete_glyphs (n)
3162 register int n;
3164 abort ();
3168 /* Clear entire frame. If updating_frame is non-null, clear that
3169 frame. Otherwise clear the selected frame. */
3171 static void
3172 x_clear_frame ()
3174 struct frame *f;
3176 if (updating_frame)
3177 f = updating_frame;
3178 else
3179 f = SELECTED_FRAME ();
3181 /* Clearing the frame will erase any cursor, so mark them all as no
3182 longer visible. */
3183 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
3184 output_cursor.hpos = output_cursor.vpos = 0;
3185 output_cursor.x = -1;
3187 /* We don't set the output cursor here because there will always
3188 follow an explicit cursor_to. */
3189 BLOCK_INPUT;
3190 XClearWindow (FRAME_MAC_DISPLAY (f), FRAME_MAC_WINDOW (f));
3192 #if 0 /* Clearing frame on Mac OS clears scroll bars. */
3193 /* We have to clear the scroll bars, too. If we have changed
3194 colors or something like that, then they should be notified. */
3195 x_scroll_bar_clear (f);
3196 #endif
3198 XFlush (FRAME_MAC_DISPLAY (f));
3199 UNBLOCK_INPUT;
3204 /* Invert the middle quarter of the frame for .15 sec. */
3206 /* We use the select system call to do the waiting, so we have to make
3207 sure it's available. If it isn't, we just won't do visual bells. */
3209 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
3212 /* Subtract the `struct timeval' values X and Y, storing the result in
3213 *RESULT. Return 1 if the difference is negative, otherwise 0. */
3215 static int
3216 timeval_subtract (result, x, y)
3217 struct timeval *result, x, y;
3219 /* Perform the carry for the later subtraction by updating y. This
3220 is safer because on some systems the tv_sec member is unsigned. */
3221 if (x.tv_usec < y.tv_usec)
3223 int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
3224 y.tv_usec -= 1000000 * nsec;
3225 y.tv_sec += nsec;
3228 if (x.tv_usec - y.tv_usec > 1000000)
3230 int nsec = (y.tv_usec - x.tv_usec) / 1000000;
3231 y.tv_usec += 1000000 * nsec;
3232 y.tv_sec -= nsec;
3235 /* Compute the time remaining to wait. tv_usec is certainly
3236 positive. */
3237 result->tv_sec = x.tv_sec - y.tv_sec;
3238 result->tv_usec = x.tv_usec - y.tv_usec;
3240 /* Return indication of whether the result should be considered
3241 negative. */
3242 return x.tv_sec < y.tv_sec;
3245 void
3246 XTflash (f)
3247 struct frame *f;
3249 BLOCK_INPUT;
3251 FlashMenuBar (0);
3254 struct timeval wakeup;
3256 EMACS_GET_TIME (wakeup);
3258 /* Compute time to wait until, propagating carry from usecs. */
3259 wakeup.tv_usec += 150000;
3260 wakeup.tv_sec += (wakeup.tv_usec / 1000000);
3261 wakeup.tv_usec %= 1000000;
3263 /* Keep waiting until past the time wakeup. */
3264 while (1)
3266 struct timeval timeout;
3268 EMACS_GET_TIME (timeout);
3270 /* In effect, timeout = wakeup - timeout.
3271 Break if result would be negative. */
3272 if (timeval_subtract (&timeout, wakeup, timeout))
3273 break;
3275 /* Try to wait that long--but we might wake up sooner. */
3276 select (0, NULL, NULL, NULL, &timeout);
3280 FlashMenuBar (0);
3282 UNBLOCK_INPUT;
3285 #endif /* defined (HAVE_TIMEVAL) && defined (HAVE_SELECT) */
3288 /* Make audible bell. */
3290 void
3291 XTring_bell ()
3293 struct frame *f = SELECTED_FRAME ();
3295 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
3296 if (visible_bell)
3297 XTflash (f);
3298 else
3299 #endif
3301 BLOCK_INPUT;
3302 SysBeep (1);
3303 XFlush (FRAME_MAC_DISPLAY (f));
3304 UNBLOCK_INPUT;
3310 /* Specify how many text lines, from the top of the window,
3311 should be affected by insert-lines and delete-lines operations.
3312 This, and those operations, are used only within an update
3313 that is bounded by calls to x_update_begin and x_update_end. */
3315 static void
3316 XTset_terminal_window (n)
3317 register int n;
3319 /* This function intentionally left blank. */
3324 /***********************************************************************
3325 Line Dance
3326 ***********************************************************************/
3328 /* Perform an insert-lines or delete-lines operation, inserting N
3329 lines or deleting -N lines at vertical position VPOS. */
3331 static void
3332 x_ins_del_lines (vpos, n)
3333 int vpos, n;
3335 abort ();
3339 /* Scroll part of the display as described by RUN. */
3341 static void
3342 x_scroll_run (w, run)
3343 struct window *w;
3344 struct run *run;
3346 struct frame *f = XFRAME (w->frame);
3347 int x, y, width, height, from_y, to_y, bottom_y;
3349 /* Get frame-relative bounding box of the text display area of W,
3350 without mode lines. Include in this box the left and right
3351 fringe of W. */
3352 window_box (w, -1, &x, &y, &width, &height);
3354 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
3355 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
3356 bottom_y = y + height;
3358 if (to_y < from_y)
3360 /* Scrolling up. Make sure we don't copy part of the mode
3361 line at the bottom. */
3362 if (from_y + run->height > bottom_y)
3363 height = bottom_y - from_y;
3364 else
3365 height = run->height;
3367 else
3369 /* Scolling down. Make sure we don't copy over the mode line.
3370 at the bottom. */
3371 if (to_y + run->height > bottom_y)
3372 height = bottom_y - to_y;
3373 else
3374 height = run->height;
3377 BLOCK_INPUT;
3379 /* Cursor off. Will be switched on again in x_update_window_end. */
3380 updated_window = w;
3381 x_clear_cursor (w);
3383 mac_scroll_area (FRAME_MAC_DISPLAY (f), FRAME_MAC_WINDOW (f),
3384 f->output_data.mac->normal_gc,
3385 x, from_y,
3386 width, height,
3387 x, to_y);
3389 UNBLOCK_INPUT;
3394 /***********************************************************************
3395 Exposure Events
3396 ***********************************************************************/
3399 static void
3400 frame_highlight (f)
3401 struct frame *f;
3403 x_update_cursor (f, 1);
3406 static void
3407 frame_unhighlight (f)
3408 struct frame *f;
3410 x_update_cursor (f, 1);
3413 /* The focus has changed. Update the frames as necessary to reflect
3414 the new situation. Note that we can't change the selected frame
3415 here, because the Lisp code we are interrupting might become confused.
3416 Each event gets marked with the frame in which it occurred, so the
3417 Lisp code can tell when the switch took place by examining the events. */
3419 static void
3420 x_new_focus_frame (dpyinfo, frame)
3421 struct x_display_info *dpyinfo;
3422 struct frame *frame;
3424 struct frame *old_focus = dpyinfo->x_focus_frame;
3426 if (frame != dpyinfo->x_focus_frame)
3428 /* Set this before calling other routines, so that they see
3429 the correct value of x_focus_frame. */
3430 dpyinfo->x_focus_frame = frame;
3432 if (old_focus && old_focus->auto_lower)
3433 x_lower_frame (old_focus);
3435 #if 0
3436 selected_frame = frame;
3437 XSETFRAME (XWINDOW (selected_frame->selected_window)->frame,
3438 selected_frame);
3439 Fselect_window (selected_frame->selected_window, Qnil);
3440 choose_minibuf_frame ();
3441 #endif /* ! 0 */
3443 if (dpyinfo->x_focus_frame && dpyinfo->x_focus_frame->auto_raise)
3444 pending_autoraise_frame = dpyinfo->x_focus_frame;
3445 else
3446 pending_autoraise_frame = 0;
3449 x_frame_rehighlight (dpyinfo);
3452 /* Handle an event saying the mouse has moved out of an Emacs frame. */
3454 void
3455 x_mouse_leave (dpyinfo)
3456 struct x_display_info *dpyinfo;
3458 x_new_focus_frame (dpyinfo, dpyinfo->x_focus_event_frame);
3461 /* The focus has changed, or we have redirected a frame's focus to
3462 another frame (this happens when a frame uses a surrogate
3463 mini-buffer frame). Shift the highlight as appropriate.
3465 The FRAME argument doesn't necessarily have anything to do with which
3466 frame is being highlighted or un-highlighted; we only use it to find
3467 the appropriate X display info. */
3469 static void
3470 XTframe_rehighlight (frame)
3471 struct frame *frame;
3473 x_frame_rehighlight (FRAME_X_DISPLAY_INFO (frame));
3476 static void
3477 x_frame_rehighlight (dpyinfo)
3478 struct x_display_info *dpyinfo;
3480 struct frame *old_highlight = dpyinfo->x_highlight_frame;
3482 if (dpyinfo->x_focus_frame)
3484 dpyinfo->x_highlight_frame
3485 = ((GC_FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame)))
3486 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
3487 : dpyinfo->x_focus_frame);
3488 if (! FRAME_LIVE_P (dpyinfo->x_highlight_frame))
3490 FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
3491 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
3494 else
3495 dpyinfo->x_highlight_frame = 0;
3497 if (dpyinfo->x_highlight_frame != old_highlight)
3499 if (old_highlight)
3500 frame_unhighlight (old_highlight);
3501 if (dpyinfo->x_highlight_frame)
3502 frame_highlight (dpyinfo->x_highlight_frame);
3508 /* Keyboard processing - modifier keys, vendor-specific keysyms, etc. */
3510 #if 0 /* MAC_TODO */
3511 /* Initialize mode_switch_bit and modifier_meaning. */
3512 static void
3513 x_find_modifier_meanings (dpyinfo)
3514 struct x_display_info *dpyinfo;
3516 int min_code, max_code;
3517 KeySym *syms;
3518 int syms_per_code;
3519 XModifierKeymap *mods;
3521 dpyinfo->meta_mod_mask = 0;
3522 dpyinfo->shift_lock_mask = 0;
3523 dpyinfo->alt_mod_mask = 0;
3524 dpyinfo->super_mod_mask = 0;
3525 dpyinfo->hyper_mod_mask = 0;
3527 #ifdef HAVE_X11R4
3528 XDisplayKeycodes (dpyinfo->display, &min_code, &max_code);
3529 #else
3530 min_code = dpyinfo->display->min_keycode;
3531 max_code = dpyinfo->display->max_keycode;
3532 #endif
3534 syms = XGetKeyboardMapping (dpyinfo->display,
3535 min_code, max_code - min_code + 1,
3536 &syms_per_code);
3537 mods = XGetModifierMapping (dpyinfo->display);
3539 /* Scan the modifier table to see which modifier bits the Meta and
3540 Alt keysyms are on. */
3542 int row, col; /* The row and column in the modifier table. */
3544 for (row = 3; row < 8; row++)
3545 for (col = 0; col < mods->max_keypermod; col++)
3547 KeyCode code
3548 = mods->modifiermap[(row * mods->max_keypermod) + col];
3550 /* Zeroes are used for filler. Skip them. */
3551 if (code == 0)
3552 continue;
3554 /* Are any of this keycode's keysyms a meta key? */
3556 int code_col;
3558 for (code_col = 0; code_col < syms_per_code; code_col++)
3560 int sym = syms[((code - min_code) * syms_per_code) + code_col];
3562 switch (sym)
3564 case XK_Meta_L:
3565 case XK_Meta_R:
3566 dpyinfo->meta_mod_mask |= (1 << row);
3567 break;
3569 case XK_Alt_L:
3570 case XK_Alt_R:
3571 dpyinfo->alt_mod_mask |= (1 << row);
3572 break;
3574 case XK_Hyper_L:
3575 case XK_Hyper_R:
3576 dpyinfo->hyper_mod_mask |= (1 << row);
3577 break;
3579 case XK_Super_L:
3580 case XK_Super_R:
3581 dpyinfo->super_mod_mask |= (1 << row);
3582 break;
3584 case XK_Shift_Lock:
3585 /* Ignore this if it's not on the lock modifier. */
3586 if ((1 << row) == LockMask)
3587 dpyinfo->shift_lock_mask = LockMask;
3588 break;
3595 /* If we couldn't find any meta keys, accept any alt keys as meta keys. */
3596 if (! dpyinfo->meta_mod_mask)
3598 dpyinfo->meta_mod_mask = dpyinfo->alt_mod_mask;
3599 dpyinfo->alt_mod_mask = 0;
3602 /* If some keys are both alt and meta,
3603 make them just meta, not alt. */
3604 if (dpyinfo->alt_mod_mask & dpyinfo->meta_mod_mask)
3606 dpyinfo->alt_mod_mask &= ~dpyinfo->meta_mod_mask;
3609 XFree ((char *) syms);
3610 XFreeModifiermap (mods);
3613 #endif /* MAC_TODO */
3615 /* Convert between the modifier bits X uses and the modifier bits
3616 Emacs uses. */
3618 static unsigned int
3619 x_mac_to_emacs_modifiers (dpyinfo, state)
3620 struct x_display_info *dpyinfo;
3621 unsigned short state;
3623 return (((state & shiftKey) ? shift_modifier : 0)
3624 | ((state & controlKey) ? ctrl_modifier : 0)
3625 | ((state & cmdKey) ? meta_modifier : 0)
3626 | ((state & optionKey) ? alt_modifier : 0));
3629 #if 0 /* MAC_TODO */
3630 static unsigned short
3631 x_emacs_to_x_modifiers (dpyinfo, state)
3632 struct x_display_info *dpyinfo;
3633 unsigned int state;
3635 return ( ((state & alt_modifier) ? dpyinfo->alt_mod_mask : 0)
3636 | ((state & super_modifier) ? dpyinfo->super_mod_mask : 0)
3637 | ((state & hyper_modifier) ? dpyinfo->hyper_mod_mask : 0)
3638 | ((state & shift_modifier) ? ShiftMask : 0)
3639 | ((state & ctrl_modifier) ? ControlMask : 0)
3640 | ((state & meta_modifier) ? dpyinfo->meta_mod_mask : 0));
3642 #endif /* MAC_TODO */
3644 /* Convert a keysym to its name. */
3646 char *
3647 x_get_keysym_name (keysym)
3648 int keysym;
3650 char *value;
3652 BLOCK_INPUT;
3653 #if 0
3654 value = XKeysymToString (keysym);
3655 #else
3656 value = 0;
3657 #endif
3658 UNBLOCK_INPUT;
3660 return value;
3665 /* Mouse clicks and mouse movement. Rah. */
3667 /* Prepare a mouse-event in *RESULT for placement in the input queue.
3669 If the event is a button press, then note that we have grabbed
3670 the mouse. */
3672 static Lisp_Object
3673 construct_mouse_click (result, event, f)
3674 struct input_event *result;
3675 EventRecord *event;
3676 struct frame *f;
3678 Point mouseLoc;
3680 result->kind = MOUSE_CLICK_EVENT;
3681 result->code = 0; /* only one mouse button */
3682 result->timestamp = event->when;
3683 result->modifiers = event->what == mouseDown ? down_modifier : up_modifier;
3685 mouseLoc = event->where;
3687 SetPortWindowPort (FRAME_MAC_WINDOW (f));
3689 GlobalToLocal (&mouseLoc);
3690 XSETINT (result->x, mouseLoc.h);
3691 XSETINT (result->y, mouseLoc.v);
3693 XSETFRAME (result->frame_or_window, f);
3695 result->arg = Qnil;
3696 return Qnil;
3700 /* Function to report a mouse movement to the mainstream Emacs code.
3701 The input handler calls this.
3703 We have received a mouse movement event, which is given in *event.
3704 If the mouse is over a different glyph than it was last time, tell
3705 the mainstream emacs code by setting mouse_moved. If not, ask for
3706 another motion event, so we can check again the next time it moves. */
3708 static Point last_mouse_motion_position;
3709 static Lisp_Object last_mouse_motion_frame;
3711 static void
3712 note_mouse_movement (frame, pos)
3713 FRAME_PTR frame;
3714 Point *pos;
3716 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (frame);
3717 #if TARGET_API_MAC_CARBON
3718 Rect r;
3719 #endif
3721 last_mouse_movement_time = TickCount () * (1000 / 60); /* to milliseconds */
3722 last_mouse_motion_position = *pos;
3723 XSETFRAME (last_mouse_motion_frame, frame);
3725 #if TARGET_API_MAC_CARBON
3726 if (!PtInRect (*pos, GetWindowPortBounds (FRAME_MAC_WINDOW (frame), &r)))
3727 #else
3728 if (!PtInRect (*pos, &FRAME_MAC_WINDOW (frame)->portRect))
3729 #endif
3731 if (frame == dpyinfo->mouse_face_mouse_frame)
3732 /* This case corresponds to LeaveNotify in X11. */
3734 /* If we move outside the frame, then we're certainly no
3735 longer on any text in the frame. */
3736 clear_mouse_face (dpyinfo);
3737 dpyinfo->mouse_face_mouse_frame = 0;
3738 if (!dpyinfo->grabbed)
3739 rif->define_frame_cursor (frame,
3740 frame->output_data.mac->nontext_cursor);
3743 /* Has the mouse moved off the glyph it was on at the last sighting? */
3744 else if (pos->h < last_mouse_glyph.left
3745 || pos->h >= last_mouse_glyph.right
3746 || pos->v < last_mouse_glyph.top
3747 || pos->v >= last_mouse_glyph.bottom)
3749 frame->mouse_moved = 1;
3750 last_mouse_scroll_bar = Qnil;
3751 note_mouse_highlight (frame, pos->h, pos->v);
3755 /* This is used for debugging, to turn off note_mouse_highlight. */
3757 int disable_mouse_highlight;
3761 /************************************************************************
3762 Mouse Face
3763 ************************************************************************/
3765 static struct scroll_bar *x_window_to_scroll_bar ();
3766 static void x_scroll_bar_report_motion ();
3767 static void x_check_fullscreen P_ ((struct frame *));
3768 static void x_check_fullscreen_move P_ ((struct frame *));
3769 static int glyph_rect P_ ((struct frame *f, int, int, Rect *));
3772 /* MAC TODO: This should be called from somewhere (or removed) ++KFS */
3774 static void
3775 redo_mouse_highlight ()
3777 if (!NILP (last_mouse_motion_frame)
3778 && FRAME_LIVE_P (XFRAME (last_mouse_motion_frame)))
3779 note_mouse_highlight (XFRAME (last_mouse_motion_frame),
3780 last_mouse_motion_position.h,
3781 last_mouse_motion_position.v);
3785 /* Try to determine frame pixel position and size of the glyph under
3786 frame pixel coordinates X/Y on frame F . Return the position and
3787 size in *RECT. Value is non-zero if we could compute these
3788 values. */
3790 static int
3791 glyph_rect (f, x, y, rect)
3792 struct frame *f;
3793 int x, y;
3794 Rect *rect;
3796 Lisp_Object window;
3798 window = window_from_coordinates (f, x, y, 0, &x, &y, 0);
3800 if (!NILP (window))
3802 struct window *w = XWINDOW (window);
3803 struct glyph_row *r = MATRIX_FIRST_TEXT_ROW (w->current_matrix);
3804 struct glyph_row *end = r + w->current_matrix->nrows - 1;
3806 for (; r < end && r->enabled_p; ++r)
3807 if (r->y <= y && r->y + r->height > y)
3809 /* Found the row at y. */
3810 struct glyph *g = r->glyphs[TEXT_AREA];
3811 struct glyph *end = g + r->used[TEXT_AREA];
3812 int gx;
3814 rect->top = WINDOW_TO_FRAME_PIXEL_Y (w, r->y);
3815 rect->bottom = rect->top + r->height;
3817 if (x < r->x)
3819 /* x is to the left of the first glyph in the row. */
3820 /* Shouldn't this be a pixel value?
3821 WINDOW_LEFT_EDGE_X (w) seems to be the right value.
3822 ++KFS */
3823 rect->left = WINDOW_LEFT_EDGE_COL (w);
3824 rect->right = WINDOW_TO_FRAME_PIXEL_X (w, r->x);
3825 return 1;
3828 for (gx = r->x; g < end; gx += g->pixel_width, ++g)
3829 if (gx <= x && gx + g->pixel_width > x)
3831 /* x is on a glyph. */
3832 rect->left = WINDOW_TO_FRAME_PIXEL_X (w, gx);
3833 rect->right = rect->left + g->pixel_width;
3834 return 1;
3837 /* x is to the right of the last glyph in the row. */
3838 rect->left = WINDOW_TO_FRAME_PIXEL_X (w, gx);
3839 /* Shouldn't this be a pixel value?
3840 WINDOW_RIGHT_EDGE_X (w) seems to be the right value.
3841 ++KFS */
3842 rect->right = WINDOW_RIGHT_EDGE_COL (w);
3843 return 1;
3847 /* The y is not on any row. */
3848 return 0;
3851 /* MAC TODO: This should be called from somewhere (or removed) ++KFS */
3853 /* Record the position of the mouse in last_mouse_glyph. */
3854 static void
3855 remember_mouse_glyph (f1, gx, gy)
3856 struct frame * f1;
3857 int gx, gy;
3859 if (!glyph_rect (f1, gx, gy, &last_mouse_glyph))
3861 int width = FRAME_SMALLEST_CHAR_WIDTH (f1);
3862 int height = FRAME_SMALLEST_FONT_HEIGHT (f1);
3864 /* Arrange for the division in FRAME_PIXEL_X_TO_COL etc. to
3865 round down even for negative values. */
3866 if (gx < 0)
3867 gx -= width - 1;
3868 if (gy < 0)
3869 gy -= height - 1;
3870 #if 0
3871 /* This was the original code from XTmouse_position, but it seems
3872 to give the position of the glyph diagonally next to the one
3873 the mouse is over. */
3874 gx = (gx + width - 1) / width * width;
3875 gy = (gy + height - 1) / height * height;
3876 #else
3877 gx = gx / width * width;
3878 gy = gy / height * height;
3879 #endif
3881 last_mouse_glyph.left = gx;
3882 last_mouse_glyph.top = gy;
3883 last_mouse_glyph.right = gx + width;
3884 last_mouse_glyph.bottom = gy + height;
3889 static WindowPtr
3890 mac_front_window ()
3892 #if TARGET_API_MAC_CARBON
3893 return GetFrontWindowOfClass (kDocumentWindowClass, true);
3894 #else
3895 WindowPtr front_window = FrontWindow ();
3897 if (tip_window && front_window == tip_window)
3898 return GetNextWindow (front_window);
3899 else
3900 return front_window;
3901 #endif
3904 #define mac_window_to_frame(wp) (((mac_output *) GetWRefCon (wp))->mFP)
3906 /* Return the current position of the mouse.
3907 *fp should be a frame which indicates which display to ask about.
3909 If the mouse movement started in a scroll bar, set *fp, *bar_window,
3910 and *part to the frame, window, and scroll bar part that the mouse
3911 is over. Set *x and *y to the portion and whole of the mouse's
3912 position on the scroll bar.
3914 If the mouse movement started elsewhere, set *fp to the frame the
3915 mouse is on, *bar_window to nil, and *x and *y to the character cell
3916 the mouse is over.
3918 Set *time to the server time-stamp for the time at which the mouse
3919 was at this position.
3921 Don't store anything if we don't have a valid set of values to report.
3923 This clears the mouse_moved flag, so we can wait for the next mouse
3924 movement. */
3926 static void
3927 XTmouse_position (fp, insist, bar_window, part, x, y, time)
3928 FRAME_PTR *fp;
3929 int insist;
3930 Lisp_Object *bar_window;
3931 enum scroll_bar_part *part;
3932 Lisp_Object *x, *y;
3933 unsigned long *time;
3935 Point mouse_pos;
3936 int ignore1, ignore2;
3937 WindowPtr wp = mac_front_window ();
3938 struct frame *f;
3939 Lisp_Object frame, tail;
3941 if (is_emacs_window(wp))
3942 f = mac_window_to_frame (wp);
3944 BLOCK_INPUT;
3946 if (! NILP (last_mouse_scroll_bar) && insist == 0)
3947 x_scroll_bar_report_motion (fp, bar_window, part, x, y, time);
3948 else
3950 /* Clear the mouse-moved flag for every frame on this display. */
3951 FOR_EACH_FRAME (tail, frame)
3952 XFRAME (frame)->mouse_moved = 0;
3954 last_mouse_scroll_bar = Qnil;
3956 SetPortWindowPort (wp);
3958 GetMouse (&mouse_pos);
3960 pixel_to_glyph_coords (f, mouse_pos.h, mouse_pos.v, &ignore1, &ignore2,
3961 &last_mouse_glyph, insist);
3963 *bar_window = Qnil;
3964 *part = scroll_bar_handle;
3965 *fp = f;
3966 XSETINT (*x, mouse_pos.h);
3967 XSETINT (*y, mouse_pos.v);
3968 *time = last_mouse_movement_time;
3971 UNBLOCK_INPUT;
3975 /***********************************************************************
3976 Tool-bars
3977 ***********************************************************************/
3979 /* Handle mouse button event on the tool-bar of frame F, at
3980 frame-relative coordinates X/Y. EVENT_TYPE is either ButtionPress
3981 or ButtonRelase. */
3983 static void
3984 mac_handle_tool_bar_click (f, button_event)
3985 struct frame *f;
3986 EventRecord *button_event;
3988 int x = button_event->where.h;
3989 int y = button_event->where.v;
3991 if (button_event->what == mouseDown)
3992 handle_tool_bar_click (f, x, y, 1, 0);
3993 else
3994 handle_tool_bar_click (f, x, y, 0,
3995 x_mac_to_emacs_modifiers (FRAME_MAC_DISPLAY_INFO (f),
3996 button_event->modifiers));
4000 /************************************************************************
4001 Scroll bars, general
4002 ************************************************************************/
4004 /* Create a scroll bar and return the scroll bar vector for it. W is
4005 the Emacs window on which to create the scroll bar. TOP, LEFT,
4006 WIDTH and HEIGHT are the pixel coordinates and dimensions of the
4007 scroll bar. */
4009 static struct scroll_bar *
4010 x_scroll_bar_create (w, top, left, width, height, disp_top, disp_height)
4011 struct window *w;
4012 int top, left, width, height, disp_top, disp_height;
4014 struct frame *f = XFRAME (w->frame);
4015 struct scroll_bar *bar
4016 = XSCROLL_BAR (Fmake_vector (make_number (SCROLL_BAR_VEC_SIZE), Qnil));
4017 Rect r;
4018 ControlHandle ch;
4020 BLOCK_INPUT;
4022 r.left = left;
4023 r.top = disp_top;
4024 r.right = left + width;
4025 r.bottom = disp_top + disp_height;
4027 #ifdef TARGET_API_MAC_CARBON
4028 ch = NewControl (FRAME_MAC_WINDOW (f), &r, "\p", 1, 0, 0, 0,
4029 kControlScrollBarProc, 0L);
4030 #else
4031 ch = NewControl (FRAME_MAC_WINDOW (f), &r, "\p", 1, 0, 0, 0, scrollBarProc,
4032 0L);
4033 #endif
4034 SET_SCROLL_BAR_CONTROL_HANDLE (bar, ch);
4035 SetControlReference (ch, (long) bar);
4037 XSETWINDOW (bar->window, w);
4038 XSETINT (bar->top, top);
4039 XSETINT (bar->left, left);
4040 XSETINT (bar->width, width);
4041 XSETINT (bar->height, height);
4042 XSETINT (bar->start, 0);
4043 XSETINT (bar->end, 0);
4044 bar->dragging = Qnil;
4046 /* Add bar to its frame's list of scroll bars. */
4047 bar->next = FRAME_SCROLL_BARS (f);
4048 bar->prev = Qnil;
4049 XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
4050 if (!NILP (bar->next))
4051 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
4053 UNBLOCK_INPUT;
4054 return bar;
4058 /* Draw BAR's handle in the proper position.
4060 If the handle is already drawn from START to END, don't bother
4061 redrawing it, unless REBUILD is non-zero; in that case, always
4062 redraw it. (REBUILD is handy for drawing the handle after expose
4063 events.)
4065 Normally, we want to constrain the start and end of the handle to
4066 fit inside its rectangle, but if the user is dragging the scroll
4067 bar handle, we want to let them drag it down all the way, so that
4068 the bar's top is as far down as it goes; otherwise, there's no way
4069 to move to the very end of the buffer. */
4071 static void
4072 x_scroll_bar_set_handle (bar, start, end, rebuild)
4073 struct scroll_bar *bar;
4074 int start, end;
4075 int rebuild;
4077 int dragging = ! NILP (bar->dragging);
4078 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4079 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4080 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, XINT (bar->height));
4081 int length = end - start;
4083 /* If the display is already accurate, do nothing. */
4084 if (! rebuild
4085 && start == XINT (bar->start)
4086 && end == XINT (bar->end))
4087 return;
4089 BLOCK_INPUT;
4091 /* Make sure the values are reasonable, and try to preserve the
4092 distance between start and end. */
4093 if (start < 0)
4094 start = 0;
4095 else if (start > top_range)
4096 start = top_range;
4097 end = start + length;
4099 if (end < start)
4100 end = start;
4101 else if (end > top_range && ! dragging)
4102 end = top_range;
4104 /* Store the adjusted setting in the scroll bar. */
4105 XSETINT (bar->start, start);
4106 XSETINT (bar->end, end);
4108 /* Clip the end position, just for display. */
4109 if (end > top_range)
4110 end = top_range;
4112 /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels below
4113 top positions, to make sure the handle is always at least that
4114 many pixels tall. */
4115 end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
4117 SetControlMinimum (ch, 0);
4118 /* Don't inadvertently activate deactivated scroll bars */
4119 if (GetControlMaximum (ch) != -1)
4120 SetControlMaximum (ch, top_range + VERTICAL_SCROLL_BAR_MIN_HANDLE
4121 - (end - start));
4122 SetControlValue (ch, start);
4123 #if TARGET_API_MAC_CARBON
4124 SetControlViewSize (ch, end - start);
4125 #endif
4127 UNBLOCK_INPUT;
4131 /* Destroy scroll bar BAR, and set its Emacs window's scroll bar to
4132 nil. */
4134 static void
4135 x_scroll_bar_remove (bar)
4136 struct scroll_bar *bar;
4138 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4140 BLOCK_INPUT;
4142 /* Destroy the Mac scroll bar control */
4143 DisposeControl (SCROLL_BAR_CONTROL_HANDLE (bar));
4145 /* Disassociate this scroll bar from its window. */
4146 XWINDOW (bar->window)->vertical_scroll_bar = Qnil;
4148 UNBLOCK_INPUT;
4151 /* Set the handle of the vertical scroll bar for WINDOW to indicate
4152 that we are displaying PORTION characters out of a total of WHOLE
4153 characters, starting at POSITION. If WINDOW has no scroll bar,
4154 create one. */
4155 static void
4156 XTset_vertical_scroll_bar (w, portion, whole, position)
4157 struct window *w;
4158 int portion, whole, position;
4160 struct frame *f = XFRAME (w->frame);
4161 struct scroll_bar *bar;
4162 int top, height, left, sb_left, width, sb_width, disp_top, disp_height;
4163 int window_y, window_height;
4165 /* Get window dimensions. */
4166 window_box (w, -1, 0, &window_y, 0, &window_height);
4167 top = window_y;
4168 #ifdef MAC_OSX
4169 width = 16;
4170 #else
4171 width = WINDOW_CONFIG_SCROLL_BAR_COLS (w) * FRAME_COLUMN_WIDTH (f);
4172 #endif
4173 height = window_height;
4175 /* Compute the left edge of the scroll bar area. */
4176 left = WINDOW_SCROLL_BAR_AREA_X (w);
4178 /* Compute the width of the scroll bar which might be less than
4179 the width of the area reserved for the scroll bar. */
4180 if (WINDOW_CONFIG_SCROLL_BAR_WIDTH (w) > 0)
4181 sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
4182 else
4183 sb_width = width;
4185 /* Compute the left edge of the scroll bar. */
4186 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
4187 sb_left = left + width - sb_width - (width - sb_width) / 2;
4188 else
4189 sb_left = left + (width - sb_width) / 2;
4191 /* Adjustments according to Inside Macintosh to make it look nice */
4192 disp_top = top;
4193 disp_height = height;
4194 if (disp_top == 0)
4196 disp_top = -1;
4197 disp_height++;
4199 else if (disp_top == FRAME_PIXEL_HEIGHT (f) - 16)
4201 disp_top++;
4202 disp_height--;
4205 if (sb_left + sb_width == FRAME_PIXEL_WIDTH (f))
4206 sb_left++;
4208 /* Does the scroll bar exist yet? */
4209 if (NILP (w->vertical_scroll_bar))
4211 BLOCK_INPUT;
4212 XClearArea (FRAME_MAC_DISPLAY (f), FRAME_MAC_WINDOW (f),
4213 left, top, width, height, 0);
4214 UNBLOCK_INPUT;
4215 bar = x_scroll_bar_create (w, top, sb_left, sb_width, height, disp_top,
4216 disp_height);
4217 XSETVECTOR (w->vertical_scroll_bar, bar);
4219 else
4221 /* It may just need to be moved and resized. */
4222 ControlHandle ch;
4224 bar = XSCROLL_BAR (w->vertical_scroll_bar);
4225 ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4227 BLOCK_INPUT;
4229 /* If already correctly positioned, do nothing. */
4230 if (XINT (bar->left) == sb_left
4231 && XINT (bar->top) == top
4232 && XINT (bar->width) == sb_width
4233 && XINT (bar->height) == height)
4234 Draw1Control (ch);
4235 else
4237 /* Clear areas not covered by the scroll bar because it's not as
4238 wide as the area reserved for it . This makes sure a
4239 previous mode line display is cleared after C-x 2 C-x 1, for
4240 example. */
4241 int area_width = WINDOW_SCROLL_BAR_AREA_WIDTH (w);
4242 XClearArea (FRAME_MAC_DISPLAY (f), FRAME_MAC_WINDOW (f),
4243 left, top, area_width, height, 0);
4245 #if 0
4246 if (sb_left + sb_width >= FRAME_PIXEL_WIDTH (f))
4247 XClearArea (FRAME_MAC_DISPLAY (f), FRAME_MAC_WINDOW (f),
4248 sb_left - 1, top, 1, height, 0);
4249 #endif
4251 HideControl (ch);
4252 MoveControl (ch, sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM, disp_top);
4253 SizeControl (ch, sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
4254 disp_height);
4255 ShowControl (ch);
4257 /* Remember new settings. */
4258 XSETINT (bar->left, sb_left);
4259 XSETINT (bar->top, top);
4260 XSETINT (bar->width, sb_width);
4261 XSETINT (bar->height, height);
4264 UNBLOCK_INPUT;
4267 /* Set the scroll bar's current state, unless we're currently being
4268 dragged. */
4269 if (NILP (bar->dragging))
4271 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, height);
4273 if (whole == 0)
4274 x_scroll_bar_set_handle (bar, 0, top_range, 0);
4275 else
4277 int start = ((double) position * top_range) / whole;
4278 int end = ((double) (position + portion) * top_range) / whole;
4279 x_scroll_bar_set_handle (bar, start, end, 0);
4285 /* The following three hooks are used when we're doing a thorough
4286 redisplay of the frame. We don't explicitly know which scroll bars
4287 are going to be deleted, because keeping track of when windows go
4288 away is a real pain - "Can you say set-window-configuration, boys
4289 and girls?" Instead, we just assert at the beginning of redisplay
4290 that *all* scroll bars are to be removed, and then save a scroll bar
4291 from the fiery pit when we actually redisplay its window. */
4293 /* Arrange for all scroll bars on FRAME to be removed at the next call
4294 to `*judge_scroll_bars_hook'. A scroll bar may be spared if
4295 `*redeem_scroll_bar_hook' is applied to its window before the judgment. */
4297 static void
4298 XTcondemn_scroll_bars (frame)
4299 FRAME_PTR frame;
4301 /* Transfer all the scroll bars to FRAME_CONDEMNED_SCROLL_BARS. */
4302 while (! NILP (FRAME_SCROLL_BARS (frame)))
4304 Lisp_Object bar;
4305 bar = FRAME_SCROLL_BARS (frame);
4306 FRAME_SCROLL_BARS (frame) = XSCROLL_BAR (bar)->next;
4307 XSCROLL_BAR (bar)->next = FRAME_CONDEMNED_SCROLL_BARS (frame);
4308 XSCROLL_BAR (bar)->prev = Qnil;
4309 if (! NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
4310 XSCROLL_BAR (FRAME_CONDEMNED_SCROLL_BARS (frame))->prev = bar;
4311 FRAME_CONDEMNED_SCROLL_BARS (frame) = bar;
4316 /* Un-mark WINDOW's scroll bar for deletion in this judgment cycle.
4317 Note that WINDOW isn't necessarily condemned at all. */
4319 static void
4320 XTredeem_scroll_bar (window)
4321 struct window *window;
4323 struct scroll_bar *bar;
4325 /* We can't redeem this window's scroll bar if it doesn't have one. */
4326 if (NILP (window->vertical_scroll_bar))
4327 abort ();
4329 bar = XSCROLL_BAR (window->vertical_scroll_bar);
4331 /* Unlink it from the condemned list. */
4333 FRAME_PTR f = XFRAME (WINDOW_FRAME (window));
4335 if (NILP (bar->prev))
4337 /* If the prev pointer is nil, it must be the first in one of
4338 the lists. */
4339 if (EQ (FRAME_SCROLL_BARS (f), window->vertical_scroll_bar))
4340 /* It's not condemned. Everything's fine. */
4341 return;
4342 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
4343 window->vertical_scroll_bar))
4344 FRAME_CONDEMNED_SCROLL_BARS (f) = bar->next;
4345 else
4346 /* If its prev pointer is nil, it must be at the front of
4347 one or the other! */
4348 abort ();
4350 else
4351 XSCROLL_BAR (bar->prev)->next = bar->next;
4353 if (! NILP (bar->next))
4354 XSCROLL_BAR (bar->next)->prev = bar->prev;
4356 bar->next = FRAME_SCROLL_BARS (f);
4357 bar->prev = Qnil;
4358 XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
4359 if (! NILP (bar->next))
4360 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
4364 /* Remove all scroll bars on FRAME that haven't been saved since the
4365 last call to `*condemn_scroll_bars_hook'. */
4367 static void
4368 XTjudge_scroll_bars (f)
4369 FRAME_PTR f;
4371 Lisp_Object bar, next;
4373 bar = FRAME_CONDEMNED_SCROLL_BARS (f);
4375 /* Clear out the condemned list now so we won't try to process any
4376 more events on the hapless scroll bars. */
4377 FRAME_CONDEMNED_SCROLL_BARS (f) = Qnil;
4379 for (; ! NILP (bar); bar = next)
4381 struct scroll_bar *b = XSCROLL_BAR (bar);
4383 x_scroll_bar_remove (b);
4385 next = b->next;
4386 b->next = b->prev = Qnil;
4389 /* Now there should be no references to the condemned scroll bars,
4390 and they should get garbage-collected. */
4394 void
4395 activate_scroll_bars (frame)
4396 FRAME_PTR frame;
4398 Lisp_Object bar;
4399 ControlHandle ch;
4401 bar = FRAME_SCROLL_BARS (frame);
4402 while (! NILP (bar))
4404 ch = SCROLL_BAR_CONTROL_HANDLE (XSCROLL_BAR (bar));
4405 #ifdef TARGET_API_MAC_CARBON
4406 ActivateControl (ch);
4407 #else
4408 SetControlMaximum (ch,
4409 VERTICAL_SCROLL_BAR_TOP_RANGE (frame,
4410 XINT (XSCROLL_BAR (bar)
4411 ->height)) - 1);
4412 #endif
4413 bar = XSCROLL_BAR (bar)->next;
4418 void
4419 deactivate_scroll_bars (frame)
4420 FRAME_PTR frame;
4422 Lisp_Object bar;
4423 ControlHandle ch;
4425 bar = FRAME_SCROLL_BARS (frame);
4426 while (! NILP (bar))
4428 ch = SCROLL_BAR_CONTROL_HANDLE (XSCROLL_BAR (bar));
4429 #ifdef TARGET_API_MAC_CARBON
4430 DeactivateControl (ch);
4431 #else
4432 SetControlMaximum (ch, XINT (-1));
4433 #endif
4434 bar = XSCROLL_BAR (bar)->next;
4438 /* Handle a mouse click on the scroll bar BAR. If *EMACS_EVENT's kind
4439 is set to something other than NO_EVENT, it is enqueued.
4441 This may be called from a signal handler, so we have to ignore GC
4442 mark bits. */
4444 static void
4445 x_scroll_bar_handle_click (bar, part_code, er, bufp)
4446 struct scroll_bar *bar;
4447 int part_code;
4448 EventRecord *er;
4449 struct input_event *bufp;
4451 int win_y, top_range;
4453 if (! GC_WINDOWP (bar->window))
4454 abort ();
4456 bufp->kind = SCROLL_BAR_CLICK_EVENT;
4457 bufp->frame_or_window = bar->window;
4458 bufp->arg = Qnil;
4460 bar->dragging = Qnil;
4462 switch (part_code)
4464 case kControlUpButtonPart:
4465 bufp->part = scroll_bar_up_arrow;
4466 break;
4467 case kControlDownButtonPart:
4468 bufp->part = scroll_bar_down_arrow;
4469 break;
4470 case kControlPageUpPart:
4471 bufp->part = scroll_bar_above_handle;
4472 break;
4473 case kControlPageDownPart:
4474 bufp->part = scroll_bar_below_handle;
4475 break;
4476 #ifdef TARGET_API_MAC_CARBON
4477 default:
4478 #else
4479 case kControlIndicatorPart:
4480 #endif
4481 if (er->what == mouseDown)
4482 bar->dragging = make_number (0);
4483 XSETVECTOR (last_mouse_scroll_bar, bar);
4484 bufp->part = scroll_bar_handle;
4485 break;
4488 win_y = XINT (bufp->y) - XINT (bar->top);
4489 top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (0/*dummy*/, XINT (bar->height));
4491 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
4493 win_y -= 24;
4495 if (! NILP (bar->dragging))
4496 win_y -= XINT (bar->dragging);
4498 if (win_y < 0)
4499 win_y = 0;
4500 if (win_y > top_range)
4501 win_y = top_range;
4503 XSETINT (bufp->x, win_y);
4504 XSETINT (bufp->y, top_range);
4508 /* Handle some mouse motion while someone is dragging the scroll bar.
4510 This may be called from a signal handler, so we have to ignore GC
4511 mark bits. */
4513 static void
4514 x_scroll_bar_note_movement (bar, y_pos, t)
4515 struct scroll_bar *bar;
4516 int y_pos;
4517 Time t;
4519 FRAME_PTR f = XFRAME (XWINDOW (bar->window)->frame);
4521 last_mouse_movement_time = t;
4523 f->mouse_moved = 1;
4524 XSETVECTOR (last_mouse_scroll_bar, bar);
4526 /* If we're dragging the bar, display it. */
4527 if (! GC_NILP (bar->dragging))
4529 /* Where should the handle be now? */
4530 int new_start = y_pos - 24;
4532 if (new_start != XINT (bar->start))
4534 int new_end = new_start + (XINT (bar->end) - XINT (bar->start));
4536 x_scroll_bar_set_handle (bar, new_start, new_end, 0);
4542 /* Return information to the user about the current position of the
4543 mouse on the scroll bar. */
4545 static void
4546 x_scroll_bar_report_motion (fp, bar_window, part, x, y, time)
4547 FRAME_PTR *fp;
4548 Lisp_Object *bar_window;
4549 enum scroll_bar_part *part;
4550 Lisp_Object *x, *y;
4551 unsigned long *time;
4553 struct scroll_bar *bar = XSCROLL_BAR (last_mouse_scroll_bar);
4554 WindowPtr wp = mac_front_window ();
4555 Point mouse_pos;
4556 struct frame *f = mac_window_to_frame (wp);
4557 int win_y, top_range;
4559 SetPortWindowPort (wp);
4561 GetMouse (&mouse_pos);
4563 win_y = mouse_pos.v - XINT (bar->top);
4564 top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, XINT (bar->height));
4566 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
4568 win_y -= 24;
4570 if (! NILP (bar->dragging))
4571 win_y -= XINT (bar->dragging);
4573 if (win_y < 0)
4574 win_y = 0;
4575 if (win_y > top_range)
4576 win_y = top_range;
4578 *fp = f;
4579 *bar_window = bar->window;
4581 if (! NILP (bar->dragging))
4582 *part = scroll_bar_handle;
4583 else if (win_y < XINT (bar->start))
4584 *part = scroll_bar_above_handle;
4585 else if (win_y < XINT (bar->end) + VERTICAL_SCROLL_BAR_MIN_HANDLE)
4586 *part = scroll_bar_handle;
4587 else
4588 *part = scroll_bar_below_handle;
4590 XSETINT (*x, win_y);
4591 XSETINT (*y, top_range);
4593 f->mouse_moved = 0;
4594 last_mouse_scroll_bar = Qnil;
4596 *time = last_mouse_movement_time;
4599 /***********************************************************************
4600 Text Cursor
4601 ***********************************************************************/
4603 /* Set clipping for output in glyph row ROW. W is the window in which
4604 we operate. GC is the graphics context to set clipping in.
4606 ROW may be a text row or, e.g., a mode line. Text rows must be
4607 clipped to the interior of the window dedicated to text display,
4608 mode lines must be clipped to the whole window. */
4610 static void
4611 x_clip_to_row (w, row, gc)
4612 struct window *w;
4613 struct glyph_row *row;
4614 GC gc;
4616 struct frame *f = XFRAME (WINDOW_FRAME (w));
4617 Rect clip_rect;
4618 int window_y, window_width;
4620 window_box (w, -1, 0, &window_y, &window_width, 0);
4622 clip_rect.left = WINDOW_TO_FRAME_PIXEL_X (w, 0);
4623 clip_rect.top = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
4624 clip_rect.top = max (clip_rect.top, window_y);
4625 clip_rect.right = clip_rect.left + window_width;
4626 clip_rect.bottom = clip_rect.top + row->visible_height;
4628 mac_set_clip_rectangle (FRAME_MAC_DISPLAY (f), FRAME_MAC_WINDOW (f), &clip_rect);
4632 /* Draw a hollow box cursor on window W in glyph row ROW. */
4634 static void
4635 x_draw_hollow_cursor (w, row)
4636 struct window *w;
4637 struct glyph_row *row;
4639 struct frame *f = XFRAME (WINDOW_FRAME (w));
4640 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
4641 Display *dpy = FRAME_MAC_DISPLAY (f);
4642 int x, y, wd, h;
4643 XGCValues xgcv;
4644 struct glyph *cursor_glyph;
4645 GC gc;
4647 /* Get the glyph the cursor is on. If we can't tell because
4648 the current matrix is invalid or such, give up. */
4649 cursor_glyph = get_phys_cursor_glyph (w);
4650 if (cursor_glyph == NULL)
4651 return;
4653 /* Compute the width of the rectangle to draw. If on a stretch
4654 glyph, and `x-stretch-block-cursor' is nil, don't draw a
4655 rectangle as wide as the glyph, but use a canonical character
4656 width instead. */
4657 wd = cursor_glyph->pixel_width - 1;
4658 if (cursor_glyph->type == STRETCH_GLYPH
4659 && !x_stretch_cursor_p)
4660 wd = min (FRAME_COLUMN_WIDTH (f), wd);
4661 w->phys_cursor_width = wd;
4663 /* Compute frame-relative coordinates from window-relative
4664 coordinates. */
4665 x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
4666 y = WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y);
4668 /* Compute the proper height and ascent of the rectangle, based
4669 on the actual glyph. Using the full height of the row looks
4670 bad when there are tall images on that row. */
4671 h = max (min (FRAME_LINE_HEIGHT (f), row->height),
4672 cursor_glyph->ascent + cursor_glyph->descent);
4673 if (h < row->height)
4674 y += row->ascent /* - w->phys_cursor_ascent */ + cursor_glyph->descent - h;
4675 h--;
4677 /* The foreground of cursor_gc is typically the same as the normal
4678 background color, which can cause the cursor box to be invisible. */
4679 xgcv.foreground = f->output_data.mac->cursor_pixel;
4680 if (dpyinfo->scratch_cursor_gc)
4681 XChangeGC (dpy, dpyinfo->scratch_cursor_gc, GCForeground, &xgcv);
4682 else
4683 dpyinfo->scratch_cursor_gc = XCreateGC (dpy, FRAME_MAC_WINDOW (f),
4684 GCForeground, &xgcv);
4685 gc = dpyinfo->scratch_cursor_gc;
4687 /* Set clipping, draw the rectangle, and reset clipping again. */
4688 x_clip_to_row (w, row, gc);
4689 mac_draw_rectangle (dpy, FRAME_MAC_WINDOW (f), gc, x, y, wd, h);
4690 mac_reset_clipping (dpy, FRAME_MAC_WINDOW (f));
4694 /* Draw a bar cursor on window W in glyph row ROW.
4696 Implementation note: One would like to draw a bar cursor with an
4697 angle equal to the one given by the font property XA_ITALIC_ANGLE.
4698 Unfortunately, I didn't find a font yet that has this property set.
4699 --gerd. */
4701 static void
4702 x_draw_bar_cursor (w, row, width, kind)
4703 struct window *w;
4704 struct glyph_row *row;
4705 int width;
4706 enum text_cursor_kinds kind;
4708 struct frame *f = XFRAME (w->frame);
4709 struct glyph *cursor_glyph;
4711 /* If cursor is out of bounds, don't draw garbage. This can happen
4712 in mini-buffer windows when switching between echo area glyphs
4713 and mini-buffer. */
4714 cursor_glyph = get_phys_cursor_glyph (w);
4715 if (cursor_glyph == NULL)
4716 return;
4718 /* If on an image, draw like a normal cursor. That's usually better
4719 visible than drawing a bar, esp. if the image is large so that
4720 the bar might not be in the window. */
4721 if (cursor_glyph->type == IMAGE_GLYPH)
4723 struct glyph_row *row;
4724 row = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos);
4725 draw_phys_cursor_glyph (w, row, DRAW_CURSOR);
4727 else
4729 Display *dpy = FRAME_MAC_DISPLAY (f);
4730 Window window = FRAME_MAC_WINDOW (f);
4731 GC gc = FRAME_MAC_DISPLAY_INFO (f)->scratch_cursor_gc;
4732 unsigned long mask = GCForeground | GCBackground;
4733 struct face *face = FACE_FROM_ID (f, cursor_glyph->face_id);
4734 XGCValues xgcv;
4736 /* If the glyph's background equals the color we normally draw
4737 the bar cursor in, the bar cursor in its normal color is
4738 invisible. Use the glyph's foreground color instead in this
4739 case, on the assumption that the glyph's colors are chosen so
4740 that the glyph is legible. */
4741 if (face->background == f->output_data.mac->cursor_pixel)
4742 xgcv.background = xgcv.foreground = face->foreground;
4743 else
4744 xgcv.background = xgcv.foreground = f->output_data.mac->cursor_pixel;
4746 if (gc)
4747 XChangeGC (dpy, gc, mask, &xgcv);
4748 else
4750 gc = XCreateGC (dpy, window, mask, &xgcv);
4751 FRAME_MAC_DISPLAY_INFO (f)->scratch_cursor_gc = gc;
4754 if (width < 0)
4755 width = FRAME_CURSOR_WIDTH (f);
4756 width = min (cursor_glyph->pixel_width, width);
4758 w->phys_cursor_width = width;
4759 x_clip_to_row (w, row, gc);
4761 if (kind == BAR_CURSOR)
4762 XFillRectangle (dpy, window, gc,
4763 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x),
4764 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
4765 width, row->height);
4766 else
4767 XFillRectangle (dpy, window, gc,
4768 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x),
4769 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y +
4770 row->height - width),
4771 cursor_glyph->pixel_width,
4772 width);
4774 mac_reset_clipping (dpy, FRAME_MAC_WINDOW (f));
4779 /* RIF: Define cursor CURSOR on frame F. */
4781 static void
4782 mac_define_frame_cursor (f, cursor)
4783 struct frame *f;
4784 Cursor cursor;
4786 #if TARGET_API_MAC_CARBON
4787 SetThemeCursor (cursor);
4788 #else
4789 SetCursor (*cursor);
4790 #endif
4794 /* RIF: Clear area on frame F. */
4796 static void
4797 mac_clear_frame_area (f, x, y, width, height)
4798 struct frame *f;
4799 int x, y, width, height;
4801 XClearArea (FRAME_MAC_DISPLAY (f), FRAME_MAC_WINDOW (f),
4802 x, y, width, height, 0);
4806 /* RIF: Draw cursor on window W. */
4808 static void
4809 mac_draw_window_cursor (w, glyph_row, x, y, cursor_type, cursor_width, on_p, active_p)
4810 struct window *w;
4811 struct glyph_row *glyph_row;
4812 int x, y;
4813 int cursor_type, cursor_width;
4814 int on_p, active_p;
4816 if (on_p)
4818 w->phys_cursor_type = cursor_type;
4819 w->phys_cursor_on_p = 1;
4821 if (glyph_row->exact_window_width_line_p
4822 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
4824 glyph_row->cursor_in_fringe_p = 1;
4825 draw_fringe_bitmap (w, glyph_row, 0);
4827 else
4828 switch (cursor_type)
4830 case HOLLOW_BOX_CURSOR:
4831 x_draw_hollow_cursor (w, glyph_row);
4832 break;
4834 case FILLED_BOX_CURSOR:
4835 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
4836 break;
4838 case BAR_CURSOR:
4839 x_draw_bar_cursor (w, glyph_row, cursor_width, BAR_CURSOR);
4840 break;
4842 case HBAR_CURSOR:
4843 x_draw_bar_cursor (w, glyph_row, cursor_width, HBAR_CURSOR);
4844 break;
4846 case NO_CURSOR:
4847 w->phys_cursor_width = 0;
4848 break;
4850 default:
4851 abort ();
4857 /* Icons. */
4859 #if 0 /* MAC_TODO: no icon support yet. */
4861 x_bitmap_icon (f, icon)
4862 struct frame *f;
4863 Lisp_Object icon;
4865 HANDLE hicon;
4867 if (FRAME_W32_WINDOW (f) == 0)
4868 return 1;
4870 if (NILP (icon))
4871 hicon = LoadIcon (hinst, EMACS_CLASS);
4872 else if (STRINGP (icon))
4873 hicon = LoadImage (NULL, (LPCTSTR) SDATA (icon), IMAGE_ICON, 0, 0,
4874 LR_DEFAULTSIZE | LR_LOADFROMFILE);
4875 else if (SYMBOLP (icon))
4877 LPCTSTR name;
4879 if (EQ (icon, intern ("application")))
4880 name = (LPCTSTR) IDI_APPLICATION;
4881 else if (EQ (icon, intern ("hand")))
4882 name = (LPCTSTR) IDI_HAND;
4883 else if (EQ (icon, intern ("question")))
4884 name = (LPCTSTR) IDI_QUESTION;
4885 else if (EQ (icon, intern ("exclamation")))
4886 name = (LPCTSTR) IDI_EXCLAMATION;
4887 else if (EQ (icon, intern ("asterisk")))
4888 name = (LPCTSTR) IDI_ASTERISK;
4889 else if (EQ (icon, intern ("winlogo")))
4890 name = (LPCTSTR) IDI_WINLOGO;
4891 else
4892 return 1;
4894 hicon = LoadIcon (NULL, name);
4896 else
4897 return 1;
4899 if (hicon == NULL)
4900 return 1;
4902 PostMessage (FRAME_W32_WINDOW (f), WM_SETICON, (WPARAM) ICON_BIG,
4903 (LPARAM) hicon);
4905 return 0;
4907 #endif /* MAC_TODO */
4909 /************************************************************************
4910 Handling X errors
4911 ************************************************************************/
4913 /* Display Error Handling functions not used on W32. Listing them here
4914 helps diff stay in step when comparing w32term.c with xterm.c.
4916 x_error_catcher (display, error)
4917 x_catch_errors (dpy)
4918 x_catch_errors_unwind (old_val)
4919 x_check_errors (dpy, format)
4920 x_had_errors_p (dpy)
4921 x_clear_errors (dpy)
4922 x_uncatch_errors (dpy, count)
4923 x_trace_wire ()
4924 x_connection_signal (signalnum)
4925 x_connection_closed (dpy, error_message)
4926 x_error_quitter (display, error)
4927 x_error_handler (display, error)
4928 x_io_error_quitter (display)
4933 /* Changing the font of the frame. */
4935 /* Give frame F the font named FONTNAME as its default font, and
4936 return the full name of that font. FONTNAME may be a wildcard
4937 pattern; in that case, we choose some font that fits the pattern.
4938 The return value shows which font we chose. */
4940 Lisp_Object
4941 x_new_font (f, fontname)
4942 struct frame *f;
4943 register char *fontname;
4945 struct font_info *fontp
4946 = FS_LOAD_FONT (f, 0, fontname, -1);
4948 if (!fontp)
4949 return Qnil;
4951 FRAME_FONT (f) = (XFontStruct *) (fontp->font);
4952 FRAME_BASELINE_OFFSET (f) = fontp->baseline_offset;
4953 FRAME_FONTSET (f) = -1;
4955 FRAME_COLUMN_WIDTH (f) = FONT_WIDTH (FRAME_FONT (f));
4956 FRAME_LINE_HEIGHT (f) = FONT_HEIGHT (FRAME_FONT (f));
4958 compute_fringe_widths (f, 1);
4960 /* Compute the scroll bar width in character columns. */
4961 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
4963 int wid = FRAME_COLUMN_WIDTH (f);
4964 FRAME_CONFIG_SCROLL_BAR_COLS (f)
4965 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid-1) / wid;
4967 else
4969 int wid = FRAME_COLUMN_WIDTH (f);
4970 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
4973 /* Now make the frame display the given font. */
4974 if (FRAME_MAC_WINDOW (f) != 0)
4976 XSetFont (FRAME_MAC_DISPLAY (f), f->output_data.mac->normal_gc,
4977 FRAME_FONT (f));
4978 XSetFont (FRAME_MAC_DISPLAY (f), f->output_data.mac->reverse_gc,
4979 FRAME_FONT (f));
4980 XSetFont (FRAME_MAC_DISPLAY (f), f->output_data.mac->cursor_gc,
4981 FRAME_FONT (f));
4983 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
4984 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
4987 return build_string (fontp->full_name);
4990 /* Give frame F the fontset named FONTSETNAME as its default font, and
4991 return the full name of that fontset. FONTSETNAME may be a wildcard
4992 pattern; in that case, we choose some fontset that fits the pattern.
4993 The return value shows which fontset we chose. */
4995 Lisp_Object
4996 x_new_fontset (f, fontsetname)
4997 struct frame *f;
4998 char *fontsetname;
5000 int fontset = fs_query_fontset (build_string (fontsetname), 0);
5001 Lisp_Object result;
5003 if (fontset < 0)
5004 return Qnil;
5006 if (FRAME_FONTSET (f) == fontset)
5007 /* This fontset is already set in frame F. There's nothing more
5008 to do. */
5009 return fontset_name (fontset);
5011 result = x_new_font (f, (SDATA (fontset_ascii (fontset))));
5013 if (!STRINGP (result))
5014 /* Can't load ASCII font. */
5015 return Qnil;
5017 /* Since x_new_font doesn't update any fontset information, do it now. */
5018 FRAME_FONTSET(f) = fontset;
5020 return build_string (fontsetname);
5024 /***********************************************************************
5025 TODO: W32 Input Methods
5026 ***********************************************************************/
5027 /* Listing missing functions from xterm.c helps diff stay in step.
5029 xim_destroy_callback (xim, client_data, call_data)
5030 xim_open_dpy (dpyinfo, resource_name)
5031 struct xim_inst_t
5032 xim_instantiate_callback (display, client_data, call_data)
5033 xim_initialize (dpyinfo, resource_name)
5034 xim_close_dpy (dpyinfo)
5039 /* Calculate the absolute position in frame F
5040 from its current recorded position values and gravity. */
5042 void
5043 x_calc_absolute_position (f)
5044 struct frame *f;
5046 Point pt;
5047 int flags = f->size_hint_flags;
5049 pt.h = pt.v = 0;
5051 /* Find the position of the outside upper-left corner of
5052 the inner window, with respect to the outer window. */
5053 if (f->output_data.mac->parent_desc != FRAME_MAC_DISPLAY_INFO (f)->root_window)
5055 GrafPtr savePort;
5056 GetPort (&savePort);
5058 SetPortWindowPort (FRAME_MAC_WINDOW (f));
5060 #if TARGET_API_MAC_CARBON
5062 Rect r;
5064 GetWindowPortBounds (FRAME_MAC_WINDOW (f), &r);
5065 SetPt(&pt, r.left, r.top);
5067 #else /* not TARGET_API_MAC_CARBON */
5068 SetPt(&pt, FRAME_MAC_WINDOW (f)->portRect.left, FRAME_MAC_WINDOW (f)->portRect.top);
5069 #endif /* not TARGET_API_MAC_CARBON */
5070 LocalToGlobal (&pt);
5071 SetPort (savePort);
5074 /* Treat negative positions as relative to the leftmost bottommost
5075 position that fits on the screen. */
5076 if (flags & XNegative)
5077 f->left_pos = (FRAME_MAC_DISPLAY_INFO (f)->width
5078 - 2 * f->border_width - pt.h
5079 - FRAME_PIXEL_WIDTH (f)
5080 + f->left_pos);
5081 /* NTEMACS_TODO: Subtract menubar height? */
5082 if (flags & YNegative)
5083 f->top_pos = (FRAME_MAC_DISPLAY_INFO (f)->height
5084 - 2 * f->border_width - pt.v
5085 - FRAME_PIXEL_HEIGHT (f)
5086 + f->top_pos);
5087 /* The left_pos and top_pos
5088 are now relative to the top and left screen edges,
5089 so the flags should correspond. */
5090 f->size_hint_flags &= ~ (XNegative | YNegative);
5093 /* CHANGE_GRAVITY is 1 when calling from Fset_frame_position,
5094 to really change the position, and 0 when calling from
5095 x_make_frame_visible (in that case, XOFF and YOFF are the current
5096 position values). It is -1 when calling from x_set_frame_parameters,
5097 which means, do adjust for borders but don't change the gravity. */
5099 void
5100 x_set_offset (f, xoff, yoff, change_gravity)
5101 struct frame *f;
5102 register int xoff, yoff;
5103 int change_gravity;
5105 int modified_top, modified_left;
5107 if (change_gravity > 0)
5109 f->top_pos = yoff;
5110 f->left_pos = xoff;
5111 f->size_hint_flags &= ~ (XNegative | YNegative);
5112 if (xoff < 0)
5113 f->size_hint_flags |= XNegative;
5114 if (yoff < 0)
5115 f->size_hint_flags |= YNegative;
5116 f->win_gravity = NorthWestGravity;
5118 x_calc_absolute_position (f);
5120 BLOCK_INPUT;
5121 x_wm_set_size_hint (f, (long) 0, 0);
5123 modified_left = f->left_pos;
5124 modified_top = f->top_pos;
5126 MoveWindow (f->output_data.mac->mWP, modified_left + 6,
5127 modified_top + 42, false);
5129 UNBLOCK_INPUT;
5132 /* Call this to change the size of frame F's x-window.
5133 If CHANGE_GRAVITY is 1, we change to top-left-corner window gravity
5134 for this size change and subsequent size changes.
5135 Otherwise we leave the window gravity unchanged. */
5137 void
5138 x_set_window_size (f, change_gravity, cols, rows)
5139 struct frame *f;
5140 int change_gravity;
5141 int cols, rows;
5143 int pixelwidth, pixelheight;
5145 BLOCK_INPUT;
5147 check_frame_size (f, &rows, &cols);
5148 f->scroll_bar_actual_width
5149 = FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f);
5151 compute_fringe_widths (f, 0);
5153 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols);
5154 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
5156 f->win_gravity = NorthWestGravity;
5157 x_wm_set_size_hint (f, (long) 0, 0);
5159 SizeWindow (FRAME_MAC_WINDOW (f), pixelwidth, pixelheight, 0);
5161 /* Now, strictly speaking, we can't be sure that this is accurate,
5162 but the window manager will get around to dealing with the size
5163 change request eventually, and we'll hear how it went when the
5164 ConfigureNotify event gets here.
5166 We could just not bother storing any of this information here,
5167 and let the ConfigureNotify event set everything up, but that
5168 might be kind of confusing to the Lisp code, since size changes
5169 wouldn't be reported in the frame parameters until some random
5170 point in the future when the ConfigureNotify event arrives.
5172 We pass 1 for DELAY since we can't run Lisp code inside of
5173 a BLOCK_INPUT. */
5174 change_frame_size (f, rows, cols, 0, 1, 0);
5175 FRAME_PIXEL_WIDTH (f) = pixelwidth;
5176 FRAME_PIXEL_HEIGHT (f) = pixelheight;
5178 /* We've set {FRAME,PIXEL}_{WIDTH,HEIGHT} to the values we hope to
5179 receive in the ConfigureNotify event; if we get what we asked
5180 for, then the event won't cause the screen to become garbaged, so
5181 we have to make sure to do it here. */
5182 SET_FRAME_GARBAGED (f);
5184 XFlush (FRAME_X_DISPLAY (f));
5186 /* If cursor was outside the new size, mark it as off. */
5187 mark_window_cursors_off (XWINDOW (f->root_window));
5189 /* Clear out any recollection of where the mouse highlighting was,
5190 since it might be in a place that's outside the new frame size.
5191 Actually checking whether it is outside is a pain in the neck,
5192 so don't try--just let the highlighting be done afresh with new size. */
5193 cancel_mouse_face (f);
5195 UNBLOCK_INPUT;
5198 /* Mouse warping. */
5200 void x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y);
5202 void
5203 x_set_mouse_position (f, x, y)
5204 struct frame *f;
5205 int x, y;
5207 int pix_x, pix_y;
5209 pix_x = FRAME_COL_TO_PIXEL_X (f, x) + FRAME_COLUMN_WIDTH (f) / 2;
5210 pix_y = FRAME_LINE_TO_PIXEL_Y (f, y) + FRAME_LINE_HEIGHT (f) / 2;
5212 if (pix_x < 0) pix_x = 0;
5213 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
5215 if (pix_y < 0) pix_y = 0;
5216 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
5218 x_set_mouse_pixel_position (f, pix_x, pix_y);
5221 void
5222 x_set_mouse_pixel_position (f, pix_x, pix_y)
5223 struct frame *f;
5224 int pix_x, pix_y;
5226 #if 0 /* MAC_TODO: CursorDeviceMoveTo is non-Carbon */
5227 BLOCK_INPUT;
5229 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
5230 0, 0, 0, 0, pix_x, pix_y);
5231 UNBLOCK_INPUT;
5232 #endif
5236 /* focus shifting, raising and lowering. */
5238 void
5239 x_focus_on_frame (f)
5240 struct frame *f;
5242 #if 0 /* This proves to be unpleasant. */
5243 x_raise_frame (f);
5244 #endif
5245 #if 0
5246 /* I don't think that the ICCCM allows programs to do things like this
5247 without the interaction of the window manager. Whatever you end up
5248 doing with this code, do it to x_unfocus_frame too. */
5249 XSetInputFocus (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5250 RevertToPointerRoot, CurrentTime);
5251 #endif /* ! 0 */
5254 void
5255 x_unfocus_frame (f)
5256 struct frame *f;
5260 /* Raise frame F. */
5261 void
5262 x_raise_frame (f)
5263 struct frame *f;
5265 if (f->async_visible)
5266 SelectWindow (FRAME_MAC_WINDOW (f));
5269 /* Lower frame F. */
5270 void
5271 x_lower_frame (f)
5272 struct frame *f;
5274 if (f->async_visible)
5275 SendBehind (FRAME_MAC_WINDOW (f), nil);
5278 static void
5279 XTframe_raise_lower (f, raise_flag)
5280 FRAME_PTR f;
5281 int raise_flag;
5283 if (raise_flag)
5284 x_raise_frame (f);
5285 else
5286 x_lower_frame (f);
5289 /* Change of visibility. */
5291 /* This tries to wait until the frame is really visible.
5292 However, if the window manager asks the user where to position
5293 the frame, this will return before the user finishes doing that.
5294 The frame will not actually be visible at that time,
5295 but it will become visible later when the window manager
5296 finishes with it. */
5298 void
5299 x_make_frame_visible (f)
5300 struct frame *f;
5302 Lisp_Object type;
5303 int original_top, original_left;
5305 BLOCK_INPUT;
5307 if (! FRAME_VISIBLE_P (f))
5309 /* We test FRAME_GARBAGED_P here to make sure we don't
5310 call x_set_offset a second time
5311 if we get to x_make_frame_visible a second time
5312 before the window gets really visible. */
5313 if (! FRAME_ICONIFIED_P (f)
5314 && ! f->output_data.mac->asked_for_visible)
5315 x_set_offset (f, f->left_pos, f->top_pos, 0);
5317 f->output_data.mac->asked_for_visible = 1;
5319 ShowWindow (FRAME_MAC_WINDOW (f));
5322 XFlush (FRAME_MAC_DISPLAY (f));
5324 #if 0 /* MAC_TODO */
5325 /* Synchronize to ensure Emacs knows the frame is visible
5326 before we do anything else. We do this loop with input not blocked
5327 so that incoming events are handled. */
5329 Lisp_Object frame;
5330 int count;
5332 /* This must come after we set COUNT. */
5333 UNBLOCK_INPUT;
5335 XSETFRAME (frame, f);
5337 /* Wait until the frame is visible. Process X events until a
5338 MapNotify event has been seen, or until we think we won't get a
5339 MapNotify at all.. */
5340 for (count = input_signal_count + 10;
5341 input_signal_count < count && !FRAME_VISIBLE_P (f);)
5343 /* Force processing of queued events. */
5344 x_sync (f);
5346 /* Machines that do polling rather than SIGIO have been
5347 observed to go into a busy-wait here. So we'll fake an
5348 alarm signal to let the handler know that there's something
5349 to be read. We used to raise a real alarm, but it seems
5350 that the handler isn't always enabled here. This is
5351 probably a bug. */
5352 if (input_polling_used ())
5354 /* It could be confusing if a real alarm arrives while
5355 processing the fake one. Turn it off and let the
5356 handler reset it. */
5357 extern void poll_for_input_1 P_ ((void));
5358 int old_poll_suppress_count = poll_suppress_count;
5359 poll_suppress_count = 1;
5360 poll_for_input_1 ();
5361 poll_suppress_count = old_poll_suppress_count;
5364 /* See if a MapNotify event has been processed. */
5365 FRAME_SAMPLE_VISIBILITY (f);
5368 #else
5369 UNBLOCK_INPUT;
5370 #endif /* MAC_TODO */
5373 /* Change from mapped state to withdrawn state. */
5375 /* Make the frame visible (mapped and not iconified). */
5377 void
5378 x_make_frame_invisible (f)
5379 struct frame *f;
5381 /* Don't keep the highlight on an invisible frame. */
5382 if (FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame == f)
5383 FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame = 0;
5385 BLOCK_INPUT;
5387 HideWindow (FRAME_MAC_WINDOW (f));
5389 /* We can't distinguish this from iconification
5390 just by the event that we get from the server.
5391 So we can't win using the usual strategy of letting
5392 FRAME_SAMPLE_VISIBILITY set this. So do it by hand,
5393 and synchronize with the server to make sure we agree. */
5394 f->visible = 0;
5395 FRAME_ICONIFIED_P (f) = 0;
5396 f->async_visible = 0;
5397 f->async_iconified = 0;
5399 UNBLOCK_INPUT;
5402 /* Change window state from mapped to iconified. */
5404 void
5405 x_iconify_frame (f)
5406 struct frame *f;
5408 /* Don't keep the highlight on an invisible frame. */
5409 if (FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame == f)
5410 FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame = 0;
5412 #if 0
5413 /* Review: Since window is still visible in dock, still allow updates? */
5414 if (f->async_iconified)
5415 return;
5416 #endif
5418 BLOCK_INPUT;
5420 CollapseWindow (FRAME_MAC_WINDOW (f), true);
5422 UNBLOCK_INPUT;
5426 /* Free X resources of frame F. */
5428 void
5429 x_free_frame_resources (f)
5430 struct frame *f;
5432 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
5433 WindowPtr wp = FRAME_MAC_WINDOW (f);
5435 BLOCK_INPUT;
5437 DisposeWindow (wp);
5438 if (wp == tip_window)
5439 /* Neither WaitNextEvent nor ReceiveNextEvent receives `window
5440 closed' event. So we reset tip_window here. */
5441 tip_window = NULL;
5443 free_frame_menubar (f);
5445 if (FRAME_FACE_CACHE (f))
5446 free_frame_faces (f);
5448 x_free_gcs (f);
5450 xfree (f->output_data.mac);
5451 f->output_data.mac = NULL;
5453 if (f == dpyinfo->x_focus_frame)
5454 dpyinfo->x_focus_frame = 0;
5455 if (f == dpyinfo->x_focus_event_frame)
5456 dpyinfo->x_focus_event_frame = 0;
5457 if (f == dpyinfo->x_highlight_frame)
5458 dpyinfo->x_highlight_frame = 0;
5460 if (f == dpyinfo->mouse_face_mouse_frame)
5462 dpyinfo->mouse_face_beg_row
5463 = dpyinfo->mouse_face_beg_col = -1;
5464 dpyinfo->mouse_face_end_row
5465 = dpyinfo->mouse_face_end_col = -1;
5466 dpyinfo->mouse_face_window = Qnil;
5467 dpyinfo->mouse_face_deferred_gc = 0;
5468 dpyinfo->mouse_face_mouse_frame = 0;
5471 UNBLOCK_INPUT;
5475 /* Destroy the X window of frame F. */
5477 void
5478 x_destroy_window (f)
5479 struct frame *f;
5481 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
5483 x_free_frame_resources (f);
5485 dpyinfo->reference_count--;
5489 /* Setting window manager hints. */
5491 /* Set the normal size hints for the window manager, for frame F.
5492 FLAGS is the flags word to use--or 0 meaning preserve the flags
5493 that the window now has.
5494 If USER_POSITION is nonzero, we set the USPosition
5495 flag (this is useful when FLAGS is 0). */
5496 void
5497 x_wm_set_size_hint (f, flags, user_position)
5498 struct frame *f;
5499 long flags;
5500 int user_position;
5502 #if 0 /* MAC_TODO: connect this to the Appearance Manager */
5503 XSizeHints size_hints;
5505 #ifdef USE_X_TOOLKIT
5506 Arg al[2];
5507 int ac = 0;
5508 Dimension widget_width, widget_height;
5509 Window window = XtWindow (f->output_data.x->widget);
5510 #else /* not USE_X_TOOLKIT */
5511 Window window = FRAME_X_WINDOW (f);
5512 #endif /* not USE_X_TOOLKIT */
5514 /* Setting PMaxSize caused various problems. */
5515 size_hints.flags = PResizeInc | PMinSize /* | PMaxSize */;
5517 size_hints.x = f->left_pos;
5518 size_hints.y = f->top_pos;
5520 #ifdef USE_X_TOOLKIT
5521 XtSetArg (al[ac], XtNwidth, &widget_width); ac++;
5522 XtSetArg (al[ac], XtNheight, &widget_height); ac++;
5523 XtGetValues (f->output_data.x->widget, al, ac);
5524 size_hints.height = widget_height;
5525 size_hints.width = widget_width;
5526 #else /* not USE_X_TOOLKIT */
5527 size_hints.height = FRAME_PIXEL_HEIGHT (f);
5528 size_hints.width = FRAME_PIXEL_WIDTH (f);
5529 #endif /* not USE_X_TOOLKIT */
5531 size_hints.width_inc = FRAME_COLUMN_WIDTH (f);
5532 size_hints.height_inc = FRAME_LINE_HEIGHT (f);
5533 size_hints.max_width
5534 = FRAME_X_DISPLAY_INFO (f)->width - FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
5535 size_hints.max_height
5536 = FRAME_X_DISPLAY_INFO (f)->height - FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
5538 /* Calculate the base and minimum sizes.
5540 (When we use the X toolkit, we don't do it here.
5541 Instead we copy the values that the widgets are using, below.) */
5542 #ifndef USE_X_TOOLKIT
5544 int base_width, base_height;
5545 int min_rows = 0, min_cols = 0;
5547 base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
5548 base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
5550 check_frame_size (f, &min_rows, &min_cols);
5552 /* The window manager uses the base width hints to calculate the
5553 current number of rows and columns in the frame while
5554 resizing; min_width and min_height aren't useful for this
5555 purpose, since they might not give the dimensions for a
5556 zero-row, zero-column frame.
5558 We use the base_width and base_height members if we have
5559 them; otherwise, we set the min_width and min_height members
5560 to the size for a zero x zero frame. */
5562 #ifdef HAVE_X11R4
5563 size_hints.flags |= PBaseSize;
5564 size_hints.base_width = base_width;
5565 size_hints.base_height = base_height;
5566 size_hints.min_width = base_width + min_cols * size_hints.width_inc;
5567 size_hints.min_height = base_height + min_rows * size_hints.height_inc;
5568 #else
5569 size_hints.min_width = base_width;
5570 size_hints.min_height = base_height;
5571 #endif
5574 /* If we don't need the old flags, we don't need the old hint at all. */
5575 if (flags)
5577 size_hints.flags |= flags;
5578 goto no_read;
5580 #endif /* not USE_X_TOOLKIT */
5583 XSizeHints hints; /* Sometimes I hate X Windows... */
5584 long supplied_return;
5585 int value;
5587 #ifdef HAVE_X11R4
5588 value = XGetWMNormalHints (FRAME_X_DISPLAY (f), window, &hints,
5589 &supplied_return);
5590 #else
5591 value = XGetNormalHints (FRAME_X_DISPLAY (f), window, &hints);
5592 #endif
5594 #ifdef USE_X_TOOLKIT
5595 size_hints.base_height = hints.base_height;
5596 size_hints.base_width = hints.base_width;
5597 size_hints.min_height = hints.min_height;
5598 size_hints.min_width = hints.min_width;
5599 #endif
5601 if (flags)
5602 size_hints.flags |= flags;
5603 else
5605 if (value == 0)
5606 hints.flags = 0;
5607 if (hints.flags & PSize)
5608 size_hints.flags |= PSize;
5609 if (hints.flags & PPosition)
5610 size_hints.flags |= PPosition;
5611 if (hints.flags & USPosition)
5612 size_hints.flags |= USPosition;
5613 if (hints.flags & USSize)
5614 size_hints.flags |= USSize;
5618 #ifndef USE_X_TOOLKIT
5619 no_read:
5620 #endif
5622 #ifdef PWinGravity
5623 size_hints.win_gravity = f->win_gravity;
5624 size_hints.flags |= PWinGravity;
5626 if (user_position)
5628 size_hints.flags &= ~ PPosition;
5629 size_hints.flags |= USPosition;
5631 #endif /* PWinGravity */
5633 #ifdef HAVE_X11R4
5634 XSetWMNormalHints (FRAME_X_DISPLAY (f), window, &size_hints);
5635 #else
5636 XSetNormalHints (FRAME_X_DISPLAY (f), window, &size_hints);
5637 #endif
5638 #endif /* MAC_TODO */
5641 #if 0 /* MAC_TODO: hide application instead of iconify? */
5642 /* Used for IconicState or NormalState */
5644 void
5645 x_wm_set_window_state (f, state)
5646 struct frame *f;
5647 int state;
5649 #ifdef USE_X_TOOLKIT
5650 Arg al[1];
5652 XtSetArg (al[0], XtNinitialState, state);
5653 XtSetValues (f->output_data.x->widget, al, 1);
5654 #else /* not USE_X_TOOLKIT */
5655 Window window = FRAME_X_WINDOW (f);
5657 f->output_data.x->wm_hints.flags |= StateHint;
5658 f->output_data.x->wm_hints.initial_state = state;
5660 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
5661 #endif /* not USE_X_TOOLKIT */
5664 void
5665 x_wm_set_icon_pixmap (f, pixmap_id)
5666 struct frame *f;
5667 int pixmap_id;
5669 Pixmap icon_pixmap;
5671 #ifndef USE_X_TOOLKIT
5672 Window window = FRAME_X_WINDOW (f);
5673 #endif
5675 if (pixmap_id > 0)
5677 icon_pixmap = x_bitmap_pixmap (f, pixmap_id);
5678 f->output_data.x->wm_hints.icon_pixmap = icon_pixmap;
5680 else
5682 /* It seems there is no way to turn off use of an icon pixmap.
5683 The following line does it, only if no icon has yet been created,
5684 for some window managers. But with mwm it crashes.
5685 Some people say it should clear the IconPixmapHint bit in this case,
5686 but that doesn't work, and the X consortium said it isn't the
5687 right thing at all. Since there is no way to win,
5688 best to explicitly give up. */
5689 #if 0
5690 f->output_data.x->wm_hints.icon_pixmap = None;
5691 #else
5692 return;
5693 #endif
5696 #ifdef USE_X_TOOLKIT /* same as in x_wm_set_window_state. */
5699 Arg al[1];
5700 XtSetArg (al[0], XtNiconPixmap, icon_pixmap);
5701 XtSetValues (f->output_data.x->widget, al, 1);
5704 #else /* not USE_X_TOOLKIT */
5706 f->output_data.x->wm_hints.flags |= IconPixmapHint;
5707 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
5709 #endif /* not USE_X_TOOLKIT */
5712 #endif /* MAC_TODO */
5714 void
5715 x_wm_set_icon_position (f, icon_x, icon_y)
5716 struct frame *f;
5717 int icon_x, icon_y;
5719 #if 0 /* MAC_TODO: no icons on Mac */
5720 #ifdef USE_X_TOOLKIT
5721 Window window = XtWindow (f->output_data.x->widget);
5722 #else
5723 Window window = FRAME_X_WINDOW (f);
5724 #endif
5726 f->output_data.x->wm_hints.flags |= IconPositionHint;
5727 f->output_data.x->wm_hints.icon_x = icon_x;
5728 f->output_data.x->wm_hints.icon_y = icon_y;
5730 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
5731 #endif /* MAC_TODO */
5735 /***********************************************************************
5736 Fonts
5737 ***********************************************************************/
5739 /* Return a pointer to struct font_info of font FONT_IDX of frame F. */
5741 struct font_info *
5742 x_get_font_info (f, font_idx)
5743 FRAME_PTR f;
5744 int font_idx;
5746 return (FRAME_MAC_FONT_TABLE (f) + font_idx);
5749 /* the global font name table */
5750 char **font_name_table = NULL;
5751 int font_name_table_size = 0;
5752 int font_name_count = 0;
5754 #if 0
5755 /* compare two strings ignoring case */
5756 static int
5757 stricmp (const char *s, const char *t)
5759 for ( ; tolower (*s) == tolower (*t); s++, t++)
5760 if (*s == '\0')
5761 return 0;
5762 return tolower (*s) - tolower (*t);
5765 /* compare two strings ignoring case and handling wildcard */
5766 static int
5767 wildstrieq (char *s1, char *s2)
5769 if (strcmp (s1, "*") == 0 || strcmp (s2, "*") == 0)
5770 return true;
5772 return stricmp (s1, s2) == 0;
5775 /* Assume parameter 1 is fully qualified, no wildcards. */
5776 static int
5777 mac_font_pattern_match (fontname, pattern)
5778 char * fontname;
5779 char * pattern;
5781 char *regex = (char *) alloca (strlen (pattern) * 2 + 3);
5782 char *font_name_copy = (char *) alloca (strlen (fontname) + 1);
5783 char *ptr;
5785 /* Copy fontname so we can modify it during comparison. */
5786 strcpy (font_name_copy, fontname);
5788 ptr = regex;
5789 *ptr++ = '^';
5791 /* Turn pattern into a regexp and do a regexp match. */
5792 for (; *pattern; pattern++)
5794 if (*pattern == '?')
5795 *ptr++ = '.';
5796 else if (*pattern == '*')
5798 *ptr++ = '.';
5799 *ptr++ = '*';
5801 else
5802 *ptr++ = *pattern;
5804 *ptr = '$';
5805 *(ptr + 1) = '\0';
5807 return (fast_c_string_match_ignore_case (build_string (regex),
5808 font_name_copy) >= 0);
5811 /* Two font specs are considered to match if their foundry, family,
5812 weight, slant, and charset match. */
5813 static int
5814 mac_font_match (char *mf, char *xf)
5816 char m_foundry[50], m_family[50], m_weight[20], m_slant[2], m_charset[20];
5817 char x_foundry[50], x_family[50], x_weight[20], x_slant[2], x_charset[20];
5819 if (sscanf (mf, "-%49[^-]-%49[^-]-%19[^-]-%1[^-]-%*[^-]--%*[^-]-%*[^-]-%*[^-]-%*[^-]-%*c-%*[^-]-%19s",
5820 m_foundry, m_family, m_weight, m_slant, m_charset) != 5)
5821 return mac_font_pattern_match (mf, xf);
5823 if (sscanf (xf, "-%49[^-]-%49[^-]-%19[^-]-%1[^-]-%*[^-]-%*[^-]-%*[^-]-%*[^-]-%*[^-]-%*[^-]-%*c-%*[^-]-%19s",
5824 x_foundry, x_family, x_weight, x_slant, x_charset) != 5)
5825 return mac_font_pattern_match (mf, xf);
5827 return (wildstrieq (m_foundry, x_foundry)
5828 && wildstrieq (m_family, x_family)
5829 && wildstrieq (m_weight, x_weight)
5830 && wildstrieq (m_slant, x_slant)
5831 && wildstrieq (m_charset, x_charset))
5832 || mac_font_pattern_match (mf, xf);
5834 #endif
5836 static Lisp_Object Qbig5, Qcn_gb, Qsjis, Qeuc_kr;
5838 static void
5839 decode_mac_font_name (char *name, int size, short scriptcode)
5841 Lisp_Object coding_system;
5842 struct coding_system coding;
5843 char *buf;
5845 switch (scriptcode)
5847 case smTradChinese:
5848 coding_system = Qbig5;
5849 break;
5850 case smSimpChinese:
5851 coding_system = Qcn_gb;
5852 break;
5853 case smJapanese:
5854 coding_system = Qsjis;
5855 break;
5856 case smKorean:
5857 coding_system = Qeuc_kr;
5858 break;
5859 default:
5860 return;
5863 setup_coding_system (coding_system, &coding);
5864 coding.src_multibyte = 0;
5865 coding.dst_multibyte = 1;
5866 coding.mode |= CODING_MODE_LAST_BLOCK;
5867 coding.composing = COMPOSITION_DISABLED;
5868 buf = (char *) alloca (size);
5870 decode_coding (&coding, name, buf, strlen (name), size - 1);
5871 bcopy (buf, name, coding.produced);
5872 name[coding.produced] = '\0';
5876 static char *
5877 mac_to_x_fontname (char *name, int size, Style style, short scriptcode)
5879 char foundry[32], family[32], cs[32];
5880 char xf[256], *result, *p;
5882 if (sscanf (name, "%31[^-]-%31[^-]-%31s", foundry, family, cs) != 3)
5884 strcpy(foundry, "Apple");
5885 strcpy(family, name);
5887 switch (scriptcode)
5889 case smTradChinese:
5890 strcpy(cs, "big5-0");
5891 break;
5892 case smSimpChinese:
5893 strcpy(cs, "gb2312.1980-0");
5894 break;
5895 case smJapanese:
5896 strcpy(cs, "jisx0208.1983-sjis");
5897 break;
5898 case -smJapanese:
5899 /* Each Apple Japanese font is entered into the font table
5900 twice: once as a jisx0208.1983-sjis font and once as a
5901 jisx0201.1976-0 font. The latter can be used to display
5902 the ascii charset and katakana-jisx0201 charset. A
5903 negative script code signals that the name of this latter
5904 font is being built. */
5905 strcpy(cs, "jisx0201.1976-0");
5906 break;
5907 case smKorean:
5908 strcpy(cs, "ksc5601.1989-0");
5909 break;
5910 default:
5911 strcpy(cs, "mac-roman");
5912 break;
5916 sprintf(xf, "-%s-%s-%s-%c-normal--%d-%d-75-75-m-%d-%s",
5917 foundry, family, style & bold ? "bold" : "medium",
5918 style & italic ? 'i' : 'r', size, size * 10, size * 10, cs);
5920 result = (char *) xmalloc (strlen (xf) + 1);
5921 strcpy (result, xf);
5922 for (p = result; *p; p++)
5923 *p = tolower(*p);
5924 return result;
5928 /* Convert an X font spec to the corresponding mac font name, which
5929 can then be passed to GetFNum after conversion to a Pascal string.
5930 For ordinary Mac fonts, this should just be their names, like
5931 "monaco", "Taipei", etc. Fonts converted from the GNU intlfonts
5932 collection contain their charset designation in their names, like
5933 "ETL-Fixed-iso8859-1", "ETL-Fixed-koi8-r", etc. Both types of font
5934 names are handled accordingly. */
5935 static void
5936 x_font_name_to_mac_font_name (char *xf, char *mf)
5938 char foundry[32], family[32], weight[20], slant[2], cs[32];
5939 Lisp_Object coding_system = Qnil;
5940 struct coding_system coding;
5942 strcpy (mf, "");
5944 if (sscanf (xf, "-%31[^-]-%31[^-]-%19[^-]-%1[^-]-%*[^-]-%*[^-]-%*[^-]-%*[^-]-%*[^-]-%*[^-]-%*c-%*[^-]-%31s",
5945 foundry, family, weight, slant, cs) != 5 &&
5946 sscanf (xf, "-%31[^-]-%31[^-]-%19[^-]-%1[^-]-%*[^-]--%*[^-]-%*[^-]-%*[^-]-%*[^-]-%*c-%*[^-]-%31s",
5947 foundry, family, weight, slant, cs) != 5)
5948 return;
5950 if (strcmp (cs, "big5-0") == 0)
5951 coding_system = Qbig5;
5952 else if (strcmp (cs, "gb2312.1980-0") == 0)
5953 coding_system = Qcn_gb;
5954 else if (strcmp (cs, "jisx0208.1983-sjis") == 0
5955 || strcmp (cs, "jisx0201.1976-0") == 0)
5956 coding_system = Qsjis;
5957 else if (strcmp (cs, "ksc5601.1989-0") == 0)
5958 coding_system = Qeuc_kr;
5959 else if (strcmp (cs, "mac-roman") == 0)
5960 strcpy (mf, family);
5961 else
5962 sprintf (mf, "%s-%s-%s", foundry, family, cs);
5964 if (!NILP (coding_system))
5966 setup_coding_system (coding_system, &coding);
5967 coding.src_multibyte = 1;
5968 coding.dst_multibyte = 1;
5969 coding.mode |= CODING_MODE_LAST_BLOCK;
5970 encode_coding (&coding, family, mf, strlen (family), sizeof (Str32) - 1);
5971 mf[coding.produced] = '\0';
5976 static void
5977 add_font_name_table_entry (char *font_name)
5979 if (font_name_table_size == 0)
5981 font_name_table_size = 16;
5982 font_name_table = (char **)
5983 xmalloc (font_name_table_size * sizeof (char *));
5985 else if (font_name_count + 1 >= font_name_table_size)
5987 font_name_table_size += 16;
5988 font_name_table = (char **)
5989 xrealloc (font_name_table,
5990 font_name_table_size * sizeof (char *));
5993 font_name_table[font_name_count++] = font_name;
5996 /* Sets up the table font_name_table to contain the list of all fonts
5997 in the system the first time the table is used so that the Resource
5998 Manager need not be accessed every time this information is
5999 needed. */
6001 static void
6002 init_font_name_table ()
6004 #if TARGET_API_MAC_CARBON
6005 SInt32 sv;
6007 if (Gestalt (gestaltSystemVersion, &sv) == noErr && sv >= 0x1000)
6009 FMFontFamilyIterator ffi;
6010 FMFontFamilyInstanceIterator ffii;
6011 FMFontFamily ff;
6013 /* Create a dummy instance iterator here to avoid creating and
6014 destroying it in the loop. */
6015 if (FMCreateFontFamilyInstanceIterator (0, &ffii) != noErr)
6016 return;
6017 /* Create an iterator to enumerate the font families. */
6018 if (FMCreateFontFamilyIterator (NULL, NULL, kFMDefaultOptions, &ffi)
6019 != noErr)
6021 FMDisposeFontFamilyInstanceIterator (&ffii);
6022 return;
6025 while (FMGetNextFontFamily (&ffi, &ff) == noErr)
6027 Str255 name;
6028 FMFont font;
6029 FMFontStyle style;
6030 FMFontSize size;
6031 SInt16 sc;
6033 if (FMGetFontFamilyName (ff, name) != noErr)
6034 break;
6035 p2cstr (name);
6036 if (*name == '.')
6037 continue;
6039 sc = FontToScript (ff);
6040 decode_mac_font_name (name, sizeof (name), sc);
6042 /* Point the instance iterator at the current font family. */
6043 if (FMResetFontFamilyInstanceIterator (ff, &ffii) != noErr)
6044 break;
6046 while (FMGetNextFontFamilyInstance (&ffii, &font, &style, &size)
6047 == noErr)
6049 /* Both jisx0208.1983-sjis and jisx0201.1976-0 parts are
6050 contained in Apple Japanese (SJIS) font. */
6051 again:
6052 if (size == 0)
6054 add_font_name_table_entry (mac_to_x_fontname (name, size,
6055 style, sc));
6056 add_font_name_table_entry (mac_to_x_fontname (name, size,
6057 italic, sc));
6058 add_font_name_table_entry (mac_to_x_fontname (name, size,
6059 bold, sc));
6060 add_font_name_table_entry (mac_to_x_fontname (name, size,
6061 italic | bold,
6062 sc));
6064 else
6065 add_font_name_table_entry (mac_to_x_fontname (name, size,
6066 style, sc));
6067 if (sc == smJapanese)
6069 sc = -smJapanese;
6070 goto again;
6072 else if (sc == -smJapanese)
6073 sc = smJapanese;
6077 /* Dispose of the iterators. */
6078 FMDisposeFontFamilyIterator (&ffi);
6079 FMDisposeFontFamilyInstanceIterator (&ffii);
6081 else
6083 #endif /* TARGET_API_MAC_CARBON */
6084 GrafPtr port;
6085 SInt16 fontnum, old_fontnum;
6086 int num_mac_fonts = CountResources('FOND');
6087 int i, j;
6088 Handle font_handle, font_handle_2;
6089 short id, scriptcode;
6090 ResType type;
6091 Str32 name;
6092 struct FontAssoc *fat;
6093 struct AsscEntry *assc_entry;
6095 GetPort (&port); /* save the current font number used */
6096 #if TARGET_API_MAC_CARBON
6097 old_fontnum = GetPortTextFont (port);
6098 #else
6099 old_fontnum = port->txFont;
6100 #endif
6102 for (i = 1; i <= num_mac_fonts; i++) /* get all available fonts */
6104 font_handle = GetIndResource ('FOND', i);
6105 if (!font_handle)
6106 continue;
6108 GetResInfo (font_handle, &id, &type, name);
6109 GetFNum (name, &fontnum);
6110 p2cstr (name);
6111 if (fontnum == 0)
6112 continue;
6114 TextFont (fontnum);
6115 scriptcode = FontToScript (fontnum);
6116 decode_mac_font_name (name, sizeof (name), scriptcode);
6119 HLock (font_handle);
6121 if (GetResourceSizeOnDisk (font_handle)
6122 >= sizeof (struct FamRec))
6124 fat = (struct FontAssoc *) (*font_handle
6125 + sizeof (struct FamRec));
6126 assc_entry
6127 = (struct AsscEntry *) (*font_handle
6128 + sizeof (struct FamRec)
6129 + sizeof (struct FontAssoc));
6131 for (j = 0; j <= fat->numAssoc; j++, assc_entry++)
6133 if (font_name_table_size == 0)
6135 font_name_table_size = 16;
6136 font_name_table = (char **)
6137 xmalloc (font_name_table_size * sizeof (char *));
6139 else if (font_name_count >= font_name_table_size)
6141 font_name_table_size += 16;
6142 font_name_table = (char **)
6143 xrealloc (font_name_table,
6144 font_name_table_size * sizeof (char *));
6146 font_name_table[font_name_count++]
6147 = mac_to_x_fontname (name,
6148 assc_entry->fontSize,
6149 assc_entry->fontStyle,
6150 scriptcode);
6151 /* Both jisx0208.1983-sjis and jisx0201.1976-0
6152 parts are contained in Apple Japanese (SJIS)
6153 font. */
6154 if (smJapanese == scriptcode)
6156 font_name_table[font_name_count++]
6157 = mac_to_x_fontname (name,
6158 assc_entry->fontSize,
6159 assc_entry->fontStyle,
6160 -smJapanese);
6165 HUnlock (font_handle);
6166 font_handle_2 = GetNextFOND (font_handle);
6167 ReleaseResource (font_handle);
6168 font_handle = font_handle_2;
6170 while (ResError () == noErr && font_handle);
6173 TextFont (old_fontnum);
6174 #if TARGET_API_MAC_CARBON
6176 #endif /* TARGET_API_MAC_CARBON */
6180 enum xlfd_scalable_field_index
6182 XLFD_SCL_PIXEL_SIZE,
6183 XLFD_SCL_POINT_SIZE,
6184 XLFD_SCL_AVGWIDTH,
6185 XLFD_SCL_LAST
6188 static int xlfd_scalable_fields[] =
6190 6, /* PIXEL_SIZE */
6191 7, /* POINT_SIZE */
6192 11, /* AVGWIDTH */
6196 static Lisp_Object
6197 mac_do_list_fonts (pattern, maxnames)
6198 char *pattern;
6199 int maxnames;
6201 int i, n_fonts = 0;
6202 Lisp_Object font_list = Qnil, pattern_regex, fontname;
6203 char *regex = (char *) alloca (strlen (pattern) * 2 + 3);
6204 char scaled[256];
6205 char *ptr;
6206 int scl_val[XLFD_SCL_LAST], *field, *val;
6208 for (i = 0; i < XLFD_SCL_LAST; i++)
6209 scl_val[i] = -1;
6211 /* If the pattern contains 14 dashes and one of PIXEL_SIZE,
6212 POINT_SIZE, and AVGWIDTH fields is explicitly specified, scalable
6213 fonts are scaled according to the specified size. */
6214 ptr = pattern;
6215 i = 0;
6216 field = xlfd_scalable_fields;
6217 val = scl_val;
6218 if (*ptr == '-')
6221 ptr++;
6222 if (i == *field)
6224 if ('1' <= *ptr && *ptr <= '9')
6226 *val = *ptr++ - '0';
6227 while ('0' <= *ptr && *ptr <= '9' && *val < 10000)
6228 *val = *val * 10 + *ptr++ - '0';
6229 if (*ptr != '-')
6230 *val = -1;
6232 field++;
6233 val++;
6235 ptr = strchr (ptr, '-');
6236 i++;
6238 while (ptr && i < 14);
6240 if (i == 14 && ptr == NULL)
6242 if (scl_val[XLFD_SCL_POINT_SIZE] > 0)
6244 scl_val[XLFD_SCL_PIXEL_SIZE] = scl_val[XLFD_SCL_POINT_SIZE] / 10;
6245 scl_val[XLFD_SCL_AVGWIDTH] = scl_val[XLFD_SCL_POINT_SIZE];
6247 else if (scl_val[XLFD_SCL_PIXEL_SIZE] > 0)
6249 scl_val[XLFD_SCL_POINT_SIZE] =
6250 scl_val[XLFD_SCL_AVGWIDTH] = scl_val[XLFD_SCL_PIXEL_SIZE] * 10;
6252 else if (scl_val[XLFD_SCL_AVGWIDTH] > 0)
6254 scl_val[XLFD_SCL_PIXEL_SIZE] = scl_val[XLFD_SCL_AVGWIDTH] / 10;
6255 scl_val[XLFD_SCL_POINT_SIZE] = scl_val[XLFD_SCL_AVGWIDTH];
6258 else
6259 scl_val[XLFD_SCL_PIXEL_SIZE] = -1;
6261 ptr = regex;
6262 *ptr++ = '^';
6264 /* Turn pattern into a regexp and do a regexp match. */
6265 for (; *pattern; pattern++)
6267 if (*pattern == '?')
6268 *ptr++ = '.';
6269 else if (*pattern == '*')
6271 *ptr++ = '.';
6272 *ptr++ = '*';
6274 else
6275 *ptr++ = tolower (*pattern);
6277 *ptr = '$';
6278 *(ptr + 1) = '\0';
6280 pattern_regex = build_string (regex);
6282 for (i = 0; i < font_name_count; i++)
6284 fontname = build_string (font_name_table[i]);
6285 if (fast_string_match (pattern_regex, fontname) >= 0)
6287 font_list = Fcons (fontname, font_list);
6289 n_fonts++;
6290 if (maxnames > 0 && n_fonts >= maxnames)
6291 break;
6293 else if (scl_val[XLFD_SCL_PIXEL_SIZE] > 0
6294 && (ptr = strstr (font_name_table[i], "-0-0-75-75-m-0-")))
6296 int former_len = ptr - font_name_table[i];
6298 memcpy (scaled, font_name_table[i], former_len);
6299 sprintf (scaled + former_len,
6300 "-%d-%d-75-75-m-%d-%s",
6301 scl_val[XLFD_SCL_PIXEL_SIZE],
6302 scl_val[XLFD_SCL_POINT_SIZE],
6303 scl_val[XLFD_SCL_AVGWIDTH],
6304 ptr + sizeof ("-0-0-75-75-m-0-") - 1);
6305 fontname = build_string (scaled);
6306 if (fast_string_match (pattern_regex, fontname) >= 0)
6308 font_list = Fcons (fontname, font_list);
6310 n_fonts++;
6311 if (maxnames > 0 && n_fonts >= maxnames)
6312 break;
6316 return font_list;
6319 /* Return a list of at most MAXNAMES font specs matching the one in
6320 PATTERN. Cache matching fonts for patterns in
6321 dpyinfo->name_list_element to avoid looking them up again by
6322 calling mac_font_pattern_match (slow). Return as many matching
6323 fonts as possible if MAXNAMES = -1. */
6325 Lisp_Object
6326 x_list_fonts (struct frame *f,
6327 Lisp_Object pattern,
6328 int size,
6329 int maxnames)
6331 Lisp_Object newlist = Qnil, tem, key;
6332 struct mac_display_info *dpyinfo = f ? FRAME_MAC_DISPLAY_INFO (f) : NULL;
6334 if (font_name_table == NULL) /* Initialize when first used. */
6335 init_font_name_table ();
6337 if (dpyinfo)
6339 tem = XCDR (dpyinfo->name_list_element);
6340 key = Fcons (pattern, make_number (maxnames));
6342 newlist = Fassoc (key, tem);
6343 if (!NILP (newlist))
6345 newlist = Fcdr_safe (newlist);
6346 goto label_cached;
6350 newlist = mac_do_list_fonts (SDATA (pattern), maxnames);
6352 /* MAC_TODO: add code for matching outline fonts here */
6354 if (dpyinfo)
6356 XSETCDR (dpyinfo->name_list_element,
6357 Fcons (Fcons (key, newlist),
6358 XCDR (dpyinfo->name_list_element)));
6360 label_cached:
6362 return newlist;
6366 #if GLYPH_DEBUG
6368 /* Check that FONT is valid on frame F. It is if it can be found in F's
6369 font table. */
6371 static void
6372 x_check_font (f, font)
6373 struct frame *f;
6374 XFontStruct *font;
6376 int i;
6377 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
6379 xassert (font != NULL);
6381 for (i = 0; i < dpyinfo->n_fonts; i++)
6382 if (dpyinfo->font_table[i].name
6383 && font == dpyinfo->font_table[i].font)
6384 break;
6386 xassert (i < dpyinfo->n_fonts);
6389 #endif /* GLYPH_DEBUG != 0 */
6391 /* Set *W to the minimum width, *H to the minimum font height of FONT.
6392 Note: There are (broken) X fonts out there with invalid XFontStruct
6393 min_bounds contents. For example, handa@etl.go.jp reports that
6394 "-adobe-courier-medium-r-normal--*-180-*-*-m-*-iso8859-1" fonts
6395 have font->min_bounds.width == 0. */
6397 static INLINE void
6398 x_font_min_bounds (font, w, h)
6399 MacFontStruct *font;
6400 int *w, *h;
6403 * TODO: Windows does not appear to offer min bound, only
6404 * average and maximum width, and maximum height.
6406 *h = FONT_HEIGHT (font);
6407 *w = FONT_WIDTH (font);
6411 /* Compute the smallest character width and smallest font height over
6412 all fonts available on frame F. Set the members smallest_char_width
6413 and smallest_font_height in F's x_display_info structure to
6414 the values computed. Value is non-zero if smallest_font_height or
6415 smallest_char_width become smaller than they were before. */
6418 x_compute_min_glyph_bounds (f)
6419 struct frame *f;
6421 int i;
6422 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
6423 MacFontStruct *font;
6424 int old_width = dpyinfo->smallest_char_width;
6425 int old_height = dpyinfo->smallest_font_height;
6427 dpyinfo->smallest_font_height = 100000;
6428 dpyinfo->smallest_char_width = 100000;
6430 for (i = 0; i < dpyinfo->n_fonts; ++i)
6431 if (dpyinfo->font_table[i].name)
6433 struct font_info *fontp = dpyinfo->font_table + i;
6434 int w, h;
6436 font = (MacFontStruct *) fontp->font;
6437 xassert (font != (MacFontStruct *) ~0);
6438 x_font_min_bounds (font, &w, &h);
6440 dpyinfo->smallest_font_height = min (dpyinfo->smallest_font_height, h);
6441 dpyinfo->smallest_char_width = min (dpyinfo->smallest_char_width, w);
6444 xassert (dpyinfo->smallest_char_width > 0
6445 && dpyinfo->smallest_font_height > 0);
6447 return (dpyinfo->n_fonts == 1
6448 || dpyinfo->smallest_char_width < old_width
6449 || dpyinfo->smallest_font_height < old_height);
6453 /* Determine whether given string is a fully-specified XLFD: all 14
6454 fields are present, none is '*'. */
6456 static int
6457 is_fully_specified_xlfd (char *p)
6459 int i;
6460 char *q;
6462 if (*p != '-')
6463 return 0;
6465 for (i = 0; i < 13; i++)
6467 q = strchr (p + 1, '-');
6468 if (q == NULL)
6469 return 0;
6470 if (q - p == 2 && *(p + 1) == '*')
6471 return 0;
6472 p = q;
6475 if (strchr (p + 1, '-') != NULL)
6476 return 0;
6478 if (*(p + 1) == '*' && *(p + 2) == '\0')
6479 return 0;
6481 return 1;
6485 const int kDefaultFontSize = 9;
6488 /* XLoadQueryFont creates and returns an internal representation for a
6489 font in a MacFontStruct struct. There is really no concept
6490 corresponding to "loading" a font on the Mac. But we check its
6491 existence and find the font number and all other information for it
6492 and store them in the returned MacFontStruct. */
6494 static MacFontStruct *
6495 XLoadQueryFont (Display *dpy, char *fontname)
6497 int i, size, is_two_byte_font, char_width;
6498 char *name;
6499 GrafPtr port;
6500 SInt16 old_fontnum, old_fontsize;
6501 Style old_fontface;
6502 Str32 mfontname;
6503 SInt16 fontnum;
6504 Style fontface = normal;
6505 MacFontStruct *font;
6506 FontInfo the_fontinfo;
6507 char s_weight[7], c_slant;
6509 if (is_fully_specified_xlfd (fontname))
6510 name = fontname;
6511 else
6513 Lisp_Object matched_fonts;
6515 matched_fonts = mac_do_list_fonts (fontname, 1);
6516 if (NILP (matched_fonts))
6517 return NULL;
6518 name = SDATA (XCAR (matched_fonts));
6521 GetPort (&port); /* save the current font number used */
6522 #if TARGET_API_MAC_CARBON
6523 old_fontnum = GetPortTextFont (port);
6524 old_fontsize = GetPortTextSize (port);
6525 old_fontface = GetPortTextFace (port);
6526 #else
6527 old_fontnum = port->txFont;
6528 old_fontsize = port->txSize;
6529 old_fontface = port->txFace;
6530 #endif
6532 if (sscanf (name, "-%*[^-]-%*[^-]-%*[^-]-%*c-%*[^-]--%d-%*[^-]-%*[^-]-%*[^-]-%*c-%*[^-]-%*s", &size) != 1)
6533 size = kDefaultFontSize;
6535 if (sscanf (name, "-%*[^-]-%*[^-]-%6[^-]-%*c-%*[^-]--%*[^-]-%*[^-]-%*[^-]-%*[^-]-%*c-%*[^-]-%*s", s_weight) == 1)
6536 if (strcmp (s_weight, "bold") == 0)
6537 fontface |= bold;
6539 if (sscanf (name, "-%*[^-]-%*[^-]-%*[^-]-%c-%*[^-]--%*[^-]-%*[^-]-%*[^-]-%*[^-]-%*c-%*[^-]-%*s", &c_slant) == 1)
6540 if (c_slant == 'i')
6541 fontface |= italic;
6543 x_font_name_to_mac_font_name (name, mfontname);
6544 c2pstr (mfontname);
6545 GetFNum (mfontname, &fontnum);
6546 if (fontnum == 0)
6547 return NULL;
6549 font = (MacFontStruct *) xmalloc (sizeof (struct MacFontStruct));
6551 font->fontname = (char *) xmalloc (strlen (name) + 1);
6552 bcopy (name, font->fontname, strlen (name) + 1);
6554 font->mac_fontnum = fontnum;
6555 font->mac_fontsize = size;
6556 font->mac_fontface = fontface;
6557 font->mac_scriptcode = FontToScript (fontnum);
6559 /* Apple Japanese (SJIS) font is listed as both
6560 "*-jisx0208.1983-sjis" (Japanese script) and "*-jisx0201.1976-0"
6561 (Roman script) in init_font_name_table (). The latter should be
6562 treated as a one-byte font. */
6564 char cs[32];
6566 if (sscanf (name,
6567 "-%*[^-]-%*[^-]-%*[^-]-%*c-%*[^-]--%*[^-]-%*[^-]-%*[^-]-%*[^-]-%*c-%*[^-]-%31s",
6568 cs) == 1
6569 && 0 == strcmp (cs, "jisx0201.1976-0"))
6570 font->mac_scriptcode = smRoman;
6573 is_two_byte_font = font->mac_scriptcode == smJapanese ||
6574 font->mac_scriptcode == smTradChinese ||
6575 font->mac_scriptcode == smSimpChinese ||
6576 font->mac_scriptcode == smKorean;
6578 TextFont (fontnum);
6579 TextSize (size);
6580 TextFace (fontface);
6582 GetFontInfo (&the_fontinfo);
6584 font->ascent = the_fontinfo.ascent;
6585 font->descent = the_fontinfo.descent;
6587 font->min_byte1 = 0;
6588 if (is_two_byte_font)
6589 font->max_byte1 = 1;
6590 else
6591 font->max_byte1 = 0;
6592 font->min_char_or_byte2 = 0x20;
6593 font->max_char_or_byte2 = 0xff;
6595 if (is_two_byte_font)
6597 /* Use the width of an "ideographic space" of that font because
6598 the_fontinfo.widMax returns the wrong width for some fonts. */
6599 switch (font->mac_scriptcode)
6601 case smJapanese:
6602 char_width = StringWidth("\p\x81\x40");
6603 break;
6604 case smTradChinese:
6605 char_width = StringWidth("\p\xa1\x40");
6606 break;
6607 case smSimpChinese:
6608 char_width = StringWidth("\p\xa1\xa1");
6609 break;
6610 case smKorean:
6611 char_width = StringWidth("\p\xa1\xa1");
6612 break;
6615 else
6616 /* Do this instead of use the_fontinfo.widMax, which incorrectly
6617 returns 15 for 12-point Monaco! */
6618 char_width = CharWidth ('m');
6620 font->max_bounds.rbearing = char_width;
6621 font->max_bounds.lbearing = 0;
6622 font->max_bounds.width = char_width;
6623 font->max_bounds.ascent = the_fontinfo.ascent;
6624 font->max_bounds.descent = the_fontinfo.descent;
6626 font->min_bounds = font->max_bounds;
6628 if (is_two_byte_font || CharWidth ('m') == CharWidth ('i'))
6629 font->per_char = NULL;
6630 else
6632 font->per_char = (XCharStruct *)
6633 xmalloc (sizeof (XCharStruct) * (0xff - 0x20 + 1));
6635 int c;
6637 for (c = 0x20; c <= 0xff; c++)
6639 font->per_char[c - 0x20] = font->max_bounds;
6640 font->per_char[c - 0x20].width =
6641 font->per_char[c - 0x20].rbearing = CharWidth (c);
6646 TextFont (old_fontnum); /* restore previous font number, size and face */
6647 TextSize (old_fontsize);
6648 TextFace (old_fontface);
6650 return font;
6654 /* Load font named FONTNAME of the size SIZE for frame F, and return a
6655 pointer to the structure font_info while allocating it dynamically.
6656 If SIZE is 0, load any size of font.
6657 If loading is failed, return NULL. */
6659 struct font_info *
6660 x_load_font (f, fontname, size)
6661 struct frame *f;
6662 register char *fontname;
6663 int size;
6665 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
6666 Lisp_Object font_names;
6668 /* Get a list of all the fonts that match this name. Once we
6669 have a list of matching fonts, we compare them against the fonts
6670 we already have by comparing names. */
6671 font_names = x_list_fonts (f, build_string (fontname), size, 1);
6673 if (!NILP (font_names))
6675 Lisp_Object tail;
6676 int i;
6678 for (i = 0; i < dpyinfo->n_fonts; i++)
6679 for (tail = font_names; CONSP (tail); tail = XCDR (tail))
6680 if (dpyinfo->font_table[i].name
6681 && (!strcmp (dpyinfo->font_table[i].name,
6682 SDATA (XCAR (tail)))
6683 || !strcmp (dpyinfo->font_table[i].full_name,
6684 SDATA (XCAR (tail)))))
6685 return (dpyinfo->font_table + i);
6688 /* Load the font and add it to the table. */
6690 char *full_name;
6691 struct MacFontStruct *font;
6692 struct font_info *fontp;
6693 unsigned long value;
6694 int i;
6696 /* If we have found fonts by x_list_font, load one of them. If
6697 not, we still try to load a font by the name given as FONTNAME
6698 because XListFonts (called in x_list_font) of some X server has
6699 a bug of not finding a font even if the font surely exists and
6700 is loadable by XLoadQueryFont. */
6701 if (size > 0 && !NILP (font_names))
6702 fontname = (char *) SDATA (XCAR (font_names));
6704 font = (MacFontStruct *) XLoadQueryFont (FRAME_MAC_DISPLAY (f), fontname);
6705 if (!font)
6706 return NULL;
6708 /* Find a free slot in the font table. */
6709 for (i = 0; i < dpyinfo->n_fonts; ++i)
6710 if (dpyinfo->font_table[i].name == NULL)
6711 break;
6713 /* If no free slot found, maybe enlarge the font table. */
6714 if (i == dpyinfo->n_fonts
6715 && dpyinfo->n_fonts == dpyinfo->font_table_size)
6717 int sz;
6718 dpyinfo->font_table_size = max (16, 2 * dpyinfo->font_table_size);
6719 sz = dpyinfo->font_table_size * sizeof *dpyinfo->font_table;
6720 dpyinfo->font_table
6721 = (struct font_info *) xrealloc (dpyinfo->font_table, sz);
6724 fontp = dpyinfo->font_table + i;
6725 if (i == dpyinfo->n_fonts)
6726 ++dpyinfo->n_fonts;
6728 /* Now fill in the slots of *FONTP. */
6729 BLOCK_INPUT;
6730 bzero (fontp, sizeof (*fontp));
6731 fontp->font = font;
6732 fontp->font_idx = i;
6733 fontp->name = (char *) xmalloc (strlen (font->fontname) + 1);
6734 bcopy (font->fontname, fontp->name, strlen (font->fontname) + 1);
6736 fontp->full_name = fontp->name;
6738 fontp->size = font->max_bounds.width;
6739 fontp->height = FONT_HEIGHT (font);
6741 /* For some font, ascent and descent in max_bounds field is
6742 larger than the above value. */
6743 int max_height = font->max_bounds.ascent + font->max_bounds.descent;
6744 if (max_height > fontp->height)
6745 fontp->height = max_height;
6748 /* The slot `encoding' specifies how to map a character
6749 code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
6750 the font code-points (0:0x20..0x7F, 1:0xA0..0xFF), or
6751 (0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF,
6752 2:0xA020..0xFF7F). For the moment, we don't know which charset
6753 uses this font. So, we set information in fontp->encoding[1]
6754 which is never used by any charset. If mapping can't be
6755 decided, set FONT_ENCODING_NOT_DECIDED. */
6756 if (font->mac_scriptcode == smJapanese)
6757 fontp->encoding[1] = 4;
6758 else
6760 fontp->encoding[1]
6761 = (font->max_byte1 == 0
6762 /* 1-byte font */
6763 ? (font->min_char_or_byte2 < 0x80
6764 ? (font->max_char_or_byte2 < 0x80
6765 ? 0 /* 0x20..0x7F */
6766 : FONT_ENCODING_NOT_DECIDED) /* 0x20..0xFF */
6767 : 1) /* 0xA0..0xFF */
6768 /* 2-byte font */
6769 : (font->min_byte1 < 0x80
6770 ? (font->max_byte1 < 0x80
6771 ? (font->min_char_or_byte2 < 0x80
6772 ? (font->max_char_or_byte2 < 0x80
6773 ? 0 /* 0x2020..0x7F7F */
6774 : FONT_ENCODING_NOT_DECIDED) /* 0x2020..0x7FFF */
6775 : 3) /* 0x20A0..0x7FFF */
6776 : FONT_ENCODING_NOT_DECIDED) /* 0x20??..0xA0?? */
6777 : (font->min_char_or_byte2 < 0x80
6778 ? (font->max_char_or_byte2 < 0x80
6779 ? 2 /* 0xA020..0xFF7F */
6780 : FONT_ENCODING_NOT_DECIDED) /* 0xA020..0xFFFF */
6781 : 1))); /* 0xA0A0..0xFFFF */
6784 #if 0 /* MAC_TODO: fill these out with more reasonably values */
6785 fontp->baseline_offset
6786 = (XGetFontProperty (font, dpyinfo->Xatom_MULE_BASELINE_OFFSET, &value)
6787 ? (long) value : 0);
6788 fontp->relative_compose
6789 = (XGetFontProperty (font, dpyinfo->Xatom_MULE_RELATIVE_COMPOSE, &value)
6790 ? (long) value : 0);
6791 fontp->default_ascent
6792 = (XGetFontProperty (font, dpyinfo->Xatom_MULE_DEFAULT_ASCENT, &value)
6793 ? (long) value : 0);
6794 #else
6795 fontp->baseline_offset = 0;
6796 fontp->relative_compose = 0;
6797 fontp->default_ascent = 0;
6798 #endif
6800 /* Set global flag fonts_changed_p to non-zero if the font loaded
6801 has a character with a smaller width than any other character
6802 before, or if the font loaded has a smalle>r height than any
6803 other font loaded before. If this happens, it will make a
6804 glyph matrix reallocation necessary. */
6805 fonts_changed_p = x_compute_min_glyph_bounds (f);
6806 UNBLOCK_INPUT;
6807 return fontp;
6812 /* Return a pointer to struct font_info of a font named FONTNAME for
6813 frame F. If no such font is loaded, return NULL. */
6815 struct font_info *
6816 x_query_font (f, fontname)
6817 struct frame *f;
6818 register char *fontname;
6820 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
6821 int i;
6823 for (i = 0; i < dpyinfo->n_fonts; i++)
6824 if (dpyinfo->font_table[i].name
6825 && (!strcmp (dpyinfo->font_table[i].name, fontname)
6826 || !strcmp (dpyinfo->font_table[i].full_name, fontname)))
6827 return (dpyinfo->font_table + i);
6828 return NULL;
6832 /* Find a CCL program for a font specified by FONTP, and set the member
6833 `encoder' of the structure. */
6835 void
6836 x_find_ccl_program (fontp)
6837 struct font_info *fontp;
6839 Lisp_Object list, elt;
6841 for (list = Vfont_ccl_encoder_alist; CONSP (list); list = XCDR (list))
6843 elt = XCAR (list);
6844 if (CONSP (elt)
6845 && STRINGP (XCAR (elt))
6846 && (fast_c_string_match_ignore_case (XCAR (elt), fontp->name)
6847 >= 0))
6848 break;
6850 if (! NILP (list))
6852 struct ccl_program *ccl
6853 = (struct ccl_program *) xmalloc (sizeof (struct ccl_program));
6855 if (setup_ccl_program (ccl, XCDR (elt)) < 0)
6856 xfree (ccl);
6857 else
6858 fontp->font_encoder = ccl;
6864 /* The Mac Event loop code */
6866 #ifndef MAC_OSX
6867 #include <Events.h>
6868 #include <Quickdraw.h>
6869 #include <Balloons.h>
6870 #include <Devices.h>
6871 #include <Fonts.h>
6872 #include <Gestalt.h>
6873 #include <Menus.h>
6874 #include <Processes.h>
6875 #include <Sound.h>
6876 #include <ToolUtils.h>
6877 #include <TextUtils.h>
6878 #include <Dialogs.h>
6879 #include <Script.h>
6880 #include <Types.h>
6881 #include <TextEncodingConverter.h>
6882 #include <Resources.h>
6884 #if __MWERKS__
6885 #include <unix.h>
6886 #endif
6887 #endif /* ! MAC_OSX */
6889 #define M_APPLE 128
6890 #define I_ABOUT 1
6892 #define WINDOW_RESOURCE 128
6893 #define TERM_WINDOW_RESOURCE 129
6895 #define DEFAULT_NUM_COLS 80
6897 #define MIN_DOC_SIZE 64
6898 #define MAX_DOC_SIZE 32767
6900 /* sleep time for WaitNextEvent */
6901 #define WNE_SLEEP_AT_SUSPEND 10
6902 #define WNE_SLEEP_AT_RESUME 1
6904 /* true when cannot handle any Mac OS events */
6905 static int handling_window_update = 0;
6907 /* the flag appl_is_suspended is used both for determining the sleep
6908 time to be passed to WaitNextEvent and whether the cursor should be
6909 drawn when updating the display. The cursor is turned off when
6910 Emacs is suspended. Redrawing it is unnecessary and what needs to
6911 be done depends on whether the cursor lies inside or outside the
6912 redraw region. So we might as well skip drawing it when Emacs is
6913 suspended. */
6914 static Boolean app_is_suspended = false;
6915 static long app_sleep_time = WNE_SLEEP_AT_RESUME;
6917 #define EXTRA_STACK_ALLOC (256 * 1024)
6919 #define ARGV_STRING_LIST_ID 129
6920 #define ABOUT_ALERT_ID 128
6921 #define RAM_TOO_LARGE_ALERT_ID 129
6923 Boolean terminate_flag = false;
6925 /* Contains the string "reverse", which is a constant for mouse button emu.*/
6926 Lisp_Object Qreverse;
6928 /* True if using command key as meta key. */
6929 Lisp_Object Vmac_command_key_is_meta;
6931 /* True if the ctrl and meta keys should be reversed. */
6932 Lisp_Object Vmac_reverse_ctrl_meta;
6934 /* True if the option and command modifiers should be used to emulate
6935 a three button mouse */
6936 Lisp_Object Vmac_emulate_three_button_mouse;
6938 #if USE_CARBON_EVENTS
6939 /* True if the mouse wheel button (i.e. button 4) should map to
6940 mouse-2, instead of mouse-3. */
6941 Lisp_Object Vmac_wheel_button_is_mouse_2;
6943 /* If Non-nil, the Mac "Command" key is passed on to the Mac Toolbox
6944 for processing before Emacs sees it. */
6945 Lisp_Object Vmac_pass_command_to_system;
6947 /* If Non-nil, the Mac "Control" key is passed on to the Mac Toolbox
6948 for processing before Emacs sees it. */
6949 Lisp_Object Vmac_pass_control_to_system;
6950 #endif
6952 /* convert input from Mac keyboard (assumed to be in Mac Roman coding)
6953 to this text encoding */
6954 int mac_keyboard_text_encoding;
6955 int current_mac_keyboard_text_encoding = kTextEncodingMacRoman;
6957 /* Set in term/mac-win.el to indicate that event loop can now generate
6958 drag and drop events. */
6959 Lisp_Object Qmac_ready_for_drag_n_drop;
6961 Lisp_Object drag_and_drop_file_list;
6963 Point saved_menu_event_location;
6965 #if !TARGET_API_MAC_CARBON
6966 /* Place holder for the default arrow cursor. */
6967 CursPtr arrow_cursor;
6968 #endif
6970 /* Apple Events */
6971 static void init_required_apple_events (void);
6972 static pascal OSErr
6973 do_ae_open_application (const AppleEvent *, AppleEvent *, long);
6974 static pascal OSErr
6975 do_ae_print_documents (const AppleEvent *, AppleEvent *, long);
6976 static pascal OSErr do_ae_open_documents (AppleEvent *, AppleEvent *, long);
6977 static pascal OSErr do_ae_quit_application (AppleEvent *, AppleEvent *, long);
6979 /* Drag and Drop */
6980 static OSErr init_mac_drag_n_drop ();
6981 static pascal OSErr mac_do_receive_drag (WindowPtr, void*, DragReference);
6983 #if USE_CARBON_EVENTS
6984 /* Preliminary Support for the OSX Services Menu */
6985 static OSStatus mac_handle_service_event (EventHandlerCallRef,EventRef,void*);
6986 static void init_service_handler ();
6987 #endif
6989 extern void init_emacs_passwd_dir ();
6990 extern int emacs_main (int, char **, char **);
6991 extern void check_alarm ();
6993 extern void initialize_applescript();
6994 extern void terminate_applescript();
6996 static unsigned int
6997 #if USE_CARBON_EVENTS
6998 mac_to_emacs_modifiers (UInt32 mods)
6999 #else
7000 mac_to_emacs_modifiers (EventModifiers mods)
7001 #endif
7003 unsigned int result = 0;
7004 if (mods & macShiftKey)
7005 result |= shift_modifier;
7006 if (mods & macCtrlKey)
7007 result |= ctrl_modifier;
7008 if (mods & macMetaKey)
7009 result |= meta_modifier;
7010 if (NILP (Vmac_command_key_is_meta) && (mods & macAltKey))
7011 result |= alt_modifier;
7012 return result;
7015 static int
7016 mac_get_emulated_btn ( UInt32 modifiers )
7018 int result = 0;
7019 if (!NILP (Vmac_emulate_three_button_mouse)) {
7020 int cmdIs3 = !EQ (Vmac_emulate_three_button_mouse, Qreverse);
7021 if (modifiers & controlKey)
7022 result = cmdIs3 ? 2 : 1;
7023 else if (modifiers & optionKey)
7024 result = cmdIs3 ? 1 : 2;
7026 return result;
7029 #if USE_CARBON_EVENTS
7030 /* Obtains the event modifiers from the event ref and then calls
7031 mac_to_emacs_modifiers. */
7032 static int
7033 mac_event_to_emacs_modifiers (EventRef eventRef)
7035 UInt32 mods = 0;
7036 GetEventParameter (eventRef, kEventParamKeyModifiers, typeUInt32, NULL,
7037 sizeof (UInt32), NULL, &mods);
7038 if (!NILP (Vmac_emulate_three_button_mouse) &&
7039 GetEventClass(eventRef) == kEventClassMouse)
7041 mods &= ~(optionKey & cmdKey);
7043 return mac_to_emacs_modifiers (mods);
7046 /* Given an event ref, return the code to use for the mouse button
7047 code in the emacs input_event. */
7048 static int
7049 mac_get_mouse_btn (EventRef ref)
7051 EventMouseButton result = kEventMouseButtonPrimary;
7052 GetEventParameter (ref, kEventParamMouseButton, typeMouseButton, NULL,
7053 sizeof (EventMouseButton), NULL, &result);
7054 switch (result)
7056 case kEventMouseButtonPrimary:
7057 if (NILP (Vmac_emulate_three_button_mouse))
7058 return 0;
7059 else {
7060 UInt32 mods = 0;
7061 GetEventParameter (ref, kEventParamKeyModifiers, typeUInt32, NULL,
7062 sizeof (UInt32), NULL, &mods);
7063 return mac_get_emulated_btn(mods);
7065 case kEventMouseButtonSecondary:
7066 return NILP (Vmac_wheel_button_is_mouse_2) ? 1 : 2;
7067 case kEventMouseButtonTertiary:
7068 case 4: /* 4 is the number for the mouse wheel button */
7069 return NILP (Vmac_wheel_button_is_mouse_2) ? 2 : 1;
7070 default:
7071 return 0;
7075 /* Normally, ConvertEventRefToEventRecord will correctly handle all
7076 events. However the click of the mouse wheel is not converted to a
7077 mouseDown or mouseUp event. This calls ConvertEventRef, but then
7078 checks to see if it is a mouse up or down carbon event that has not
7079 been converted, and if so, converts it by hand (to be picked up in
7080 the XTread_socket loop). */
7081 static Boolean mac_convert_event_ref (EventRef eventRef, EventRecord *eventRec)
7083 Boolean result = ConvertEventRefToEventRecord (eventRef, eventRec);
7084 /* Do special case for mouse wheel button. */
7085 if (!result && GetEventClass (eventRef) == kEventClassMouse)
7087 UInt32 kind = GetEventKind (eventRef);
7088 if (kind == kEventMouseDown && !(eventRec->what == mouseDown))
7090 eventRec->what = mouseDown;
7091 result=1;
7093 if (kind == kEventMouseUp && !(eventRec->what == mouseUp))
7095 eventRec->what = mouseUp;
7096 result=1;
7098 if (result)
7100 /* Need where and when. */
7101 UInt32 mods;
7102 GetEventParameter (eventRef, kEventParamMouseLocation,
7103 typeQDPoint, NULL, sizeof (Point),
7104 NULL, &eventRec->where);
7105 /* Use two step process because new event modifiers are
7106 32-bit and old are 16-bit. Currently, only loss is
7107 NumLock & Fn. */
7108 GetEventParameter (eventRef, kEventParamKeyModifiers,
7109 typeUInt32, NULL, sizeof (UInt32),
7110 NULL, &mods);
7111 eventRec->modifiers = mods;
7113 eventRec->when = EventTimeToTicks (GetEventTime (eventRef));
7116 return result;
7119 #endif
7121 static void
7122 do_get_menus (void)
7124 Handle menubar_handle;
7125 MenuHandle menu_handle;
7127 menubar_handle = GetNewMBar (128);
7128 if(menubar_handle == NULL)
7129 abort ();
7130 SetMenuBar (menubar_handle);
7131 DrawMenuBar ();
7133 menu_handle = GetMenuHandle (M_APPLE);
7134 if(menu_handle != NULL)
7135 AppendResMenu (menu_handle,'DRVR');
7136 else
7137 abort ();
7141 static void
7142 do_init_managers (void)
7144 #if !TARGET_API_MAC_CARBON
7145 InitGraf (&qd.thePort);
7146 InitFonts ();
7147 FlushEvents (everyEvent, 0);
7148 InitWindows ();
7149 InitMenus ();
7150 TEInit ();
7151 InitDialogs (NULL);
7152 #endif /* !TARGET_API_MAC_CARBON */
7153 InitCursor ();
7155 #if !TARGET_API_MAC_CARBON
7156 arrow_cursor = &qd.arrow;
7158 /* set up some extra stack space for use by emacs */
7159 SetApplLimit ((Ptr) ((long) GetApplLimit () - EXTRA_STACK_ALLOC));
7161 /* MaxApplZone must be called for AppleScript to execute more
7162 complicated scripts */
7163 MaxApplZone ();
7164 MoreMasters ();
7165 #endif /* !TARGET_API_MAC_CARBON */
7168 static void
7169 do_check_ram_size (void)
7171 SInt32 physical_ram_size, logical_ram_size;
7173 if (Gestalt (gestaltPhysicalRAMSize, &physical_ram_size) != noErr
7174 || Gestalt (gestaltLogicalRAMSize, &logical_ram_size) != noErr
7175 || physical_ram_size > (1 << VALBITS)
7176 || logical_ram_size > (1 << VALBITS))
7178 StopAlert (RAM_TOO_LARGE_ALERT_ID, NULL);
7179 exit (1);
7183 static void
7184 do_window_update (WindowPtr win)
7186 struct frame *f = mac_window_to_frame (win);
7188 if (win == tip_window)
7189 /* The tooltip has been drawn already. Avoid the
7190 SET_FRAME_GARBAGED below. */
7191 return;
7193 if (f)
7195 if (f->async_visible == 0)
7197 f->async_visible = 1;
7198 f->async_iconified = 0;
7199 SET_FRAME_GARBAGED (f);
7201 /* An update event is equivalent to MapNotify on X, so report
7202 visibility changes properly. */
7203 if (! NILP(Vframe_list) && ! NILP (XCDR (Vframe_list)))
7204 /* Force a redisplay sooner or later to update the
7205 frame titles in case this is the second frame. */
7206 record_asynch_buffer_change ();
7208 else
7210 BeginUpdate (win);
7211 handling_window_update = 1;
7213 XClearWindow (FRAME_MAC_DISPLAY (f), FRAME_MAC_WINDOW (f));
7215 expose_frame (f, 0, 0, 0, 0);
7217 handling_window_update = 0;
7218 EndUpdate (win);
7223 static int
7224 is_emacs_window (WindowPtr win)
7226 Lisp_Object tail, frame;
7228 if (!win)
7229 return 0;
7231 FOR_EACH_FRAME (tail, frame)
7232 if (FRAME_MAC_P (XFRAME (frame)))
7233 if (FRAME_MAC_WINDOW (XFRAME (frame)) == win)
7234 return 1;
7236 return 0;
7239 static void
7240 do_window_activate (WindowPtr win)
7242 struct frame *f;
7244 if (is_emacs_window (win))
7246 f = mac_window_to_frame (win);
7248 if (f)
7250 x_new_focus_frame (FRAME_MAC_DISPLAY_INFO (f), f);
7251 activate_scroll_bars (f);
7256 static void
7257 do_window_deactivate (WindowPtr win)
7259 struct frame *f;
7261 if (is_emacs_window (win))
7263 f = mac_window_to_frame (win);
7265 if (f == FRAME_MAC_DISPLAY_INFO (f)->x_focus_frame)
7267 x_new_focus_frame (FRAME_MAC_DISPLAY_INFO (f), 0);
7268 deactivate_scroll_bars (f);
7273 static void
7274 do_app_resume ()
7276 WindowPtr wp;
7277 struct frame *f;
7279 wp = mac_front_window ();
7280 if (is_emacs_window (wp))
7282 f = mac_window_to_frame (wp);
7284 if (f)
7286 x_new_focus_frame (FRAME_MAC_DISPLAY_INFO (f), f);
7287 activate_scroll_bars (f);
7291 app_is_suspended = false;
7292 app_sleep_time = WNE_SLEEP_AT_RESUME;
7295 static void
7296 do_app_suspend ()
7298 WindowPtr wp;
7299 struct frame *f;
7301 wp = mac_front_window ();
7302 if (is_emacs_window (wp))
7304 f = mac_window_to_frame (wp);
7306 if (f == FRAME_MAC_DISPLAY_INFO (f)->x_focus_frame)
7308 x_new_focus_frame (FRAME_MAC_DISPLAY_INFO (f), 0);
7309 deactivate_scroll_bars (f);
7313 app_is_suspended = true;
7314 app_sleep_time = WNE_SLEEP_AT_SUSPEND;
7318 static void
7319 do_mouse_moved (mouse_pos, f)
7320 Point mouse_pos;
7321 FRAME_PTR *f;
7323 WindowPtr wp = mac_front_window ();
7324 struct x_display_info *dpyinfo;
7326 if (is_emacs_window (wp))
7328 *f = mac_window_to_frame (wp);
7329 dpyinfo = FRAME_MAC_DISPLAY_INFO (*f);
7331 if (dpyinfo->mouse_face_hidden)
7333 dpyinfo->mouse_face_hidden = 0;
7334 clear_mouse_face (dpyinfo);
7337 SetPortWindowPort (wp);
7339 GlobalToLocal (&mouse_pos);
7341 if (dpyinfo->grabbed && tracked_scroll_bar)
7342 x_scroll_bar_note_movement (tracked_scroll_bar,
7343 mouse_pos.v
7344 - XINT (tracked_scroll_bar->top),
7345 TickCount() * (1000 / 60));
7346 else
7347 note_mouse_movement (*f, &mouse_pos);
7352 static void
7353 do_apple_menu (SInt16 menu_item)
7355 #if !TARGET_API_MAC_CARBON
7356 Str255 item_name;
7357 SInt16 da_driver_refnum;
7359 if (menu_item == I_ABOUT)
7360 NoteAlert (ABOUT_ALERT_ID, NULL);
7361 else
7363 GetMenuItemText (GetMenuHandle (M_APPLE), menu_item, item_name);
7364 da_driver_refnum = OpenDeskAcc (item_name);
7366 #endif /* !TARGET_API_MAC_CARBON */
7369 void
7370 do_menu_choice (SInt32 menu_choice)
7372 SInt16 menu_id, menu_item;
7374 menu_id = HiWord (menu_choice);
7375 menu_item = LoWord (menu_choice);
7377 if (menu_id == 0)
7378 return;
7380 switch (menu_id)
7382 case M_APPLE:
7383 do_apple_menu (menu_item);
7384 break;
7386 default:
7388 struct frame *f = mac_window_to_frame (mac_front_window ());
7389 MenuHandle menu = GetMenuHandle (menu_id);
7390 if (menu)
7392 UInt32 refcon;
7394 GetMenuItemRefCon (menu, menu_item, &refcon);
7395 menubar_selection_callback (f, refcon);
7400 HiliteMenu (0);
7404 /* Handle drags in size box. Based on code contributed by Ben
7405 Mesander and IM - Window Manager A. */
7407 static void
7408 do_grow_window (WindowPtr w, EventRecord *e)
7410 long grow_size;
7411 Rect limit_rect;
7412 int rows, columns;
7413 struct frame *f = mac_window_to_frame (w);
7415 SetRect(&limit_rect, MIN_DOC_SIZE, MIN_DOC_SIZE, MAX_DOC_SIZE, MAX_DOC_SIZE);
7417 grow_size = GrowWindow (w, e->where, &limit_rect);
7419 /* see if it really changed size */
7420 if (grow_size != 0)
7422 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, HiWord (grow_size));
7423 columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, LoWord (grow_size));
7425 x_set_window_size (f, 0, columns, rows);
7430 /* Handle clicks in zoom box. Calculation of "standard state" based
7431 on code in IM - Window Manager A and code contributed by Ben
7432 Mesander. The standard state of an Emacs window is 80-characters
7433 wide (DEFAULT_NUM_COLS) and as tall as will fit on the screen. */
7435 static void
7436 do_zoom_window (WindowPtr w, int zoom_in_or_out)
7438 GrafPtr save_port;
7439 Rect zoom_rect, port_rect;
7440 Point top_left;
7441 int w_title_height, columns, rows, width, height, dummy, x, y;
7442 struct frame *f = mac_window_to_frame (w);
7444 GetPort (&save_port);
7446 SetPortWindowPort (w);
7448 /* Clear window to avoid flicker. */
7449 #if TARGET_API_MAC_CARBON
7451 Rect r;
7452 BitMap bm;
7454 GetWindowPortBounds (w, &r);
7455 EraseRect (&r);
7457 if (zoom_in_or_out == inZoomOut)
7459 /* calculate height of window's title bar (hard card it for now). */
7460 w_title_height = 20 + GetMBarHeight ();
7462 /* get maximum height of window into zoom_rect.bottom -
7463 zoom_rect.top */
7464 GetQDGlobalsScreenBits (&bm);
7465 zoom_rect = bm.bounds;
7466 zoom_rect.top += w_title_height;
7467 InsetRect (&zoom_rect, 8, 4); /* not too tight */
7469 zoom_rect.right = zoom_rect.left
7470 + FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, DEFAULT_NUM_COLS);
7472 SetWindowStandardState (w, &zoom_rect);
7475 #else /* not TARGET_API_MAC_CARBON */
7476 EraseRect (&(w->portRect));
7477 if (zoom_in_or_out == inZoomOut)
7479 SetPt (&top_left, w->portRect.left, w->portRect.top);
7480 LocalToGlobal (&top_left);
7482 /* calculate height of window's title bar */
7483 w_title_height = top_left.v - 1
7484 - (**((WindowPeek) w)->strucRgn).rgnBBox.top + GetMBarHeight ();
7486 /* get maximum height of window into zoom_rect.bottom - zoom_rect.top */
7487 zoom_rect = qd.screenBits.bounds;
7488 zoom_rect.top += w_title_height;
7489 InsetRect (&zoom_rect, 8, 4); /* not too tight */
7491 zoom_rect.right = zoom_rect.left
7492 + FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, DEFAULT_NUM_COLS);
7494 (**((WStateDataHandle) ((WindowPeek) w)->dataHandle)).stdState
7495 = zoom_rect;
7497 #endif /* not TARGET_API_MAC_CARBON */
7499 ZoomWindow (w, zoom_in_or_out, w == mac_front_window ());
7501 /* retrieve window size and update application values */
7502 #if TARGET_API_MAC_CARBON
7503 GetWindowPortBounds (w, &port_rect);
7504 #else
7505 port_rect = w->portRect;
7506 #endif
7507 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, port_rect.bottom - port_rect.top);
7508 columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, port_rect.right - port_rect.left);
7509 x_set_window_size (f, 0, columns, rows);
7511 SetPort (save_port);
7514 /* Initialize Drag And Drop to allow files to be dropped onto emacs frames */
7515 static OSErr
7516 init_mac_drag_n_drop ()
7518 OSErr result = InstallReceiveHandler (mac_do_receive_drag, 0L, NULL);
7519 return result;
7522 /* Intialize AppleEvent dispatcher table for the required events. */
7523 void
7524 init_required_apple_events ()
7526 OSErr err;
7527 long result;
7529 /* Make sure we have apple events before starting. */
7530 err = Gestalt (gestaltAppleEventsAttr, &result);
7531 if (err != noErr)
7532 abort ();
7534 if (!(result & (1 << gestaltAppleEventsPresent)))
7535 abort ();
7537 #if TARGET_API_MAC_CARBON
7538 err = AEInstallEventHandler(kCoreEventClass, kAEOpenApplication,
7539 NewAEEventHandlerUPP
7540 ((AEEventHandlerProcPtr) do_ae_open_application),
7541 0L, false);
7542 #else
7543 err = AEInstallEventHandler(kCoreEventClass, kAEOpenApplication,
7544 NewAEEventHandlerProc
7545 ((AEEventHandlerProcPtr) do_ae_open_application),
7546 0L, false);
7547 #endif
7548 if (err != noErr)
7549 abort ();
7551 #if TARGET_API_MAC_CARBON
7552 err = AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments,
7553 NewAEEventHandlerUPP
7554 ((AEEventHandlerProcPtr) do_ae_open_documents),
7555 0L, false);
7556 #else
7557 err = AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments,
7558 NewAEEventHandlerProc
7559 ((AEEventHandlerProcPtr) do_ae_open_documents),
7560 0L, false);
7561 #endif
7562 if (err != noErr)
7563 abort ();
7565 #if TARGET_API_MAC_CARBON
7566 err = AEInstallEventHandler(kCoreEventClass, kAEPrintDocuments,
7567 NewAEEventHandlerUPP
7568 ((AEEventHandlerProcPtr) do_ae_print_documents),
7569 0L, false);
7570 #else
7571 err = AEInstallEventHandler(kCoreEventClass, kAEPrintDocuments,
7572 NewAEEventHandlerProc
7573 ((AEEventHandlerProcPtr) do_ae_print_documents),
7574 0L, false);
7575 #endif
7576 if (err != noErr)
7577 abort ();
7579 #if TARGET_API_MAC_CARBON
7580 err = AEInstallEventHandler(kCoreEventClass, kAEQuitApplication,
7581 NewAEEventHandlerUPP
7582 ((AEEventHandlerProcPtr) do_ae_quit_application),
7583 0L, false);
7584 #else
7585 err = AEInstallEventHandler(kCoreEventClass, kAEQuitApplication,
7586 NewAEEventHandlerProc
7587 ((AEEventHandlerProcPtr) do_ae_quit_application),
7588 0L, false);
7589 #endif
7590 if (err != noErr)
7591 abort ();
7594 #if USE_CARBON_EVENTS
7596 void
7597 init_service_handler ()
7599 EventTypeSpec specs[] = {{kEventClassService, kEventServiceGetTypes},
7600 {kEventClassService, kEventServiceCopy},
7601 {kEventClassService, kEventServicePaste}};
7602 InstallApplicationEventHandler (NewEventHandlerUPP (mac_handle_service_event),
7603 3, specs, NULL, NULL);
7607 MAC_TODO: Check to see if this is called by AEProcessDesc...
7609 OSStatus
7610 mac_handle_service_event (EventHandlerCallRef callRef,
7611 EventRef event, void *data)
7613 OSStatus err = noErr;
7614 switch (GetEventKind (event))
7616 case kEventServiceGetTypes:
7618 CFMutableArrayRef copyTypes, pasteTypes;
7619 CFStringRef type;
7620 Boolean selection = true;
7622 GetEventParameter(event, kEventParamServicePasteTypes,
7623 typeCFMutableArrayRef, NULL,
7624 sizeof (CFMutableArrayRef), NULL, &pasteTypes);
7626 GetEventParameter(event, kEventParamServiceCopyTypes,
7627 typeCFMutableArrayRef, NULL,
7628 sizeof (CFMutableArrayRef), NULL, &copyTypes);
7629 type = CreateTypeStringWithOSType (kScrapFlavorTypeText);
7630 if (type) {
7631 CFArrayAppendValue (copyTypes, type);
7632 //CFArrayAppendValue (pasteTypes, type);
7633 CFRelease (type);
7636 case kEventServiceCopy:
7638 ScrapRef currentScrap, specificScrap;
7639 char * buf = "";
7640 Size byteCount = 0;
7642 GetCurrentScrap (&currentScrap);
7644 err = GetScrapFlavorSize (currentScrap, kScrapFlavorTypeText, &byteCount);
7645 if (err == noErr)
7647 void *buffer = xmalloc (byteCount);
7648 if (buffer != NULL)
7650 GetEventParameter (event, kEventParamScrapRef, typeScrapRef, NULL,
7651 sizeof (ScrapRef), NULL, &specificScrap);
7653 err = GetScrapFlavorData (currentScrap, kScrapFlavorTypeText,
7654 &byteCount, buffer);
7655 if (err == noErr)
7656 PutScrapFlavor (specificScrap, kScrapFlavorTypeText,
7657 kScrapFlavorMaskNone, byteCount, buffer);
7658 xfree (buffer);
7661 err = noErr;
7663 case kEventServicePaste:
7666 // Get the current location
7667 Size byteCount;
7668 ScrapRef specificScrap;
7669 GetEventParameter(event, kEventParamScrapRef, typeScrapRef, NULL,
7670 sizeof(ScrapRef), NULL, &specificScrap);
7671 err = GetScrapFlavorSize(specificScrap, kScrapFlavorTypeText, &byteCount);
7672 if (err == noErr) {
7673 void * buffer = xmalloc(byteCount);
7674 if (buffer != NULL ) {
7675 err = GetScrapFlavorData(specificScrap, kScrapFlavorTypeText,
7676 &byteCount, buffer);
7677 if (err == noErr) {
7678 // Actually place in the buffer
7679 BLOCK_INPUT;
7680 // Get the current "selection" string here
7681 UNBLOCK_INPUT;
7684 xfree(buffer);
7689 return err;
7691 #endif
7693 /* Open Application Apple Event */
7694 static pascal OSErr
7695 do_ae_open_application(const AppleEvent *pae, AppleEvent *preply, long prefcon)
7697 return noErr;
7701 /* Defined in mac.c. */
7702 extern int
7703 path_from_vol_dir_name (char *, int, short, long, char *);
7706 /* Called when we receive an AppleEvent with an ID of
7707 "kAEOpenDocuments". This routine gets the direct parameter,
7708 extracts the FSSpecs in it, and puts their names on a list. */
7709 static pascal OSErr
7710 do_ae_open_documents(AppleEvent *message, AppleEvent *reply, long refcon)
7712 OSErr err, err2;
7713 AEDesc the_desc;
7714 AEKeyword keyword;
7715 DescType actual_type;
7716 Size actual_size;
7718 err = AEGetParamDesc (message, keyDirectObject, typeAEList, &the_desc);
7719 if (err != noErr)
7720 goto descriptor_error_exit;
7722 /* Check to see that we got all of the required parameters from the
7723 event descriptor. For an 'odoc' event this should just be the
7724 file list. */
7725 err = AEGetAttributePtr(message, keyMissedKeywordAttr, typeWildCard,
7726 &actual_type, (Ptr) &keyword,
7727 sizeof (keyword), &actual_size);
7728 /* No error means that we found some unused parameters.
7729 errAEDescNotFound means that there are no more parameters. If we
7730 get an error code other than that, flag it. */
7731 if ((err == noErr) || (err != errAEDescNotFound))
7733 err = errAEEventNotHandled;
7734 goto error_exit;
7736 err = noErr;
7738 /* Got all the parameters we need. Now, go through the direct
7739 object list and parse it up. */
7741 long num_files_to_open;
7743 err = AECountItems (&the_desc, &num_files_to_open);
7744 if (err == noErr)
7746 int i;
7748 /* AE file list is one based so just use that for indexing here. */
7749 for (i = 1; (err == noErr) && (i <= num_files_to_open); i++)
7751 FSSpec fs;
7752 Str255 path_name, unix_path_name;
7753 #ifdef MAC_OSX
7754 FSRef fref;
7755 #endif
7757 err = AEGetNthPtr(&the_desc, i, typeFSS, &keyword, &actual_type,
7758 (Ptr) &fs, sizeof (fs), &actual_size);
7759 if (err != noErr) break;
7761 #ifdef MAC_OSX
7762 err = FSpMakeFSRef (&fs, &fref);
7763 if (err != noErr) break;
7765 if (FSRefMakePath (&fref, unix_path_name, 255) == noErr)
7766 #else
7767 if (path_from_vol_dir_name (path_name, 255, fs.vRefNum, fs.parID,
7768 fs.name) &&
7769 mac_to_posix_pathname (path_name, unix_path_name, 255))
7770 #endif
7771 drag_and_drop_file_list = Fcons (build_string (unix_path_name),
7772 drag_and_drop_file_list);
7777 error_exit:
7778 /* Nuke the coerced file list in any case */
7779 err2 = AEDisposeDesc(&the_desc);
7781 descriptor_error_exit:
7782 /* InvalRect(&(gFrontMacWindowP->mWP->portRect)); */
7783 return err;
7787 static pascal OSErr
7788 mac_do_receive_drag (WindowPtr window, void *handlerRefCon,
7789 DragReference theDrag)
7791 short items;
7792 short index;
7793 FlavorFlags theFlags;
7794 Point mouse;
7795 OSErr result;
7796 ItemReference theItem;
7797 HFSFlavor data;
7798 FSRef fref;
7799 Size size = sizeof (HFSFlavor);
7801 drag_and_drop_file_list = Qnil;
7802 GetDragMouse (theDrag, &mouse, 0L);
7803 CountDragItems (theDrag, &items);
7804 for (index = 1; index <= items; index++)
7806 /* Only handle file references. */
7807 GetDragItemReferenceNumber (theDrag, index, &theItem);
7808 result = GetFlavorFlags (theDrag, theItem, flavorTypeHFS, &theFlags);
7809 if (result == noErr)
7811 #ifdef MAC_OSX
7812 FSRef frref;
7813 #else
7814 Str255 path_name;
7815 #endif
7816 Str255 unix_path_name;
7817 GetFlavorData (theDrag, theItem, flavorTypeHFS, &data, &size, 0L);
7818 #ifdef MAC_OSX
7819 /* Use Carbon routines, otherwise it converts the file name
7820 to /Macintosh HD/..., which is not correct. */
7821 FSpMakeFSRef (&data.fileSpec, &fref);
7822 if (! FSRefMakePath (&fref, unix_path_name, sizeof (unix_path_name)));
7823 #else
7824 if (path_from_vol_dir_name (path_name, 255, data.fileSpec.vRefNum,
7825 data.fileSpec.parID, data.fileSpec.name) &&
7826 mac_to_posix_pathname (path_name, unix_path_name, 255))
7827 #endif
7828 drag_and_drop_file_list = Fcons (build_string (unix_path_name),
7829 drag_and_drop_file_list);
7831 else
7832 return;
7834 /* If there are items in the list, construct an event and post it to
7835 the queue like an interrupt using kbd_buffer_store_event. */
7836 if (!NILP (drag_and_drop_file_list))
7838 struct input_event event;
7839 Lisp_Object frame;
7840 struct frame *f = mac_window_to_frame (window);
7841 SetPortWindowPort (window);
7842 GlobalToLocal (&mouse);
7844 event.kind = DRAG_N_DROP_EVENT;
7845 event.code = 0;
7846 event.modifiers = 0;
7847 event.timestamp = TickCount () * (1000 / 60);
7848 XSETINT (event.x, mouse.h);
7849 XSETINT (event.y, mouse.v);
7850 XSETFRAME (frame, f);
7851 event.frame_or_window = Fcons (frame, drag_and_drop_file_list);
7852 event.arg = Qnil;
7853 /* Post to the interrupt queue */
7854 kbd_buffer_store_event (&event);
7855 /* MAC_TODO: Mimic behavior of windows by switching contexts to Emacs */
7857 ProcessSerialNumber psn;
7858 GetCurrentProcess (&psn);
7859 SetFrontProcess (&psn);
7865 /* Print Document Apple Event */
7866 static pascal OSErr
7867 do_ae_print_documents (const AppleEvent *pAE, AppleEvent *reply, long refcon)
7869 return errAEEventNotHandled;
7873 static pascal OSErr
7874 do_ae_quit_application (AppleEvent* message, AppleEvent *reply, long refcon)
7876 /* FixMe: Do we need an unwind-protect or something here? And what
7877 do we do about unsaved files. Currently just forces quit rather
7878 than doing recursive callback to get user input. */
7880 terminate_flag = true;
7882 /* Fkill_emacs doesn't return. We have to return. (TI) */
7883 return noErr;
7887 #if __profile__
7888 void
7889 profiler_exit_proc ()
7891 ProfilerDump ("\pEmacs.prof");
7892 ProfilerTerm ();
7894 #endif
7896 /* These few functions implement Emacs as a normal Mac application
7897 (almost): set up the heap and the Toolbox, handle necessary
7898 system events plus a few simple menu events. They also set up
7899 Emacs's access to functions defined in the rest of this file.
7900 Emacs uses function hooks to perform all its terminal I/O. A
7901 complete list of these functions appear in termhooks.h. For what
7902 they do, read the comments there and see also w32term.c and
7903 xterm.c. What's noticeably missing here is the event loop, which
7904 is normally present in most Mac application. After performing the
7905 necessary Mac initializations, main passes off control to
7906 emacs_main (corresponding to main in emacs.c). Emacs_main calls
7907 mac_read_socket (defined further below) to read input. This is
7908 where WaitNextEvent is called to process Mac events. This is also
7909 where check_alarm in sysdep.c is called to simulate alarm signals.
7910 This makes the cursor jump back to its correct position after
7911 briefly jumping to that of the matching parenthesis, print useful
7912 hints and prompts in the minibuffer after the user stops typing for
7913 a wait, etc. */
7915 #if !TARGET_API_MAC_CARBON
7916 #undef main
7918 main (void)
7920 #if __profile__ /* is the profiler on? */
7921 if (ProfilerInit(collectDetailed, bestTimeBase, 5000, 200))
7922 exit(1);
7923 #endif
7925 #if __MWERKS__
7926 /* set creator and type for files created by MSL */
7927 _fcreator = 'EMAx';
7928 _ftype = 'TEXT';
7929 #endif
7931 do_init_managers ();
7933 do_get_menus ();
7935 #ifndef USE_LSB_TAG
7936 do_check_ram_size ();
7937 #endif
7939 init_emacs_passwd_dir ();
7941 init_environ ();
7943 initialize_applescript ();
7945 init_required_apple_events ();
7948 char **argv;
7949 int argc = 0;
7951 /* set up argv array from STR# resource */
7952 get_string_list (&argv, ARGV_STRING_LIST_ID);
7953 while (argv[argc])
7954 argc++;
7956 /* free up AppleScript resources on exit */
7957 atexit (terminate_applescript);
7959 #if __profile__ /* is the profiler on? */
7960 atexit (profiler_exit_proc);
7961 #endif
7963 /* 3rd param "envp" never used in emacs_main */
7964 (void) emacs_main (argc, argv, 0);
7967 /* Never reached - real exit in Fkill_emacs */
7968 return 0;
7970 #endif
7972 /* Table for translating Mac keycode to X keysym values. Contributed
7973 by Sudhir Shenoy. */
7974 static unsigned char keycode_to_xkeysym_table[] = {
7975 /*0x00*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7976 /*0x10*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7977 /*0x20*/ 0, 0, 0, 0, 0x0d /*return*/, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7979 /*0x30*/ 0x09 /*tab*/, 0 /*0x0020 space*/, 0, 0x08 /*backspace*/,
7980 /*0x34*/ 0, 0x1b /*escape*/, 0, 0,
7981 /*0x38*/ 0, 0, 0, 0,
7982 /*0x3C*/ 0, 0, 0, 0,
7984 /*0x40*/ 0, 0xae /*kp-.*/, 0, 0xaa /*kp-**/,
7985 /*0x44*/ 0, 0xab /*kp-+*/, 0, 0x7f /*kp-clear*/,
7986 /*0x48*/ 0, 0, 0, 0xaf /*kp-/*/,
7987 /*0x4C*/ 0x8d /*kp-enter*/, 0, 0xad /*kp--*/, 0,
7989 /*0x50*/ 0, 0xbd /*kp-=*/, 0xb0 /*kp-0*/, 0xb1 /*kp-1*/,
7990 /*0x54*/ 0xb2 /*kp-2*/, 0xb3 /*kp-3*/, 0xb4 /*kp-4*/, 0xb5 /*kp-5*/,
7991 /*0x58*/ 0xb6 /*kp-6*/, 0xb7 /*kp-7*/, 0, 0xb8 /*kp-8*/,
7992 /*0x5C*/ 0xb9 /*kp-9*/, 0, 0, 0,
7994 /*0x60*/ 0xc2 /*f5*/, 0xc3 /*f6*/, 0xc4 /*f7*/, 0xc0 /*f3*/,
7995 /*0x64*/ 0xc5 /*f8*/, 0xc6 /*f9*/, 0, 0xc8 /*f11*/,
7996 /*0x68*/ 0, 0xca /*f13*/, 0, 0xcb /*f14*/,
7997 /*0x6C*/ 0, 0xc7 /*f10*/, 0, 0xc9 /*f12*/,
7999 /*0x70*/ 0, 0xcc /*f15*/, 0x9e /*insert (or 0x6a==help)*/, 0x95 /*home*/,
8000 /*0x74*/ 0x9a /*pgup*/, 0x9f /*delete*/, 0xc1 /*f4*/, 0x9c /*end*/,
8001 /*0x78*/ 0xbf /*f2*/, 0x9b /*pgdown*/, 0xbe /*f1*/, 0x51 /*left*/,
8002 /*0x7C*/ 0x53 /*right*/, 0x54 /*down*/, 0x52 /*up*/, 0
8005 static int
8006 keycode_to_xkeysym (int keyCode, int *xKeySym)
8008 *xKeySym = keycode_to_xkeysym_table [keyCode & 0x7f];
8009 return *xKeySym != 0;
8012 /* Emacs calls this whenever it wants to read an input event from the
8013 user. */
8015 XTread_socket (sd, expected, hold_quit)
8016 int sd, expected;
8017 struct input_event *hold_quit;
8019 struct input_event inev;
8020 int count = 0;
8021 #if USE_CARBON_EVENTS
8022 EventRef eventRef;
8023 EventTargetRef toolbox_dispatcher = GetEventDispatcherTarget ();
8024 #else
8025 EventMask event_mask;
8026 #endif
8027 EventRecord er;
8028 struct mac_display_info *dpyinfo = &one_mac_display_info;
8030 if (interrupt_input_blocked)
8032 interrupt_input_pending = 1;
8033 return -1;
8036 interrupt_input_pending = 0;
8037 BLOCK_INPUT;
8039 /* So people can tell when we have read the available input. */
8040 input_signal_count++;
8042 /* Don't poll for events to process (specifically updateEvt) if
8043 window update currently already in progress. A call to redisplay
8044 (in do_window_update) can be preempted by another call to
8045 redisplay, causing blank regions to be left on the screen and the
8046 cursor to be left at strange places. */
8047 if (handling_window_update)
8049 UNBLOCK_INPUT;
8050 return 0;
8053 if (terminate_flag)
8054 Fkill_emacs (make_number (1));
8056 #if !USE_CARBON_EVENTS
8057 event_mask = everyEvent;
8058 if (NILP (Fboundp (Qmac_ready_for_drag_n_drop)))
8059 event_mask -= highLevelEventMask;
8061 while (WaitNextEvent (event_mask, &er,
8062 (expected ? app_sleep_time : 0L), NULL))
8063 #else
8064 while (!ReceiveNextEvent (0, NULL,
8065 (expected ? TicksToEventTime (app_sleep_time) : 0),
8066 kEventRemoveFromQueue, &eventRef))
8067 #endif /* !USE_CARBON_EVENTS */
8069 int do_help = 0;
8070 struct frame *f;
8072 expected = 0;
8074 /* It is necessary to set this (additional) argument slot of an
8075 event to nil because keyboard.c protects incompletely
8076 processed event from being garbage collected by placing them
8077 in the kbd_buffer_gcpro vector. */
8078 EVENT_INIT (inev);
8079 inev.kind = NO_EVENT;
8080 inev.arg = Qnil;
8082 #if USE_CARBON_EVENTS
8083 /* Handle new events */
8084 if (!mac_convert_event_ref (eventRef, &er))
8085 switch (GetEventClass (eventRef))
8087 case kEventClassMouse:
8088 if (GetEventKind (eventRef) == kEventMouseWheelMoved)
8090 SInt32 delta;
8091 Point point;
8092 WindowPtr window_ptr = mac_front_window ();
8094 if (!IsValidWindowPtr (window_ptr))
8096 SysBeep(1);
8097 break;
8100 GetEventParameter(eventRef, kEventParamMouseWheelDelta,
8101 typeSInt32, NULL, sizeof (SInt32),
8102 NULL, &delta);
8103 GetEventParameter(eventRef, kEventParamMouseLocation,
8104 typeQDPoint, NULL, sizeof (Point),
8105 NULL, &point);
8106 inev.kind = WHEEL_EVENT;
8107 inev.code = 0;
8108 inev.modifiers = (mac_event_to_emacs_modifiers (eventRef)
8109 | ((delta < 0) ? down_modifier
8110 : up_modifier));
8111 SetPortWindowPort (window_ptr);
8112 GlobalToLocal (&point);
8113 XSETINT (inev.x, point.h);
8114 XSETINT (inev.y, point.v);
8115 XSETFRAME (inev.frame_or_window,
8116 mac_window_to_frame (window_ptr));
8117 inev.timestamp = EventTimeToTicks (GetEventTime (eventRef))*(1000/60);
8119 else
8120 SendEventToEventTarget (eventRef, toolbox_dispatcher);
8122 break;
8123 default:
8124 /* Send the event to the appropriate receiver. */
8125 SendEventToEventTarget (eventRef, toolbox_dispatcher);
8127 else
8128 #endif /* USE_CARBON_EVENTS */
8129 switch (er.what)
8131 case mouseDown:
8132 case mouseUp:
8134 WindowPtr window_ptr;
8135 SInt16 part_code;
8136 int tool_bar_p = 0;
8138 if (dpyinfo->grabbed && last_mouse_frame
8139 && FRAME_LIVE_P (last_mouse_frame))
8141 window_ptr = FRAME_MAC_WINDOW (last_mouse_frame);
8142 part_code = inContent;
8144 else
8146 window_ptr = FrontWindow ();
8147 if (tip_window && window_ptr == tip_window)
8149 HideWindow (tip_window);
8150 window_ptr = FrontWindow ();
8153 #if USE_CARBON_EVENTS
8154 /* This is needed to send mouse events like aqua
8155 window buttons to the correct handler. */
8156 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
8157 != eventNotHandledErr)
8158 break;
8160 if (!is_emacs_window (window_ptr))
8161 break;
8162 #endif
8163 part_code = FindWindow (er.where, &window_ptr);
8166 switch (part_code)
8168 case inMenuBar:
8169 if (er.what == mouseDown)
8171 f = mac_window_to_frame (mac_front_window ());
8172 saved_menu_event_location = er.where;
8173 inev.kind = MENU_BAR_ACTIVATE_EVENT;
8174 XSETFRAME (inev.frame_or_window, f);
8176 break;
8178 case inContent:
8179 if (window_ptr != mac_front_window ())
8180 SelectWindow (window_ptr);
8181 else
8183 SInt16 control_part_code;
8184 ControlHandle ch;
8185 Point mouse_loc = er.where;
8187 f = mac_window_to_frame (window_ptr);
8188 /* convert to local coordinates of new window */
8189 SetPortWindowPort (window_ptr);
8191 GlobalToLocal (&mouse_loc);
8192 #if TARGET_API_MAC_CARBON
8193 ch = FindControlUnderMouse (mouse_loc, window_ptr,
8194 &control_part_code);
8195 #else
8196 control_part_code = FindControl (mouse_loc, window_ptr,
8197 &ch);
8198 #endif
8200 #if USE_CARBON_EVENTS
8201 inev.code = mac_get_mouse_btn (eventRef);
8202 inev.modifiers = mac_event_to_emacs_modifiers (eventRef);
8203 #else
8204 inev.code = mac_get_emulated_btn (er.modifiers);
8205 inev.modifiers = mac_to_emacs_modifiers (er.modifiers);
8206 #endif
8207 XSETINT (inev.x, mouse_loc.h);
8208 XSETINT (inev.y, mouse_loc.v);
8209 inev.timestamp = er.when * (1000 / 60);
8210 /* ticks to milliseconds */
8212 if (dpyinfo->grabbed && tracked_scroll_bar
8213 #if TARGET_API_MAC_CARBON
8214 || ch != 0
8215 #else
8216 || control_part_code != 0
8217 #endif
8220 struct scroll_bar *bar;
8222 if (dpyinfo->grabbed && tracked_scroll_bar)
8224 bar = tracked_scroll_bar;
8225 control_part_code = kControlIndicatorPart;
8227 else
8228 bar = (struct scroll_bar *) GetControlReference (ch);
8229 x_scroll_bar_handle_click (bar, control_part_code,
8230 &er, &inev);
8231 if (er.what == mouseDown
8232 && control_part_code == kControlIndicatorPart)
8233 tracked_scroll_bar = bar;
8234 else
8235 tracked_scroll_bar = NULL;
8237 else
8239 Lisp_Object window;
8240 int x = mouse_loc.h;
8241 int y = mouse_loc.v;
8243 window = window_from_coordinates (f, x, y, 0, 0, 0, 1);
8244 if (EQ (window, f->tool_bar_window))
8246 if (er.what == mouseDown)
8247 handle_tool_bar_click (f, x, y, 1, 0);
8248 else
8249 handle_tool_bar_click (f, x, y, 0,
8250 inev.modifiers);
8251 tool_bar_p = 1;
8253 else
8255 XSETFRAME (inev.frame_or_window, f);
8256 inev.kind = MOUSE_CLICK_EVENT;
8260 if (er.what == mouseDown)
8262 dpyinfo->grabbed |= (1 << inev.code);
8263 last_mouse_frame = f;
8264 /* Ignore any mouse motion that happened
8265 before this event; any subsequent
8266 mouse-movement Emacs events should reflect
8267 only motion after the ButtonPress. */
8268 if (f != 0)
8269 f->mouse_moved = 0;
8271 if (!tool_bar_p)
8272 last_tool_bar_item = -1;
8274 else
8276 if (dpyinfo->grabbed & (1 << inev.code) == 0)
8277 /* If a button is released though it was not
8278 previously pressed, that would be because
8279 of multi-button emulation. */
8280 dpyinfo->grabbed = 0;
8281 else
8282 dpyinfo->grabbed &= ~(1 << inev.code);
8285 switch (er.what)
8287 case mouseDown:
8288 inev.modifiers |= down_modifier;
8289 break;
8290 case mouseUp:
8291 inev.modifiers |= up_modifier;
8292 break;
8295 break;
8297 case inDrag:
8298 #if TARGET_API_MAC_CARBON
8299 if (er.what == mouseDown)
8301 BitMap bm;
8303 GetQDGlobalsScreenBits (&bm);
8304 DragWindow (window_ptr, er.where, &bm.bounds);
8306 #else /* not TARGET_API_MAC_CARBON */
8307 DragWindow (window_ptr, er.where, &qd.screenBits.bounds);
8308 #endif /* not TARGET_API_MAC_CARBON */
8309 break;
8311 case inGoAway:
8312 if (TrackGoAway (window_ptr, er.where))
8314 inev.kind = DELETE_WINDOW_EVENT;
8315 XSETFRAME (inev.frame_or_window,
8316 mac_window_to_frame (window_ptr));
8318 break;
8320 /* window resize handling added --ben */
8321 case inGrow:
8322 if (er.what == mouseDown)
8324 do_grow_window(window_ptr, &er);
8325 break;
8328 /* window zoom handling added --ben */
8329 case inZoomIn:
8330 case inZoomOut:
8331 if (TrackBox (window_ptr, er.where, part_code))
8332 do_zoom_window (window_ptr, part_code);
8333 break;
8335 default:
8336 break;
8339 break;
8341 case updateEvt:
8342 #if USE_CARBON_EVENTS
8343 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
8344 != eventNotHandledErr)
8345 break;
8346 #endif
8347 do_window_update ((WindowPtr) er.message);
8348 break;
8350 case osEvt:
8351 #if USE_CARBON_EVENTS
8352 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
8353 != eventNotHandledErr)
8354 break;
8355 #endif
8356 switch ((er.message >> 24) & 0x000000FF)
8358 case suspendResumeMessage:
8359 if ((er.message & resumeFlag) == 1)
8360 do_app_resume ();
8361 else
8362 do_app_suspend ();
8363 break;
8365 case mouseMovedMessage:
8366 previous_help_echo_string = help_echo_string;
8367 help_echo_string = help_echo_object = help_echo_window = Qnil;
8368 help_echo_pos = -1;
8370 do_mouse_moved (er.where, &f);
8372 /* If the contents of the global variable
8373 help_echo_string has changed, generate a
8374 HELP_EVENT. */
8375 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
8376 do_help = 1;
8377 break;
8379 break;
8381 case activateEvt:
8383 WindowPtr window_ptr = (WindowPtr) er.message;
8385 #if USE_CARBON_EVENTS
8386 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
8387 != eventNotHandledErr)
8388 break;
8389 #endif
8390 if (window_ptr == tip_window)
8392 HideWindow (tip_window);
8393 break;
8396 if ((er.modifiers & activeFlag) != 0)
8398 Point mouse_loc = er.where;
8400 do_window_activate (window_ptr);
8402 SetPortWindowPort (window_ptr);
8403 GlobalToLocal (&mouse_loc);
8404 /* activateEvt counts as mouse movement,
8405 so update things that depend on mouse position. */
8406 note_mouse_movement (mac_window_to_frame (window_ptr),
8407 &mouse_loc);
8409 else
8411 do_window_deactivate (window_ptr);
8413 f = mac_window_to_frame (window_ptr);
8414 if (f == dpyinfo->mouse_face_mouse_frame)
8416 /* If we move outside the frame, then we're
8417 certainly no longer on any text in the
8418 frame. */
8419 clear_mouse_face (dpyinfo);
8420 dpyinfo->mouse_face_mouse_frame = 0;
8423 /* Generate a nil HELP_EVENT to cancel a help-echo.
8424 Do it only if there's something to cancel.
8425 Otherwise, the startup message is cleared when the
8426 mouse leaves the frame. */
8427 if (any_help_event_p)
8428 do_help = -1;
8431 break;
8433 case keyDown:
8434 case autoKey:
8436 int keycode = (er.message & keyCodeMask) >> 8;
8437 int xkeysym;
8439 #if USE_CARBON_EVENTS
8440 /* When using Carbon Events, we need to pass raw keyboard
8441 events to the TSM ourselves. If TSM handles it, it
8442 will pass back noErr, otherwise it will pass back
8443 "eventNotHandledErr" and we can process it
8444 normally. */
8445 if ((!NILP (Vmac_pass_command_to_system)
8446 || !(er.modifiers & cmdKey))
8447 && (!NILP (Vmac_pass_control_to_system)
8448 || !(er.modifiers & controlKey)))
8449 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
8450 != eventNotHandledErr)
8451 break;
8452 #endif
8454 #if TARGET_API_MAC_CARBON
8455 if (!IsValidWindowPtr (mac_front_window ()))
8457 SysBeep (1);
8458 break;
8460 #endif
8462 ObscureCursor ();
8464 if (!dpyinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
8466 clear_mouse_face (dpyinfo);
8467 dpyinfo->mouse_face_hidden = 1;
8470 if (keycode_to_xkeysym (keycode, &xkeysym))
8472 inev.code = 0xff00 | xkeysym;
8473 inev.kind = NON_ASCII_KEYSTROKE_EVENT;
8475 else
8477 if (er.modifiers & (controlKey |
8478 (NILP (Vmac_command_key_is_meta) ? optionKey
8479 : cmdKey)))
8481 /* This code comes from Keyboard Resource,
8482 Appendix C of IM - Text. This is necessary
8483 since shift is ignored in KCHR table
8484 translation when option or command is pressed.
8485 It also does not translate correctly
8486 control-shift chars like C-% so mask off shift
8487 here also */
8488 int new_modifiers = er.modifiers & 0xe600;
8489 /* mask off option and command */
8490 int new_keycode = keycode | new_modifiers;
8491 Ptr kchr_ptr = (Ptr) GetScriptManagerVariable (smKCHRCache);
8492 unsigned long some_state = 0;
8493 inev.code = KeyTranslate (kchr_ptr, new_keycode,
8494 &some_state) & 0xff;
8496 else
8497 inev.code = er.message & charCodeMask;
8498 inev.kind = ASCII_KEYSTROKE_EVENT;
8502 /* If variable mac-convert-keyboard-input-to-latin-1 is
8503 non-nil, convert non-ASCII characters typed at the Mac
8504 keyboard (presumed to be in the Mac Roman encoding) to
8505 iso-latin-1 encoding before they are passed to Emacs.
8506 This enables the Mac keyboard to be used to enter
8507 non-ASCII iso-latin-1 characters directly. */
8508 if (mac_keyboard_text_encoding != kTextEncodingMacRoman
8509 && inev.kind == ASCII_KEYSTROKE_EVENT && inev.code >= 128)
8511 static TECObjectRef converter = NULL;
8512 OSStatus the_err = noErr;
8513 OSStatus convert_status = noErr;
8515 if (converter == NULL)
8517 the_err = TECCreateConverter (&converter,
8518 kTextEncodingMacRoman,
8519 mac_keyboard_text_encoding);
8520 current_mac_keyboard_text_encoding
8521 = mac_keyboard_text_encoding;
8523 else if (mac_keyboard_text_encoding
8524 != current_mac_keyboard_text_encoding)
8526 /* Free the converter for the current encoding
8527 before creating a new one. */
8528 TECDisposeConverter (converter);
8529 the_err = TECCreateConverter (&converter,
8530 kTextEncodingMacRoman,
8531 mac_keyboard_text_encoding);
8532 current_mac_keyboard_text_encoding
8533 = mac_keyboard_text_encoding;
8536 if (the_err == noErr)
8538 unsigned char ch = inev.code;
8539 ByteCount actual_input_length, actual_output_length;
8540 unsigned char outch;
8542 convert_status = TECConvertText (converter, &ch, 1,
8543 &actual_input_length,
8544 &outch, 1,
8545 &actual_output_length);
8546 if (convert_status == noErr
8547 && actual_input_length == 1
8548 && actual_output_length == 1)
8549 inev.code = outch;
8553 #if USE_CARBON_EVENTS
8554 inev.modifiers = mac_event_to_emacs_modifiers (eventRef);
8555 #else
8556 inev.modifiers = mac_to_emacs_modifiers (er.modifiers);
8557 #endif
8558 XSETFRAME (inev.frame_or_window,
8559 mac_window_to_frame (mac_front_window ()));
8560 inev.timestamp = er.when * (1000 / 60); /* ticks to milliseconds */
8561 break;
8563 case kHighLevelEvent:
8564 drag_and_drop_file_list = Qnil;
8566 AEProcessAppleEvent(&er);
8568 /* Build a DRAG_N_DROP_EVENT type event as is done in
8569 constuct_drag_n_drop in w32term.c. */
8570 if (!NILP (drag_and_drop_file_list))
8572 struct frame *f = NULL;
8573 WindowPtr wp;
8574 Lisp_Object frame;
8576 wp = mac_front_window ();
8578 if (!wp)
8580 struct frame *f = XFRAME (XCAR (Vframe_list));
8581 CollapseWindow (FRAME_MAC_WINDOW (f), false);
8582 wp = mac_front_window ();
8585 if (wp && is_emacs_window (wp))
8586 f = mac_window_to_frame (wp);
8588 inev.kind = DRAG_N_DROP_EVENT;
8589 inev.code = 0;
8590 inev.timestamp = er.when * (1000 / 60);
8591 /* ticks to milliseconds */
8592 #if USE_CARBON_EVENTS
8593 inev.modifiers = mac_event_to_emacs_modifiers (eventRef);
8594 #else
8595 inev.modifiers = mac_to_emacs_modifiers (er.modifiers);
8596 #endif
8598 XSETINT (inev.x, 0);
8599 XSETINT (inev.y, 0);
8601 XSETFRAME (frame, f);
8602 inev.frame_or_window = Fcons (frame, drag_and_drop_file_list);
8604 /* Regardless of whether Emacs was suspended or in the
8605 foreground, ask it to redraw its entire screen.
8606 Otherwise parts of the screen can be left in an
8607 inconsistent state. */
8608 if (wp)
8609 #if TARGET_API_MAC_CARBON
8611 Rect r;
8613 GetWindowPortBounds (wp, &r);
8614 InvalWindowRect (wp, &r);
8616 #else /* not TARGET_API_MAC_CARBON */
8617 InvalRect (&(wp->portRect));
8618 #endif /* not TARGET_API_MAC_CARBON */
8620 default:
8621 break;
8623 #if USE_CARBON_EVENTS
8624 ReleaseEvent (eventRef);
8625 #endif
8627 if (inev.kind != NO_EVENT)
8629 kbd_buffer_store_event_hold (&inev, hold_quit);
8630 count++;
8633 if (do_help
8634 && !(hold_quit && hold_quit->kind != NO_EVENT))
8636 Lisp_Object frame;
8638 if (f)
8639 XSETFRAME (frame, f);
8640 else
8641 frame = Qnil;
8643 if (do_help > 0)
8645 any_help_event_p = 1;
8646 gen_help_event (help_echo_string, frame, help_echo_window,
8647 help_echo_object, help_echo_pos);
8649 else
8651 help_echo_string = Qnil;
8652 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
8654 count++;
8659 /* If the focus was just given to an autoraising frame,
8660 raise it now. */
8661 /* ??? This ought to be able to handle more than one such frame. */
8662 if (pending_autoraise_frame)
8664 x_raise_frame (pending_autoraise_frame);
8665 pending_autoraise_frame = 0;
8668 #if !TARGET_API_MAC_CARBON
8669 check_alarm (); /* simulate the handling of a SIGALRM */
8670 #endif
8672 UNBLOCK_INPUT;
8673 return count;
8677 /* Need to override CodeWarrior's input function so no conversion is
8678 done on newlines Otherwise compiled functions in .elc files will be
8679 read incorrectly. Defined in ...:MSL C:MSL
8680 Common:Source:buffer_io.c. */
8681 #ifdef __MWERKS__
8682 void
8683 __convert_to_newlines (unsigned char * p, size_t * n)
8685 #pragma unused(p,n)
8688 void
8689 __convert_from_newlines (unsigned char * p, size_t * n)
8691 #pragma unused(p,n)
8693 #endif
8696 /* Initialize the struct pointed to by MW to represent a new COLS x
8697 ROWS Macintosh window, using font with name FONTNAME and size
8698 FONTSIZE. */
8699 void
8700 make_mac_frame (FRAME_PTR fp)
8702 mac_output *mwp;
8703 #if TARGET_API_MAC_CARBON
8704 static int making_terminal_window = 0;
8705 #else
8706 static int making_terminal_window = 1;
8707 #endif
8709 mwp = fp->output_data.mac;
8711 if (making_terminal_window)
8713 if (!(mwp->mWP = GetNewCWindow (TERM_WINDOW_RESOURCE, NULL,
8714 (WindowPtr) -1)))
8715 abort ();
8716 making_terminal_window = 0;
8718 else
8720 #if TARGET_API_MAC_CARBON
8721 Rect r;
8723 SetRect (&r, 0, 0, 1, 1);
8724 if (CreateNewWindow (kDocumentWindowClass,
8725 kWindowStandardDocumentAttributes
8726 /* | kWindowToolbarButtonAttribute */,
8727 &r, &mwp->mWP) != noErr)
8728 #else
8729 if (!(mwp->mWP = GetNewCWindow (WINDOW_RESOURCE, NULL, (WindowPtr) -1)))
8730 #endif
8731 abort ();
8734 SetWRefCon (mwp->mWP, (long) mwp);
8735 /* so that update events can find this mac_output struct */
8736 mwp->mFP = fp; /* point back to emacs frame */
8738 SetPortWindowPort (mwp->mWP);
8740 SizeWindow (mwp->mWP, FRAME_PIXEL_WIDTH (fp), FRAME_PIXEL_HEIGHT (fp), false);
8744 void
8745 make_mac_terminal_frame (struct frame *f)
8747 Lisp_Object frame;
8749 XSETFRAME (frame, f);
8751 f->output_method = output_mac;
8752 f->output_data.mac = (struct mac_output *)
8753 xmalloc (sizeof (struct mac_output));
8754 bzero (f->output_data.mac, sizeof (struct mac_output));
8756 XSETFRAME (FRAME_KBOARD (f)->Vdefault_minibuffer_frame, f);
8758 FRAME_COLS (f) = 96;
8759 FRAME_LINES (f) = 4;
8761 FRAME_CAN_HAVE_SCROLL_BARS (f) = 1;
8762 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = vertical_scroll_bar_right;
8764 FRAME_DESIRED_CURSOR (f) = FILLED_BOX_CURSOR;
8766 f->output_data.mac->cursor_pixel = 0;
8767 f->output_data.mac->border_pixel = 0x00ff00;
8768 f->output_data.mac->mouse_pixel = 0xff00ff;
8769 f->output_data.mac->cursor_foreground_pixel = 0x0000ff;
8771 FRAME_FONTSET (f) = -1;
8772 f->output_data.mac->explicit_parent = 0;
8773 f->left_pos = 4;
8774 f->top_pos = 4;
8775 f->border_width = 0;
8777 f->internal_border_width = 0;
8779 f->auto_raise = 1;
8780 f->auto_lower = 1;
8782 f->new_text_cols = 0;
8783 f->new_text_lines = 0;
8785 make_mac_frame (f);
8787 x_make_gc (f);
8789 /* Need to be initialized for unshow_buffer in window.c. */
8790 selected_window = f->selected_window;
8792 Fmodify_frame_parameters (frame,
8793 Fcons (Fcons (Qfont,
8794 build_string ("-*-monaco-medium-r-*--*-90-*-*-*-*-mac-roman")), Qnil));
8795 Fmodify_frame_parameters (frame,
8796 Fcons (Fcons (Qforeground_color,
8797 build_string ("black")), Qnil));
8798 Fmodify_frame_parameters (frame,
8799 Fcons (Fcons (Qbackground_color,
8800 build_string ("white")), Qnil));
8802 ShowWindow (f->output_data.mac->mWP);
8806 /***********************************************************************
8807 Initialization
8808 ***********************************************************************/
8810 int mac_initialized = 0;
8812 void
8813 mac_initialize_display_info ()
8815 struct mac_display_info *dpyinfo = &one_mac_display_info;
8816 GDHandle main_device_handle;
8818 bzero (dpyinfo, sizeof (*dpyinfo));
8820 /* Put it on x_display_name_list. */
8821 x_display_name_list = Fcons (Fcons (build_string ("Mac"), Qnil),
8822 x_display_name_list);
8823 dpyinfo->name_list_element = XCAR (x_display_name_list);
8825 #if 0
8826 dpyinfo->mac_id_name
8827 = (char *) xmalloc (SCHARS (Vinvocation_name)
8828 + SCHARS (Vsystem_name)
8829 + 2);
8830 sprintf (dpyinfo->mac_id_name, "%s@%s",
8831 SDATA (Vinvocation_name), SDATA (Vsystem_name));
8832 #else
8833 dpyinfo->mac_id_name = (char *) xmalloc (strlen ("Mac Display") + 1);
8834 strcpy (dpyinfo->mac_id_name, "Mac Display");
8835 #endif
8837 main_device_handle = LMGetMainDevice();
8839 dpyinfo->reference_count = 0;
8840 dpyinfo->resx = 75.0;
8841 dpyinfo->resy = 75.0;
8842 dpyinfo->color_p = TestDeviceAttribute (main_device_handle, gdDevType);
8843 for (dpyinfo->n_planes = 32; dpyinfo->n_planes > 0; dpyinfo->n_planes >>= 1)
8844 if (HasDepth (main_device_handle, dpyinfo->n_planes,
8845 gdDevType, dpyinfo->color_p))
8846 break;
8847 dpyinfo->height = (**main_device_handle).gdRect.bottom;
8848 dpyinfo->width = (**main_device_handle).gdRect.right;
8849 dpyinfo->grabbed = 0;
8850 dpyinfo->root_window = NULL;
8851 dpyinfo->image_cache = make_image_cache ();
8853 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
8854 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
8855 dpyinfo->mouse_face_face_id = DEFAULT_FACE_ID;
8856 dpyinfo->mouse_face_window = Qnil;
8857 dpyinfo->mouse_face_overlay = Qnil;
8858 dpyinfo->mouse_face_hidden = 0;
8861 struct mac_display_info *
8862 mac_term_init (display_name, xrm_option, resource_name)
8863 Lisp_Object display_name;
8864 char *xrm_option;
8865 char *resource_name;
8867 struct mac_display_info *dpyinfo;
8868 GDHandle main_device_handle;
8870 if (!mac_initialized)
8872 mac_initialize ();
8873 mac_initialized = 1;
8876 mac_initialize_display_info (display_name);
8878 dpyinfo = &one_mac_display_info;
8880 main_device_handle = LMGetMainDevice();
8882 dpyinfo->height = (**main_device_handle).gdRect.bottom;
8883 dpyinfo->width = (**main_device_handle).gdRect.right;
8885 return dpyinfo;
8888 #ifdef MAC_OSX
8889 void
8890 mac_check_bundle()
8892 extern int inhibit_window_system;
8893 extern int noninteractive;
8894 CFBundleRef appsBundle;
8895 pid_t child;
8897 /* No need to test if already -nw*/
8898 if (inhibit_window_system || noninteractive)
8899 return;
8901 appsBundle = CFBundleGetMainBundle();
8902 if (appsBundle != NULL)
8904 CFStringRef cfBI = CFSTR("CFBundleIdentifier");
8905 CFTypeRef res = CFBundleGetValueForInfoDictionaryKey(appsBundle, cfBI);
8906 /* We found the bundle identifier, now we know we are valid. */
8907 if (res != NULL)
8909 CFRelease(res);
8910 return;
8913 /* MAC_TODO: Have this start the bundled executable */
8915 /* For now, prevent the fatal error by bringing it up in the terminal */
8916 inhibit_window_system = 1;
8919 void
8920 MakeMeTheFrontProcess ()
8922 ProcessSerialNumber psn;
8923 OSErr err;
8925 err = GetCurrentProcess (&psn);
8926 if (err == noErr)
8927 (void) SetFrontProcess (&psn);
8930 /***** Code to handle C-g testing *****/
8932 /* Contains the Mac modifier formed from quit_char */
8933 static mac_quit_char_modifiers = 0;
8934 static mac_quit_char_keycode;
8935 extern int quit_char;
8937 static void
8938 mac_determine_quit_char_modifiers()
8940 /* Todo: Determine modifiers from quit_char. */
8941 UInt32 qc_modifiers = ctrl_modifier;
8943 /* Map modifiers */
8944 mac_quit_char_modifiers = 0;
8945 if (qc_modifiers & ctrl_modifier) mac_quit_char_modifiers |= macCtrlKey;
8946 if (qc_modifiers & shift_modifier) mac_quit_char_modifiers |= macShiftKey;
8947 if (qc_modifiers & meta_modifier) mac_quit_char_modifiers |= macMetaKey;
8948 if (qc_modifiers & alt_modifier) mac_quit_char_modifiers |= macAltKey;
8951 static void
8952 init_quit_char_handler ()
8954 /* TODO: Let this support keys other the 'g' */
8955 mac_quit_char_keycode = 5;
8956 /* Look at <architecture/adb_kb_map.h> for details */
8957 /* http://gemma.apple.com/techpubs/mac/Toolbox/Toolbox-40.html#MARKER-9-184*/
8959 mac_determine_quit_char_modifiers();
8962 static Boolean
8963 quit_char_comp (EventRef inEvent, void *inCompData)
8965 if (GetEventClass(inEvent) != kEventClassKeyboard)
8966 return false;
8967 if (GetEventKind(inEvent) != kEventRawKeyDown)
8968 return false;
8970 UInt32 keyCode;
8971 UInt32 keyModifiers;
8972 GetEventParameter(inEvent, kEventParamKeyCode,
8973 typeUInt32, NULL, sizeof(UInt32), NULL, &keyCode);
8974 if (keyCode != mac_quit_char_keycode)
8975 return false;
8976 GetEventParameter(inEvent, kEventParamKeyModifiers,
8977 typeUInt32, NULL, sizeof(UInt32), NULL, &keyModifiers);
8978 if (keyModifiers != mac_quit_char_modifiers)
8979 return false;
8981 return true;
8984 void
8985 mac_check_for_quit_char ()
8987 EventRef event;
8988 static EMACS_TIME last_check_time = { 0, 0 };
8989 static EMACS_TIME one_second = { 1, 0 };
8990 EMACS_TIME now, t;
8992 /* If windows are not initialized, return immediately (keep it bouncin'). */
8993 if (!mac_quit_char_modifiers)
8994 return;
8996 /* Don't check if last check is less than a second ago. */
8997 EMACS_GET_TIME (now);
8998 EMACS_SUB_TIME (t, now, last_check_time);
8999 if (EMACS_TIME_LT (t, one_second))
9000 return;
9001 last_check_time = now;
9003 /* Redetermine modifiers because they are based on lisp variables */
9004 mac_determine_quit_char_modifiers ();
9006 /* Fill the queue with events */
9007 BLOCK_INPUT;
9008 ReceiveNextEvent (0, NULL, kEventDurationNoWait, false, &event);
9009 event = FindSpecificEventInQueue (GetMainEventQueue (), quit_char_comp,
9010 NULL);
9011 UNBLOCK_INPUT;
9012 if (event)
9014 struct input_event e;
9016 /* Use an input_event to emulate what the interrupt handler does. */
9017 EVENT_INIT (e);
9018 e.kind = ASCII_KEYSTROKE_EVENT;
9019 e.code = quit_char;
9020 e.arg = Qnil;
9021 e.modifiers = NULL;
9022 e.timestamp = EventTimeToTicks (GetEventTime (event)) * (1000/60);
9023 XSETFRAME (e.frame_or_window, mac_window_to_frame (mac_front_window ()));
9024 /* Remove event from queue to prevent looping. */
9025 RemoveEventFromQueue (GetMainEventQueue (), event);
9026 ReleaseEvent (event);
9027 kbd_buffer_store_event (&e);
9031 #endif /* MAC_OSX */
9033 /* Set up use of X before we make the first connection. */
9035 extern frame_parm_handler mac_frame_parm_handlers[];
9037 static struct redisplay_interface x_redisplay_interface =
9039 mac_frame_parm_handlers,
9040 x_produce_glyphs,
9041 x_write_glyphs,
9042 x_insert_glyphs,
9043 x_clear_end_of_line,
9044 x_scroll_run,
9045 x_after_update_window_line,
9046 x_update_window_begin,
9047 x_update_window_end,
9048 x_cursor_to,
9049 x_flush,
9050 x_flush,
9051 x_clear_window_mouse_face,
9052 x_get_glyph_overhangs,
9053 x_fix_overlapping_area,
9054 x_draw_fringe_bitmap,
9055 0, /* define_fringe_bitmap */
9056 0, /* destroy_fringe_bitmap */
9057 mac_per_char_metric,
9058 mac_encode_char,
9059 NULL, /* mac_compute_glyph_string_overhangs */
9060 x_draw_glyph_string,
9061 mac_define_frame_cursor,
9062 mac_clear_frame_area,
9063 mac_draw_window_cursor,
9064 mac_draw_vertical_window_border,
9065 mac_shift_glyphs_for_insert
9068 void
9069 mac_initialize ()
9071 rif = &x_redisplay_interface;
9073 clear_frame_hook = x_clear_frame;
9074 ins_del_lines_hook = x_ins_del_lines;
9075 delete_glyphs_hook = x_delete_glyphs;
9076 ring_bell_hook = XTring_bell;
9077 reset_terminal_modes_hook = XTreset_terminal_modes;
9078 set_terminal_modes_hook = XTset_terminal_modes;
9079 update_begin_hook = x_update_begin;
9080 update_end_hook = x_update_end;
9081 set_terminal_window_hook = XTset_terminal_window;
9082 read_socket_hook = XTread_socket;
9083 frame_up_to_date_hook = XTframe_up_to_date;
9084 mouse_position_hook = XTmouse_position;
9085 frame_rehighlight_hook = XTframe_rehighlight;
9086 frame_raise_lower_hook = XTframe_raise_lower;
9088 set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
9089 condemn_scroll_bars_hook = XTcondemn_scroll_bars;
9090 redeem_scroll_bar_hook = XTredeem_scroll_bar;
9091 judge_scroll_bars_hook = XTjudge_scroll_bars;
9093 scroll_region_ok = 1; /* we'll scroll partial frames */
9094 char_ins_del_ok = 1;
9095 line_ins_del_ok = 1; /* we'll just blt 'em */
9096 fast_clear_end_of_line = 1; /* X does this well */
9097 memory_below_frame = 0; /* we don't remember what scrolls
9098 off the bottom */
9099 baud_rate = 19200;
9101 x_noop_count = 0;
9102 last_tool_bar_item = -1;
9103 any_help_event_p = 0;
9105 /* Try to use interrupt input; if we can't, then start polling. */
9106 Fset_input_mode (Qt, Qnil, Qt, Qnil);
9108 #ifdef USE_X_TOOLKIT
9109 XtToolkitInitialize ();
9110 Xt_app_con = XtCreateApplicationContext ();
9111 XtAppSetFallbackResources (Xt_app_con, Xt_default_resources);
9113 /* Install an asynchronous timer that processes Xt timeout events
9114 every 0.1s. This is necessary because some widget sets use
9115 timeouts internally, for example the LessTif menu bar, or the
9116 Xaw3d scroll bar. When Xt timouts aren't processed, these
9117 widgets don't behave normally. */
9119 EMACS_TIME interval;
9120 EMACS_SET_SECS_USECS (interval, 0, 100000);
9121 start_atimer (ATIMER_CONTINUOUS, interval, x_process_timeouts, 0);
9123 #endif
9125 #if USE_TOOLKIT_SCROLL_BARS
9126 xaw3d_arrow_scroll = False;
9127 xaw3d_pick_top = True;
9128 #endif
9130 #if 0
9131 /* Note that there is no real way portable across R3/R4 to get the
9132 original error handler. */
9133 XSetErrorHandler (x_error_handler);
9134 XSetIOErrorHandler (x_io_error_quitter);
9136 /* Disable Window Change signals; they are handled by X events. */
9137 #ifdef SIGWINCH
9138 signal (SIGWINCH, SIG_DFL);
9139 #endif /* ! defined (SIGWINCH) */
9141 signal (SIGPIPE, x_connection_signal);
9142 #endif
9144 mac_initialize_display_info ();
9146 #if TARGET_API_MAC_CARBON
9147 init_required_apple_events ();
9149 init_mac_drag_n_drop ();
9151 #if USE_CARBON_EVENTS
9152 init_service_handler ();
9154 init_quit_char_handler ();
9155 #endif
9157 DisableMenuCommand (NULL, kHICommandQuit);
9159 if (!inhibit_window_system)
9160 MakeMeTheFrontProcess ();
9161 #endif
9165 void
9166 syms_of_macterm ()
9168 #if 0
9169 staticpro (&x_error_message_string);
9170 x_error_message_string = Qnil;
9171 #endif
9173 Fprovide (intern ("mac-carbon"), Qnil);
9175 staticpro (&Qreverse);
9176 Qreverse = intern ("reverse");
9178 staticpro (&x_display_name_list);
9179 x_display_name_list = Qnil;
9181 staticpro (&last_mouse_scroll_bar);
9182 last_mouse_scroll_bar = Qnil;
9184 staticpro (&Qvendor_specific_keysyms);
9185 Qvendor_specific_keysyms = intern ("vendor-specific-keysyms");
9187 staticpro (&last_mouse_press_frame);
9188 last_mouse_press_frame = Qnil;
9190 Qmac_ready_for_drag_n_drop = intern ("mac-ready-for-drag-n-drop");
9191 staticpro (&Qmac_ready_for_drag_n_drop);
9193 Qbig5 = intern ("big5");
9194 staticpro (&Qbig5);
9196 Qcn_gb = intern ("cn-gb");
9197 staticpro (&Qcn_gb);
9199 Qsjis = intern ("sjis");
9200 staticpro (&Qsjis);
9202 Qeuc_kr = intern ("euc-kr");
9203 staticpro (&Qeuc_kr);
9205 DEFVAR_BOOL ("x-autoselect-window", &x_autoselect_window_p,
9206 doc: /* *Non-nil means autoselect window with mouse pointer. */);
9207 x_autoselect_window_p = 0;
9209 DEFVAR_LISP ("x-toolkit-scroll-bars", &Vx_toolkit_scroll_bars,
9210 doc: /* If not nil, Emacs uses toolkit scroll bars. */);
9211 Vx_toolkit_scroll_bars = Qt;
9213 DEFVAR_BOOL ("x-use-underline-position-properties",
9214 &x_use_underline_position_properties,
9215 doc: /* *Non-nil means make use of UNDERLINE_POSITION font properties.
9216 nil means ignore them. If you encounter fonts with bogus
9217 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
9218 to 4.1, set this to nil. */);
9219 x_use_underline_position_properties = 0;
9221 staticpro (&last_mouse_motion_frame);
9222 last_mouse_motion_frame = Qnil;
9224 DEFVAR_LISP ("mac-command-key-is-meta", &Vmac_command_key_is_meta,
9225 doc: /* Non-nil means that the command key is used as the Emacs meta key.
9226 Otherwise the option key is used. */);
9227 Vmac_command_key_is_meta = Qt;
9229 DEFVAR_LISP ("mac-reverse-ctrl-meta", &Vmac_reverse_ctrl_meta,
9230 doc: /* Non-nil means that the control and meta keys are reversed. This is
9231 useful for non-standard keyboard layouts. */);
9232 Vmac_reverse_ctrl_meta = Qnil;
9234 DEFVAR_LISP ("mac-emulate-three-button-mouse",
9235 &Vmac_emulate_three_button_mouse,
9236 doc: /* t means that when the option-key is held down while pressing the
9237 mouse button, the click will register as mouse-2 and while the
9238 command-key is held down, the click will register as mouse-3.
9239 'reverse means that the the option-key will register for mouse-3
9240 and the command-key will register for mouse-2. nil means that
9241 not emulation should be done and the modifiers should be placed
9242 on the mouse-1 event. */);
9243 Vmac_emulate_three_button_mouse = Qnil;
9245 #if USE_CARBON_EVENTS
9246 DEFVAR_LISP ("mac-wheel-button-is-mouse-2", &Vmac_wheel_button_is_mouse_2,
9247 doc: /* Non-nil means that the wheel button will be treated as mouse-2 and
9248 the right click will be mouse-3.
9249 Otherwise, the right click will be mouse-2 and the wheel button mouse-3.*/);
9250 Vmac_wheel_button_is_mouse_2 = Qt;
9252 DEFVAR_LISP ("mac-pass-command-to-system", &Vmac_pass_command_to_system,
9253 doc: /* If non-nil, the Mac \"Command\" key is passed on to the Mac
9254 Toolbox for processing before Emacs sees it. */);
9255 Vmac_pass_command_to_system = Qt;
9257 DEFVAR_LISP ("mac-pass-control-to-system", &Vmac_pass_control_to_system,
9258 doc: /* If non-nil, the Mac \"Control\" key is passed on to the Mac
9259 Toolbox for processing before Emacs sees it. */);
9260 Vmac_pass_control_to_system = Qt;
9261 #endif
9263 DEFVAR_INT ("mac-keyboard-text-encoding", &mac_keyboard_text_encoding,
9264 doc: /* One of the Text Encoding Base constant values defined in the
9265 Basic Text Constants section of Inside Macintosh - Text Encoding
9266 Conversion Manager. Its value determines the encoding characters
9267 typed at the Mac keyboard (presumed to be in the MacRoman encoding)
9268 will convert into. E.g., if it is set to kTextEncodingMacRoman (0),
9269 its default value, no conversion takes place. If it is set to
9270 kTextEncodingISOLatin1 (0x201) or kTextEncodingISOLatin2 (0x202),
9271 characters typed on Mac keyboard are first converted into the
9272 ISO Latin-1 or ISO Latin-2 encoding, respectively before being
9273 passed to Emacs. Together with Emacs's set-keyboard-coding-system
9274 command, this enables the Mac keyboard to be used to enter non-ASCII
9275 characters directly. */);
9276 mac_keyboard_text_encoding = kTextEncodingMacRoman;
9279 /* arch-tag: f2259165-4454-4c04-a029-a133c8af7b5b
9280 (do not change this comment) */