3 * \brief OS X front end
5 * Copyright (c) 2011 Peter Ammon
7 * This work is free software; you can redistribute it and/or modify it
8 * under the terms of either:
10 * a) the GNU General Public License as published by the Free Software
11 * Foundation, version 2, or
13 * b) the "Angband licence":
14 * This software may be copied and distributed for educational, research,
15 * and not for profit purposes provided that this copyright and statement
16 * are included in all such copies. Other copyrights may also apply.
20 /* This is not included in angband.h in Hengband. */
23 #if defined(MACH_O_COCOA)
26 #include <cocoa/AppDelegate.h>
27 //#include <Carbon/Carbon.h> /* For keycodes */
28 /* Hack - keycodes to enable compiling in macOS 10.14 */
29 #define kVK_Return 0x24
31 #define kVK_Delete 0x33
32 #define kVK_Escape 0x35
33 #define kVK_ANSI_KeypadEnter 0x4C
35 static NSString * const AngbandDirectoryNameLib = @"lib";
36 static NSString * const AngbandDirectoryNameBase = @"Hengband";
38 static NSString * const AngbandMessageCatalog = @"Localizable";
39 static NSString * const AngbandTerminalsDefaultsKey = @"Terminals";
40 static NSString * const AngbandTerminalRowsDefaultsKey = @"Rows";
41 static NSString * const AngbandTerminalColumnsDefaultsKey = @"Columns";
42 static NSString * const AngbandTerminalVisibleDefaultsKey = @"Visible";
43 static NSString * const AngbandGraphicsDefaultsKey = @"GraphicsID";
44 static NSString * const AngbandFrameRateDefaultsKey = @"FramesPerSecond";
45 static NSString * const AngbandSoundDefaultsKey = @"AllowSound";
46 static NSInteger const AngbandWindowMenuItemTagBase = 1000;
47 static NSInteger const AngbandCommandMenuItemTagBase = 2000;
49 /* We can blit to a large layer or image and then scale it down during live
50 * resize, which makes resizing much faster, at the cost of some image quality
52 #ifndef USE_LIVE_RESIZE_CACHE
53 # define USE_LIVE_RESIZE_CACHE 1
56 /* Global defines etc from Angband 3.5-dev - NRM */
57 #define ANGBAND_TERM_MAX 8
59 static bool new_game = TRUE;
61 #define MAX_COLORS 256
62 #define MSG_MAX SOUND_MAX
64 /* End Angband stuff - NRM */
66 /* Application defined event numbers */
69 AngbandEventWakeup = 1
72 /* Redeclare some 10.7 constants and methods so we can build on 10.6 */
75 Angband_NSWindowCollectionBehaviorFullScreenPrimary = 1 << 7,
76 Angband_NSWindowCollectionBehaviorFullScreenAuxiliary = 1 << 8
79 @interface NSWindow (AngbandLionRedeclares)
80 - (void)setRestorable:(BOOL)flag;
83 /* Delay handling of pre-emptive "quit" event */
84 static BOOL quit_when_ready = FALSE;
86 /* Set to indicate the game is over and we can quit without delay */
87 static Boolean game_is_finished = FALSE;
89 /* Our frames per second (e.g. 60). A value of 0 means unthrottled. */
90 static int frames_per_second;
92 /* Function to get the default font */
93 static NSFont *default_font;
98 * To handle fonts where an individual glyph's bounding box can extend into
99 * neighboring columns, Term_curs_cocoa(), Term_pict_cocoa(),
100 * Term_text_cocoa(), and Term_wipe_cocoa() merely record what needs to be
101 * done with the actual drawing happening in response to the notification to
102 * flush all rows, the TERM_XTRA_FRESH case in Term_xtra_cocoa(). Can not use
103 * the TERM_XTRA_FROSH notification (the per-row flush), since with a software
104 * cursor, there are calls to Term_pict_cocoa(), Term_text_cocoa(), or
105 * Term_wipe_cocoa() to take care of the old cursor position which are not
106 * followed by a row flush.
108 enum PendingCellChangeType {
109 CELL_CHANGE_NONE = 0,
114 struct PendingCellChange {
116 * For text rendering, stores the character as a wchar_t; for tile
117 * rendering, stores the column in the tile set for the source tile.
119 union { wchar_t w; char c; } c;
121 * For text rendering, stores the color; for tile rendering, stores the
122 * row in the tile set for the source tile.
126 * For text rendering, is one if wc is a character that takes up two
127 * columns (i.e. Japanese kanji); otherwise it is zero. For tile
128 * rendering, Stores the column in the tile set for the terrain tile. */
131 * For tile rendering, stores the row in the tile set for the
135 enum PendingCellChangeType change_type;
138 struct PendingRowChange
141 * These are the first and last columns, inclusive, that have been
142 * modified. xmin is greater than xmax if no changes have been made.
146 * This points to storage for a number of elements equal to the number
147 * of columns (implicitly gotten from the enclosing AngbandContext).
149 struct PendingCellChange* cell_changes;
152 static struct PendingRowChange* create_row_change(int ncol)
154 struct PendingRowChange* prc =
155 (struct PendingRowChange*) malloc(sizeof(struct PendingRowChange));
156 struct PendingCellChange* pcc = (struct PendingCellChange*)
157 malloc(ncol * sizeof(struct PendingCellChange));
160 if (prc == 0 || pcc == 0) {
172 prc->cell_changes = pcc;
173 for (i = 0; i < ncol; ++i) {
174 pcc[i].change_type = CELL_CHANGE_NONE;
180 static void destroy_row_change(struct PendingRowChange* prc)
183 if (prc->cell_changes != 0) {
184 free(prc->cell_changes);
191 struct PendingChanges
193 /* Hold the number of rows specified at creation. */
196 * Hold the position set for the software cursor. Use negative indices
197 * to indicate that the cursor is not displayed.
200 /* Is nonzero if the cursor should be drawn at double the tile width. */
202 /* Record whether the changes include any text, picts, or wipes. */
203 int has_text, has_pict, has_wipe;
205 * These are the first and last rows, inclusive, that have been
206 * modified. ymin is greater than ymax if no changes have been made.
210 * This is an array of pointers to the changes. The number of elements
211 * is the number of rows. An element will be a NULL pointer if no
212 * modifications have been made to the row.
214 struct PendingRowChange** rows;
218 static struct PendingChanges* create_pending_changes(int ncol, int nrow)
220 struct PendingChanges* pc =
221 (struct PendingChanges*) malloc(sizeof(struct PendingChanges));
222 struct PendingRowChange** pprc = (struct PendingRowChange**)
223 malloc(nrow * sizeof(struct PendingRowChange*));
226 if (pc == 0 || pprc == 0) {
246 for (i = 0; i < nrow; ++i) {
253 static void destroy_pending_changes(struct PendingChanges* pc)
259 for (i = 0; i < pc->nrow; ++i) {
260 if (pc->rows[i] != 0) {
261 destroy_row_change(pc->rows[i]);
271 static void clear_pending_changes(struct PendingChanges* pc)
284 for (i = 0; i < pc->nrow; ++i) {
285 if (pc->rows[i] != 0) {
286 destroy_row_change(pc->rows[i]);
294 /* Return zero if successful; otherwise return a nonzero value. */
295 static int resize_pending_changes(struct PendingChanges* pc, int nrow)
297 struct PendingRowChange** pprc;
304 pprc = (struct PendingRowChange**)
305 malloc(nrow * sizeof(struct PendingRowChange*));
309 for (i = 0; i < nrow; ++i) {
314 for (i = 0; i < pc->nrow; ++i) {
315 if (pc->rows[i] != 0) {
316 destroy_row_change(pc->rows[i]);
335 /* The max number of glyphs we support. Currently this only affects
336 * updateGlyphInfo() for the calculation of the tile size, fontAscender,
337 * fontDescender, ncol_pre, and ncol_post (the glyphArray and glyphWidths
338 * members of AngbandContext are only used in updateGlyphInfo()). The
339 * rendering in drawWChar will work for glyphs not in updateGlyphInfo()'s
340 * set, and that is used for rendering Japanese characters.
342 #define GLYPH_COUNT 256
344 /* An AngbandContext represents a logical Term (i.e. what Angband thinks is
345 * a window). This typically maps to one NSView, but may map to more than one
346 * NSView (e.g. the Test and real screen saver view). */
347 @interface AngbandContext : NSObject <NSWindowDelegate>
351 /* The Angband term */
354 /* Column and row cont, by default 80 x 24 */
358 /* The size of the border between the window edge and the contents */
361 /* Our array of views */
362 NSMutableArray *angbandViews;
364 /* The buffered image */
365 CGLayerRef angbandLayer;
367 /* The font of this context */
368 NSFont *angbandViewFont;
370 /* If this context owns a window, here it is */
371 NSWindow *primaryWindow;
373 /* "Glyph info": an array of the CGGlyphs and their widths corresponding to
375 CGGlyph glyphArray[GLYPH_COUNT];
376 CGFloat glyphWidths[GLYPH_COUNT];
378 /* The size of one tile */
381 /* Font's ascender and descender */
382 CGFloat fontAscender, fontDescender;
384 /* Whether we are currently in live resize, which affects how big we render
388 /* Last time we drew, so we can throttle drawing */
389 CFAbsoluteTime lastRefreshTime;
391 struct PendingChanges* changes;
393 * These are the number of columns before or after, respectively, a text
394 * change that may need to be redrawn.
396 int ncol_pre, ncol_post;
398 /* Flags whether or not a fullscreen transition is in progress. */
399 BOOL in_fullscreen_transition;
403 BOOL _hasSubwindowFlags;
404 BOOL _windowVisibilityChecked;
407 @property (nonatomic, assign) BOOL hasSubwindowFlags;
408 @property (nonatomic, assign) BOOL windowVisibilityChecked;
410 - (void)drawRect:(NSRect)rect inView:(NSView *)view;
412 /* Called at initialization to set the term */
413 - (void)setTerm:(term *)t;
415 /* Called when the context is going down. */
418 /* Returns the size of the image. */
421 /* Return the rect for a tile at given coordinates. */
422 - (NSRect)rectInImageForTileAtX:(int)x Y:(int)y;
424 /* Draw the given wide character into the given tile rect. */
425 - (void)drawWChar:(wchar_t)wchar inRect:(NSRect)tile context:(CGContextRef)ctx;
427 /* Locks focus on the Angband image, and scales the CTM appropriately. */
428 - (CGContextRef)lockFocus;
430 /* Locks focus on the Angband image but does NOT scale the CTM. Appropriate
431 * for drawing hairlines. */
432 - (CGContextRef)lockFocusUnscaled;
437 /* Returns the primary window for this angband context, creating it if
439 - (NSWindow *)makePrimaryWindow;
441 /* Called to add a new Angband view */
442 - (void)addAngbandView:(AngbandView *)view;
444 /* Make the context aware that one of its views changed size */
445 - (void)angbandViewDidScale:(AngbandView *)view;
447 /* Handle becoming the main window */
448 - (void)windowDidBecomeMain:(NSNotification *)notification;
450 /* Return whether the context's primary window is ordered in or not */
453 /* Return whether the context's primary window is key */
454 - (BOOL)isMainWindow;
456 /* Invalidate the whole image */
457 - (void)setNeedsDisplay:(BOOL)val;
459 /* Invalidate part of the image, with the rect expressed in base coordinates */
460 - (void)setNeedsDisplayInBaseRect:(NSRect)rect;
462 /* Display (flush) our Angband views */
463 - (void)displayIfNeeded;
465 /* Resize context to size of contentRect, and optionally save size to
467 - (void)resizeTerminalWithContentRect: (NSRect)contentRect saveToDefaults: (BOOL)saveToDefaults;
470 * Change the minimum size for the window associated with the context.
471 * If termIdx is not negative, use it as the terminal index (that is useful
472 * if self->terminal has not been set yet). Otherwise, [self terminalIndex]
473 * will be used as the index.
475 - (void)setMinimumWindowSize:(int)termIdx;
477 /* Called from the view to indicate that it is starting or ending live resize */
478 - (void)viewWillStartLiveResize:(AngbandView *)view;
479 - (void)viewDidEndLiveResize:(AngbandView *)view;
480 - (void)saveWindowVisibleToDefaults: (BOOL)windowVisible;
481 - (BOOL)windowVisibleUsingDefaults;
485 /* Begins an Angband game. This is the entry point for starting off. */
488 /* Ends an Angband game. */
491 /* Internal method */
492 - (AngbandView *)activeView;
497 * Generate a mask for the subwindow flags. The mask is just a safety check to
498 * make sure that our windows show and hide as expected. This function allows
499 * for future changes to the set of flags without needed to update it here
500 * (unless the underlying types change).
502 u32b AngbandMaskForValidSubwindowFlags(void)
504 int windowFlagBits = sizeof(*(window_flag)) * CHAR_BIT;
505 int maxBits = MIN( 16, windowFlagBits );
508 for( int i = 0; i < maxBits; i++ )
510 if( window_flag_desc[i] != NULL )
520 * Check for changes in the subwindow flags and update window visibility.
521 * This seems to be called for every user event, so we don't
522 * want to do any unnecessary hiding or showing of windows.
524 static void AngbandUpdateWindowVisibility(void)
526 /* Because this function is called frequently, we'll make the mask static.
527 * It doesn't change between calls, as the flags themselves are hardcoded */
528 static u32b validWindowFlagsMask = 0;
530 if( validWindowFlagsMask == 0 )
532 validWindowFlagsMask = AngbandMaskForValidSubwindowFlags();
535 /* Loop through all of the subwindows and see if there is a change in the
536 * flags. If so, show or hide the corresponding window. We don't care about
537 * the flags themselves; we just want to know if any are set. */
538 for( int i = 1; i < ANGBAND_TERM_MAX; i++ )
540 AngbandContext *angbandContext = angband_term[i]->data;
542 if( angbandContext == nil )
547 /* This horrible mess of flags is so that we can try to maintain some
548 * user visibility preference. This should allow the user a window and
549 * have it stay closed between application launches. However, this
550 * means that when a subwindow is turned on, it will no longer appear
551 * automatically. Angband has no concept of user control over window
552 * visibility, other than the subwindow flags. */
553 if( !angbandContext.windowVisibilityChecked )
555 if( [angbandContext windowVisibleUsingDefaults] )
557 [angbandContext->primaryWindow orderFront: nil];
558 angbandContext.windowVisibilityChecked = YES;
562 [angbandContext->primaryWindow close];
563 angbandContext.windowVisibilityChecked = NO;
568 BOOL termHasSubwindowFlags = ((window_flag[i] & validWindowFlagsMask) > 0);
570 if( angbandContext.hasSubwindowFlags && !termHasSubwindowFlags )
572 [angbandContext->primaryWindow close];
573 angbandContext.hasSubwindowFlags = NO;
574 [angbandContext saveWindowVisibleToDefaults: NO];
576 else if( !angbandContext.hasSubwindowFlags && termHasSubwindowFlags )
578 [angbandContext->primaryWindow orderFront: nil];
579 angbandContext.hasSubwindowFlags = YES;
580 [angbandContext saveWindowVisibleToDefaults: YES];
585 /* Make the main window key so that user events go to the right spot */
586 AngbandContext *mainWindow = angband_term[0]->data;
587 [mainWindow->primaryWindow makeKeyAndOrderFront: nil];
591 * ------------------------------------------------------------------------
593 * ------------------------------------------------------------------------ */
598 static CGImageRef pict_image;
601 * Numbers of rows and columns in a tileset,
602 * calculated by the PICT/PNG loading code
604 static int pict_cols = 0;
605 static int pict_rows = 0;
608 * Requested graphics mode (as a grafID).
609 * The current mode is stored in current_graphics_mode.
611 static int graf_mode_req = 0;
614 * Helper function to check the various ways that graphics can be enabled,
615 * guarding against NULL
617 static BOOL graphics_are_enabled(void)
619 return current_graphics_mode
620 && current_graphics_mode->grafID != GRAPHICS_NONE;
624 * Hack -- game in progress
626 static Boolean game_in_progress = FALSE;
629 #pragma mark Prototypes
630 static void wakeup_event_loop(void);
631 static void hook_plog(const char *str);
632 static void hook_quit(const char * str);
633 static void load_prefs(void);
634 static void load_sounds(void);
635 static void init_windows(void);
636 static void handle_open_when_ready(void);
637 static void play_sound(int event);
638 static BOOL check_events(int wait);
639 static BOOL send_event(NSEvent *event);
640 static void record_current_savefile(void);
642 static wchar_t convert_two_byte_eucjp_to_utf16_native(const char *cp);
646 * Available values for 'wait'
648 #define CHECK_EVENTS_DRAIN -1
649 #define CHECK_EVENTS_NO_WAIT 0
650 #define CHECK_EVENTS_WAIT 1
654 * Note when "open"/"new" become valid
656 static bool initialized = FALSE;
658 /* Methods for getting the appropriate NSUserDefaults */
659 @interface NSUserDefaults (AngbandDefaults)
660 + (NSUserDefaults *)angbandDefaults;
663 @implementation NSUserDefaults (AngbandDefaults)
664 + (NSUserDefaults *)angbandDefaults
666 return [NSUserDefaults standardUserDefaults];
670 /* Methods for pulling images out of the Angband bundle (which may be separate
671 * from the current bundle in the case of a screensaver */
672 @interface NSImage (AngbandImages)
673 + (NSImage *)angbandImage:(NSString *)name;
676 /* The NSView subclass that draws our Angband image */
677 @interface AngbandView : NSView
679 AngbandContext *angbandContext;
682 - (void)setAngbandContext:(AngbandContext *)context;
683 - (AngbandContext *)angbandContext;
687 @implementation NSImage (AngbandImages)
689 /* Returns an image in the resource directoy of the bundle containing the
690 * Angband view class. */
691 + (NSImage *)angbandImage:(NSString *)name
693 NSBundle *bundle = [NSBundle bundleForClass:[AngbandView class]];
694 NSString *path = [bundle pathForImageResource:name];
696 if (path) result = [[[NSImage alloc] initByReferencingFile:path] autorelease];
704 @implementation AngbandContext
706 @synthesize hasSubwindowFlags=_hasSubwindowFlags;
707 @synthesize windowVisibilityChecked=_windowVisibilityChecked;
709 - (NSFont *)selectionFont
711 return angbandViewFont;
714 - (BOOL)useLiveResizeOptimization
716 /* If we have graphics turned off, text rendering is fast enough that we
717 * don't need to use a live resize optimization. */
718 return inLiveResize && graphics_are_enabled();
723 /* We round the base size down. If we round it up, I believe we may end up
724 * with pixels that nobody "owns" that may accumulate garbage. In general
725 * rounding down is harmless, because any lost pixels may be sopped up by
727 return NSMakeSize(floor(cols * tileSize.width + 2 * borderSize.width), floor(rows * tileSize.height + 2 * borderSize.height));
730 /* qsort-compatible compare function for CGSizes */
731 static int compare_advances(const void *ap, const void *bp)
733 const CGSize *a = ap, *b = bp;
734 return (a->width > b->width) - (a->width < b->width);
737 - (void)updateGlyphInfo
739 /* Update glyphArray and glyphWidths */
740 NSFont *screenFont = [angbandViewFont screenFont];
742 /* Generate a string containing each MacRoman character */
743 unsigned char latinString[GLYPH_COUNT];
745 for (i=0; i < GLYPH_COUNT; i++) latinString[i] = (unsigned char)i;
747 /* Turn that into unichar. Angband uses ISO Latin 1. */
748 unichar unicharString[GLYPH_COUNT] = {0};
749 NSString *allCharsString = [[NSString alloc] initWithBytes:latinString length:sizeof latinString encoding:NSISOLatin1StringEncoding];
750 [allCharsString getCharacters:unicharString range:NSMakeRange(0, MIN(GLYPH_COUNT, [allCharsString length]))];
751 [allCharsString autorelease];
754 memset(glyphArray, 0, sizeof glyphArray);
755 CTFontGetGlyphsForCharacters((CTFontRef)screenFont, unicharString, glyphArray, GLYPH_COUNT);
757 /* Get advances. Record the max advance. */
758 CGSize advances[GLYPH_COUNT] = {};
759 CTFontGetAdvancesForGlyphs((CTFontRef)screenFont, kCTFontHorizontalOrientation, glyphArray, advances, GLYPH_COUNT);
760 for (i=0; i < GLYPH_COUNT; i++) {
761 glyphWidths[i] = advances[i].width;
764 /* For good non-mono-font support, use the median advance. Start by sorting
766 qsort(advances, GLYPH_COUNT, sizeof *advances, compare_advances);
768 /* Skip over any initially empty run */
770 for (startIdx = 0; startIdx < GLYPH_COUNT; startIdx++)
772 if (advances[startIdx].width > 0) break;
775 /* Pick the center to find the median */
776 CGFloat medianAdvance = 0;
777 if (startIdx < GLYPH_COUNT)
779 /* In case we have all zero advances for some reason */
780 medianAdvance = advances[(startIdx + GLYPH_COUNT)/2].width;
784 * Record the ascender and descender. Some fonts, for instance DIN
785 * Condensed and Rockwell in 10.14, the ascent on '@' exceeds that
786 * reported by [screenFont ascender]. Get the overall bounding box
787 * for the glyphs and use that instead of the ascender and descender
788 * values if the bounding box result extends farther from the baseline.
790 CGRect bounds = CTFontGetBoundingRectsForGlyphs((CTFontRef) screenFont, kCTFontHorizontalOrientation, glyphArray, NULL, GLYPH_COUNT);
791 fontAscender = [screenFont ascender];
792 if (fontAscender < bounds.origin.y + bounds.size.height) {
793 fontAscender = bounds.origin.y + bounds.size.height;
795 fontDescender = [screenFont descender];
796 if (fontDescender > bounds.origin.y) {
797 fontDescender = bounds.origin.y;
801 * Record the tile size. Round both values up to have tile boundaries
802 * match pixel boundaries.
804 tileSize.width = ceil(medianAdvance);
805 tileSize.height = ceil(fontAscender - fontDescender);
808 * Determine whether neighboring columns need to redrawn when a character
811 CGRect boxes[GLYPH_COUNT] = {};
812 CGFloat beyond_right = 0.;
813 CGFloat beyond_left = 0.;
814 CTFontGetBoundingRectsForGlyphs(
815 (CTFontRef)screenFont,
816 kCTFontHorizontalOrientation,
820 for (i = 0; i < GLYPH_COUNT; i++) {
821 /* Account for the compression and offset used by drawWChar(). */
822 CGFloat compression, offset;
825 if (glyphWidths[i] <= tileSize.width) {
827 offset = 0.5 * (tileSize.width - glyphWidths[i]);
829 compression = tileSize.width / glyphWidths[i];
832 v = (offset + boxes[i].origin.x) * compression;
833 if (beyond_left > v) {
836 v = (offset + boxes[i].origin.x + boxes[i].size.width) * compression;
837 if (beyond_right < v) {
841 ncol_pre = ceil(-beyond_left / tileSize.width);
842 if (beyond_right > tileSize.width) {
843 ncol_post = ceil((beyond_right - tileSize.width) / tileSize.width);
851 NSSize size = NSMakeSize(1, 1);
853 AngbandView *activeView = [self activeView];
856 /* If we are in live resize, draw as big as the screen, so we can scale
857 * nicely to any size. If we are not in live resize, then use the
858 * bounds of the active view. */
860 if ([self useLiveResizeOptimization] && (screen = [[activeView window] screen]) != NULL)
862 size = [screen frame].size;
866 size = [activeView bounds].size;
870 CGLayerRelease(angbandLayer);
872 /* Use the highest monitor scale factor on the system to work out what
873 * scale to draw at - not the recommended method, but works where we
874 * can't easily get the monitor the current draw is occurring on. */
875 float angbandLayerScale = 1.0;
876 if ([[NSScreen mainScreen] respondsToSelector:@selector(backingScaleFactor)]) {
877 for (NSScreen *screen in [NSScreen screens]) {
878 angbandLayerScale = fmax(angbandLayerScale, [screen backingScaleFactor]);
882 /* Make a bitmap context as an example for our layer */
883 CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();
884 CGContextRef exampleCtx = CGBitmapContextCreate(NULL, 1, 1, 8 /* bits per component */, 48 /* bytesPerRow */, cs, kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Host);
885 CGColorSpaceRelease(cs);
887 /* Create the layer at the appropriate size */
888 size.width = fmax(1, ceil(size.width * angbandLayerScale));
889 size.height = fmax(1, ceil(size.height * angbandLayerScale));
890 angbandLayer = CGLayerCreateWithContext(exampleCtx, *(CGSize *)&size, NULL);
892 CFRelease(exampleCtx);
894 /* Set the new context of the layer to draw at the correct scale */
895 CGContextRef ctx = CGLayerGetContext(angbandLayer);
896 CGContextScaleCTM(ctx, angbandLayerScale, angbandLayerScale);
899 [[NSColor blackColor] set];
900 NSRectFill((NSRect){NSZeroPoint, [self baseSize]});
904 - (void)requestRedraw
906 if (! self->terminal) return;
910 /* Activate the term */
911 Term_activate(self->terminal);
913 /* Redraw the contents */
916 /* Flush the output */
919 /* Restore the old term */
923 - (void)setTerm:(term *)t
928 - (void)viewWillStartLiveResize:(AngbandView *)view
930 #if USE_LIVE_RESIZE_CACHE
931 if (inLiveResize < INT_MAX) inLiveResize++;
932 else [NSException raise:NSInternalInconsistencyException format:@"inLiveResize overflow"];
934 if (inLiveResize == 1 && graphics_are_enabled())
938 [self setNeedsDisplay:YES]; /* We'll need to redisplay everything anyways, so avoid creating all those little redisplay rects */
939 [self requestRedraw];
944 - (void)viewDidEndLiveResize:(AngbandView *)view
946 #if USE_LIVE_RESIZE_CACHE
947 if (inLiveResize > 0) inLiveResize--;
948 else [NSException raise:NSInternalInconsistencyException format:@"inLiveResize underflow"];
950 if (inLiveResize == 0 && graphics_are_enabled())
954 [self setNeedsDisplay:YES]; /* We'll need to redisplay everything anyways, so avoid creating all those little redisplay rects */
955 [self requestRedraw];
961 * If we're trying to limit ourselves to a certain number of frames per second,
962 * then compute how long it's been since we last drew, and then wait until the
963 * next frame has passed. */
966 if (frames_per_second > 0)
968 CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
969 CFTimeInterval timeSinceLastRefresh = now - lastRefreshTime;
970 CFTimeInterval timeUntilNextRefresh = (1. / (double)frames_per_second) - timeSinceLastRefresh;
972 if (timeUntilNextRefresh > 0)
974 usleep((unsigned long)(timeUntilNextRefresh * 1000000.));
977 lastRefreshTime = CFAbsoluteTimeGetCurrent();
980 - (void)drawWChar:(wchar_t)wchar inRect:(NSRect)tile context:(CGContextRef)ctx
982 CGFloat tileOffsetY = fontAscender;
983 CGFloat tileOffsetX = 0.0;
984 NSFont *screenFont = [angbandViewFont screenFont];
985 UniChar unicharString[2] = {(UniChar)wchar, 0};
987 /* Get glyph and advance */
988 CGGlyph thisGlyphArray[1] = { 0 };
989 CGSize advances[1] = { { 0, 0 } };
990 CTFontGetGlyphsForCharacters((CTFontRef)screenFont, unicharString, thisGlyphArray, 1);
991 CGGlyph glyph = thisGlyphArray[0];
992 CTFontGetAdvancesForGlyphs((CTFontRef)screenFont, kCTFontHorizontalOrientation, thisGlyphArray, advances, 1);
993 CGSize advance = advances[0];
995 /* If our font is not monospaced, our tile width is deliberately not big
996 * enough for every character. In that event, if our glyph is too wide, we
997 * need to compress it horizontally. Compute the compression ratio.
998 * 1.0 means no compression. */
999 double compressionRatio;
1000 if (advance.width <= NSWidth(tile))
1002 /* Our glyph fits, so we can just draw it, possibly with an offset */
1003 compressionRatio = 1.0;
1004 tileOffsetX = (NSWidth(tile) - advance.width)/2;
1008 /* Our glyph doesn't fit, so we'll have to compress it */
1009 compressionRatio = NSWidth(tile) / advance.width;
1015 CGAffineTransform textMatrix = CGContextGetTextMatrix(ctx);
1016 CGFloat savedA = textMatrix.a;
1018 /* Set the position */
1019 textMatrix.tx = tile.origin.x + tileOffsetX;
1020 textMatrix.ty = tile.origin.y + tileOffsetY;
1022 /* Maybe squish it horizontally. */
1023 if (compressionRatio != 1.)
1025 textMatrix.a *= compressionRatio;
1028 textMatrix = CGAffineTransformScale( textMatrix, 1.0, -1.0 );
1029 CGContextSetTextMatrix(ctx, textMatrix);
1030 CGContextShowGlyphsAtPositions(ctx, &glyph, &CGPointZero, 1);
1032 /* Restore the text matrix if we messed with the compression ratio */
1033 if (compressionRatio != 1.)
1035 textMatrix.a = savedA;
1036 CGContextSetTextMatrix(ctx, textMatrix);
1039 textMatrix = CGAffineTransformScale( textMatrix, 1.0, -1.0 );
1040 CGContextSetTextMatrix(ctx, textMatrix);
1043 /* Lock and unlock focus on our image or layer, setting up the CTM
1045 - (CGContextRef)lockFocusUnscaled
1047 /* Create an NSGraphicsContext representing this CGLayer */
1048 CGContextRef ctx = CGLayerGetContext(angbandLayer);
1049 NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithGraphicsPort:ctx flipped:NO];
1050 [NSGraphicsContext saveGraphicsState];
1051 [NSGraphicsContext setCurrentContext:context];
1052 CGContextSaveGState(ctx);
1058 /* Restore the graphics state */
1059 CGContextRef ctx = [[NSGraphicsContext currentContext] graphicsPort];
1060 CGContextRestoreGState(ctx);
1061 [NSGraphicsContext restoreGraphicsState];
1066 /* Return the size of our layer */
1067 CGSize result = CGLayerGetSize(angbandLayer);
1068 return NSMakeSize(result.width, result.height);
1071 - (CGContextRef)lockFocus
1073 return [self lockFocusUnscaled];
1077 - (NSRect)rectInImageForTileAtX:(int)x Y:(int)y
1080 return NSMakeRect(x * tileSize.width + borderSize.width, flippedY * tileSize.height + borderSize.height, tileSize.width, tileSize.height);
1083 - (void)setSelectionFont:(NSFont*)font adjustTerminal: (BOOL)adjustTerminal
1085 /* Record the new font */
1087 [angbandViewFont release];
1088 angbandViewFont = font;
1090 /* Update our glyph info */
1091 [self updateGlyphInfo];
1093 if( adjustTerminal )
1095 /* Adjust terminal to fit window with new font; save the new columns
1096 * and rows since they could be changed */
1097 NSRect contentRect = [self->primaryWindow contentRectForFrameRect: [self->primaryWindow frame]];
1099 [self setMinimumWindowSize:-1];
1100 NSSize size = self->primaryWindow.contentMinSize;
1101 BOOL windowNeedsResizing = NO;
1102 if (contentRect.size.width < size.width) {
1103 contentRect.size.width = size.width;
1104 windowNeedsResizing = YES;
1106 if (contentRect.size.height < size.height) {
1107 contentRect.size.height = size.height;
1108 windowNeedsResizing = YES;
1110 if (windowNeedsResizing) {
1111 size.width = contentRect.size.width;
1112 size.height = contentRect.size.height;
1113 [self->primaryWindow setContentSize:size];
1115 [self resizeTerminalWithContentRect: contentRect saveToDefaults: YES];
1118 /* Update our image */
1124 if ((self = [super init]))
1126 /* Default rows and cols */
1130 /* Default border size */
1131 self->borderSize = NSMakeSize(2, 2);
1133 /* Allocate our array of views */
1134 angbandViews = [[NSMutableArray alloc] init];
1136 self->changes = create_pending_changes(self->cols, self->rows);
1137 if (self->changes == 0) {
1138 NSLog(@"AngbandContext init: out of memory for pending changes");
1141 self->ncol_post = 0;
1143 self->in_fullscreen_transition = NO;
1145 /* Make the image. Since we have no views, it'll just be a puny 1x1 image. */
1148 _windowVisibilityChecked = NO;
1154 * Destroy all the receiver's stuff. This is intended to be callable more than
1161 /* Disassociate ourselves from our angbandViews */
1162 [angbandViews makeObjectsPerformSelector:@selector(setAngbandContext:) withObject:nil];
1163 [angbandViews release];
1166 /* Destroy the layer/image */
1167 CGLayerRelease(angbandLayer);
1168 angbandLayer = NULL;
1171 [angbandViewFont release];
1172 angbandViewFont = nil;
1175 [primaryWindow setDelegate:nil];
1176 [primaryWindow close];
1177 [primaryWindow release];
1178 primaryWindow = nil;
1180 /* Pending changes */
1181 destroy_pending_changes(self->changes);
1185 /* Usual Cocoa fare */
1195 #pragma mark Directories and Paths Setup
1198 * Return the path for Angband's lib directory and bail if it isn't found. The
1199 * lib directory should be in the bundle's resources directory, since it's
1200 * copied when built.
1202 + (NSString *)libDirectoryPath
1204 NSString *bundleLibPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: AngbandDirectoryNameLib];
1205 BOOL isDirectory = NO;
1206 BOOL libExists = [[NSFileManager defaultManager] fileExistsAtPath: bundleLibPath isDirectory: &isDirectory];
1208 if( !libExists || !isDirectory )
1210 NSLog( @"[%@ %@]: can't find %@/ in bundle: isDirectory: %d libExists: %d", NSStringFromClass( [self class] ), NSStringFromSelector( _cmd ), AngbandDirectoryNameLib, isDirectory, libExists );
1212 NSString *msg = NSLocalizedStringWithDefaultValue(
1213 @"Error.MissingResources",
1214 AngbandMessageCatalog,
1215 [NSBundle mainBundle],
1216 @"Missing Resources",
1217 @"Alert text for missing resources");
1218 NSString *info = NSLocalizedStringWithDefaultValue(
1219 @"Error.MissingAngbandLib",
1220 AngbandMessageCatalog,
1221 [NSBundle mainBundle],
1222 @"Hengband was unable to find required resources and must quit. Please report a bug on the Angband forums.",
1223 @"Alert informative message for missing Angband lib/ folder");
1224 NSString *quit_label = NSLocalizedStringWithDefaultValue(
1225 @"Label.Quit", AngbandMessageCatalog, [NSBundle mainBundle],
1227 NSAlert *alert = [[NSAlert alloc] init];
1230 * Note that NSCriticalAlertStyle was deprecated in 10.10. The
1231 * replacement is NSAlertStyleCritical.
1233 alert.alertStyle = NSCriticalAlertStyle;
1234 alert.messageText = msg;
1235 alert.informativeText = info;
1236 [alert addButtonWithTitle:quit_label];
1237 NSModalResponse result = [alert runModal];
1242 return bundleLibPath;
1246 * Return the path for the directory where Angband should look for its standard
1249 + (NSString *)angbandDocumentsPath
1251 NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
1253 #if defined(SAFE_DIRECTORY)
1254 NSString *versionedDirectory = [NSString stringWithFormat: @"%@-%s", AngbandDirectoryNameBase, VERSION_STRING];
1255 return [documents stringByAppendingPathComponent: versionedDirectory];
1257 return [documents stringByAppendingPathComponent: AngbandDirectoryNameBase];
1262 * Adjust directory paths as needed to correct for any differences needed by
1263 * Angband. \c init_file_paths() currently requires that all paths provided have
1264 * a trailing slash and all other platforms honor this.
1266 * \param originalPath The directory path to adjust.
1267 * \return A path suitable for Angband or nil if an error occurred.
1269 static NSString *AngbandCorrectedDirectoryPath(NSString *originalPath)
1271 if ([originalPath length] == 0) {
1275 if (![originalPath hasSuffix: @"/"]) {
1276 return [originalPath stringByAppendingString: @"/"];
1279 return originalPath;
1283 * Give Angband the base paths that should be used for the various directories
1284 * it needs. It will create any needed directories.
1286 + (void)prepareFilePathsAndDirectories
1288 char libpath[PATH_MAX + 1] = "\0";
1289 NSString *libDirectoryPath = AngbandCorrectedDirectoryPath([self libDirectoryPath]);
1290 [libDirectoryPath getFileSystemRepresentation: libpath maxLength: sizeof(libpath)];
1292 char basepath[PATH_MAX + 1] = "\0";
1293 NSString *angbandDocumentsPath = AngbandCorrectedDirectoryPath([self angbandDocumentsPath]);
1294 [angbandDocumentsPath getFileSystemRepresentation: basepath maxLength: sizeof(basepath)];
1296 init_file_paths(libpath, basepath);
1297 create_needed_dirs();
1303 /* From the Linux mbstowcs(3) man page:
1304 * If dest is NULL, n is ignored, and the conversion proceeds as above,
1305 * except that the converted wide characters are not written out to mem‐
1306 * ory, and that no length limit exists.
1308 static size_t Term_mbcs_cocoa(wchar_t *dest, const char *src, int n)
1313 /* Unicode code point to UTF-8
1314 * 0x0000-0x007f: 0xxxxxxx
1315 * 0x0080-0x07ff: 110xxxxx 10xxxxxx
1316 * 0x0800-0xffff: 1110xxxx 10xxxxxx 10xxxxxx
1317 * 0x10000-0x1fffff: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
1318 * Note that UTF-16 limits Unicode to 0x10ffff. This code is not
1321 for (i = 0; i < n || dest == NULL; i++) {
1322 if ((src[i] & 0x80) == 0) {
1323 if (dest != NULL) dest[count] = src[i];
1324 if (src[i] == 0) break;
1325 } else if ((src[i] & 0xe0) == 0xc0) {
1326 if (dest != NULL) dest[count] =
1327 (((unsigned char)src[i] & 0x1f) << 6)|
1328 ((unsigned char)src[i+1] & 0x3f);
1330 } else if ((src[i] & 0xf0) == 0xe0) {
1331 if (dest != NULL) dest[count] =
1332 (((unsigned char)src[i] & 0x0f) << 12) |
1333 (((unsigned char)src[i+1] & 0x3f) << 6) |
1334 ((unsigned char)src[i+2] & 0x3f);
1336 } else if ((src[i] & 0xf8) == 0xf0) {
1337 if (dest != NULL) dest[count] =
1338 (((unsigned char)src[i] & 0x0f) << 18) |
1339 (((unsigned char)src[i+1] & 0x3f) << 12) |
1340 (((unsigned char)src[i+2] & 0x3f) << 6) |
1341 ((unsigned char)src[i+3] & 0x3f);
1344 /* Found an invalid multibyte sequence */
1354 * Entry point for initializing Angband
1358 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1360 /* Hooks in some "z-util.c" hooks */
1361 plog_aux = hook_plog;
1362 quit_aux = hook_quit;
1364 /* Initialize file paths */
1365 [self prepareFilePathsAndDirectories];
1367 /* Note the "system" */
1368 ANGBAND_SYS = "coc";
1370 /* Load preferences */
1373 /* Load possible graphics modes */
1374 init_graphics_modes();
1376 /* Prepare the windows */
1379 /* Set up game event handlers */
1380 /* init_display(); */
1382 /* Register the sound hook */
1383 /* sound_hook = play_sound; */
1385 /* Initialise game */
1388 /* Initialize some save file stuff */
1389 player_egid = getegid();
1391 /* We are now initialized */
1394 /* Handle "open_when_ready" */
1395 handle_open_when_ready();
1397 /* Handle pending events (most notably update) and flush input */
1400 /* Prompt the user. */
1401 int message_row = (Term->hgt - 23) / 5 + 23;
1402 Term_erase(0, message_row, 255);
1405 "['ファイル' メニューから '新' または '開く' を選択します]",
1406 message_row, (Term->wid - 57) / 2
1408 "[Choose 'New' or 'Open' from the 'File' menu]",
1409 message_row, (Term->wid - 45) / 2
1415 * Play a game -- "new_game" is set by "new", "open" or the open document
1416 * even handler as appropriate
1421 while (!game_in_progress) {
1422 NSAutoreleasePool *splashScreenPool = [[NSAutoreleasePool alloc] init];
1423 NSEvent *event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:[NSDate distantFuture] inMode:NSDefaultRunLoopMode dequeue:YES];
1424 if (event) [NSApp sendEvent:event];
1425 [splashScreenPool drain];
1429 play_game(new_game);
1436 /* Hack -- Forget messages */
1439 p_ptr->playing = FALSE;
1440 p_ptr->leaving = TRUE;
1441 quit_when_ready = TRUE;
1444 - (void)addAngbandView:(AngbandView *)view
1446 if (! [angbandViews containsObject:view])
1448 [angbandViews addObject:view];
1450 [self setNeedsDisplay:YES]; /* We'll need to redisplay everything anyways, so avoid creating all those little redisplay rects */
1451 [self requestRedraw];
1456 * We have this notion of an "active" AngbandView, which is the largest - the
1457 * idea being that in the screen saver, when the user hits Test in System
1458 * Preferences, we don't want to keep driving the AngbandView in the
1459 * background. Our active AngbandView is the widest - that's a hack all right.
1460 * Mercifully when we're just playing the game there's only one view.
1462 - (AngbandView *)activeView
1464 if ([angbandViews count] == 1)
1465 return [angbandViews objectAtIndex:0];
1467 AngbandView *result = nil;
1469 for (AngbandView *angbandView in angbandViews)
1471 float width = [angbandView frame].size.width;
1472 if (width > maxWidth)
1475 result = angbandView;
1481 - (void)angbandViewDidScale:(AngbandView *)view
1483 /* If we're live-resizing with graphics, we're using the live resize
1484 * optimization, so don't update the image. Otherwise do it. */
1485 if (! (inLiveResize && graphics_are_enabled()) && view == [self activeView])
1489 [self setNeedsDisplay:YES]; /*we'll need to redisplay everything anyways, so avoid creating all those little redisplay rects */
1490 [self requestRedraw];
1495 - (void)removeAngbandView:(AngbandView *)view
1497 if ([angbandViews containsObject:view])
1499 [angbandViews removeObject:view];
1501 [self setNeedsDisplay:YES]; /* We'll need to redisplay everything anyways, so avoid creating all those little redisplay rects */
1502 if ([angbandViews count]) [self requestRedraw];
1507 - (NSWindow *)makePrimaryWindow
1509 if (! primaryWindow)
1511 /* This has to be done after the font is set, which it already is in
1512 * term_init_cocoa() */
1513 CGFloat width = self->cols * tileSize.width + borderSize.width * 2.0;
1514 CGFloat height = self->rows * tileSize.height + borderSize.height * 2.0;
1515 NSRect contentRect = NSMakeRect( 0.0, 0.0, width, height );
1517 NSUInteger styleMask = NSTitledWindowMask | NSResizableWindowMask | NSMiniaturizableWindowMask;
1519 /* Make every window other than the main window closable */
1520 if( angband_term[0]->data != self )
1522 styleMask |= NSClosableWindowMask;
1525 primaryWindow = [[NSWindow alloc] initWithContentRect:contentRect styleMask: styleMask backing:NSBackingStoreBuffered defer:YES];
1527 /* Not to be released when closed */
1528 [primaryWindow setReleasedWhenClosed:NO];
1529 [primaryWindow setExcludedFromWindowsMenu: YES]; /* we're using custom window menu handling */
1532 AngbandView *angbandView = [[AngbandView alloc] initWithFrame:contentRect];
1533 [angbandView setAngbandContext:self];
1534 [angbandViews addObject:angbandView];
1535 [primaryWindow setContentView:angbandView];
1536 [angbandView release];
1538 /* We are its delegate */
1539 [primaryWindow setDelegate:self];
1541 /* Update our image, since this is probably the first angband view
1545 return primaryWindow;
1550 #pragma mark View/Window Passthrough
1553 * This is what our views call to get us to draw to the window
1555 - (void)drawRect:(NSRect)rect inView:(NSView *)view
1557 /* Take this opportunity to throttle so we don't flush faster than desired.
1559 BOOL viewInLiveResize = [view inLiveResize];
1560 if (! viewInLiveResize) [self throttle];
1562 /* With a GLayer, use CGContextDrawLayerInRect */
1563 CGContextRef context = [[NSGraphicsContext currentContext] graphicsPort];
1564 NSRect bounds = [view bounds];
1565 if (viewInLiveResize) CGContextSetInterpolationQuality(context, kCGInterpolationLow);
1566 CGContextSetBlendMode(context, kCGBlendModeCopy);
1567 CGContextDrawLayerInRect(context, *(CGRect *)&bounds, angbandLayer);
1568 if (viewInLiveResize) CGContextSetInterpolationQuality(context, kCGInterpolationDefault);
1573 return [[[angbandViews lastObject] window] isVisible];
1576 - (BOOL)isMainWindow
1578 return [[[angbandViews lastObject] window] isMainWindow];
1581 - (void)setNeedsDisplay:(BOOL)val
1583 for (NSView *angbandView in angbandViews)
1585 [angbandView setNeedsDisplay:val];
1589 - (void)setNeedsDisplayInBaseRect:(NSRect)rect
1591 for (NSView *angbandView in angbandViews)
1593 [angbandView setNeedsDisplayInRect: rect];
1597 - (void)displayIfNeeded
1599 [[self activeView] displayIfNeeded];
1602 - (int)terminalIndex
1606 for( termIndex = 0; termIndex < ANGBAND_TERM_MAX; termIndex++ )
1608 if( angband_term[termIndex] == self->terminal )
1617 - (void)resizeTerminalWithContentRect: (NSRect)contentRect saveToDefaults: (BOOL)saveToDefaults
1619 CGFloat newRows = floor( (contentRect.size.height - (borderSize.height * 2.0)) / tileSize.height );
1620 CGFloat newColumns = ceil( (contentRect.size.width - (borderSize.width * 2.0)) / tileSize.width );
1622 if (newRows < 1 || newColumns < 1) return;
1623 self->cols = newColumns;
1624 self->rows = newRows;
1626 if (resize_pending_changes(self->changes, self->rows) != 0) {
1627 destroy_pending_changes(self->changes);
1629 NSLog(@"out of memory for pending changes with resize of terminal %d",
1630 [self terminalIndex]);
1633 if( saveToDefaults )
1635 int termIndex = [self terminalIndex];
1636 NSArray *terminals = [[NSUserDefaults standardUserDefaults] valueForKey: AngbandTerminalsDefaultsKey];
1638 if( termIndex < (int)[terminals count] )
1640 NSMutableDictionary *mutableTerm = [[NSMutableDictionary alloc] initWithDictionary: [terminals objectAtIndex: termIndex]];
1641 [mutableTerm setValue: [NSNumber numberWithUnsignedInt: self->cols] forKey: AngbandTerminalColumnsDefaultsKey];
1642 [mutableTerm setValue: [NSNumber numberWithUnsignedInt: self->rows] forKey: AngbandTerminalRowsDefaultsKey];
1644 NSMutableArray *mutableTerminals = [[NSMutableArray alloc] initWithArray: terminals];
1645 [mutableTerminals replaceObjectAtIndex: termIndex withObject: mutableTerm];
1647 [[NSUserDefaults standardUserDefaults] setValue: mutableTerminals forKey: AngbandTerminalsDefaultsKey];
1648 [mutableTerminals release];
1649 [mutableTerm release];
1651 [[NSUserDefaults standardUserDefaults] synchronize];
1655 Term_activate( self->terminal );
1656 Term_resize( (int)newColumns, (int)newRows);
1658 Term_activate( old );
1661 - (void)setMinimumWindowSize:(int)termIdx
1666 termIdx = [self terminalIndex];
1670 minsize.height = 24;
1676 minsize.width * self->tileSize.width + self->borderSize.width * 2.0;
1678 minsize.height * self->tileSize.height + self->borderSize.height * 2.0;
1679 [[self makePrimaryWindow] setContentMinSize:minsize];
1682 - (void)saveWindowVisibleToDefaults: (BOOL)windowVisible
1684 int termIndex = [self terminalIndex];
1685 BOOL safeVisibility = (termIndex == 0) ? YES : windowVisible; /* Ensure main term doesn't go away because of these defaults */
1686 NSArray *terminals = [[NSUserDefaults standardUserDefaults] valueForKey: AngbandTerminalsDefaultsKey];
1688 if( termIndex < (int)[terminals count] )
1690 NSMutableDictionary *mutableTerm = [[NSMutableDictionary alloc] initWithDictionary: [terminals objectAtIndex: termIndex]];
1691 [mutableTerm setValue: [NSNumber numberWithBool: safeVisibility] forKey: AngbandTerminalVisibleDefaultsKey];
1693 NSMutableArray *mutableTerminals = [[NSMutableArray alloc] initWithArray: terminals];
1694 [mutableTerminals replaceObjectAtIndex: termIndex withObject: mutableTerm];
1696 [[NSUserDefaults standardUserDefaults] setValue: mutableTerminals forKey: AngbandTerminalsDefaultsKey];
1697 [mutableTerminals release];
1698 [mutableTerm release];
1702 - (BOOL)windowVisibleUsingDefaults
1704 int termIndex = [self terminalIndex];
1706 if( termIndex == 0 )
1711 NSArray *terminals = [[NSUserDefaults standardUserDefaults] valueForKey: AngbandTerminalsDefaultsKey];
1714 if( termIndex < (int)[terminals count] )
1716 NSDictionary *term = [terminals objectAtIndex: termIndex];
1717 NSNumber *visibleValue = [term valueForKey: AngbandTerminalVisibleDefaultsKey];
1719 if( visibleValue != nil )
1721 visible = [visibleValue boolValue];
1729 #pragma mark NSWindowDelegate Methods
1731 /*- (void)windowWillStartLiveResize: (NSNotification *)notification
1735 - (void)windowDidEndLiveResize: (NSNotification *)notification
1737 NSWindow *window = [notification object];
1738 NSRect contentRect = [window contentRectForFrameRect: [window frame]];
1739 [self resizeTerminalWithContentRect: contentRect saveToDefaults: !(self->in_fullscreen_transition)];
1742 /*- (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
1746 - (void)windowWillEnterFullScreen: (NSNotification *)notification
1748 self->in_fullscreen_transition = YES;
1751 - (void)windowDidEnterFullScreen: (NSNotification *)notification
1753 NSWindow *window = [notification object];
1754 NSRect contentRect = [window contentRectForFrameRect: [window frame]];
1755 self->in_fullscreen_transition = NO;
1756 [self resizeTerminalWithContentRect: contentRect saveToDefaults: NO];
1759 - (void)windowWillExitFullScreen: (NSNotification *)notification
1761 self->in_fullscreen_transition = YES;
1764 - (void)windowDidExitFullScreen: (NSNotification *)notification
1766 NSWindow *window = [notification object];
1767 NSRect contentRect = [window contentRectForFrameRect: [window frame]];
1768 self->in_fullscreen_transition = NO;
1769 [self resizeTerminalWithContentRect: contentRect saveToDefaults: NO];
1772 - (void)windowDidBecomeMain:(NSNotification *)notification
1774 NSWindow *window = [notification object];
1776 if( window != self->primaryWindow )
1781 int termIndex = [self terminalIndex];
1782 NSMenuItem *item = [[[NSApplication sharedApplication] windowsMenu] itemWithTag: AngbandWindowMenuItemTagBase + termIndex];
1783 [item setState: NSOnState];
1785 if( [[NSFontPanel sharedFontPanel] isVisible] )
1787 [[NSFontPanel sharedFontPanel] setPanelFont: [self selectionFont] isMultiple: NO];
1791 - (void)windowDidResignMain: (NSNotification *)notification
1793 NSWindow *window = [notification object];
1795 if( window != self->primaryWindow )
1800 int termIndex = [self terminalIndex];
1801 NSMenuItem *item = [[[NSApplication sharedApplication] windowsMenu] itemWithTag: AngbandWindowMenuItemTagBase + termIndex];
1802 [item setState: NSOffState];
1805 - (void)windowWillClose: (NSNotification *)notification
1807 [self saveWindowVisibleToDefaults: NO];
1813 @implementation AngbandView
1825 - (void)drawRect:(NSRect)rect
1827 if (! angbandContext)
1829 /* Draw bright orange, 'cause this ain't right */
1830 [[NSColor orangeColor] set];
1831 NSRectFill([self bounds]);
1835 /* Tell the Angband context to draw into us */
1836 [angbandContext drawRect:rect inView:self];
1840 - (void)setAngbandContext:(AngbandContext *)context
1842 angbandContext = context;
1845 - (AngbandContext *)angbandContext
1847 return angbandContext;
1850 - (void)setFrameSize:(NSSize)size
1852 BOOL changed = ! NSEqualSizes(size, [self frame].size);
1853 [super setFrameSize:size];
1854 if (changed) [angbandContext angbandViewDidScale:self];
1857 - (void)viewWillStartLiveResize
1859 [angbandContext viewWillStartLiveResize:self];
1862 - (void)viewDidEndLiveResize
1864 [angbandContext viewDidEndLiveResize:self];
1870 * Delay handling of double-clicked savefiles
1872 Boolean open_when_ready = FALSE;
1877 * ------------------------------------------------------------------------
1878 * Some generic functions
1879 * ------------------------------------------------------------------------ */
1882 * Sets an Angband color at a given index
1884 static void set_color_for_index(int idx)
1888 /* Extract the R,G,B data */
1889 rv = angband_color_table[idx][1];
1890 gv = angband_color_table[idx][2];
1891 bv = angband_color_table[idx][3];
1893 CGContextSetRGBFillColor([[NSGraphicsContext currentContext] graphicsPort], rv/255., gv/255., bv/255., 1.);
1897 * Remember the current character in UserDefaults so we can select it by
1898 * default next time.
1900 static void record_current_savefile(void)
1902 NSString *savefileString = [[NSString stringWithCString:savefile encoding:NSMacOSRomanStringEncoding] lastPathComponent];
1905 NSUserDefaults *angbandDefs = [NSUserDefaults angbandDefaults];
1906 [angbandDefs setObject:savefileString forKey:@"SaveFile"];
1907 [angbandDefs synchronize];
1914 * Convert a two-byte EUC-JP encoded character (both *cp and (*cp + 1) are in
1915 * the range, 0xA1-0xFE, or *cp is 0x8E) to a utf16 value in the native byte
1918 static wchar_t convert_two_byte_eucjp_to_utf16_native(const char *cp)
1920 NSString* str = [[NSString alloc] initWithBytes:cp length:2
1921 encoding:NSJapaneseEUCStringEncoding];
1922 wchar_t result = [str characterAtIndex:0];
1931 * ------------------------------------------------------------------------
1932 * Support for the "z-term.c" package
1933 * ------------------------------------------------------------------------ */
1937 * Initialize a new Term
1939 static void Term_init_cocoa(term *t)
1941 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1942 AngbandContext *context = [[AngbandContext alloc] init];
1944 /* Give the term a hard retain on context (for GC) */
1945 t->data = (void *)CFRetain(context);
1948 /* Handle graphics */
1949 t->higher_pict = !! use_graphics;
1950 t->always_pict = FALSE;
1952 NSDisableScreenUpdates();
1954 /* Figure out the frame autosave name based on the index of this term */
1955 NSString *autosaveName = nil;
1957 for (termIdx = 0; termIdx < ANGBAND_TERM_MAX; termIdx++)
1959 if (angband_term[termIdx] == t)
1961 autosaveName = [NSString stringWithFormat:@"AngbandTerm-%d", termIdx];
1967 NSString *fontName = [[NSUserDefaults angbandDefaults] stringForKey:[NSString stringWithFormat:@"FontName-%d", termIdx]];
1968 if (! fontName) fontName = [default_font fontName];
1970 /* Use a smaller default font for the other windows, but only if the font
1971 * hasn't been explicitly set */
1972 float fontSize = (termIdx > 0) ? 10.0 : [default_font pointSize];
1973 NSNumber *fontSizeNumber = [[NSUserDefaults angbandDefaults] valueForKey: [NSString stringWithFormat: @"FontSize-%d", termIdx]];
1975 if( fontSizeNumber != nil )
1977 fontSize = [fontSizeNumber floatValue];
1980 [context setSelectionFont:[NSFont fontWithName:fontName size:fontSize] adjustTerminal: NO];
1982 NSArray *terminalDefaults = [[NSUserDefaults standardUserDefaults] valueForKey: AngbandTerminalsDefaultsKey];
1983 NSInteger rows = 24;
1984 NSInteger columns = 80;
1986 if( termIdx < (int)[terminalDefaults count] )
1988 NSDictionary *term = [terminalDefaults objectAtIndex: termIdx];
1989 NSInteger defaultRows = [[term valueForKey: AngbandTerminalRowsDefaultsKey] integerValue];
1990 NSInteger defaultColumns = [[term valueForKey: AngbandTerminalColumnsDefaultsKey] integerValue];
1992 if (defaultRows > 0) rows = defaultRows;
1993 if (defaultColumns > 0) columns = defaultColumns;
1996 context->cols = columns;
1997 context->rows = rows;
1999 if (resize_pending_changes(context->changes, context->rows) != 0) {
2000 destroy_pending_changes(context->changes);
2001 context->changes = 0;
2002 NSLog(@"initializing terminal %d: out of memory for pending changes",
2006 /* Get the window */
2007 NSWindow *window = [context makePrimaryWindow];
2009 /* Set its title and, for auxiliary terms, tentative size */
2010 NSString *title = [NSString stringWithCString:angband_term_name[termIdx]
2012 encoding:NSJapaneseEUCStringEncoding
2014 encoding:NSMacOSRomanStringEncoding
2017 [window setTitle:title];
2018 [context setMinimumWindowSize:termIdx];
2020 /* If this is the first term, and we support full screen (Mac OS X Lion or
2021 * later), then allow it to go full screen (sweet). Allow other terms to be
2022 * FullScreenAuxilliary, so they can at least show up. Unfortunately in
2023 * Lion they don't get brought to the full screen space; but they would
2024 * only make sense on multiple displays anyways so it's not a big loss. */
2025 if ([window respondsToSelector:@selector(toggleFullScreen:)])
2027 NSWindowCollectionBehavior behavior = [window collectionBehavior];
2028 behavior |= (termIdx == 0 ? Angband_NSWindowCollectionBehaviorFullScreenPrimary : Angband_NSWindowCollectionBehaviorFullScreenAuxiliary);
2029 [window setCollectionBehavior:behavior];
2032 /* No Resume support yet, though it would not be hard to add */
2033 if ([window respondsToSelector:@selector(setRestorable:)])
2035 [window setRestorable:NO];
2038 /* default window placement */ {
2039 static NSRect overallBoundingRect;
2043 /* This is a bit of a trick to allow us to display multiple windows
2044 * in the "standard default" window position in OS X: the upper
2045 * center of the screen.
2046 * The term sizes set in load_prefs() are based on a 5-wide by
2047 * 3-high grid, with the main term being 4/5 wide by 2/3 high
2048 * (hence the scaling to find */
2050 /* What the containing rect would be). */
2051 NSRect originalMainTermFrame = [window frame];
2052 NSRect scaledFrame = originalMainTermFrame;
2053 scaledFrame.size.width *= 5.0 / 4.0;
2054 scaledFrame.size.height *= 3.0 / 2.0;
2055 scaledFrame.size.width += 1.0; /* spacing between window columns */
2056 scaledFrame.size.height += 1.0; /* spacing between window rows */
2057 [window setFrame: scaledFrame display: NO];
2059 overallBoundingRect = [window frame];
2060 [window setFrame: originalMainTermFrame display: NO];
2063 static NSRect mainTermBaseRect;
2064 NSRect windowFrame = [window frame];
2068 /* The height and width adjustments were determined experimentally,
2069 * so that the rest of the windows line up nicely without
2071 windowFrame.size.width += 7.0;
2072 windowFrame.size.height += 9.0;
2073 windowFrame.origin.x = NSMinX( overallBoundingRect );
2074 windowFrame.origin.y = NSMaxY( overallBoundingRect ) - NSHeight( windowFrame );
2075 mainTermBaseRect = windowFrame;
2077 else if( termIdx == 1 )
2079 windowFrame.origin.x = NSMinX( mainTermBaseRect );
2080 windowFrame.origin.y = NSMinY( mainTermBaseRect ) - NSHeight( windowFrame ) - 1.0;
2082 else if( termIdx == 2 )
2084 windowFrame.origin.x = NSMaxX( mainTermBaseRect ) + 1.0;
2085 windowFrame.origin.y = NSMaxY( mainTermBaseRect ) - NSHeight( windowFrame );
2087 else if( termIdx == 3 )
2089 windowFrame.origin.x = NSMaxX( mainTermBaseRect ) + 1.0;
2090 windowFrame.origin.y = NSMinY( mainTermBaseRect ) - NSHeight( windowFrame ) - 1.0;
2092 else if( termIdx == 4 )
2094 windowFrame.origin.x = NSMaxX( mainTermBaseRect ) + 1.0;
2095 windowFrame.origin.y = NSMinY( mainTermBaseRect );
2097 else if( termIdx == 5 )
2099 windowFrame.origin.x = NSMinX( mainTermBaseRect ) + NSWidth( windowFrame ) + 1.0;
2100 windowFrame.origin.y = NSMinY( mainTermBaseRect ) - NSHeight( windowFrame ) - 1.0;
2103 [window setFrame: windowFrame display: NO];
2106 /* Override the default frame above if the user has adjusted windows in
2108 if (autosaveName) [window setFrameAutosaveName:autosaveName];
2110 /* Tell it about its term. Do this after we've sized it so that the sizing
2111 * doesn't trigger redrawing and such. */
2112 [context setTerm:t];
2114 /* Only order front if it's the first term. Other terms will be ordered
2115 * front from AngbandUpdateWindowVisibility(). This is to work around a
2116 * problem where Angband aggressively tells us to initialize terms that
2117 * don't do anything! */
2118 if (t == angband_term[0]) [context->primaryWindow makeKeyAndOrderFront: nil];
2120 NSEnableScreenUpdates();
2122 /* Set "mapped" flag */
2123 t->mapped_flag = true;
2132 static void Term_nuke_cocoa(term *t)
2134 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
2136 AngbandContext *context = t->data;
2139 /* Tell the context to get rid of its windows, etc. */
2142 /* Balance our CFRetain from when we created it */
2153 * Returns the CGImageRef corresponding to an image with the given name in the
2154 * resource directory, transferring ownership to the caller
2156 static CGImageRef create_angband_image(NSString *path)
2158 CGImageRef decodedImage = NULL, result = NULL;
2160 /* Try using ImageIO to load the image */
2163 NSURL *url = [[NSURL alloc] initFileURLWithPath:path isDirectory:NO];
2166 NSDictionary *options = [[NSDictionary alloc] initWithObjectsAndKeys:(id)kCFBooleanTrue, kCGImageSourceShouldCache, nil];
2167 CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)url, (CFDictionaryRef)options);
2170 /* We really want the largest image, but in practice there's
2171 * only going to be one */
2172 decodedImage = CGImageSourceCreateImageAtIndex(source, 0, (CFDictionaryRef)options);
2180 /* Draw the sucker to defeat ImageIO's weird desire to cache and decode on
2181 * demand. Our images aren't that big! */
2184 size_t width = CGImageGetWidth(decodedImage), height = CGImageGetHeight(decodedImage);
2186 /* Compute our own bitmap info */
2187 CGBitmapInfo imageBitmapInfo = CGImageGetBitmapInfo(decodedImage);
2188 CGBitmapInfo contextBitmapInfo = kCGBitmapByteOrderDefault;
2190 switch (imageBitmapInfo & kCGBitmapAlphaInfoMask) {
2191 case kCGImageAlphaNone:
2192 case kCGImageAlphaNoneSkipLast:
2193 case kCGImageAlphaNoneSkipFirst:
2195 contextBitmapInfo |= kCGImageAlphaNone;
2198 /* Some alpha, use premultiplied last which is most efficient. */
2199 contextBitmapInfo |= kCGImageAlphaPremultipliedLast;
2203 /* Draw the source image flipped, since the view is flipped */
2204 CGContextRef ctx = CGBitmapContextCreate(NULL, width, height, CGImageGetBitsPerComponent(decodedImage), CGImageGetBytesPerRow(decodedImage), CGImageGetColorSpace(decodedImage), contextBitmapInfo);
2205 CGContextSetBlendMode(ctx, kCGBlendModeCopy);
2206 CGContextTranslateCTM(ctx, 0.0, height);
2207 CGContextScaleCTM(ctx, 1.0, -1.0);
2208 CGContextDrawImage(ctx, CGRectMake(0, 0, width, height), decodedImage);
2209 result = CGBitmapContextCreateImage(ctx);
2211 /* Done with these things */
2213 CGImageRelease(decodedImage);
2221 static errr Term_xtra_cocoa_react(void)
2223 /* Don't actually switch graphics until the game is running */
2224 if (!initialized || !game_in_progress) return (-1);
2226 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
2227 AngbandContext *angbandContext = Term->data;
2229 /* Handle graphics */
2230 int expected_graf_mode = (current_graphics_mode) ?
2231 current_graphics_mode->grafID : GRAPHICS_NONE;
2232 if (graf_mode_req != expected_graf_mode)
2234 graphics_mode *new_mode;
2235 if (graf_mode_req != GRAPHICS_NONE) {
2236 new_mode = get_graphics_mode(graf_mode_req);
2241 /* Get rid of the old image. CGImageRelease is NULL-safe. */
2242 CGImageRelease(pict_image);
2245 /* Try creating the image if we want one */
2246 if (new_mode != NULL)
2248 NSString *img_path = [NSString stringWithFormat:@"%s/%s", new_mode->path, new_mode->file];
2249 pict_image = create_angband_image(img_path);
2251 /* If we failed to create the image, set the new desired mode to
2257 /* Record what we did */
2258 use_graphics = new_mode ? new_mode->grafID : 0;
2259 ANGBAND_GRAF = (new_mode ? new_mode->graf : "ascii");
2260 current_graphics_mode = new_mode;
2262 /* Enable or disable higher picts. Note: this should be done for all
2264 angbandContext->terminal->higher_pict = !! use_graphics;
2266 if (pict_image && current_graphics_mode)
2268 /* Compute the row and column count via the image height and width.
2270 pict_rows = (int)(CGImageGetHeight(pict_image) / current_graphics_mode->cell_height);
2271 pict_cols = (int)(CGImageGetWidth(pict_image) / current_graphics_mode->cell_width);
2280 if (initialized && game_in_progress)
2294 * Draws one tile as a helper function for Term_xtra_cocoa_fresh().
2296 static void draw_image_tile(
2297 NSGraphicsContext* nsContext,
2298 CGContextRef cgContext,
2302 NSCompositingOperation op)
2304 /* Flip the source rect since the source image is flipped */
2305 CGAffineTransform flip = CGAffineTransformIdentity;
2306 flip = CGAffineTransformTranslate(flip, 0.0, CGImageGetHeight(image));
2307 flip = CGAffineTransformScale(flip, 1.0, -1.0);
2308 CGRect flippedSourceRect =
2309 CGRectApplyAffineTransform(NSRectToCGRect(srcRect), flip);
2312 * When we use high-quality resampling to draw a tile, pixels from outside
2313 * the tile may bleed in, causing graphics artifacts. Work around that.
2315 CGImageRef subimage =
2316 CGImageCreateWithImageInRect(image, flippedSourceRect);
2317 [nsContext setCompositingOperation:op];
2318 CGContextDrawImage(cgContext, NSRectToCGRect(dstRect), subimage);
2319 CGImageRelease(subimage);
2324 * This is a helper function for Term_xtra_cocoa_fresh(): look before a block
2325 * of text on a row to see if the bounds for rendering and clipping need to be
2328 static void query_before_text(
2329 struct PendingRowChange* prc, int iy, int npre, int* pclip, int* prend)
2335 if (i < 0 || i < start - npre) {
2339 if (prc->cell_changes[i].change_type == CELL_CHANGE_PICT) {
2341 * The cell has been rendered with a tile. Do not want to modify
2342 * its contents so the clipping and rendering region can not be
2346 } else if (prc->cell_changes[i].change_type == CELL_CHANGE_NONE) {
2347 /* It has not changed so inquire what it is. */
2351 Term_what(i, iy, a + 1, c + 1);
2352 if (use_graphics && (a[1] & 0x80) && (c[1] & 0x80)) {
2354 * It is an unchanged location rendered with a tile. Do not
2355 * want to modify its contents so the clipping and rendering
2356 * region can not be extended.
2361 * It is unchanged text. A character from the changed region
2362 * may have extended into it so render it to clear that.
2365 /* Check to see if it is the second part of a kanji character. */
2367 Term_what(i - 1, iy, a, c);
2369 prc->cell_changes[i - 1].c.w =
2370 convert_two_byte_eucjp_to_utf16_native(c);
2371 prc->cell_changes[i - 1].a = a[0];
2372 prc->cell_changes[i - 1].tcol = 1;
2373 prc->cell_changes[i].c.w = 0;
2374 prc->cell_changes[i].a = a[0];
2375 prc->cell_changes[i].tcol = 0;
2380 prc->cell_changes[i].c.w = c[1];
2381 prc->cell_changes[i].a = a[1];
2382 prc->cell_changes[i].tcol = 0;
2387 prc->cell_changes[i].c.w = c[1];
2388 prc->cell_changes[i].a = a[1];
2389 prc->cell_changes[i].tcol = 0;
2394 prc->cell_changes[i].c.w = c[1];
2395 prc->cell_changes[i].a = a[1];
2396 prc->cell_changes[i].tcol = 0;
2403 * The cell has been wiped or had changed text rendered. Do
2404 * not need to render. Can extend the clipping rectangle into it.
2414 * This is a helper function for Term_xtra_cocoa_fresh(): look after a block
2415 * of text on a row to see if the bounds for rendering and clipping need to be
2418 static void query_after_text(
2419 struct PendingRowChange* prc,
2431 * Be willing to consolidate this block with the one after it. This
2432 * logic should be sufficient to avoid redraws of the region between
2433 * changed blocks of text if angbandContext->ncol_pre is zero or one.
2434 * For larger values of ncol_pre, would need to do something more to
2435 * avoid extra redraws.
2439 prc->cell_changes[i].change_type != CELL_CHANGE_TEXT &&
2440 prc->cell_changes[i].change_type != CELL_CHANGE_WIPE)) {
2444 if (prc->cell_changes[i].change_type == CELL_CHANGE_PICT) {
2446 * The cell has been rendered with a tile. Do not want to modify
2447 * its contents so the clipping and rendering region can not be
2451 } else if (prc->cell_changes[i].change_type == CELL_CHANGE_NONE) {
2452 /* It has not changed so inquire what it is. */
2456 Term_what(i, iy, a, c);
2457 if (use_graphics && (a[0] & 0x80) && (c[0] & 0x80)) {
2459 * It is an unchanged location rendered with a tile. Do not
2460 * want to modify its contents so the clipping and rendering
2461 * region can not be extended.
2466 * It is unchanged text. A character from the changed region
2467 * may have extended into it so render it to clear that.
2470 /* Check to see if it is the first part of a kanji character. */
2472 Term_what(i + 1, iy, a + 1, c + 1);
2474 prc->cell_changes[i].c.w =
2475 convert_two_byte_eucjp_to_utf16_native(c);
2476 prc->cell_changes[i].a = a[0];
2477 prc->cell_changes[i].tcol = 1;
2478 prc->cell_changes[i + 1].c.w = 0;
2479 prc->cell_changes[i + 1].a = a[0];
2480 prc->cell_changes[i + 1].tcol = 0;
2485 prc->cell_changes[i].c.w = c[0];
2486 prc->cell_changes[i].a = a[0];
2487 prc->cell_changes[i].tcol = 0;
2492 prc->cell_changes[i].c.w = c[0];
2493 prc->cell_changes[i].a = a[0];
2494 prc->cell_changes[i].tcol = 0;
2499 prc->cell_changes[i].c.w = c[0];
2500 prc->cell_changes[i].a = a[0];
2501 prc->cell_changes[i].tcol = 0;
2508 * Have come to another region of changed text or another region
2509 * to wipe. Combine the regions to minimize redraws.
2521 * Draw the pending changes saved in angbandContext->changes.
2523 static void Term_xtra_cocoa_fresh(AngbandContext* angbandContext)
2525 int graf_width, graf_height, alphablend;
2527 if (angbandContext->changes->has_pict) {
2528 CGImageAlphaInfo ainfo = CGImageGetAlphaInfo(pict_image);
2530 graf_width = current_graphics_mode->cell_width;
2531 graf_height = current_graphics_mode->cell_height;
2533 * As of this writing, a value of zero for
2534 * current_graphics_mode->alphablend can mean either that the tile set
2535 * doesn't have an alpha channel or it does but it only takes on values
2536 * of 0 or 255. For main-cocoa.m's purposes, the latter is rendered
2537 * using the same procedure as if alphablend was nonzero. The former
2538 * is handled differently, but alphablend doesn't distinguish it from
2539 * the latter. So ignore alphablend and directly test whether an
2540 * alpha channel is present.
2542 alphablend = (ainfo & (kCGImageAlphaPremultipliedFirst |
2543 kCGImageAlphaPremultipliedLast)) ? 1 : 0;
2550 CGContextRef ctx = [angbandContext lockFocus];
2552 if (angbandContext->changes->has_text ||
2553 angbandContext->changes->has_wipe) {
2554 NSFont *selectionFont = [[angbandContext selectionFont] screenFont];
2555 [selectionFont set];
2559 for (iy = angbandContext->changes->ymin;
2560 iy <= angbandContext->changes->ymax;
2562 struct PendingRowChange* prc = angbandContext->changes->rows[iy];
2565 /* Skip untouched rows. */
2574 if (ix > prc->xmax) {
2578 switch (prc->cell_changes[ix].change_type) {
2579 case CELL_CHANGE_NONE:
2583 case CELL_CHANGE_PICT:
2586 * Because changes are made to the compositing mode, save
2587 * the incoming value.
2589 NSGraphicsContext *nsContext =
2590 [NSGraphicsContext currentContext];
2591 NSCompositingOperation op = nsContext.compositingOperation;
2594 while (jx <= prc->xmax &&
2595 prc->cell_changes[jx].change_type
2596 == CELL_CHANGE_PICT) {
2597 NSRect destinationRect =
2598 [angbandContext rectInImageForTileAtX:jx Y:iy];
2599 NSRect sourceRect, terrainRect;
2601 sourceRect.origin.x = graf_width *
2602 prc->cell_changes[jx].c.c;
2603 sourceRect.origin.y = graf_height *
2604 prc->cell_changes[jx].a;
2605 sourceRect.size.width = graf_width;
2606 sourceRect.size.height = graf_height;
2607 terrainRect.origin.x = graf_width *
2608 prc->cell_changes[jx].tcol;
2609 terrainRect.origin.y = graf_height *
2610 prc->cell_changes[jx].trow;
2611 terrainRect.size.width = graf_width;
2612 terrainRect.size.height = graf_height;
2622 * Skip drawing the foreground if it is the same
2623 * as the background.
2625 if (sourceRect.origin.x != terrainRect.origin.x ||
2626 sourceRect.origin.y != terrainRect.origin.y) {
2633 NSCompositeSourceOver);
2647 [nsContext setCompositingOperation:op];
2650 [angbandContext rectInImageForTileAtX:ix Y:iy];
2652 angbandContext->tileSize.width * (jx - ix);
2653 [angbandContext setNeedsDisplayInBaseRect:rect];
2658 case CELL_CHANGE_WIPE:
2659 case CELL_CHANGE_TEXT:
2661 * For a wiped region, treat it as if it had text (the only
2662 * loss if it was not is some extra work rendering
2663 * neighboring unchanged text).
2666 while (jx < angbandContext->cols &&
2667 (prc->cell_changes[jx].change_type
2669 || prc->cell_changes[jx].change_type
2670 == CELL_CHANGE_WIPE)) {
2675 int ieclip = jx - 1;
2677 int ierend = jx - 1;
2679 TERM_COLOR alast = 0;
2684 prc, iy, angbandContext->ncol_pre, &isclip, &isrend);
2688 angbandContext->cols,
2689 angbandContext->ncol_post,
2695 /* Save the state since the clipping will be modified. */
2696 CGContextSaveGState(ctx);
2698 /* Clear the area where rendering will be done. */
2699 r = [angbandContext rectInImageForTileAtX:isrend Y:iy];
2700 r.size.width = angbandContext->tileSize.width *
2701 (ierend - isrend + 1);
2702 [[NSColor blackColor] set];
2706 * Clear the current path so it does not affect clipping.
2707 * Then set the clipping rectangle. Using
2708 * CGContextSetTextDrawingMode() to include clipping does
2709 * not appear to be necessary on 10.14 and is actually
2710 * detrimental: when displaying more than one character,
2711 * only the first is visible.
2713 CGContextBeginPath(ctx);
2714 r = [angbandContext rectInImageForTileAtX:isclip Y:iy];
2715 r.size.width = angbandContext->tileSize.width *
2716 (ieclip - isclip + 1);
2717 CGContextClipToRect(ctx, r);
2721 while (k <= ierend) {
2724 if (prc->cell_changes[k].change_type
2725 == CELL_CHANGE_WIPE) {
2726 /* Skip over since no rendering is necessary. */
2731 if (set_color || alast != prc->cell_changes[k].a) {
2733 alast = prc->cell_changes[k].a;
2734 set_color_for_index(alast % MAX_COLORS);
2738 [angbandContext rectInImageForTileAtX:k Y:iy];
2739 if (prc->cell_changes[k].tcol) {
2740 rectToDraw.size.width *= 2.0;
2741 [angbandContext drawWChar:prc->cell_changes[k].c.w
2742 inRect:rectToDraw context:ctx];
2745 [angbandContext drawWChar:prc->cell_changes[k].c.w
2746 inRect:rectToDraw context:ctx];
2752 * Inform the context that the area in the clipping
2753 * rectangle needs to be redisplayed.
2755 [angbandContext setNeedsDisplayInBaseRect:r];
2757 CGContextRestoreGState(ctx);
2764 if (angbandContext->changes->xcurs >= 0 &&
2765 angbandContext->changes->ycurs >= 0) {
2766 NSRect rect = [angbandContext
2767 rectInImageForTileAtX:angbandContext->changes->xcurs
2768 Y:angbandContext->changes->ycurs];
2770 if (angbandContext->changes->bigcurs) {
2771 rect.size.width += angbandContext->tileSize.width;
2773 [[NSColor yellowColor] set];
2774 NSFrameRectWithWidth(rect, 1);
2775 /* Invalidate that rect */
2776 [angbandContext setNeedsDisplayInBaseRect:rect];
2779 [angbandContext unlockFocus];
2784 * Do a "special thing"
2786 static errr Term_xtra_cocoa(int n, int v)
2788 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
2789 AngbandContext* angbandContext = Term->data;
2797 case TERM_XTRA_NOISE:
2806 case TERM_XTRA_SOUND:
2810 /* Process random events */
2811 case TERM_XTRA_BORED:
2813 /* Show or hide cocoa windows based on the subwindow flags set by
2815 AngbandUpdateWindowVisibility();
2817 /* Process an event */
2818 (void)check_events(CHECK_EVENTS_NO_WAIT);
2824 /* Process pending events */
2825 case TERM_XTRA_EVENT:
2827 /* Process an event */
2828 (void)check_events(v);
2834 /* Flush all pending events (if any) */
2835 case TERM_XTRA_FLUSH:
2837 /* Hack -- flush all events */
2838 while (check_events(CHECK_EVENTS_DRAIN)) /* loop */;
2844 /* Hack -- Change the "soft level" */
2845 case TERM_XTRA_LEVEL:
2847 /* Here we could activate (if requested), but I don't think Angband
2848 * should be telling us our window order (the user should decide
2849 * that), so do nothing. */
2853 /* Clear the screen */
2854 case TERM_XTRA_CLEAR:
2856 [angbandContext lockFocus];
2857 [[NSColor blackColor] set];
2858 NSRect imageRect = {NSZeroPoint, [angbandContext imageSize]};
2859 NSRectFillUsingOperation(imageRect, NSCompositeCopy);
2860 [angbandContext unlockFocus];
2861 [angbandContext setNeedsDisplay:YES];
2866 /* React to changes */
2867 case TERM_XTRA_REACT:
2869 /* React to changes */
2870 return (Term_xtra_cocoa_react());
2873 /* Delay (milliseconds) */
2874 case TERM_XTRA_DELAY:
2880 double seconds = v / 1000.;
2881 NSDate* date = [NSDate dateWithTimeIntervalSinceNow:seconds];
2887 event = [NSApp nextEventMatchingMask:-1 untilDate:date inMode:NSDefaultRunLoopMode dequeue:YES];
2888 if (event) send_event(event);
2890 } while ([date timeIntervalSinceNow] >= 0);
2898 case TERM_XTRA_FRESH:
2899 /* Draw the pending changes. */
2900 if (angbandContext->changes != 0) {
2901 Term_xtra_cocoa_fresh(angbandContext);
2902 clear_pending_changes(angbandContext->changes);
2918 static errr Term_curs_cocoa(int x, int y)
2920 AngbandContext *angbandContext = Term->data;
2922 if (angbandContext->changes == 0) {
2923 /* Bail out; there was an earlier memory allocation failure. */
2926 angbandContext->changes->xcurs = x;
2927 angbandContext->changes->ycurs = y;
2928 angbandContext->changes->bigcurs = 0;
2935 * Draw a cursor that's two tiles wide. For Japanese, that's used when
2936 * the cursor points at a kanji character, irregardless of whether operating
2939 static errr Term_bigcurs_cocoa(int x, int y)
2941 AngbandContext *angbandContext = Term->data;
2943 if (angbandContext->changes == 0) {
2944 /* Bail out; there was an earlier memory allocation failure. */
2947 angbandContext->changes->xcurs = x;
2948 angbandContext->changes->ycurs = y;
2949 angbandContext->changes->bigcurs = 1;
2956 * Low level graphics (Assumes valid input)
2958 * Erase "n" characters starting at (x,y)
2960 static errr Term_wipe_cocoa(int x, int y, int n)
2962 AngbandContext *angbandContext = Term->data;
2963 struct PendingCellChange *pc;
2965 if (angbandContext->changes == 0) {
2966 /* Bail out; there was an earlier memory allocation failure. */
2969 if (angbandContext->changes->rows[y] == 0) {
2970 angbandContext->changes->rows[y] =
2971 create_row_change(angbandContext->cols);
2972 if (angbandContext->changes->rows[y] == 0) {
2973 NSLog(@"failed to allocate changes for row %d", y);
2976 if (angbandContext->changes->ymin > y) {
2977 angbandContext->changes->ymin = y;
2979 if (angbandContext->changes->ymax < y) {
2980 angbandContext->changes->ymax = y;
2984 angbandContext->changes->has_wipe = 1;
2985 if (angbandContext->changes->rows[y]->xmin > x) {
2986 angbandContext->changes->rows[y]->xmin = x;
2988 if (angbandContext->changes->rows[y]->xmax < x + n - 1) {
2989 angbandContext->changes->rows[y]->xmax = x + n - 1;
2991 for (pc = angbandContext->changes->rows[y]->cell_changes + x;
2992 pc != angbandContext->changes->rows[y]->cell_changes + x + n;
2994 pc->change_type = CELL_CHANGE_WIPE;
3001 static errr Term_pict_cocoa(int x, int y, int n, TERM_COLOR *ap,
3002 const char *cp, const TERM_COLOR *tap,
3006 /* Paranoia: Bail if we don't have a current graphics mode */
3007 if (! current_graphics_mode) return -1;
3009 AngbandContext* angbandContext = Term->data;
3011 struct PendingCellChange *pc;
3013 if (angbandContext->changes == 0) {
3014 /* Bail out; there was an earlier memory allocation failure. */
3017 if (angbandContext->changes->rows[y] == 0) {
3018 angbandContext->changes->rows[y] =
3019 create_row_change(angbandContext->cols);
3020 if (angbandContext->changes->rows[y] == 0) {
3021 NSLog(@"failed to allocate changes for row %d", y);
3024 if (angbandContext->changes->ymin > y) {
3025 angbandContext->changes->ymin = y;
3027 if (angbandContext->changes->ymax < y) {
3028 angbandContext->changes->ymax = y;
3032 if (angbandContext->changes->rows[y]->xmin > x) {
3033 angbandContext->changes->rows[y]->xmin = x;
3035 if (angbandContext->changes->rows[y]->xmax < x + n - 1) {
3036 angbandContext->changes->rows[y]->xmax = x + n - 1;
3038 for (pc = angbandContext->changes->rows[y]->cell_changes + x;
3039 pc != angbandContext->changes->rows[y]->cell_changes + x + n;
3041 TERM_COLOR a = *ap++;
3043 TERM_COLOR ta = *tap++;
3046 if (use_graphics && (a & 0x80) && (c & 0x80)) {
3047 pc->c.c = ((byte)c & 0x7F) % pict_cols;
3048 pc->a = ((byte)a & 0x7F) % pict_rows;
3049 pc->tcol = ((byte)tc & 0x7F) % pict_cols;
3050 pc->trow = ((byte)ta & 0x7F) % pict_rows;
3051 pc->change_type = CELL_CHANGE_PICT;
3056 angbandContext->changes->has_pict = 1;
3064 * Low level graphics. Assumes valid input.
3066 * Draw several ("n") chars, with an attr, at a given location.
3068 static errr Term_text_cocoa(int x, int y, int n, byte_hack a, concptr cp)
3070 AngbandContext* angbandContext = Term->data;
3071 struct PendingCellChange *pc;
3073 if (angbandContext->changes == 0) {
3074 /* Bail out; there was an earlier memory allocation failure. */
3077 if (angbandContext->changes->rows[y] == 0) {
3078 angbandContext->changes->rows[y] =
3079 create_row_change(angbandContext->cols);
3080 if (angbandContext->changes->rows[y] == 0) {
3081 NSLog(@"failed to allocate changes for row %d", y);
3084 if (angbandContext->changes->ymin > y) {
3085 angbandContext->changes->ymin = y;
3087 if (angbandContext->changes->ymax < y) {
3088 angbandContext->changes->ymax = y;
3092 angbandContext->changes->has_text = 1;
3093 if (angbandContext->changes->rows[y]->xmin > x) {
3094 angbandContext->changes->rows[y]->xmin = x;
3096 if (angbandContext->changes->rows[y]->xmax < x + n - 1) {
3097 angbandContext->changes->rows[y]->xmax = x + n - 1;
3099 pc = angbandContext->changes->rows[y]->cell_changes + x;
3100 while (pc != angbandContext->changes->rows[y]->cell_changes + x + n) {
3104 angbandContext->changes->rows[y]->cell_changes + x + n) {
3106 * The second byte of the character is past the end. Ignore
3111 pc->c.w = convert_two_byte_eucjp_to_utf16_native(cp);
3114 pc->change_type = CELL_CHANGE_TEXT;
3117 * Fill in a dummy value since the previous character will take
3123 pc->change_type = CELL_CHANGE_TEXT;
3131 pc->change_type = CELL_CHANGE_TEXT;
3139 pc->change_type = CELL_CHANGE_TEXT;
3150 * Post a nonsense event so that our event loop wakes up
3152 static void wakeup_event_loop(void)
3154 /* Big hack - send a nonsense event to make us update */
3155 NSEvent *event = [NSEvent otherEventWithType:NSApplicationDefined location:NSZeroPoint modifierFlags:0 timestamp:0 windowNumber:0 context:NULL subtype:AngbandEventWakeup data1:0 data2:0];
3156 [NSApp postEvent:event atStart:NO];
3161 * Create and initialize window number "i"
3163 static term *term_data_link(int i)
3165 NSArray *terminalDefaults = [[NSUserDefaults standardUserDefaults] valueForKey: AngbandTerminalsDefaultsKey];
3166 NSInteger rows = 24;
3167 NSInteger columns = 80;
3169 if( i < (int)[terminalDefaults count] )
3171 NSDictionary *term = [terminalDefaults objectAtIndex: i];
3172 rows = [[term valueForKey: AngbandTerminalRowsDefaultsKey] integerValue];
3173 columns = [[term valueForKey: AngbandTerminalColumnsDefaultsKey] integerValue];
3177 term *newterm = ZNEW(term);
3179 /* Initialize the term */
3180 term_init(newterm, columns, rows, 256 /* keypresses, for some reason? */);
3182 /* Differentiate between BS/^h, Tab/^i, etc. */
3183 /* newterm->complex_input = TRUE; */
3185 /* Use a "software" cursor */
3186 newterm->soft_cursor = TRUE;
3188 /* Disable the per-row flush notifications since they are not used. */
3189 newterm->never_frosh = TRUE;
3191 /* Erase with "white space" */
3192 newterm->attr_blank = TERM_WHITE;
3193 newterm->char_blank = ' ';
3195 /* Prepare the init/nuke hooks */
3196 newterm->init_hook = Term_init_cocoa;
3197 newterm->nuke_hook = Term_nuke_cocoa;
3199 /* Prepare the function hooks */
3200 newterm->xtra_hook = Term_xtra_cocoa;
3201 newterm->wipe_hook = Term_wipe_cocoa;
3202 newterm->curs_hook = Term_curs_cocoa;
3203 newterm->bigcurs_hook = Term_bigcurs_cocoa;
3204 newterm->text_hook = Term_text_cocoa;
3205 newterm->pict_hook = Term_pict_cocoa;
3206 /* newterm->mbcs_hook = Term_mbcs_cocoa; */
3208 /* Global pointer */
3209 angband_term[i] = newterm;
3215 * Load preferences from preferences file for current host+current user+
3216 * current application.
3218 static void load_prefs()
3220 NSUserDefaults *defs = [NSUserDefaults angbandDefaults];
3222 /* Make some default defaults */
3223 NSMutableArray *defaultTerms = [[NSMutableArray alloc] init];
3225 /* The following default rows/cols were determined experimentally by first
3226 * finding the ideal window/font size combinations. But because of awful
3227 * temporal coupling in Term_init_cocoa(), it's impossible to set up the
3228 * defaults there, so we do it this way. */
3229 for( NSUInteger i = 0; i < ANGBAND_TERM_MAX; i++ )
3267 NSDictionary *standardTerm = [NSDictionary dictionaryWithObjectsAndKeys:
3268 [NSNumber numberWithInt: rows], AngbandTerminalRowsDefaultsKey,
3269 [NSNumber numberWithInt: columns], AngbandTerminalColumnsDefaultsKey,
3270 [NSNumber numberWithBool: visible], AngbandTerminalVisibleDefaultsKey,
3272 [defaultTerms addObject: standardTerm];
3275 NSDictionary *defaults = [[NSDictionary alloc] initWithObjectsAndKeys:
3277 @"Osaka", @"FontName",
3279 @"Menlo", @"FontName",
3281 [NSNumber numberWithFloat:13.f], @"FontSize",
3282 [NSNumber numberWithInt:60], AngbandFrameRateDefaultsKey,
3283 [NSNumber numberWithBool:YES], AngbandSoundDefaultsKey,
3284 [NSNumber numberWithInt:GRAPHICS_NONE], AngbandGraphicsDefaultsKey,
3285 defaultTerms, AngbandTerminalsDefaultsKey,
3287 [defs registerDefaults:defaults];
3289 [defaultTerms release];
3291 /* Preferred graphics mode */
3292 graf_mode_req = [defs integerForKey:AngbandGraphicsDefaultsKey];
3294 /* Use sounds; set the Angband global */
3295 use_sound = ([defs boolForKey:AngbandSoundDefaultsKey] == YES) ? TRUE : FALSE;
3298 frames_per_second = [defs integerForKey:AngbandFrameRateDefaultsKey];
3301 default_font = [[NSFont fontWithName:[defs valueForKey:@"FontName-0"] size:[defs floatForKey:@"FontSize-0"]] retain];
3302 if (! default_font) default_font = [[NSFont fontWithName:@"Menlo" size:13.] retain];
3306 * Arbitary limit on number of possible samples per event
3308 #define MAX_SAMPLES 16
3311 * Struct representing all data for a set of event samples
3315 int num; /* Number of available samples for this event */
3316 NSSound *sound[MAX_SAMPLES];
3317 } sound_sample_list;
3320 * Array of event sound structs
3322 static sound_sample_list samples[MSG_MAX];
3326 * Load sound effects based on sound.cfg within the xtra/sound directory;
3327 * bridge to Cocoa to use NSSound for simple loading and playback, avoiding
3328 * I/O latency by cacheing all sounds at the start. Inherits full sound
3329 * format support from Quicktime base/plugins.
3330 * pelpel favoured a plist-based parser for the future but .cfg support
3331 * improves cross-platform compatibility.
3333 static void load_sounds(void)
3335 char sound_dir[1024];
3340 /* Build the "sound" path */
3341 path_build(sound_dir, sizeof(sound_dir), ANGBAND_DIR_XTRA, "sound");
3343 /* Find and open the config file */
3344 path_build(path, sizeof(path), sound_dir, "sound.cfg");
3345 fff = my_fopen(path, "r");
3350 NSLog(@"The sound configuration file could not be opened.");
3354 /* Instantiate an autorelease pool for use by NSSound */
3355 NSAutoreleasePool *autorelease_pool;
3356 autorelease_pool = [[NSAutoreleasePool alloc] init];
3358 /* Use a dictionary to unique sounds, so we can share NSSounds across
3359 * multiple events */
3360 NSMutableDictionary *sound_dict = [NSMutableDictionary dictionary];
3363 * This loop may take a while depending on the count and size of samples
3367 /* Parse the file */
3368 /* Lines are always of the form "name = sample [sample ...]" */
3369 while (my_fgets(fff, buffer, sizeof(buffer)) == 0)
3372 char *cfg_sample_list;
3378 /* Skip anything not beginning with an alphabetic character */
3379 if (!buffer[0] || !isalpha((unsigned char)buffer[0])) continue;
3381 /* Split the line into two: message name, and the rest */
3382 search = strchr(buffer, ' ');
3383 cfg_sample_list = strchr(search + 1, ' ');
3384 if (!search) continue;
3385 if (!cfg_sample_list) continue;
3387 /* Set the message name, and terminate at first space */
3391 /* Make sure this is a valid event name */
3392 for (event = MSG_MAX - 1; event >= 0; event--)
3394 if (strcmp(msg_name, angband_sound_name[event]) == 0)
3397 if (event < 0) continue;
3399 /* Advance the sample list pointer so it's at the beginning of text */
3401 if (!cfg_sample_list[0]) continue;
3403 /* Terminate the current token */
3404 cur_token = cfg_sample_list;
3405 search = strchr(cur_token, ' ');
3409 next_token = search + 1;
3417 * Now we find all the sample names and add them one by one
3421 int num = samples[event].num;
3423 /* Don't allow too many samples */
3424 if (num >= MAX_SAMPLES) break;
3426 NSString *token_string = [NSString stringWithUTF8String:cur_token];
3427 NSSound *sound = [sound_dict objectForKey:token_string];
3433 /* We have to load the sound. Build the path to the sample */
3434 path_build(path, sizeof(path), sound_dir, cur_token);
3435 if (stat(path, &stb) == 0)
3438 /* Load the sound into memory */
3439 sound = [[[NSSound alloc] initWithContentsOfFile:[NSString stringWithUTF8String:path] byReference:YES] autorelease];
3440 if (sound) [sound_dict setObject:sound forKey:token_string];
3444 /* Store it if we loaded it */
3447 samples[event].sound[num] = [sound retain];
3449 /* Imcrement the sample count */
3450 samples[event].num++;
3454 /* Figure out next token */
3455 cur_token = next_token;
3458 /* Try to find a space */
3459 search = strchr(cur_token, ' ');
3461 /* If we can find one, terminate, and set new "next" */
3465 next_token = search + 1;
3469 /* Otherwise prevent infinite looping */
3476 /* Release the autorelease pool */
3477 [autorelease_pool release];
3479 /* Close the file */
3484 * Play sound effects asynchronously. Select a sound from any available
3485 * for the required event, and bridge to Cocoa to play it.
3487 static void play_sound(int event)
3490 if (event < 0 || event >= MSG_MAX) return;
3492 /* Load sounds just-in-time (once) */
3493 static BOOL loaded = NO;
3499 /* Check there are samples for this event */
3500 if (!samples[event].num) return;
3502 /* Instantiate an autorelease pool for use by NSSound */
3503 NSAutoreleasePool *autorelease_pool;
3504 autorelease_pool = [[NSAutoreleasePool alloc] init];
3506 /* Choose a random event */
3507 int s = randint0(samples[event].num);
3509 /* Stop the sound if it's currently playing */
3510 if ([samples[event].sound[s] isPlaying])
3511 [samples[event].sound[s] stop];
3513 /* Play the sound */
3514 [samples[event].sound[s] play];
3516 /* Release the autorelease pool */
3517 [autorelease_pool drain];
3523 static void init_windows(void)
3525 /* Create the main window */
3526 term *primary = term_data_link(0);
3528 /* Prepare to create any additional windows */
3530 for (i=1; i < ANGBAND_TERM_MAX; i++) {
3534 /* Activate the primary term */
3535 Term_activate(primary);
3539 * Handle the "open_when_ready" flag
3541 static void handle_open_when_ready(void)
3543 /* Check the flag XXX XXX XXX make a function for this */
3544 if (open_when_ready && initialized && !game_in_progress)
3547 open_when_ready = FALSE;
3549 /* Game is in progress */
3550 game_in_progress = TRUE;
3552 /* Wait for a keypress */
3553 pause_line(Term->hgt - 1);
3559 * Handle quit_when_ready, by Peter Ammon,
3560 * slightly modified to check inkey_flag.
3562 static void quit_calmly(void)
3564 /* Quit immediately if game's not started */
3565 if (!game_in_progress || !character_generated) quit(NULL);
3567 /* Save the game and Quit (if it's safe) */
3570 /* Hack -- Forget messages and term */
3572 Term->mapped_flag = FALSE;
3575 do_cmd_save_game(FALSE);
3576 record_current_savefile();
3582 /* Wait until inkey_flag is set */
3588 * Returns YES if we contain an AngbandView (and hence should direct our events
3591 static BOOL contains_angband_view(NSView *view)
3593 if ([view isKindOfClass:[AngbandView class]]) return YES;
3594 for (NSView *subview in [view subviews]) {
3595 if (contains_angband_view(subview)) return YES;
3602 * Queue mouse presses if they occur in the map section of the main window.
3604 static void AngbandHandleEventMouseDown( NSEvent *event )
3607 AngbandContext *angbandContext = [[[event window] contentView] angbandContext];
3608 AngbandContext *mainAngbandContext = angband_term[0]->data;
3610 if (mainAngbandContext->primaryWindow && [[event window] windowNumber] == [mainAngbandContext->primaryWindow windowNumber])
3612 int cols, rows, x, y;
3613 Term_get_size(&cols, &rows);
3614 NSSize tileSize = angbandContext->tileSize;
3615 NSSize border = angbandContext->borderSize;
3616 NSPoint windowPoint = [event locationInWindow];
3618 /* Adjust for border; add border height because window origin is at
3620 windowPoint = NSMakePoint( windowPoint.x - border.width, windowPoint.y + border.height );
3622 NSPoint p = [[[event window] contentView] convertPoint: windowPoint fromView: nil];
3623 x = floor( p.x / tileSize.width );
3624 y = floor( p.y / tileSize.height );
3626 /* Being safe about this, since xcode doesn't seem to like the
3627 * bool_hack stuff */
3628 BOOL displayingMapInterface = ((int)inkey_flag != 0);
3630 /* Sidebar plus border == thirteen characters; top row is reserved. */
3631 /* Coordinates run from (0,0) to (cols-1, rows-1). */
3632 BOOL mouseInMapSection = (x > 13 && x <= cols - 1 && y > 0 && y <= rows - 2);
3634 /* If we are displaying a menu, allow clicks anywhere; if we are
3635 * displaying the main game interface, only allow clicks in the map
3637 if (!displayingMapInterface || (displayingMapInterface && mouseInMapSection))
3639 /* [event buttonNumber] will return 0 for left click,
3640 * 1 for right click, but this is safer */
3641 int button = ([event type] == NSLeftMouseDown) ? 1 : 2;
3644 NSUInteger eventModifiers = [event modifierFlags];
3645 byte angbandModifiers = 0;
3646 angbandModifiers |= (eventModifiers & NSShiftKeyMask) ? KC_MOD_SHIFT : 0;
3647 angbandModifiers |= (eventModifiers & NSControlKeyMask) ? KC_MOD_CONTROL : 0;
3648 angbandModifiers |= (eventModifiers & NSAlternateKeyMask) ? KC_MOD_ALT : 0;
3649 button |= (angbandModifiers & 0x0F) << 4; /* encode modifiers in the button number (see Term_mousepress()) */
3652 Term_mousepress(x, y, button);
3656 /* Pass click through to permit focus change, resize, etc. */
3657 [NSApp sendEvent:event];
3663 * Encodes an NSEvent Angband-style, or forwards it along. Returns YES if the
3664 * event was sent to Angband, NO if Cocoa (or nothing) handled it */
3665 static BOOL send_event(NSEvent *event)
3668 /* If the receiving window is not an Angband window, then do nothing */
3669 if (! contains_angband_view([[event window] contentView]))
3671 [NSApp sendEvent:event];
3675 /* Analyze the event */
3676 switch ([event type])
3680 /* Try performing a key equivalent */
3681 if ([[NSApp mainMenu] performKeyEquivalent:event]) break;
3683 unsigned modifiers = [event modifierFlags];
3685 /* Send all NSCommandKeyMasks through */
3686 if (modifiers & NSCommandKeyMask)
3688 [NSApp sendEvent:event];
3692 if (! [[event characters] length]) break;
3695 /* Extract some modifiers */
3696 int mc = !! (modifiers & NSControlKeyMask);
3697 int ms = !! (modifiers & NSShiftKeyMask);
3698 int mo = !! (modifiers & NSAlternateKeyMask);
3699 int kp = !! (modifiers & NSNumericPadKeyMask);
3702 /* Get the Angband char corresponding to this unichar */
3703 unichar c = [[event characters] characterAtIndex:0];
3706 * Have anything from the numeric keypad generate a macro
3707 * trigger so that shift or control modifiers can be passed.
3709 if (c <= 0x7F && !kp)
3715 * The rest of Hengband uses Angband 2.7's or so key handling:
3716 * so for the rest do something like the encoding that
3717 * main-win.c does: send a macro trigger with the Unicode
3718 * value encoded into printable ASCII characters.
3723 /* override special keys */
3724 switch([event keyCode]) {
3725 case kVK_Return: ch = '\r'; break;
3726 case kVK_Escape: ch = 27; break;
3727 case kVK_Tab: ch = '\t'; break;
3728 case kVK_Delete: ch = '\b'; break;
3729 case kVK_ANSI_KeypadEnter: ch = '\r'; kp = TRUE; break;
3732 /* Hide the mouse pointer */
3733 [NSCursor setHiddenUntilMouseMoves:YES];
3743 * Could use the hexsym global but some characters overlap with
3744 * those used to indicate modifiers.
3746 const char encoded[16] = {
3747 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b',
3751 /* Begin the macro trigger. */
3754 /* Send the modifiers. */
3755 if (mc) Term_keypress('C');
3756 if (ms) Term_keypress('S');
3757 if (mo) Term_keypress('O');
3758 if (kp) Term_keypress('K');
3761 Term_keypress(encoded[c & 0xF]);
3765 /* End the macro trigger. */
3772 case NSLeftMouseDown:
3773 case NSRightMouseDown:
3774 AngbandHandleEventMouseDown(event);
3777 case NSApplicationDefined:
3779 if ([event subtype] == AngbandEventWakeup)
3787 [NSApp sendEvent:event];
3794 * Check for Events, return TRUE if we process any
3796 static BOOL check_events(int wait)
3799 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
3801 /* Handles the quit_when_ready flag */
3802 if (quit_when_ready) quit_calmly();
3805 if (wait == CHECK_EVENTS_WAIT) endDate = [NSDate distantFuture];
3806 else endDate = [NSDate distantPast];
3810 if (quit_when_ready)
3812 /* send escape events until we quit */
3813 Term_keypress(0x1B);
3818 event = [NSApp nextEventMatchingMask:-1 untilDate:endDate inMode:NSDefaultRunLoopMode dequeue:YES];
3824 if (send_event(event)) break;
3830 /* Something happened */
3836 * Hook to tell the user something important
3838 static void hook_plog(const char * str)
3842 NSString *msg = NSLocalizedStringWithDefaultValue(
3843 @"Warning", AngbandMessageCatalog, [NSBundle mainBundle],
3844 @"Warning", @"Alert text for generic warning");
3845 NSString *info = [NSString stringWithCString:str
3847 encoding:NSJapaneseEUCStringEncoding
3849 encoding:NSMacOSRomanStringEncoding
3852 NSAlert *alert = [[NSAlert alloc] init];
3854 alert.messageText = msg;
3855 alert.informativeText = info;
3856 NSModalResponse result = [alert runModal];
3863 * Hook to tell the user something, and then quit
3865 static void hook_quit(const char * str)
3872 * ------------------------------------------------------------------------
3874 * ------------------------------------------------------------------------ */
3876 @implementation AngbandAppDelegate
3878 @synthesize graphicsMenu=_graphicsMenu;
3879 @synthesize commandMenu=_commandMenu;
3880 @synthesize commandMenuTagMap=_commandMenuTagMap;
3882 - (IBAction)newGame:sender
3884 /* Game is in progress */
3885 game_in_progress = TRUE;
3889 - (IBAction)editFont:sender
3891 NSFontPanel *panel = [NSFontPanel sharedFontPanel];
3892 NSFont *termFont = default_font;
3895 for (i=0; i < ANGBAND_TERM_MAX; i++) {
3896 if ([(id)angband_term[i]->data isMainWindow]) {
3897 termFont = [(id)angband_term[i]->data selectionFont];
3902 [panel setPanelFont:termFont isMultiple:NO];
3903 [panel orderFront:self];
3907 * Implent NSObject's changeFont() method to receive a notification about the
3908 * changed font. Note that, as of 10.14, changeFont() is deprecated in
3909 * NSObject - it will be removed at some point and the application delegate
3910 * will have to be declared as implementing the NSFontChanging protocol.
3912 - (void)changeFont:(id)sender
3915 for (mainTerm=0; mainTerm < ANGBAND_TERM_MAX; mainTerm++) {
3916 if ([(id)angband_term[mainTerm]->data isMainWindow]) {
3921 /* Bug #1709: Only change font for angband windows */
3922 if (mainTerm == ANGBAND_TERM_MAX) return;
3924 NSFont *oldFont = default_font;
3925 NSFont *newFont = [sender convertFont:oldFont];
3926 if (! newFont) return; /*paranoia */
3928 /* Store as the default font if we changed the first term */
3929 if (mainTerm == 0) {
3931 [default_font release];
3932 default_font = newFont;
3935 /* Record it in the preferences */
3936 NSUserDefaults *defs = [NSUserDefaults angbandDefaults];
3937 [defs setValue:[newFont fontName]
3938 forKey:[NSString stringWithFormat:@"FontName-%d", mainTerm]];
3939 [defs setFloat:[newFont pointSize]
3940 forKey:[NSString stringWithFormat:@"FontSize-%d", mainTerm]];
3943 NSDisableScreenUpdates();
3946 AngbandContext *angbandContext = angband_term[mainTerm]->data;
3947 [(id)angbandContext setSelectionFont:newFont adjustTerminal: YES];
3949 NSEnableScreenUpdates();
3951 if (mainTerm == 0 && game_in_progress) {
3952 /* Mimics the logic in setGraphicsMode(). */
3954 wakeup_event_loop();
3956 [(id)angbandContext requestRedraw];
3960 - (IBAction)openGame:sender
3962 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
3963 BOOL selectedSomething = NO;
3966 /* Get where we think the save files are */
3967 NSURL *startingDirectoryURL = [NSURL fileURLWithPath:[NSString stringWithCString:ANGBAND_DIR_SAVE encoding:NSASCIIStringEncoding] isDirectory:YES];
3969 /* Set up an open panel */
3970 NSOpenPanel* panel = [NSOpenPanel openPanel];
3971 [panel setCanChooseFiles:YES];
3972 [panel setCanChooseDirectories:NO];
3973 [panel setResolvesAliases:YES];
3974 [panel setAllowsMultipleSelection:NO];
3975 [panel setTreatsFilePackagesAsDirectories:YES];
3976 [panel setDirectoryURL:startingDirectoryURL];
3979 panelResult = [panel runModal];
3980 if (panelResult == NSOKButton)
3982 NSArray* fileURLs = [panel URLs];
3983 if ([fileURLs count] > 0 && [[fileURLs objectAtIndex:0] isFileURL])
3985 NSURL* savefileURL = (NSURL *)[fileURLs objectAtIndex:0];
3986 /* The path property doesn't do the right thing except for
3987 * URLs with the file scheme. We had getFileSystemRepresentation
3988 * here before, but that wasn't introduced until OS X 10.9. */
3989 selectedSomething = [[savefileURL path] getCString:savefile
3990 maxLength:sizeof savefile encoding:NSMacOSRomanStringEncoding];
3994 if (selectedSomething)
3996 /* Remember this so we can select it by default next time */
3997 record_current_savefile();
3999 /* Game is in progress */
4000 game_in_progress = TRUE;
4007 - (IBAction)saveGame:sender
4009 /* Hack -- Forget messages */
4013 do_cmd_save_game(FALSE);
4015 /* Record the current save file so we can select it by default next time.
4016 * It's a little sketchy that this only happens when we save through the
4017 * menu; ideally game-triggered saves would trigger it too. */
4018 record_current_savefile();
4022 * Implement NSObject's validateMenuItem() method to override enabling or
4023 * disabling a menu item. Note that, as of 10.14, validateMenuItem() is
4024 * deprecated in NSObject - it will be removed at some point and the
4025 * application delegate will have to be declared as implementing the
4026 * NSMenuItemValidation protocol.
4028 - (BOOL)validateMenuItem:(NSMenuItem *)menuItem
4030 SEL sel = [menuItem action];
4031 NSInteger tag = [menuItem tag];
4033 if( tag >= AngbandWindowMenuItemTagBase && tag < AngbandWindowMenuItemTagBase + ANGBAND_TERM_MAX )
4035 if( tag == AngbandWindowMenuItemTagBase )
4037 /* The main window should always be available and visible */
4043 * Another window is only usable after Term_init_cocoa() has
4044 * been called for it. For Angband if window_flag[i] is nonzero
4045 * then that has happened for window i. For Hengband, that is
4046 * not the case so also test angband_term[i]->data.
4048 NSInteger subwindowNumber = tag - AngbandWindowMenuItemTagBase;
4049 return (angband_term[subwindowNumber]->data != 0
4050 && window_flag[subwindowNumber] > 0);
4056 if (sel == @selector(newGame:))
4058 return ! game_in_progress;
4060 else if (sel == @selector(editFont:))
4064 else if (sel == @selector(openGame:))
4066 return ! game_in_progress;
4068 else if (sel == @selector(setRefreshRate:) &&
4069 [[menuItem parentItem] tag] == 150)
4071 NSInteger fps = [[NSUserDefaults standardUserDefaults] integerForKey:AngbandFrameRateDefaultsKey];
4072 [menuItem setState: ([menuItem tag] == fps)];
4075 else if( sel == @selector(setGraphicsMode:) )
4077 NSInteger requestedGraphicsMode = [[NSUserDefaults standardUserDefaults] integerForKey:AngbandGraphicsDefaultsKey];
4078 [menuItem setState: (tag == requestedGraphicsMode)];
4081 else if( sel == @selector(toggleSound:) )
4083 BOOL is_on = [[NSUserDefaults standardUserDefaults]
4084 boolForKey:AngbandSoundDefaultsKey];
4086 [menuItem setState: ((is_on) ? NSOnState : NSOffState)];
4089 else if( sel == @selector(sendAngbandCommand:) ||
4090 sel == @selector(saveGame:) )
4093 * we only want to be able to send commands during an active game
4094 * after the birth screens
4096 return !!game_in_progress && character_generated;
4102 - (IBAction)setRefreshRate:(NSMenuItem *)menuItem
4104 frames_per_second = [menuItem tag];
4105 [[NSUserDefaults angbandDefaults] setInteger:frames_per_second forKey:AngbandFrameRateDefaultsKey];
4108 - (void)selectWindow: (id)sender
4110 NSInteger subwindowNumber = [(NSMenuItem *)sender tag] - AngbandWindowMenuItemTagBase;
4111 AngbandContext *context = angband_term[subwindowNumber]->data;
4112 [context->primaryWindow makeKeyAndOrderFront: self];
4113 [context saveWindowVisibleToDefaults: YES];
4116 - (void)prepareWindowsMenu
4118 /* Get the window menu with default items and add a separator and item for
4119 * the main window */
4120 NSMenu *windowsMenu = [[NSApplication sharedApplication] windowsMenu];
4121 [windowsMenu addItem: [NSMenuItem separatorItem]];
4123 NSString *title1 = [NSString stringWithCString:angband_term_name[0]
4125 encoding:NSJapaneseEUCStringEncoding
4127 encoding:NSMacOSRomanStringEncoding
4130 NSMenuItem *angbandItem = [[NSMenuItem alloc] initWithTitle:title1 action: @selector(selectWindow:) keyEquivalent: @"0"];
4131 [angbandItem setTarget: self];
4132 [angbandItem setTag: AngbandWindowMenuItemTagBase];
4133 [windowsMenu addItem: angbandItem];
4134 [angbandItem release];
4136 /* Add items for the additional term windows */
4137 for( NSInteger i = 1; i < ANGBAND_TERM_MAX; i++ )
4139 NSString *title = [NSString stringWithCString:angband_term_name[i]
4141 encoding:NSJapaneseEUCStringEncoding
4143 encoding:NSMacOSRomanStringEncoding
4146 NSString *keyEquivalent = [NSString stringWithFormat: @"%ld", (long)i];
4147 NSMenuItem *windowItem = [[NSMenuItem alloc] initWithTitle: title action: @selector(selectWindow:) keyEquivalent: keyEquivalent];
4148 [windowItem setTarget: self];
4149 [windowItem setTag: AngbandWindowMenuItemTagBase + i];
4150 [windowsMenu addItem: windowItem];
4151 [windowItem release];
4155 - (void)setGraphicsMode:(NSMenuItem *)sender
4157 /* We stashed the graphics mode ID in the menu item's tag */
4158 graf_mode_req = [sender tag];
4160 /* Stash it in UserDefaults */
4161 [[NSUserDefaults angbandDefaults] setInteger:graf_mode_req forKey:AngbandGraphicsDefaultsKey];
4162 [[NSUserDefaults angbandDefaults] synchronize];
4164 if (game_in_progress)
4166 /* Hack -- Force redraw */
4169 /* Wake up the event loop so it notices the change */
4170 wakeup_event_loop();
4174 - (IBAction) toggleSound: (NSMenuItem *) sender
4176 BOOL is_on = (sender.state == NSOnState);
4178 /* Toggle the state and update the Angband global and preferences. */
4179 sender.state = (is_on) ? NSOffState : NSOnState;
4180 use_sound = (is_on) ? FALSE : TRUE;
4181 [[NSUserDefaults angbandDefaults] setBool:(! is_on)
4182 forKey:AngbandSoundDefaultsKey];
4186 * Send a command to Angband via a menu item. This places the appropriate key
4187 * down events into the queue so that it seems like the user pressed them
4188 * (instead of trying to use the term directly).
4190 - (void)sendAngbandCommand: (id)sender
4192 NSMenuItem *menuItem = (NSMenuItem *)sender;
4193 NSString *command = [self.commandMenuTagMap objectForKey: [NSNumber numberWithInteger: [menuItem tag]]];
4194 NSInteger windowNumber = [((AngbandContext *)angband_term[0]->data)->primaryWindow windowNumber];
4196 /* Send a \ to bypass keymaps */
4197 NSEvent *escape = [NSEvent keyEventWithType: NSKeyDown
4198 location: NSZeroPoint
4201 windowNumber: windowNumber
4204 charactersIgnoringModifiers: @"\\"
4207 [[NSApplication sharedApplication] postEvent: escape atStart: NO];
4209 /* Send the actual command (from the original command set) */
4210 NSEvent *keyDown = [NSEvent keyEventWithType: NSKeyDown
4211 location: NSZeroPoint
4214 windowNumber: windowNumber
4217 charactersIgnoringModifiers: command
4220 [[NSApplication sharedApplication] postEvent: keyDown atStart: NO];
4224 * Set up the command menu dynamically, based on CommandMenu.plist.
4226 - (void)prepareCommandMenu
4228 NSString *commandMenuPath = [[NSBundle mainBundle] pathForResource: @"CommandMenu" ofType: @"plist"];
4229 NSArray *commandMenuItems = [[NSArray alloc] initWithContentsOfFile: commandMenuPath];
4230 NSMutableDictionary *angbandCommands = [[NSMutableDictionary alloc] init];
4231 NSString *tblname = @"CommandMenu";
4232 NSInteger tagOffset = 0;
4234 for( NSDictionary *item in commandMenuItems )
4236 BOOL useShiftModifier = [[item valueForKey: @"ShiftModifier"] boolValue];
4237 BOOL useOptionModifier = [[item valueForKey: @"OptionModifier"] boolValue];
4238 NSUInteger keyModifiers = NSCommandKeyMask;
4239 keyModifiers |= (useShiftModifier) ? NSShiftKeyMask : 0;
4240 keyModifiers |= (useOptionModifier) ? NSAlternateKeyMask : 0;
4242 NSString *lookup = [item valueForKey: @"Title"];
4243 NSString *title = NSLocalizedStringWithDefaultValue(
4244 lookup, tblname, [NSBundle mainBundle], lookup, @"");
4245 NSString *key = [item valueForKey: @"KeyEquivalent"];
4246 NSMenuItem *menuItem = [[NSMenuItem alloc] initWithTitle: title action: @selector(sendAngbandCommand:) keyEquivalent: key];
4247 [menuItem setTarget: self];
4248 [menuItem setKeyEquivalentModifierMask: keyModifiers];
4249 [menuItem setTag: AngbandCommandMenuItemTagBase + tagOffset];
4250 [self.commandMenu addItem: menuItem];
4253 NSString *angbandCommand = [item valueForKey: @"AngbandCommand"];
4254 [angbandCommands setObject: angbandCommand forKey: [NSNumber numberWithInteger: [menuItem tag]]];
4258 [commandMenuItems release];
4260 NSDictionary *safeCommands = [[NSDictionary alloc] initWithDictionary: angbandCommands];
4261 self.commandMenuTagMap = safeCommands;
4262 [safeCommands release];
4263 [angbandCommands release];
4266 - (void)awakeFromNib
4268 [super awakeFromNib];
4270 [self prepareWindowsMenu];
4271 [self prepareCommandMenu];
4274 - (void)applicationDidFinishLaunching:sender
4276 [AngbandContext beginGame];
4278 /* Once beginGame finished, the game is over - that's how Angband works,
4279 * and we should quit */
4280 game_is_finished = TRUE;
4281 [NSApp terminate:self];
4284 - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
4286 if (p_ptr->playing == FALSE || game_is_finished == TRUE)
4288 return NSTerminateNow;
4290 else if (! inkey_flag)
4292 /* For compatibility with other ports, do not quit in this case */
4293 return NSTerminateCancel;
4298 /* player->upkeep->playing = FALSE; */
4300 /* Post an escape event so that we can return from our get-key-event
4302 wakeup_event_loop();
4303 quit_when_ready = true;
4304 /* Must return Cancel, not Later, because we need to get out of the
4305 * run loop and back to Angband's loop */
4306 return NSTerminateCancel;
4311 * Dynamically build the Graphics menu
4313 - (void)menuNeedsUpdate:(NSMenu *)menu {
4315 /* Only the graphics menu is dynamic */
4316 if (! [menu isEqual:self.graphicsMenu])
4319 /* If it's non-empty, then we've already built it. Currently graphics modes
4320 * won't change once created; if they ever can we can remove this check.
4321 * Note that the check mark does change, but that's handled in
4322 * validateMenuItem: instead of menuNeedsUpdate: */
4323 if ([menu numberOfItems] > 0)
4326 /* This is the action for all these menu items */
4327 SEL action = @selector(setGraphicsMode:);
4329 /* Add an initial Classic ASCII menu item */
4330 NSString *tblname = @"GraphicsMenu";
4331 NSString *key = @"Classic ASCII";
4332 NSString *title = NSLocalizedStringWithDefaultValue(
4333 key, tblname, [NSBundle mainBundle], key, @"");
4334 NSMenuItem *classicItem = [menu addItemWithTitle:title action:action keyEquivalent:@""];
4335 [classicItem setTag:GRAPHICS_NONE];
4337 /* Walk through the list of graphics modes */
4338 if (graphics_modes) {
4341 for (i=0; graphics_modes[i].pNext; i++)
4343 const graphics_mode *graf = &graphics_modes[i];
4345 if (graf->grafID == GRAPHICS_NONE) {
4348 /* Make the title. NSMenuItem throws on a nil title, so ensure it's
4350 key = [[NSString alloc] initWithUTF8String:graf->menuname];
4351 title = NSLocalizedStringWithDefaultValue(
4352 key, tblname, [NSBundle mainBundle], key, @"");
4355 NSMenuItem *item = [menu addItemWithTitle:title action:action keyEquivalent:@""];
4357 [item setTag:graf->grafID];
4363 * Delegate method that gets called if we're asked to open a file.
4365 - (void)application:(NSApplication *)sender openFiles:(NSArray *)filenames
4367 /* Can't open a file once we've started */
4368 if (game_in_progress) {
4369 [[NSApplication sharedApplication]
4370 replyToOpenOrPrint:NSApplicationDelegateReplyFailure];
4374 /* We can only open one file. Use the last one. */
4375 NSString *file = [filenames lastObject];
4377 [[NSApplication sharedApplication]
4378 replyToOpenOrPrint:NSApplicationDelegateReplyFailure];
4382 /* Put it in savefile */
4383 if (! [file getFileSystemRepresentation:savefile maxLength:sizeof savefile]) {
4384 [[NSApplication sharedApplication]
4385 replyToOpenOrPrint:NSApplicationDelegateReplyFailure];
4389 game_in_progress = TRUE;
4392 /* Wake us up in case this arrives while we're sitting at the Welcome
4394 wakeup_event_loop();
4396 [[NSApplication sharedApplication]
4397 replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
4402 int main(int argc, char* argv[])
4404 NSApplicationMain(argc, (void*)argv);
4408 #endif /* MACINTOSH || MACH_O_COCOA */