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 * termIdx is the index for the terminal: pass it so this function can be
472 * used when self->terminal has not yet been set.
474 - (void)setMinimumWindowSize:(int)termIdx;
476 /* Called from the view to indicate that it is starting or ending live resize */
477 - (void)viewWillStartLiveResize:(AngbandView *)view;
478 - (void)viewDidEndLiveResize:(AngbandView *)view;
479 - (void)saveWindowVisibleToDefaults: (BOOL)windowVisible;
480 - (BOOL)windowVisibleUsingDefaults;
484 /* Begins an Angband game. This is the entry point for starting off. */
487 /* Internal method */
488 - (AngbandView *)activeView;
493 * Generate a mask for the subwindow flags. The mask is just a safety check to
494 * make sure that our windows show and hide as expected. This function allows
495 * for future changes to the set of flags without needed to update it here
496 * (unless the underlying types change).
498 u32b AngbandMaskForValidSubwindowFlags(void)
500 int windowFlagBits = sizeof(*(window_flag)) * CHAR_BIT;
501 int maxBits = MIN( 16, windowFlagBits );
504 for( int i = 0; i < maxBits; i++ )
506 if( window_flag_desc[i] != NULL )
516 * Check for changes in the subwindow flags and update window visibility.
517 * This seems to be called for every user event, so we don't
518 * want to do any unnecessary hiding or showing of windows.
520 static void AngbandUpdateWindowVisibility(void)
522 /* Because this function is called frequently, we'll make the mask static.
523 * It doesn't change between calls, as the flags themselves are hardcoded */
524 static u32b validWindowFlagsMask = 0;
526 if( validWindowFlagsMask == 0 )
528 validWindowFlagsMask = AngbandMaskForValidSubwindowFlags();
531 /* Loop through all of the subwindows and see if there is a change in the
532 * flags. If so, show or hide the corresponding window. We don't care about
533 * the flags themselves; we just want to know if any are set. */
534 for( int i = 1; i < ANGBAND_TERM_MAX; i++ )
536 AngbandContext *angbandContext = angband_term[i]->data;
538 if( angbandContext == nil )
543 /* This horrible mess of flags is so that we can try to maintain some
544 * user visibility preference. This should allow the user a window and
545 * have it stay closed between application launches. However, this
546 * means that when a subwindow is turned on, it will no longer appear
547 * automatically. Angband has no concept of user control over window
548 * visibility, other than the subwindow flags. */
549 if( !angbandContext.windowVisibilityChecked )
551 if( [angbandContext windowVisibleUsingDefaults] )
553 [angbandContext->primaryWindow orderFront: nil];
554 angbandContext.windowVisibilityChecked = YES;
558 [angbandContext->primaryWindow close];
559 angbandContext.windowVisibilityChecked = NO;
564 BOOL termHasSubwindowFlags = ((window_flag[i] & validWindowFlagsMask) > 0);
566 if( angbandContext.hasSubwindowFlags && !termHasSubwindowFlags )
568 [angbandContext->primaryWindow close];
569 angbandContext.hasSubwindowFlags = NO;
570 [angbandContext saveWindowVisibleToDefaults: NO];
572 else if( !angbandContext.hasSubwindowFlags && termHasSubwindowFlags )
574 [angbandContext->primaryWindow orderFront: nil];
575 angbandContext.hasSubwindowFlags = YES;
576 [angbandContext saveWindowVisibleToDefaults: YES];
581 /* Make the main window key so that user events go to the right spot */
582 AngbandContext *mainWindow = angband_term[0]->data;
583 [mainWindow->primaryWindow makeKeyAndOrderFront: nil];
587 * ------------------------------------------------------------------------
589 * ------------------------------------------------------------------------ */
594 static CGImageRef pict_image;
597 * Numbers of rows and columns in a tileset,
598 * calculated by the PICT/PNG loading code
600 static int pict_cols = 0;
601 static int pict_rows = 0;
604 * Requested graphics mode (as a grafID).
605 * The current mode is stored in current_graphics_mode.
607 static int graf_mode_req = 0;
610 * Helper function to check the various ways that graphics can be enabled,
611 * guarding against NULL
613 static BOOL graphics_are_enabled(void)
615 return current_graphics_mode
616 && current_graphics_mode->grafID != GRAPHICS_NONE;
620 * Hack -- game in progress
622 static Boolean game_in_progress = FALSE;
625 #pragma mark Prototypes
626 static void wakeup_event_loop(void);
627 static void hook_plog(const char *str);
628 static void hook_quit(const char * str);
629 static void load_prefs(void);
630 static void load_sounds(void);
631 static void init_windows(void);
632 static void handle_open_when_ready(void);
633 static void play_sound(int event);
634 static BOOL check_events(int wait);
635 static BOOL send_event(NSEvent *event);
636 static void record_current_savefile(void);
638 static wchar_t convert_two_byte_eucjp_to_utf16_native(const char *cp);
642 * Available values for 'wait'
644 #define CHECK_EVENTS_DRAIN -1
645 #define CHECK_EVENTS_NO_WAIT 0
646 #define CHECK_EVENTS_WAIT 1
650 * Note when "open"/"new" become valid
652 static bool initialized = FALSE;
654 /* Methods for getting the appropriate NSUserDefaults */
655 @interface NSUserDefaults (AngbandDefaults)
656 + (NSUserDefaults *)angbandDefaults;
659 @implementation NSUserDefaults (AngbandDefaults)
660 + (NSUserDefaults *)angbandDefaults
662 return [NSUserDefaults standardUserDefaults];
666 /* Methods for pulling images out of the Angband bundle (which may be separate
667 * from the current bundle in the case of a screensaver */
668 @interface NSImage (AngbandImages)
669 + (NSImage *)angbandImage:(NSString *)name;
672 /* The NSView subclass that draws our Angband image */
673 @interface AngbandView : NSView
675 AngbandContext *angbandContext;
678 - (void)setAngbandContext:(AngbandContext *)context;
679 - (AngbandContext *)angbandContext;
683 @implementation NSImage (AngbandImages)
685 /* Returns an image in the resource directoy of the bundle containing the
686 * Angband view class. */
687 + (NSImage *)angbandImage:(NSString *)name
689 NSBundle *bundle = [NSBundle bundleForClass:[AngbandView class]];
690 NSString *path = [bundle pathForImageResource:name];
692 if (path) result = [[[NSImage alloc] initByReferencingFile:path] autorelease];
700 @implementation AngbandContext
702 @synthesize hasSubwindowFlags=_hasSubwindowFlags;
703 @synthesize windowVisibilityChecked=_windowVisibilityChecked;
705 - (NSFont *)selectionFont
707 return angbandViewFont;
710 - (BOOL)useLiveResizeOptimization
712 /* If we have graphics turned off, text rendering is fast enough that we
713 * don't need to use a live resize optimization. */
714 return inLiveResize && graphics_are_enabled();
719 /* We round the base size down. If we round it up, I believe we may end up
720 * with pixels that nobody "owns" that may accumulate garbage. In general
721 * rounding down is harmless, because any lost pixels may be sopped up by
723 return NSMakeSize(floor(cols * tileSize.width + 2 * borderSize.width), floor(rows * tileSize.height + 2 * borderSize.height));
726 /* qsort-compatible compare function for CGSizes */
727 static int compare_advances(const void *ap, const void *bp)
729 const CGSize *a = ap, *b = bp;
730 return (a->width > b->width) - (a->width < b->width);
733 - (void)updateGlyphInfo
735 /* Update glyphArray and glyphWidths */
736 NSFont *screenFont = [angbandViewFont screenFont];
738 /* Generate a string containing each MacRoman character */
739 unsigned char latinString[GLYPH_COUNT];
741 for (i=0; i < GLYPH_COUNT; i++) latinString[i] = (unsigned char)i;
743 /* Turn that into unichar. Angband uses ISO Latin 1. */
744 unichar unicharString[GLYPH_COUNT] = {0};
745 NSString *allCharsString = [[NSString alloc] initWithBytes:latinString length:sizeof latinString encoding:NSISOLatin1StringEncoding];
746 [allCharsString getCharacters:unicharString range:NSMakeRange(0, MIN(GLYPH_COUNT, [allCharsString length]))];
747 [allCharsString autorelease];
750 memset(glyphArray, 0, sizeof glyphArray);
751 CTFontGetGlyphsForCharacters((CTFontRef)screenFont, unicharString, glyphArray, GLYPH_COUNT);
753 /* Get advances. Record the max advance. */
754 CGSize advances[GLYPH_COUNT] = {};
755 CTFontGetAdvancesForGlyphs((CTFontRef)screenFont, kCTFontHorizontalOrientation, glyphArray, advances, GLYPH_COUNT);
756 for (i=0; i < GLYPH_COUNT; i++) {
757 glyphWidths[i] = advances[i].width;
760 /* For good non-mono-font support, use the median advance. Start by sorting
762 qsort(advances, GLYPH_COUNT, sizeof *advances, compare_advances);
764 /* Skip over any initially empty run */
766 for (startIdx = 0; startIdx < GLYPH_COUNT; startIdx++)
768 if (advances[startIdx].width > 0) break;
771 /* Pick the center to find the median */
772 CGFloat medianAdvance = 0;
773 if (startIdx < GLYPH_COUNT)
775 /* In case we have all zero advances for some reason */
776 medianAdvance = advances[(startIdx + GLYPH_COUNT)/2].width;
780 * Record the ascender and descender. Some fonts, for instance DIN
781 * Condensed and Rockwell in 10.14, the ascent on '@' exceeds that
782 * reported by [screenFont ascender]. Get the overall bounding box
783 * for the glyphs and use that instead of the ascender and descender
784 * values if the bounding box result extends farther from the baseline.
786 CGRect bounds = CTFontGetBoundingRectsForGlyphs((CTFontRef) screenFont, kCTFontHorizontalOrientation, glyphArray, NULL, GLYPH_COUNT);
787 fontAscender = [screenFont ascender];
788 if (fontAscender < bounds.origin.y + bounds.size.height) {
789 fontAscender = bounds.origin.y + bounds.size.height;
791 fontDescender = [screenFont descender];
792 if (fontDescender > bounds.origin.y) {
793 fontDescender = bounds.origin.y;
797 * Record the tile size. Round both values up to have tile boundaries
798 * match pixel boundaries.
800 tileSize.width = ceil(medianAdvance);
801 tileSize.height = ceil(fontAscender - fontDescender);
804 * Determine whether neighboring columns need to redrawn when a character
807 CGRect boxes[GLYPH_COUNT] = {};
808 CGFloat beyond_right = 0.;
809 CGFloat beyond_left = 0.;
810 CTFontGetBoundingRectsForGlyphs(
811 (CTFontRef)screenFont,
812 kCTFontHorizontalOrientation,
816 for (i = 0; i < GLYPH_COUNT; i++) {
817 /* Account for the compression and offset used by drawWChar(). */
818 CGFloat compression, offset;
821 if (glyphWidths[i] <= tileSize.width) {
823 offset = 0.5 * (tileSize.width - glyphWidths[i]);
825 compression = tileSize.width / glyphWidths[i];
828 v = (offset + boxes[i].origin.x) * compression;
829 if (beyond_left > v) {
832 v = (offset + boxes[i].origin.x + boxes[i].size.width) * compression;
833 if (beyond_right < v) {
837 ncol_pre = ceil(-beyond_left / tileSize.width);
838 if (beyond_right > tileSize.width) {
839 ncol_post = ceil((beyond_right - tileSize.width) / tileSize.width);
847 NSSize size = NSMakeSize(1, 1);
849 AngbandView *activeView = [self activeView];
852 /* If we are in live resize, draw as big as the screen, so we can scale
853 * nicely to any size. If we are not in live resize, then use the
854 * bounds of the active view. */
856 if ([self useLiveResizeOptimization] && (screen = [[activeView window] screen]) != NULL)
858 size = [screen frame].size;
862 size = [activeView bounds].size;
866 CGLayerRelease(angbandLayer);
868 /* Use the highest monitor scale factor on the system to work out what
869 * scale to draw at - not the recommended method, but works where we
870 * can't easily get the monitor the current draw is occurring on. */
871 float angbandLayerScale = 1.0;
872 if ([[NSScreen mainScreen] respondsToSelector:@selector(backingScaleFactor)]) {
873 for (NSScreen *screen in [NSScreen screens]) {
874 angbandLayerScale = fmax(angbandLayerScale, [screen backingScaleFactor]);
878 /* Make a bitmap context as an example for our layer */
879 CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();
880 CGContextRef exampleCtx = CGBitmapContextCreate(NULL, 1, 1, 8 /* bits per component */, 48 /* bytesPerRow */, cs, kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Host);
881 CGColorSpaceRelease(cs);
883 /* Create the layer at the appropriate size */
884 size.width = fmax(1, ceil(size.width * angbandLayerScale));
885 size.height = fmax(1, ceil(size.height * angbandLayerScale));
886 angbandLayer = CGLayerCreateWithContext(exampleCtx, *(CGSize *)&size, NULL);
888 CFRelease(exampleCtx);
890 /* Set the new context of the layer to draw at the correct scale */
891 CGContextRef ctx = CGLayerGetContext(angbandLayer);
892 CGContextScaleCTM(ctx, angbandLayerScale, angbandLayerScale);
895 [[NSColor blackColor] set];
896 NSRectFill((NSRect){NSZeroPoint, [self baseSize]});
900 - (void)requestRedraw
902 if (! self->terminal) return;
906 /* Activate the term */
907 Term_activate(self->terminal);
909 /* Redraw the contents */
912 /* Flush the output */
915 /* Restore the old term */
919 - (void)setTerm:(term *)t
924 - (void)viewWillStartLiveResize:(AngbandView *)view
926 #if USE_LIVE_RESIZE_CACHE
927 if (inLiveResize < INT_MAX) inLiveResize++;
928 else [NSException raise:NSInternalInconsistencyException format:@"inLiveResize overflow"];
930 if (inLiveResize == 1 && graphics_are_enabled())
934 [self setNeedsDisplay:YES]; /* We'll need to redisplay everything anyways, so avoid creating all those little redisplay rects */
935 [self requestRedraw];
940 - (void)viewDidEndLiveResize:(AngbandView *)view
942 #if USE_LIVE_RESIZE_CACHE
943 if (inLiveResize > 0) inLiveResize--;
944 else [NSException raise:NSInternalInconsistencyException format:@"inLiveResize underflow"];
946 if (inLiveResize == 0 && graphics_are_enabled())
950 [self setNeedsDisplay:YES]; /* We'll need to redisplay everything anyways, so avoid creating all those little redisplay rects */
951 [self requestRedraw];
957 * If we're trying to limit ourselves to a certain number of frames per second,
958 * then compute how long it's been since we last drew, and then wait until the
959 * next frame has passed. */
962 if (frames_per_second > 0)
964 CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
965 CFTimeInterval timeSinceLastRefresh = now - lastRefreshTime;
966 CFTimeInterval timeUntilNextRefresh = (1. / (double)frames_per_second) - timeSinceLastRefresh;
968 if (timeUntilNextRefresh > 0)
970 usleep((unsigned long)(timeUntilNextRefresh * 1000000.));
973 lastRefreshTime = CFAbsoluteTimeGetCurrent();
976 - (void)drawWChar:(wchar_t)wchar inRect:(NSRect)tile context:(CGContextRef)ctx
978 CGFloat tileOffsetY = fontAscender;
979 CGFloat tileOffsetX = 0.0;
980 NSFont *screenFont = [angbandViewFont screenFont];
981 UniChar unicharString[2] = {(UniChar)wchar, 0};
983 /* Get glyph and advance */
984 CGGlyph thisGlyphArray[1] = { 0 };
985 CGSize advances[1] = { { 0, 0 } };
986 CTFontGetGlyphsForCharacters((CTFontRef)screenFont, unicharString, thisGlyphArray, 1);
987 CGGlyph glyph = thisGlyphArray[0];
988 CTFontGetAdvancesForGlyphs((CTFontRef)screenFont, kCTFontHorizontalOrientation, thisGlyphArray, advances, 1);
989 CGSize advance = advances[0];
991 /* If our font is not monospaced, our tile width is deliberately not big
992 * enough for every character. In that event, if our glyph is too wide, we
993 * need to compress it horizontally. Compute the compression ratio.
994 * 1.0 means no compression. */
995 double compressionRatio;
996 if (advance.width <= NSWidth(tile))
998 /* Our glyph fits, so we can just draw it, possibly with an offset */
999 compressionRatio = 1.0;
1000 tileOffsetX = (NSWidth(tile) - advance.width)/2;
1004 /* Our glyph doesn't fit, so we'll have to compress it */
1005 compressionRatio = NSWidth(tile) / advance.width;
1011 CGAffineTransform textMatrix = CGContextGetTextMatrix(ctx);
1012 CGFloat savedA = textMatrix.a;
1014 /* Set the position */
1015 textMatrix.tx = tile.origin.x + tileOffsetX;
1016 textMatrix.ty = tile.origin.y + tileOffsetY;
1018 /* Maybe squish it horizontally. */
1019 if (compressionRatio != 1.)
1021 textMatrix.a *= compressionRatio;
1024 textMatrix = CGAffineTransformScale( textMatrix, 1.0, -1.0 );
1025 CGContextSetTextMatrix(ctx, textMatrix);
1026 CGContextShowGlyphsAtPositions(ctx, &glyph, &CGPointZero, 1);
1028 /* Restore the text matrix if we messed with the compression ratio */
1029 if (compressionRatio != 1.)
1031 textMatrix.a = savedA;
1032 CGContextSetTextMatrix(ctx, textMatrix);
1035 textMatrix = CGAffineTransformScale( textMatrix, 1.0, -1.0 );
1036 CGContextSetTextMatrix(ctx, textMatrix);
1039 /* Lock and unlock focus on our image or layer, setting up the CTM
1041 - (CGContextRef)lockFocusUnscaled
1043 /* Create an NSGraphicsContext representing this CGLayer */
1044 CGContextRef ctx = CGLayerGetContext(angbandLayer);
1045 NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithGraphicsPort:ctx flipped:NO];
1046 [NSGraphicsContext saveGraphicsState];
1047 [NSGraphicsContext setCurrentContext:context];
1048 CGContextSaveGState(ctx);
1054 /* Restore the graphics state */
1055 CGContextRef ctx = [[NSGraphicsContext currentContext] graphicsPort];
1056 CGContextRestoreGState(ctx);
1057 [NSGraphicsContext restoreGraphicsState];
1062 /* Return the size of our layer */
1063 CGSize result = CGLayerGetSize(angbandLayer);
1064 return NSMakeSize(result.width, result.height);
1067 - (CGContextRef)lockFocus
1069 return [self lockFocusUnscaled];
1073 - (NSRect)rectInImageForTileAtX:(int)x Y:(int)y
1076 return NSMakeRect(x * tileSize.width + borderSize.width, flippedY * tileSize.height + borderSize.height, tileSize.width, tileSize.height);
1079 - (void)setSelectionFont:(NSFont*)font adjustTerminal: (BOOL)adjustTerminal
1081 /* Record the new font */
1083 [angbandViewFont release];
1084 angbandViewFont = font;
1086 /* Update our glyph info */
1087 [self updateGlyphInfo];
1089 if( adjustTerminal )
1091 /* Adjust terminal to fit window with new font; save the new columns
1092 * and rows since they could be changed */
1093 NSRect contentRect = [self->primaryWindow contentRectForFrameRect: [self->primaryWindow frame]];
1095 [self setMinimumWindowSize:[self terminalIndex]];
1096 NSSize size = self->primaryWindow.contentMinSize;
1097 BOOL windowNeedsResizing = NO;
1098 if (contentRect.size.width < size.width) {
1099 contentRect.size.width = size.width;
1100 windowNeedsResizing = YES;
1102 if (contentRect.size.height < size.height) {
1103 contentRect.size.height = size.height;
1104 windowNeedsResizing = YES;
1106 if (windowNeedsResizing) {
1107 size.width = contentRect.size.width;
1108 size.height = contentRect.size.height;
1109 [self->primaryWindow setContentSize:size];
1111 [self resizeTerminalWithContentRect: contentRect saveToDefaults: YES];
1114 /* Update our image */
1120 if ((self = [super init]))
1122 /* Default rows and cols */
1126 /* Default border size */
1127 self->borderSize = NSMakeSize(2, 2);
1129 /* Allocate our array of views */
1130 angbandViews = [[NSMutableArray alloc] init];
1132 self->changes = create_pending_changes(self->cols, self->rows);
1133 if (self->changes == 0) {
1134 NSLog(@"AngbandContext init: out of memory for pending changes");
1137 self->ncol_post = 0;
1139 self->in_fullscreen_transition = NO;
1141 /* Make the image. Since we have no views, it'll just be a puny 1x1 image. */
1144 _windowVisibilityChecked = NO;
1150 * Destroy all the receiver's stuff. This is intended to be callable more than
1157 /* Disassociate ourselves from our angbandViews */
1158 [angbandViews makeObjectsPerformSelector:@selector(setAngbandContext:) withObject:nil];
1159 [angbandViews release];
1162 /* Destroy the layer/image */
1163 CGLayerRelease(angbandLayer);
1164 angbandLayer = NULL;
1167 [angbandViewFont release];
1168 angbandViewFont = nil;
1171 [primaryWindow setDelegate:nil];
1172 [primaryWindow close];
1173 [primaryWindow release];
1174 primaryWindow = nil;
1176 /* Pending changes */
1177 destroy_pending_changes(self->changes);
1181 /* Usual Cocoa fare */
1191 #pragma mark Directories and Paths Setup
1194 * Return the path for Angband's lib directory and bail if it isn't found. The
1195 * lib directory should be in the bundle's resources directory, since it's
1196 * copied when built.
1198 + (NSString *)libDirectoryPath
1200 NSString *bundleLibPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: AngbandDirectoryNameLib];
1201 BOOL isDirectory = NO;
1202 BOOL libExists = [[NSFileManager defaultManager] fileExistsAtPath: bundleLibPath isDirectory: &isDirectory];
1204 if( !libExists || !isDirectory )
1206 NSLog( @"[%@ %@]: can't find %@/ in bundle: isDirectory: %d libExists: %d", NSStringFromClass( [self class] ), NSStringFromSelector( _cmd ), AngbandDirectoryNameLib, isDirectory, libExists );
1208 NSString *msg = NSLocalizedStringWithDefaultValue(
1209 @"Error.MissingResources",
1210 AngbandMessageCatalog,
1211 [NSBundle mainBundle],
1212 @"Missing Resources",
1213 @"Alert text for missing resources");
1214 NSString *info = NSLocalizedStringWithDefaultValue(
1215 @"Error.MissingAngbandLib",
1216 AngbandMessageCatalog,
1217 [NSBundle mainBundle],
1218 @"Hengband was unable to find required resources and must quit. Please report a bug on the Angband forums.",
1219 @"Alert informative message for missing Angband lib/ folder");
1220 NSString *quit_label = NSLocalizedStringWithDefaultValue(
1221 @"Label.Quit", AngbandMessageCatalog, [NSBundle mainBundle],
1223 NSAlert *alert = [[NSAlert alloc] init];
1226 * Note that NSCriticalAlertStyle was deprecated in 10.10. The
1227 * replacement is NSAlertStyleCritical.
1229 alert.alertStyle = NSCriticalAlertStyle;
1230 alert.messageText = msg;
1231 alert.informativeText = info;
1232 [alert addButtonWithTitle:quit_label];
1233 NSModalResponse result = [alert runModal];
1238 return bundleLibPath;
1242 * Return the path for the directory where Angband should look for its standard
1245 + (NSString *)angbandDocumentsPath
1247 NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
1249 #if defined(SAFE_DIRECTORY)
1250 NSString *versionedDirectory = [NSString stringWithFormat: @"%@-%s", AngbandDirectoryNameBase, VERSION_STRING];
1251 return [documents stringByAppendingPathComponent: versionedDirectory];
1253 return [documents stringByAppendingPathComponent: AngbandDirectoryNameBase];
1258 * Adjust directory paths as needed to correct for any differences needed by
1259 * Angband. \c init_file_paths() currently requires that all paths provided have
1260 * a trailing slash and all other platforms honor this.
1262 * \param originalPath The directory path to adjust.
1263 * \return A path suitable for Angband or nil if an error occurred.
1265 static NSString *AngbandCorrectedDirectoryPath(NSString *originalPath)
1267 if ([originalPath length] == 0) {
1271 if (![originalPath hasSuffix: @"/"]) {
1272 return [originalPath stringByAppendingString: @"/"];
1275 return originalPath;
1279 * Give Angband the base paths that should be used for the various directories
1280 * it needs. It will create any needed directories.
1282 + (void)prepareFilePathsAndDirectories
1284 char libpath[PATH_MAX + 1] = "\0";
1285 NSString *libDirectoryPath = AngbandCorrectedDirectoryPath([self libDirectoryPath]);
1286 [libDirectoryPath getFileSystemRepresentation: libpath maxLength: sizeof(libpath)];
1288 char basepath[PATH_MAX + 1] = "\0";
1289 NSString *angbandDocumentsPath = AngbandCorrectedDirectoryPath([self angbandDocumentsPath]);
1290 [angbandDocumentsPath getFileSystemRepresentation: basepath maxLength: sizeof(basepath)];
1292 init_file_paths(libpath, basepath);
1293 create_needed_dirs();
1299 /* From the Linux mbstowcs(3) man page:
1300 * If dest is NULL, n is ignored, and the conversion proceeds as above,
1301 * except that the converted wide characters are not written out to mem‐
1302 * ory, and that no length limit exists.
1304 static size_t Term_mbcs_cocoa(wchar_t *dest, const char *src, int n)
1309 /* Unicode code point to UTF-8
1310 * 0x0000-0x007f: 0xxxxxxx
1311 * 0x0080-0x07ff: 110xxxxx 10xxxxxx
1312 * 0x0800-0xffff: 1110xxxx 10xxxxxx 10xxxxxx
1313 * 0x10000-0x1fffff: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
1314 * Note that UTF-16 limits Unicode to 0x10ffff. This code is not
1317 for (i = 0; i < n || dest == NULL; i++) {
1318 if ((src[i] & 0x80) == 0) {
1319 if (dest != NULL) dest[count] = src[i];
1320 if (src[i] == 0) break;
1321 } else if ((src[i] & 0xe0) == 0xc0) {
1322 if (dest != NULL) dest[count] =
1323 (((unsigned char)src[i] & 0x1f) << 6)|
1324 ((unsigned char)src[i+1] & 0x3f);
1326 } else if ((src[i] & 0xf0) == 0xe0) {
1327 if (dest != NULL) dest[count] =
1328 (((unsigned char)src[i] & 0x0f) << 12) |
1329 (((unsigned char)src[i+1] & 0x3f) << 6) |
1330 ((unsigned char)src[i+2] & 0x3f);
1332 } else if ((src[i] & 0xf8) == 0xf0) {
1333 if (dest != NULL) dest[count] =
1334 (((unsigned char)src[i] & 0x0f) << 18) |
1335 (((unsigned char)src[i+1] & 0x3f) << 12) |
1336 (((unsigned char)src[i+2] & 0x3f) << 6) |
1337 ((unsigned char)src[i+3] & 0x3f);
1340 /* Found an invalid multibyte sequence */
1350 * Entry point for initializing Angband
1354 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1356 /* Hooks in some "z-util.c" hooks */
1357 plog_aux = hook_plog;
1358 quit_aux = hook_quit;
1360 /* Initialize file paths */
1361 [self prepareFilePathsAndDirectories];
1363 /* Note the "system" */
1364 ANGBAND_SYS = "coc";
1366 /* Load preferences */
1369 /* Load possible graphics modes */
1370 init_graphics_modes();
1372 /* Prepare the windows */
1375 /* Set up game event handlers */
1376 /* init_display(); */
1378 /* Register the sound hook */
1379 /* sound_hook = play_sound; */
1381 /* Initialise game */
1384 /* Initialize some save file stuff */
1385 player_egid = getegid();
1387 /* We are now initialized */
1390 /* Handle "open_when_ready" */
1391 handle_open_when_ready();
1393 /* Handle pending events (most notably update) and flush input */
1396 /* Prompt the user. */
1397 int message_row = (Term->hgt - 23) / 5 + 23;
1398 Term_erase(0, message_row, 255);
1401 "['ファイル' メニューから '新' または '開く' を選択します]",
1402 message_row, (Term->wid - 57) / 2
1404 "[Choose 'New' or 'Open' from the 'File' menu]",
1405 message_row, (Term->wid - 45) / 2
1411 * Play a game -- "new_game" is set by "new", "open" or the open document
1412 * even handler as appropriate
1417 while (!game_in_progress) {
1418 NSAutoreleasePool *splashScreenPool = [[NSAutoreleasePool alloc] init];
1419 NSEvent *event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:[NSDate distantFuture] inMode:NSDefaultRunLoopMode dequeue:YES];
1420 if (event) [NSApp sendEvent:event];
1421 [splashScreenPool drain];
1425 play_game(new_game);
1430 - (void)addAngbandView:(AngbandView *)view
1432 if (! [angbandViews containsObject:view])
1434 [angbandViews addObject:view];
1436 [self setNeedsDisplay:YES]; /* We'll need to redisplay everything anyways, so avoid creating all those little redisplay rects */
1437 [self requestRedraw];
1442 * We have this notion of an "active" AngbandView, which is the largest - the
1443 * idea being that in the screen saver, when the user hits Test in System
1444 * Preferences, we don't want to keep driving the AngbandView in the
1445 * background. Our active AngbandView is the widest - that's a hack all right.
1446 * Mercifully when we're just playing the game there's only one view.
1448 - (AngbandView *)activeView
1450 if ([angbandViews count] == 1)
1451 return [angbandViews objectAtIndex:0];
1453 AngbandView *result = nil;
1455 for (AngbandView *angbandView in angbandViews)
1457 float width = [angbandView frame].size.width;
1458 if (width > maxWidth)
1461 result = angbandView;
1467 - (void)angbandViewDidScale:(AngbandView *)view
1469 /* If we're live-resizing with graphics, we're using the live resize
1470 * optimization, so don't update the image. Otherwise do it. */
1471 if (! (inLiveResize && graphics_are_enabled()) && view == [self activeView])
1475 [self setNeedsDisplay:YES]; /*we'll need to redisplay everything anyways, so avoid creating all those little redisplay rects */
1476 [self requestRedraw];
1481 - (void)removeAngbandView:(AngbandView *)view
1483 if ([angbandViews containsObject:view])
1485 [angbandViews removeObject:view];
1487 [self setNeedsDisplay:YES]; /* We'll need to redisplay everything anyways, so avoid creating all those little redisplay rects */
1488 if ([angbandViews count]) [self requestRedraw];
1493 - (NSWindow *)makePrimaryWindow
1495 if (! primaryWindow)
1497 /* This has to be done after the font is set, which it already is in
1498 * term_init_cocoa() */
1499 CGFloat width = self->cols * tileSize.width + borderSize.width * 2.0;
1500 CGFloat height = self->rows * tileSize.height + borderSize.height * 2.0;
1501 NSRect contentRect = NSMakeRect( 0.0, 0.0, width, height );
1503 NSUInteger styleMask = NSTitledWindowMask | NSResizableWindowMask | NSMiniaturizableWindowMask;
1505 /* Make every window other than the main window closable */
1506 if( angband_term[0]->data != self )
1508 styleMask |= NSClosableWindowMask;
1511 primaryWindow = [[NSWindow alloc] initWithContentRect:contentRect styleMask: styleMask backing:NSBackingStoreBuffered defer:YES];
1513 /* Not to be released when closed */
1514 [primaryWindow setReleasedWhenClosed:NO];
1515 [primaryWindow setExcludedFromWindowsMenu: YES]; /* we're using custom window menu handling */
1518 AngbandView *angbandView = [[AngbandView alloc] initWithFrame:contentRect];
1519 [angbandView setAngbandContext:self];
1520 [angbandViews addObject:angbandView];
1521 [primaryWindow setContentView:angbandView];
1522 [angbandView release];
1524 /* We are its delegate */
1525 [primaryWindow setDelegate:self];
1527 /* Update our image, since this is probably the first angband view
1531 return primaryWindow;
1536 #pragma mark View/Window Passthrough
1539 * This is what our views call to get us to draw to the window
1541 - (void)drawRect:(NSRect)rect inView:(NSView *)view
1543 /* Take this opportunity to throttle so we don't flush faster than desired.
1545 BOOL viewInLiveResize = [view inLiveResize];
1546 if (! viewInLiveResize) [self throttle];
1548 /* With a GLayer, use CGContextDrawLayerInRect */
1549 CGContextRef context = [[NSGraphicsContext currentContext] graphicsPort];
1550 NSRect bounds = [view bounds];
1551 if (viewInLiveResize) CGContextSetInterpolationQuality(context, kCGInterpolationLow);
1552 CGContextSetBlendMode(context, kCGBlendModeCopy);
1553 CGContextDrawLayerInRect(context, *(CGRect *)&bounds, angbandLayer);
1554 if (viewInLiveResize) CGContextSetInterpolationQuality(context, kCGInterpolationDefault);
1559 return [[[angbandViews lastObject] window] isVisible];
1562 - (BOOL)isMainWindow
1564 return [[[angbandViews lastObject] window] isMainWindow];
1567 - (void)setNeedsDisplay:(BOOL)val
1569 for (NSView *angbandView in angbandViews)
1571 [angbandView setNeedsDisplay:val];
1575 - (void)setNeedsDisplayInBaseRect:(NSRect)rect
1577 for (NSView *angbandView in angbandViews)
1579 [angbandView setNeedsDisplayInRect: rect];
1583 - (void)displayIfNeeded
1585 [[self activeView] displayIfNeeded];
1588 - (int)terminalIndex
1592 for( termIndex = 0; termIndex < ANGBAND_TERM_MAX; termIndex++ )
1594 if( angband_term[termIndex] == self->terminal )
1603 - (void)resizeTerminalWithContentRect: (NSRect)contentRect saveToDefaults: (BOOL)saveToDefaults
1605 CGFloat newRows = floor( (contentRect.size.height - (borderSize.height * 2.0)) / tileSize.height );
1606 CGFloat newColumns = ceil( (contentRect.size.width - (borderSize.width * 2.0)) / tileSize.width );
1608 if (newRows < 1 || newColumns < 1) return;
1609 self->cols = newColumns;
1610 self->rows = newRows;
1612 if (resize_pending_changes(self->changes, self->rows) != 0) {
1613 destroy_pending_changes(self->changes);
1615 NSLog(@"out of memory for pending changes with resize of terminal %d",
1616 [self terminalIndex]);
1619 if( saveToDefaults )
1621 int termIndex = [self terminalIndex];
1622 NSArray *terminals = [[NSUserDefaults standardUserDefaults] valueForKey: AngbandTerminalsDefaultsKey];
1624 if( termIndex < (int)[terminals count] )
1626 NSMutableDictionary *mutableTerm = [[NSMutableDictionary alloc] initWithDictionary: [terminals objectAtIndex: termIndex]];
1627 [mutableTerm setValue: [NSNumber numberWithUnsignedInt: self->cols] forKey: AngbandTerminalColumnsDefaultsKey];
1628 [mutableTerm setValue: [NSNumber numberWithUnsignedInt: self->rows] forKey: AngbandTerminalRowsDefaultsKey];
1630 NSMutableArray *mutableTerminals = [[NSMutableArray alloc] initWithArray: terminals];
1631 [mutableTerminals replaceObjectAtIndex: termIndex withObject: mutableTerm];
1633 [[NSUserDefaults standardUserDefaults] setValue: mutableTerminals forKey: AngbandTerminalsDefaultsKey];
1634 [mutableTerminals release];
1635 [mutableTerm release];
1637 [[NSUserDefaults standardUserDefaults] synchronize];
1641 Term_activate( self->terminal );
1642 Term_resize( (int)newColumns, (int)newRows);
1644 Term_activate( old );
1647 - (void)setMinimumWindowSize:(int)termIdx
1653 minsize.height = 24;
1659 minsize.width * self->tileSize.width + self->borderSize.width * 2.0;
1661 minsize.height * self->tileSize.height + self->borderSize.height * 2.0;
1662 [[self makePrimaryWindow] setContentMinSize:minsize];
1665 - (void)saveWindowVisibleToDefaults: (BOOL)windowVisible
1667 int termIndex = [self terminalIndex];
1668 BOOL safeVisibility = (termIndex == 0) ? YES : windowVisible; /* Ensure main term doesn't go away because of these defaults */
1669 NSArray *terminals = [[NSUserDefaults standardUserDefaults] valueForKey: AngbandTerminalsDefaultsKey];
1671 if( termIndex < (int)[terminals count] )
1673 NSMutableDictionary *mutableTerm = [[NSMutableDictionary alloc] initWithDictionary: [terminals objectAtIndex: termIndex]];
1674 [mutableTerm setValue: [NSNumber numberWithBool: safeVisibility] forKey: AngbandTerminalVisibleDefaultsKey];
1676 NSMutableArray *mutableTerminals = [[NSMutableArray alloc] initWithArray: terminals];
1677 [mutableTerminals replaceObjectAtIndex: termIndex withObject: mutableTerm];
1679 [[NSUserDefaults standardUserDefaults] setValue: mutableTerminals forKey: AngbandTerminalsDefaultsKey];
1680 [mutableTerminals release];
1681 [mutableTerm release];
1685 - (BOOL)windowVisibleUsingDefaults
1687 int termIndex = [self terminalIndex];
1689 if( termIndex == 0 )
1694 NSArray *terminals = [[NSUserDefaults standardUserDefaults] valueForKey: AngbandTerminalsDefaultsKey];
1697 if( termIndex < (int)[terminals count] )
1699 NSDictionary *term = [terminals objectAtIndex: termIndex];
1700 NSNumber *visibleValue = [term valueForKey: AngbandTerminalVisibleDefaultsKey];
1702 if( visibleValue != nil )
1704 visible = [visibleValue boolValue];
1712 #pragma mark NSWindowDelegate Methods
1714 /*- (void)windowWillStartLiveResize: (NSNotification *)notification
1718 - (void)windowDidEndLiveResize: (NSNotification *)notification
1720 NSWindow *window = [notification object];
1721 NSRect contentRect = [window contentRectForFrameRect: [window frame]];
1722 [self resizeTerminalWithContentRect: contentRect saveToDefaults: !(self->in_fullscreen_transition)];
1725 /*- (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
1729 - (void)windowWillEnterFullScreen: (NSNotification *)notification
1731 self->in_fullscreen_transition = YES;
1734 - (void)windowDidEnterFullScreen: (NSNotification *)notification
1736 NSWindow *window = [notification object];
1737 NSRect contentRect = [window contentRectForFrameRect: [window frame]];
1738 self->in_fullscreen_transition = NO;
1739 [self resizeTerminalWithContentRect: contentRect saveToDefaults: NO];
1742 - (void)windowWillExitFullScreen: (NSNotification *)notification
1744 self->in_fullscreen_transition = YES;
1747 - (void)windowDidExitFullScreen: (NSNotification *)notification
1749 NSWindow *window = [notification object];
1750 NSRect contentRect = [window contentRectForFrameRect: [window frame]];
1751 self->in_fullscreen_transition = NO;
1752 [self resizeTerminalWithContentRect: contentRect saveToDefaults: NO];
1755 - (void)windowDidBecomeMain:(NSNotification *)notification
1757 NSWindow *window = [notification object];
1759 if( window != self->primaryWindow )
1764 int termIndex = [self terminalIndex];
1765 NSMenuItem *item = [[[NSApplication sharedApplication] windowsMenu] itemWithTag: AngbandWindowMenuItemTagBase + termIndex];
1766 [item setState: NSOnState];
1768 if( [[NSFontPanel sharedFontPanel] isVisible] )
1770 [[NSFontPanel sharedFontPanel] setPanelFont: [self selectionFont] isMultiple: NO];
1774 - (void)windowDidResignMain: (NSNotification *)notification
1776 NSWindow *window = [notification object];
1778 if( window != self->primaryWindow )
1783 int termIndex = [self terminalIndex];
1784 NSMenuItem *item = [[[NSApplication sharedApplication] windowsMenu] itemWithTag: AngbandWindowMenuItemTagBase + termIndex];
1785 [item setState: NSOffState];
1788 - (void)windowWillClose: (NSNotification *)notification
1790 [self saveWindowVisibleToDefaults: NO];
1796 @implementation AngbandView
1808 - (void)drawRect:(NSRect)rect
1810 if (! angbandContext)
1812 /* Draw bright orange, 'cause this ain't right */
1813 [[NSColor orangeColor] set];
1814 NSRectFill([self bounds]);
1818 /* Tell the Angband context to draw into us */
1819 [angbandContext drawRect:rect inView:self];
1823 - (void)setAngbandContext:(AngbandContext *)context
1825 angbandContext = context;
1828 - (AngbandContext *)angbandContext
1830 return angbandContext;
1833 - (void)setFrameSize:(NSSize)size
1835 BOOL changed = ! NSEqualSizes(size, [self frame].size);
1836 [super setFrameSize:size];
1837 if (changed) [angbandContext angbandViewDidScale:self];
1840 - (void)viewWillStartLiveResize
1842 [angbandContext viewWillStartLiveResize:self];
1845 - (void)viewDidEndLiveResize
1847 [angbandContext viewDidEndLiveResize:self];
1853 * Delay handling of double-clicked savefiles
1855 Boolean open_when_ready = FALSE;
1860 * ------------------------------------------------------------------------
1861 * Some generic functions
1862 * ------------------------------------------------------------------------ */
1865 * Sets an Angband color at a given index
1867 static void set_color_for_index(int idx)
1871 /* Extract the R,G,B data */
1872 rv = angband_color_table[idx][1];
1873 gv = angband_color_table[idx][2];
1874 bv = angband_color_table[idx][3];
1876 CGContextSetRGBFillColor([[NSGraphicsContext currentContext] graphicsPort], rv/255., gv/255., bv/255., 1.);
1880 * Remember the current character in UserDefaults so we can select it by
1881 * default next time.
1883 static void record_current_savefile(void)
1885 NSString *savefileString = [[NSString stringWithCString:savefile encoding:NSMacOSRomanStringEncoding] lastPathComponent];
1888 NSUserDefaults *angbandDefs = [NSUserDefaults angbandDefaults];
1889 [angbandDefs setObject:savefileString forKey:@"SaveFile"];
1890 [angbandDefs synchronize];
1897 * Convert a two-byte EUC-JP encoded character (both *cp and (*cp + 1) are in
1898 * the range, 0xA1-0xFE, or *cp is 0x8E) to a utf16 value in the native byte
1901 static wchar_t convert_two_byte_eucjp_to_utf16_native(const char *cp)
1903 NSString* str = [[NSString alloc] initWithBytes:cp length:2
1904 encoding:NSJapaneseEUCStringEncoding];
1905 wchar_t result = [str characterAtIndex:0];
1914 * ------------------------------------------------------------------------
1915 * Support for the "z-term.c" package
1916 * ------------------------------------------------------------------------ */
1920 * Initialize a new Term
1922 static void Term_init_cocoa(term *t)
1924 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1925 AngbandContext *context = [[AngbandContext alloc] init];
1927 /* Give the term a hard retain on context (for GC) */
1928 t->data = (void *)CFRetain(context);
1931 /* Handle graphics */
1932 t->higher_pict = !! use_graphics;
1933 t->always_pict = FALSE;
1935 NSDisableScreenUpdates();
1937 /* Figure out the frame autosave name based on the index of this term */
1938 NSString *autosaveName = nil;
1940 for (termIdx = 0; termIdx < ANGBAND_TERM_MAX; termIdx++)
1942 if (angband_term[termIdx] == t)
1944 autosaveName = [NSString stringWithFormat:@"AngbandTerm-%d", termIdx];
1950 NSString *fontName = [[NSUserDefaults angbandDefaults] stringForKey:[NSString stringWithFormat:@"FontName-%d", termIdx]];
1951 if (! fontName) fontName = [default_font fontName];
1953 /* Use a smaller default font for the other windows, but only if the font
1954 * hasn't been explicitly set */
1955 float fontSize = (termIdx > 0) ? 10.0 : [default_font pointSize];
1956 NSNumber *fontSizeNumber = [[NSUserDefaults angbandDefaults] valueForKey: [NSString stringWithFormat: @"FontSize-%d", termIdx]];
1958 if( fontSizeNumber != nil )
1960 fontSize = [fontSizeNumber floatValue];
1963 [context setSelectionFont:[NSFont fontWithName:fontName size:fontSize] adjustTerminal: NO];
1965 NSArray *terminalDefaults = [[NSUserDefaults standardUserDefaults] valueForKey: AngbandTerminalsDefaultsKey];
1966 NSInteger rows = 24;
1967 NSInteger columns = 80;
1969 if( termIdx < (int)[terminalDefaults count] )
1971 NSDictionary *term = [terminalDefaults objectAtIndex: termIdx];
1972 NSInteger defaultRows = [[term valueForKey: AngbandTerminalRowsDefaultsKey] integerValue];
1973 NSInteger defaultColumns = [[term valueForKey: AngbandTerminalColumnsDefaultsKey] integerValue];
1975 if (defaultRows > 0) rows = defaultRows;
1976 if (defaultColumns > 0) columns = defaultColumns;
1979 context->cols = columns;
1980 context->rows = rows;
1982 if (resize_pending_changes(context->changes, context->rows) != 0) {
1983 destroy_pending_changes(context->changes);
1984 context->changes = 0;
1985 NSLog(@"initializing terminal %d: out of memory for pending changes",
1989 /* Get the window */
1990 NSWindow *window = [context makePrimaryWindow];
1992 /* Set its title and, for auxiliary terms, tentative size */
1993 NSString *title = [NSString stringWithCString:angband_term_name[termIdx]
1995 encoding:NSJapaneseEUCStringEncoding
1997 encoding:NSMacOSRomanStringEncoding
2000 [window setTitle:title];
2001 [context setMinimumWindowSize:termIdx];
2003 /* If this is the first term, and we support full screen (Mac OS X Lion or
2004 * later), then allow it to go full screen (sweet). Allow other terms to be
2005 * FullScreenAuxilliary, so they can at least show up. Unfortunately in
2006 * Lion they don't get brought to the full screen space; but they would
2007 * only make sense on multiple displays anyways so it's not a big loss. */
2008 if ([window respondsToSelector:@selector(toggleFullScreen:)])
2010 NSWindowCollectionBehavior behavior = [window collectionBehavior];
2011 behavior |= (termIdx == 0 ? Angband_NSWindowCollectionBehaviorFullScreenPrimary : Angband_NSWindowCollectionBehaviorFullScreenAuxiliary);
2012 [window setCollectionBehavior:behavior];
2015 /* No Resume support yet, though it would not be hard to add */
2016 if ([window respondsToSelector:@selector(setRestorable:)])
2018 [window setRestorable:NO];
2021 /* default window placement */ {
2022 static NSRect overallBoundingRect;
2026 /* This is a bit of a trick to allow us to display multiple windows
2027 * in the "standard default" window position in OS X: the upper
2028 * center of the screen.
2029 * The term sizes set in load_prefs() are based on a 5-wide by
2030 * 3-high grid, with the main term being 4/5 wide by 2/3 high
2031 * (hence the scaling to find */
2033 /* What the containing rect would be). */
2034 NSRect originalMainTermFrame = [window frame];
2035 NSRect scaledFrame = originalMainTermFrame;
2036 scaledFrame.size.width *= 5.0 / 4.0;
2037 scaledFrame.size.height *= 3.0 / 2.0;
2038 scaledFrame.size.width += 1.0; /* spacing between window columns */
2039 scaledFrame.size.height += 1.0; /* spacing between window rows */
2040 [window setFrame: scaledFrame display: NO];
2042 overallBoundingRect = [window frame];
2043 [window setFrame: originalMainTermFrame display: NO];
2046 static NSRect mainTermBaseRect;
2047 NSRect windowFrame = [window frame];
2051 /* The height and width adjustments were determined experimentally,
2052 * so that the rest of the windows line up nicely without
2054 windowFrame.size.width += 7.0;
2055 windowFrame.size.height += 9.0;
2056 windowFrame.origin.x = NSMinX( overallBoundingRect );
2057 windowFrame.origin.y = NSMaxY( overallBoundingRect ) - NSHeight( windowFrame );
2058 mainTermBaseRect = windowFrame;
2060 else if( termIdx == 1 )
2062 windowFrame.origin.x = NSMinX( mainTermBaseRect );
2063 windowFrame.origin.y = NSMinY( mainTermBaseRect ) - NSHeight( windowFrame ) - 1.0;
2065 else if( termIdx == 2 )
2067 windowFrame.origin.x = NSMaxX( mainTermBaseRect ) + 1.0;
2068 windowFrame.origin.y = NSMaxY( mainTermBaseRect ) - NSHeight( windowFrame );
2070 else if( termIdx == 3 )
2072 windowFrame.origin.x = NSMaxX( mainTermBaseRect ) + 1.0;
2073 windowFrame.origin.y = NSMinY( mainTermBaseRect ) - NSHeight( windowFrame ) - 1.0;
2075 else if( termIdx == 4 )
2077 windowFrame.origin.x = NSMaxX( mainTermBaseRect ) + 1.0;
2078 windowFrame.origin.y = NSMinY( mainTermBaseRect );
2080 else if( termIdx == 5 )
2082 windowFrame.origin.x = NSMinX( mainTermBaseRect ) + NSWidth( windowFrame ) + 1.0;
2083 windowFrame.origin.y = NSMinY( mainTermBaseRect ) - NSHeight( windowFrame ) - 1.0;
2086 [window setFrame: windowFrame display: NO];
2089 /* Override the default frame above if the user has adjusted windows in
2091 if (autosaveName) [window setFrameAutosaveName:autosaveName];
2093 /* Tell it about its term. Do this after we've sized it so that the sizing
2094 * doesn't trigger redrawing and such. */
2095 [context setTerm:t];
2097 /* Only order front if it's the first term. Other terms will be ordered
2098 * front from AngbandUpdateWindowVisibility(). This is to work around a
2099 * problem where Angband aggressively tells us to initialize terms that
2100 * don't do anything! */
2101 if (t == angband_term[0]) [context->primaryWindow makeKeyAndOrderFront: nil];
2103 NSEnableScreenUpdates();
2105 /* Set "mapped" flag */
2106 t->mapped_flag = true;
2115 static void Term_nuke_cocoa(term *t)
2117 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
2119 AngbandContext *context = t->data;
2122 /* Tell the context to get rid of its windows, etc. */
2125 /* Balance our CFRetain from when we created it */
2136 * Returns the CGImageRef corresponding to an image with the given name in the
2137 * resource directory, transferring ownership to the caller
2139 static CGImageRef create_angband_image(NSString *path)
2141 CGImageRef decodedImage = NULL, result = NULL;
2143 /* Try using ImageIO to load the image */
2146 NSURL *url = [[NSURL alloc] initFileURLWithPath:path isDirectory:NO];
2149 NSDictionary *options = [[NSDictionary alloc] initWithObjectsAndKeys:(id)kCFBooleanTrue, kCGImageSourceShouldCache, nil];
2150 CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)url, (CFDictionaryRef)options);
2153 /* We really want the largest image, but in practice there's
2154 * only going to be one */
2155 decodedImage = CGImageSourceCreateImageAtIndex(source, 0, (CFDictionaryRef)options);
2163 /* Draw the sucker to defeat ImageIO's weird desire to cache and decode on
2164 * demand. Our images aren't that big! */
2167 size_t width = CGImageGetWidth(decodedImage), height = CGImageGetHeight(decodedImage);
2169 /* Compute our own bitmap info */
2170 CGBitmapInfo imageBitmapInfo = CGImageGetBitmapInfo(decodedImage);
2171 CGBitmapInfo contextBitmapInfo = kCGBitmapByteOrderDefault;
2173 switch (imageBitmapInfo & kCGBitmapAlphaInfoMask) {
2174 case kCGImageAlphaNone:
2175 case kCGImageAlphaNoneSkipLast:
2176 case kCGImageAlphaNoneSkipFirst:
2178 contextBitmapInfo |= kCGImageAlphaNone;
2181 /* Some alpha, use premultiplied last which is most efficient. */
2182 contextBitmapInfo |= kCGImageAlphaPremultipliedLast;
2186 /* Draw the source image flipped, since the view is flipped */
2187 CGContextRef ctx = CGBitmapContextCreate(NULL, width, height, CGImageGetBitsPerComponent(decodedImage), CGImageGetBytesPerRow(decodedImage), CGImageGetColorSpace(decodedImage), contextBitmapInfo);
2188 CGContextSetBlendMode(ctx, kCGBlendModeCopy);
2189 CGContextTranslateCTM(ctx, 0.0, height);
2190 CGContextScaleCTM(ctx, 1.0, -1.0);
2191 CGContextDrawImage(ctx, CGRectMake(0, 0, width, height), decodedImage);
2192 result = CGBitmapContextCreateImage(ctx);
2194 /* Done with these things */
2196 CGImageRelease(decodedImage);
2204 static errr Term_xtra_cocoa_react(void)
2206 /* Don't actually switch graphics until the game is running */
2207 if (!initialized || !game_in_progress) return (-1);
2209 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
2210 AngbandContext *angbandContext = Term->data;
2212 /* Handle graphics */
2213 int expected_graf_mode = (current_graphics_mode) ?
2214 current_graphics_mode->grafID : GRAPHICS_NONE;
2215 if (graf_mode_req != expected_graf_mode)
2217 graphics_mode *new_mode;
2218 if (graf_mode_req != GRAPHICS_NONE) {
2219 new_mode = get_graphics_mode(graf_mode_req);
2224 /* Get rid of the old image. CGImageRelease is NULL-safe. */
2225 CGImageRelease(pict_image);
2228 /* Try creating the image if we want one */
2229 if (new_mode != NULL)
2231 NSString *img_path = [NSString stringWithFormat:@"%s/%s", new_mode->path, new_mode->file];
2232 pict_image = create_angband_image(img_path);
2234 /* If we failed to create the image, set the new desired mode to
2240 /* Record what we did */
2241 use_graphics = new_mode ? new_mode->grafID : 0;
2242 ANGBAND_GRAF = (new_mode ? new_mode->graf : "ascii");
2243 current_graphics_mode = new_mode;
2245 /* Enable or disable higher picts. Note: this should be done for all
2247 angbandContext->terminal->higher_pict = !! use_graphics;
2249 if (pict_image && current_graphics_mode)
2251 /* Compute the row and column count via the image height and width.
2253 pict_rows = (int)(CGImageGetHeight(pict_image) / current_graphics_mode->cell_height);
2254 pict_cols = (int)(CGImageGetWidth(pict_image) / current_graphics_mode->cell_width);
2263 if (initialized && game_in_progress)
2277 * Draws one tile as a helper function for Term_xtra_cocoa_fresh().
2279 static void draw_image_tile(
2280 NSGraphicsContext* nsContext,
2281 CGContextRef cgContext,
2285 NSCompositingOperation op)
2287 /* Flip the source rect since the source image is flipped */
2288 CGAffineTransform flip = CGAffineTransformIdentity;
2289 flip = CGAffineTransformTranslate(flip, 0.0, CGImageGetHeight(image));
2290 flip = CGAffineTransformScale(flip, 1.0, -1.0);
2291 CGRect flippedSourceRect =
2292 CGRectApplyAffineTransform(NSRectToCGRect(srcRect), flip);
2295 * When we use high-quality resampling to draw a tile, pixels from outside
2296 * the tile may bleed in, causing graphics artifacts. Work around that.
2298 CGImageRef subimage =
2299 CGImageCreateWithImageInRect(image, flippedSourceRect);
2300 [nsContext setCompositingOperation:op];
2301 CGContextDrawImage(cgContext, NSRectToCGRect(dstRect), subimage);
2302 CGImageRelease(subimage);
2307 * This is a helper function for Term_xtra_cocoa_fresh(): look before a block
2308 * of text on a row to see if the bounds for rendering and clipping need to be
2311 static void query_before_text(
2312 struct PendingRowChange* prc, int iy, int npre, int* pclip, int* prend)
2318 if (i < 0 || i < start - npre) {
2322 if (prc->cell_changes[i].change_type == CELL_CHANGE_PICT) {
2324 * The cell has been rendered with a tile. Do not want to modify
2325 * its contents so the clipping and rendering region can not be
2329 } else if (prc->cell_changes[i].change_type == CELL_CHANGE_NONE) {
2330 /* It has not changed so inquire what it is. */
2334 Term_what(i, iy, a + 1, c + 1);
2335 if (use_graphics && (a[1] & 0x80) && (c[1] & 0x80)) {
2337 * It is an unchanged location rendered with a tile. Do not
2338 * want to modify its contents so the clipping and rendering
2339 * region can not be extended.
2344 * It is unchanged text. A character from the changed region
2345 * may have extended into it so render it to clear that.
2348 /* Check to see if it is the second part of a kanji character. */
2350 Term_what(i - 1, iy, a, c);
2352 prc->cell_changes[i - 1].c.w =
2353 convert_two_byte_eucjp_to_utf16_native(c);
2354 prc->cell_changes[i - 1].a = a[0];
2355 prc->cell_changes[i - 1].tcol = 1;
2356 prc->cell_changes[i].c.w = 0;
2357 prc->cell_changes[i].a = a[0];
2358 prc->cell_changes[i].tcol = 0;
2363 prc->cell_changes[i].c.w = c[1];
2364 prc->cell_changes[i].a = a[1];
2365 prc->cell_changes[i].tcol = 0;
2370 prc->cell_changes[i].c.w = c[1];
2371 prc->cell_changes[i].a = a[1];
2372 prc->cell_changes[i].tcol = 0;
2377 prc->cell_changes[i].c.w = c[1];
2378 prc->cell_changes[i].a = a[1];
2379 prc->cell_changes[i].tcol = 0;
2386 * The cell has been wiped or had changed text rendered. Do
2387 * not need to render. Can extend the clipping rectangle into it.
2397 * This is a helper function for Term_xtra_cocoa_fresh(): look after a block
2398 * of text on a row to see if the bounds for rendering and clipping need to be
2401 static void query_after_text(
2402 struct PendingRowChange* prc,
2414 * Be willing to consolidate this block with the one after it. This
2415 * logic should be sufficient to avoid redraws of the region between
2416 * changed blocks of text if angbandContext->ncol_pre is zero or one.
2417 * For larger values of ncol_pre, would need to do something more to
2418 * avoid extra redraws.
2422 prc->cell_changes[i].change_type != CELL_CHANGE_TEXT &&
2423 prc->cell_changes[i].change_type != CELL_CHANGE_WIPE)) {
2427 if (prc->cell_changes[i].change_type == CELL_CHANGE_PICT) {
2429 * The cell has been rendered with a tile. Do not want to modify
2430 * its contents so the clipping and rendering region can not be
2434 } else if (prc->cell_changes[i].change_type == CELL_CHANGE_NONE) {
2435 /* It has not changed so inquire what it is. */
2439 Term_what(i, iy, a, c);
2440 if (use_graphics && (a[0] & 0x80) && (c[0] & 0x80)) {
2442 * It is an unchanged location rendered with a tile. Do not
2443 * want to modify its contents so the clipping and rendering
2444 * region can not be extended.
2449 * It is unchanged text. A character from the changed region
2450 * may have extended into it so render it to clear that.
2453 /* Check to see if it is the first part of a kanji character. */
2455 Term_what(i + 1, iy, a + 1, c + 1);
2457 prc->cell_changes[i].c.w =
2458 convert_two_byte_eucjp_to_utf16_native(c);
2459 prc->cell_changes[i].a = a[0];
2460 prc->cell_changes[i].tcol = 1;
2461 prc->cell_changes[i + 1].c.w = 0;
2462 prc->cell_changes[i + 1].a = a[0];
2463 prc->cell_changes[i + 1].tcol = 0;
2468 prc->cell_changes[i].c.w = c[0];
2469 prc->cell_changes[i].a = a[0];
2470 prc->cell_changes[i].tcol = 0;
2475 prc->cell_changes[i].c.w = c[0];
2476 prc->cell_changes[i].a = a[0];
2477 prc->cell_changes[i].tcol = 0;
2482 prc->cell_changes[i].c.w = c[0];
2483 prc->cell_changes[i].a = a[0];
2484 prc->cell_changes[i].tcol = 0;
2491 * Have come to another region of changed text or another region
2492 * to wipe. Combine the regions to minimize redraws.
2504 * Draw the pending changes saved in angbandContext->changes.
2506 static void Term_xtra_cocoa_fresh(AngbandContext* angbandContext)
2508 int graf_width, graf_height, alphablend;
2510 if (angbandContext->changes->has_pict) {
2511 CGImageAlphaInfo ainfo = CGImageGetAlphaInfo(pict_image);
2513 graf_width = current_graphics_mode->cell_width;
2514 graf_height = current_graphics_mode->cell_height;
2516 * As of this writing, a value of zero for
2517 * current_graphics_mode->alphablend can mean either that the tile set
2518 * doesn't have an alpha channel or it does but it only takes on values
2519 * of 0 or 255. For main-cocoa.m's purposes, the latter is rendered
2520 * using the same procedure as if alphablend was nonzero. The former
2521 * is handled differently, but alphablend doesn't distinguish it from
2522 * the latter. So ignore alphablend and directly test whether an
2523 * alpha channel is present.
2525 alphablend = (ainfo & (kCGImageAlphaPremultipliedFirst |
2526 kCGImageAlphaPremultipliedLast)) ? 1 : 0;
2533 CGContextRef ctx = [angbandContext lockFocus];
2535 if (angbandContext->changes->has_text ||
2536 angbandContext->changes->has_wipe) {
2537 NSFont *selectionFont = [[angbandContext selectionFont] screenFont];
2538 [selectionFont set];
2542 for (iy = angbandContext->changes->ymin;
2543 iy <= angbandContext->changes->ymax;
2545 struct PendingRowChange* prc = angbandContext->changes->rows[iy];
2548 /* Skip untouched rows. */
2557 if (ix > prc->xmax) {
2561 switch (prc->cell_changes[ix].change_type) {
2562 case CELL_CHANGE_NONE:
2566 case CELL_CHANGE_PICT:
2569 * Because changes are made to the compositing mode, save
2570 * the incoming value.
2572 NSGraphicsContext *nsContext =
2573 [NSGraphicsContext currentContext];
2574 NSCompositingOperation op = nsContext.compositingOperation;
2577 while (jx <= prc->xmax &&
2578 prc->cell_changes[jx].change_type
2579 == CELL_CHANGE_PICT) {
2580 NSRect destinationRect =
2581 [angbandContext rectInImageForTileAtX:jx Y:iy];
2582 NSRect sourceRect, terrainRect;
2584 sourceRect.origin.x = graf_width *
2585 prc->cell_changes[jx].c.c;
2586 sourceRect.origin.y = graf_height *
2587 prc->cell_changes[jx].a;
2588 sourceRect.size.width = graf_width;
2589 sourceRect.size.height = graf_height;
2590 terrainRect.origin.x = graf_width *
2591 prc->cell_changes[jx].tcol;
2592 terrainRect.origin.y = graf_height *
2593 prc->cell_changes[jx].trow;
2594 terrainRect.size.width = graf_width;
2595 terrainRect.size.height = graf_height;
2605 * Skip drawing the foreground if it is the same
2606 * as the background.
2608 if (sourceRect.origin.x != terrainRect.origin.x ||
2609 sourceRect.origin.y != terrainRect.origin.y) {
2616 NSCompositeSourceOver);
2630 [nsContext setCompositingOperation:op];
2633 [angbandContext rectInImageForTileAtX:ix Y:iy];
2635 angbandContext->tileSize.width * (jx - ix);
2636 [angbandContext setNeedsDisplayInBaseRect:rect];
2641 case CELL_CHANGE_WIPE:
2642 case CELL_CHANGE_TEXT:
2644 * For a wiped region, treat it as if it had text (the only
2645 * loss if it was not is some extra work rendering
2646 * neighboring unchanged text).
2649 while (jx < angbandContext->cols &&
2650 (prc->cell_changes[jx].change_type
2652 || prc->cell_changes[jx].change_type
2653 == CELL_CHANGE_WIPE)) {
2658 int ieclip = jx - 1;
2660 int ierend = jx - 1;
2662 TERM_COLOR alast = 0;
2667 prc, iy, angbandContext->ncol_pre, &isclip, &isrend);
2671 angbandContext->cols,
2672 angbandContext->ncol_post,
2678 /* Save the state since the clipping will be modified. */
2679 CGContextSaveGState(ctx);
2681 /* Clear the area where rendering will be done. */
2682 r = [angbandContext rectInImageForTileAtX:isrend Y:iy];
2683 r.size.width = angbandContext->tileSize.width *
2684 (ierend - isrend + 1);
2685 [[NSColor blackColor] set];
2689 * Clear the current path so it does not affect clipping.
2690 * Then set the clipping rectangle. Using
2691 * CGContextSetTextDrawingMode() to include clipping does
2692 * not appear to be necessary on 10.14 and is actually
2693 * detrimental: when displaying more than one character,
2694 * only the first is visible.
2696 CGContextBeginPath(ctx);
2697 r = [angbandContext rectInImageForTileAtX:isclip Y:iy];
2698 r.size.width = angbandContext->tileSize.width *
2699 (ieclip - isclip + 1);
2700 CGContextClipToRect(ctx, r);
2704 while (k <= ierend) {
2707 if (prc->cell_changes[k].change_type
2708 == CELL_CHANGE_WIPE) {
2709 /* Skip over since no rendering is necessary. */
2714 if (set_color || alast != prc->cell_changes[k].a) {
2716 alast = prc->cell_changes[k].a;
2717 set_color_for_index(alast % MAX_COLORS);
2721 [angbandContext rectInImageForTileAtX:k Y:iy];
2722 if (prc->cell_changes[k].tcol) {
2723 rectToDraw.size.width *= 2.0;
2724 [angbandContext drawWChar:prc->cell_changes[k].c.w
2725 inRect:rectToDraw context:ctx];
2728 [angbandContext drawWChar:prc->cell_changes[k].c.w
2729 inRect:rectToDraw context:ctx];
2735 * Inform the context that the area in the clipping
2736 * rectangle needs to be redisplayed.
2738 [angbandContext setNeedsDisplayInBaseRect:r];
2740 CGContextRestoreGState(ctx);
2747 if (angbandContext->changes->xcurs >= 0 &&
2748 angbandContext->changes->ycurs >= 0) {
2749 NSRect rect = [angbandContext
2750 rectInImageForTileAtX:angbandContext->changes->xcurs
2751 Y:angbandContext->changes->ycurs];
2753 if (angbandContext->changes->bigcurs) {
2754 rect.size.width += angbandContext->tileSize.width;
2756 [[NSColor yellowColor] set];
2757 NSFrameRectWithWidth(rect, 1);
2758 /* Invalidate that rect */
2759 [angbandContext setNeedsDisplayInBaseRect:rect];
2762 [angbandContext unlockFocus];
2767 * Do a "special thing"
2769 static errr Term_xtra_cocoa(int n, int v)
2771 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
2772 AngbandContext* angbandContext = Term->data;
2780 case TERM_XTRA_NOISE:
2789 case TERM_XTRA_SOUND:
2793 /* Process random events */
2794 case TERM_XTRA_BORED:
2796 /* Show or hide cocoa windows based on the subwindow flags set by
2798 AngbandUpdateWindowVisibility();
2800 /* Process an event */
2801 (void)check_events(CHECK_EVENTS_NO_WAIT);
2807 /* Process pending events */
2808 case TERM_XTRA_EVENT:
2810 /* Process an event */
2811 (void)check_events(v);
2817 /* Flush all pending events (if any) */
2818 case TERM_XTRA_FLUSH:
2820 /* Hack -- flush all events */
2821 while (check_events(CHECK_EVENTS_DRAIN)) /* loop */;
2827 /* Hack -- Change the "soft level" */
2828 case TERM_XTRA_LEVEL:
2830 /* Here we could activate (if requested), but I don't think Angband
2831 * should be telling us our window order (the user should decide
2832 * that), so do nothing. */
2836 /* Clear the screen */
2837 case TERM_XTRA_CLEAR:
2839 [angbandContext lockFocus];
2840 [[NSColor blackColor] set];
2841 NSRect imageRect = {NSZeroPoint, [angbandContext imageSize]};
2842 NSRectFillUsingOperation(imageRect, NSCompositeCopy);
2843 [angbandContext unlockFocus];
2844 [angbandContext setNeedsDisplay:YES];
2849 /* React to changes */
2850 case TERM_XTRA_REACT:
2852 /* React to changes */
2853 return (Term_xtra_cocoa_react());
2856 /* Delay (milliseconds) */
2857 case TERM_XTRA_DELAY:
2863 double seconds = v / 1000.;
2864 NSDate* date = [NSDate dateWithTimeIntervalSinceNow:seconds];
2870 event = [NSApp nextEventMatchingMask:-1 untilDate:date inMode:NSDefaultRunLoopMode dequeue:YES];
2871 if (event) send_event(event);
2873 } while ([date timeIntervalSinceNow] >= 0);
2881 case TERM_XTRA_FRESH:
2882 /* Draw the pending changes. */
2883 if (angbandContext->changes != 0) {
2884 Term_xtra_cocoa_fresh(angbandContext);
2885 clear_pending_changes(angbandContext->changes);
2901 static errr Term_curs_cocoa(int x, int y)
2903 AngbandContext *angbandContext = Term->data;
2905 if (angbandContext->changes == 0) {
2906 /* Bail out; there was an earlier memory allocation failure. */
2909 angbandContext->changes->xcurs = x;
2910 angbandContext->changes->ycurs = y;
2911 angbandContext->changes->bigcurs = 0;
2918 * Draw a cursor that's two tiles wide. For Japanese, that's used when
2919 * the cursor points at a kanji character, irregardless of whether operating
2922 static errr Term_bigcurs_cocoa(int x, int y)
2924 AngbandContext *angbandContext = Term->data;
2926 if (angbandContext->changes == 0) {
2927 /* Bail out; there was an earlier memory allocation failure. */
2930 angbandContext->changes->xcurs = x;
2931 angbandContext->changes->ycurs = y;
2932 angbandContext->changes->bigcurs = 1;
2939 * Low level graphics (Assumes valid input)
2941 * Erase "n" characters starting at (x,y)
2943 static errr Term_wipe_cocoa(int x, int y, int n)
2945 AngbandContext *angbandContext = Term->data;
2946 struct PendingCellChange *pc;
2948 if (angbandContext->changes == 0) {
2949 /* Bail out; there was an earlier memory allocation failure. */
2952 if (angbandContext->changes->rows[y] == 0) {
2953 angbandContext->changes->rows[y] =
2954 create_row_change(angbandContext->cols);
2955 if (angbandContext->changes->rows[y] == 0) {
2956 NSLog(@"failed to allocate changes for row %d", y);
2959 if (angbandContext->changes->ymin > y) {
2960 angbandContext->changes->ymin = y;
2962 if (angbandContext->changes->ymax < y) {
2963 angbandContext->changes->ymax = y;
2967 angbandContext->changes->has_wipe = 1;
2968 if (angbandContext->changes->rows[y]->xmin > x) {
2969 angbandContext->changes->rows[y]->xmin = x;
2971 if (angbandContext->changes->rows[y]->xmax < x + n - 1) {
2972 angbandContext->changes->rows[y]->xmax = x + n - 1;
2974 for (pc = angbandContext->changes->rows[y]->cell_changes + x;
2975 pc != angbandContext->changes->rows[y]->cell_changes + x + n;
2977 pc->change_type = CELL_CHANGE_WIPE;
2984 static errr Term_pict_cocoa(int x, int y, int n, TERM_COLOR *ap,
2985 const char *cp, const TERM_COLOR *tap,
2989 /* Paranoia: Bail if we don't have a current graphics mode */
2990 if (! current_graphics_mode) return -1;
2992 AngbandContext* angbandContext = Term->data;
2994 struct PendingCellChange *pc;
2996 if (angbandContext->changes == 0) {
2997 /* Bail out; there was an earlier memory allocation failure. */
3000 if (angbandContext->changes->rows[y] == 0) {
3001 angbandContext->changes->rows[y] =
3002 create_row_change(angbandContext->cols);
3003 if (angbandContext->changes->rows[y] == 0) {
3004 NSLog(@"failed to allocate changes for row %d", y);
3007 if (angbandContext->changes->ymin > y) {
3008 angbandContext->changes->ymin = y;
3010 if (angbandContext->changes->ymax < y) {
3011 angbandContext->changes->ymax = y;
3015 if (angbandContext->changes->rows[y]->xmin > x) {
3016 angbandContext->changes->rows[y]->xmin = x;
3018 if (angbandContext->changes->rows[y]->xmax < x + n - 1) {
3019 angbandContext->changes->rows[y]->xmax = x + n - 1;
3021 for (pc = angbandContext->changes->rows[y]->cell_changes + x;
3022 pc != angbandContext->changes->rows[y]->cell_changes + x + n;
3024 TERM_COLOR a = *ap++;
3026 TERM_COLOR ta = *tap++;
3029 if (use_graphics && (a & 0x80) && (c & 0x80)) {
3030 pc->c.c = ((byte)c & 0x7F) % pict_cols;
3031 pc->a = ((byte)a & 0x7F) % pict_rows;
3032 pc->tcol = ((byte)tc & 0x7F) % pict_cols;
3033 pc->trow = ((byte)ta & 0x7F) % pict_rows;
3034 pc->change_type = CELL_CHANGE_PICT;
3039 angbandContext->changes->has_pict = 1;
3047 * Low level graphics. Assumes valid input.
3049 * Draw several ("n") chars, with an attr, at a given location.
3051 static errr Term_text_cocoa(int x, int y, int n, byte_hack a, concptr cp)
3053 AngbandContext* angbandContext = Term->data;
3054 struct PendingCellChange *pc;
3056 if (angbandContext->changes == 0) {
3057 /* Bail out; there was an earlier memory allocation failure. */
3060 if (angbandContext->changes->rows[y] == 0) {
3061 angbandContext->changes->rows[y] =
3062 create_row_change(angbandContext->cols);
3063 if (angbandContext->changes->rows[y] == 0) {
3064 NSLog(@"failed to allocate changes for row %d", y);
3067 if (angbandContext->changes->ymin > y) {
3068 angbandContext->changes->ymin = y;
3070 if (angbandContext->changes->ymax < y) {
3071 angbandContext->changes->ymax = y;
3075 angbandContext->changes->has_text = 1;
3076 if (angbandContext->changes->rows[y]->xmin > x) {
3077 angbandContext->changes->rows[y]->xmin = x;
3079 if (angbandContext->changes->rows[y]->xmax < x + n - 1) {
3080 angbandContext->changes->rows[y]->xmax = x + n - 1;
3082 pc = angbandContext->changes->rows[y]->cell_changes + x;
3083 while (pc != angbandContext->changes->rows[y]->cell_changes + x + n) {
3087 angbandContext->changes->rows[y]->cell_changes + x + n) {
3089 * The second byte of the character is past the end. Ignore
3094 pc->c.w = convert_two_byte_eucjp_to_utf16_native(cp);
3097 pc->change_type = CELL_CHANGE_TEXT;
3100 * Fill in a dummy value since the previous character will take
3106 pc->change_type = CELL_CHANGE_TEXT;
3114 pc->change_type = CELL_CHANGE_TEXT;
3122 pc->change_type = CELL_CHANGE_TEXT;
3133 * Post a nonsense event so that our event loop wakes up
3135 static void wakeup_event_loop(void)
3137 /* Big hack - send a nonsense event to make us update */
3138 NSEvent *event = [NSEvent otherEventWithType:NSApplicationDefined location:NSZeroPoint modifierFlags:0 timestamp:0 windowNumber:0 context:NULL subtype:AngbandEventWakeup data1:0 data2:0];
3139 [NSApp postEvent:event atStart:NO];
3144 * Create and initialize window number "i"
3146 static term *term_data_link(int i)
3148 NSArray *terminalDefaults = [[NSUserDefaults standardUserDefaults] valueForKey: AngbandTerminalsDefaultsKey];
3149 NSInteger rows = 24;
3150 NSInteger columns = 80;
3152 if( i < (int)[terminalDefaults count] )
3154 NSDictionary *term = [terminalDefaults objectAtIndex: i];
3155 rows = [[term valueForKey: AngbandTerminalRowsDefaultsKey] integerValue];
3156 columns = [[term valueForKey: AngbandTerminalColumnsDefaultsKey] integerValue];
3160 term *newterm = ZNEW(term);
3162 /* Initialize the term */
3163 term_init(newterm, columns, rows, 256 /* keypresses, for some reason? */);
3165 /* Differentiate between BS/^h, Tab/^i, etc. */
3166 /* newterm->complex_input = TRUE; */
3168 /* Use a "software" cursor */
3169 newterm->soft_cursor = TRUE;
3171 /* Disable the per-row flush notifications since they are not used. */
3172 newterm->never_frosh = TRUE;
3174 /* Erase with "white space" */
3175 newterm->attr_blank = TERM_WHITE;
3176 newterm->char_blank = ' ';
3178 /* Prepare the init/nuke hooks */
3179 newterm->init_hook = Term_init_cocoa;
3180 newterm->nuke_hook = Term_nuke_cocoa;
3182 /* Prepare the function hooks */
3183 newterm->xtra_hook = Term_xtra_cocoa;
3184 newterm->wipe_hook = Term_wipe_cocoa;
3185 newterm->curs_hook = Term_curs_cocoa;
3186 newterm->bigcurs_hook = Term_bigcurs_cocoa;
3187 newterm->text_hook = Term_text_cocoa;
3188 newterm->pict_hook = Term_pict_cocoa;
3189 /* newterm->mbcs_hook = Term_mbcs_cocoa; */
3191 /* Global pointer */
3192 angband_term[i] = newterm;
3198 * Load preferences from preferences file for current host+current user+
3199 * current application.
3201 static void load_prefs()
3203 NSUserDefaults *defs = [NSUserDefaults angbandDefaults];
3205 /* Make some default defaults */
3206 NSMutableArray *defaultTerms = [[NSMutableArray alloc] init];
3208 /* The following default rows/cols were determined experimentally by first
3209 * finding the ideal window/font size combinations. But because of awful
3210 * temporal coupling in Term_init_cocoa(), it's impossible to set up the
3211 * defaults there, so we do it this way. */
3212 for( NSUInteger i = 0; i < ANGBAND_TERM_MAX; i++ )
3250 NSDictionary *standardTerm = [NSDictionary dictionaryWithObjectsAndKeys:
3251 [NSNumber numberWithInt: rows], AngbandTerminalRowsDefaultsKey,
3252 [NSNumber numberWithInt: columns], AngbandTerminalColumnsDefaultsKey,
3253 [NSNumber numberWithBool: visible], AngbandTerminalVisibleDefaultsKey,
3255 [defaultTerms addObject: standardTerm];
3258 NSDictionary *defaults = [[NSDictionary alloc] initWithObjectsAndKeys:
3260 @"Osaka", @"FontName",
3262 @"Menlo", @"FontName",
3264 [NSNumber numberWithFloat:13.f], @"FontSize",
3265 [NSNumber numberWithInt:60], AngbandFrameRateDefaultsKey,
3266 [NSNumber numberWithBool:YES], AngbandSoundDefaultsKey,
3267 [NSNumber numberWithInt:GRAPHICS_NONE], AngbandGraphicsDefaultsKey,
3268 defaultTerms, AngbandTerminalsDefaultsKey,
3270 [defs registerDefaults:defaults];
3272 [defaultTerms release];
3274 /* Preferred graphics mode */
3275 graf_mode_req = [defs integerForKey:AngbandGraphicsDefaultsKey];
3277 /* Use sounds; set the Angband global */
3278 use_sound = ([defs boolForKey:AngbandSoundDefaultsKey] == YES) ? TRUE : FALSE;
3281 frames_per_second = [defs integerForKey:AngbandFrameRateDefaultsKey];
3284 default_font = [[NSFont fontWithName:[defs valueForKey:@"FontName-0"] size:[defs floatForKey:@"FontSize-0"]] retain];
3285 if (! default_font) default_font = [[NSFont fontWithName:@"Menlo" size:13.] retain];
3289 * Arbitary limit on number of possible samples per event
3291 #define MAX_SAMPLES 16
3294 * Struct representing all data for a set of event samples
3298 int num; /* Number of available samples for this event */
3299 NSSound *sound[MAX_SAMPLES];
3300 } sound_sample_list;
3303 * Array of event sound structs
3305 static sound_sample_list samples[MSG_MAX];
3309 * Load sound effects based on sound.cfg within the xtra/sound directory;
3310 * bridge to Cocoa to use NSSound for simple loading and playback, avoiding
3311 * I/O latency by cacheing all sounds at the start. Inherits full sound
3312 * format support from Quicktime base/plugins.
3313 * pelpel favoured a plist-based parser for the future but .cfg support
3314 * improves cross-platform compatibility.
3316 static void load_sounds(void)
3318 char sound_dir[1024];
3323 /* Build the "sound" path */
3324 path_build(sound_dir, sizeof(sound_dir), ANGBAND_DIR_XTRA, "sound");
3326 /* Find and open the config file */
3327 path_build(path, sizeof(path), sound_dir, "sound.cfg");
3328 fff = my_fopen(path, "r");
3333 NSLog(@"The sound configuration file could not be opened.");
3337 /* Instantiate an autorelease pool for use by NSSound */
3338 NSAutoreleasePool *autorelease_pool;
3339 autorelease_pool = [[NSAutoreleasePool alloc] init];
3341 /* Use a dictionary to unique sounds, so we can share NSSounds across
3342 * multiple events */
3343 NSMutableDictionary *sound_dict = [NSMutableDictionary dictionary];
3346 * This loop may take a while depending on the count and size of samples
3350 /* Parse the file */
3351 /* Lines are always of the form "name = sample [sample ...]" */
3352 while (my_fgets(fff, buffer, sizeof(buffer)) == 0)
3355 char *cfg_sample_list;
3361 /* Skip anything not beginning with an alphabetic character */
3362 if (!buffer[0] || !isalpha((unsigned char)buffer[0])) continue;
3364 /* Split the line into two: message name, and the rest */
3365 search = strchr(buffer, ' ');
3366 cfg_sample_list = strchr(search + 1, ' ');
3367 if (!search) continue;
3368 if (!cfg_sample_list) continue;
3370 /* Set the message name, and terminate at first space */
3374 /* Make sure this is a valid event name */
3375 for (event = MSG_MAX - 1; event >= 0; event--)
3377 if (strcmp(msg_name, angband_sound_name[event]) == 0)
3380 if (event < 0) continue;
3382 /* Advance the sample list pointer so it's at the beginning of text */
3384 if (!cfg_sample_list[0]) continue;
3386 /* Terminate the current token */
3387 cur_token = cfg_sample_list;
3388 search = strchr(cur_token, ' ');
3392 next_token = search + 1;
3400 * Now we find all the sample names and add them one by one
3404 int num = samples[event].num;
3406 /* Don't allow too many samples */
3407 if (num >= MAX_SAMPLES) break;
3409 NSString *token_string = [NSString stringWithUTF8String:cur_token];
3410 NSSound *sound = [sound_dict objectForKey:token_string];
3416 /* We have to load the sound. Build the path to the sample */
3417 path_build(path, sizeof(path), sound_dir, cur_token);
3418 if (stat(path, &stb) == 0)
3421 /* Load the sound into memory */
3422 sound = [[[NSSound alloc] initWithContentsOfFile:[NSString stringWithUTF8String:path] byReference:YES] autorelease];
3423 if (sound) [sound_dict setObject:sound forKey:token_string];
3427 /* Store it if we loaded it */
3430 samples[event].sound[num] = [sound retain];
3432 /* Imcrement the sample count */
3433 samples[event].num++;
3437 /* Figure out next token */
3438 cur_token = next_token;
3441 /* Try to find a space */
3442 search = strchr(cur_token, ' ');
3444 /* If we can find one, terminate, and set new "next" */
3448 next_token = search + 1;
3452 /* Otherwise prevent infinite looping */
3459 /* Release the autorelease pool */
3460 [autorelease_pool release];
3462 /* Close the file */
3467 * Play sound effects asynchronously. Select a sound from any available
3468 * for the required event, and bridge to Cocoa to play it.
3470 static void play_sound(int event)
3473 if (event < 0 || event >= MSG_MAX) return;
3475 /* Load sounds just-in-time (once) */
3476 static BOOL loaded = NO;
3482 /* Check there are samples for this event */
3483 if (!samples[event].num) return;
3485 /* Instantiate an autorelease pool for use by NSSound */
3486 NSAutoreleasePool *autorelease_pool;
3487 autorelease_pool = [[NSAutoreleasePool alloc] init];
3489 /* Choose a random event */
3490 int s = randint0(samples[event].num);
3492 /* Stop the sound if it's currently playing */
3493 if ([samples[event].sound[s] isPlaying])
3494 [samples[event].sound[s] stop];
3496 /* Play the sound */
3497 [samples[event].sound[s] play];
3499 /* Release the autorelease pool */
3500 [autorelease_pool drain];
3506 static void init_windows(void)
3508 /* Create the main window */
3509 term *primary = term_data_link(0);
3511 /* Prepare to create any additional windows */
3513 for (i=1; i < ANGBAND_TERM_MAX; i++) {
3517 /* Activate the primary term */
3518 Term_activate(primary);
3522 * Handle the "open_when_ready" flag
3524 static void handle_open_when_ready(void)
3526 /* Check the flag XXX XXX XXX make a function for this */
3527 if (open_when_ready && initialized && !game_in_progress)
3530 open_when_ready = FALSE;
3532 /* Game is in progress */
3533 game_in_progress = TRUE;
3535 /* Wait for a keypress */
3536 pause_line(Term->hgt - 1);
3542 * Handle quit_when_ready, by Peter Ammon,
3543 * slightly modified to check inkey_flag.
3545 static void quit_calmly(void)
3547 /* Quit immediately if game's not started */
3548 if (!game_in_progress || !character_generated) quit(NULL);
3550 /* Save the game and Quit (if it's safe) */
3553 /* Hack -- Forget messages and term */
3555 Term->mapped_flag = FALSE;
3558 do_cmd_save_game(FALSE);
3559 record_current_savefile();
3565 /* Wait until inkey_flag is set */
3571 * Returns YES if we contain an AngbandView (and hence should direct our events
3574 static BOOL contains_angband_view(NSView *view)
3576 if ([view isKindOfClass:[AngbandView class]]) return YES;
3577 for (NSView *subview in [view subviews]) {
3578 if (contains_angband_view(subview)) return YES;
3585 * Queue mouse presses if they occur in the map section of the main window.
3587 static void AngbandHandleEventMouseDown( NSEvent *event )
3590 AngbandContext *angbandContext = [[[event window] contentView] angbandContext];
3591 AngbandContext *mainAngbandContext = angband_term[0]->data;
3593 if (mainAngbandContext->primaryWindow && [[event window] windowNumber] == [mainAngbandContext->primaryWindow windowNumber])
3595 int cols, rows, x, y;
3596 Term_get_size(&cols, &rows);
3597 NSSize tileSize = angbandContext->tileSize;
3598 NSSize border = angbandContext->borderSize;
3599 NSPoint windowPoint = [event locationInWindow];
3601 /* Adjust for border; add border height because window origin is at
3603 windowPoint = NSMakePoint( windowPoint.x - border.width, windowPoint.y + border.height );
3605 NSPoint p = [[[event window] contentView] convertPoint: windowPoint fromView: nil];
3606 x = floor( p.x / tileSize.width );
3607 y = floor( p.y / tileSize.height );
3609 /* Being safe about this, since xcode doesn't seem to like the
3610 * bool_hack stuff */
3611 BOOL displayingMapInterface = ((int)inkey_flag != 0);
3613 /* Sidebar plus border == thirteen characters; top row is reserved. */
3614 /* Coordinates run from (0,0) to (cols-1, rows-1). */
3615 BOOL mouseInMapSection = (x > 13 && x <= cols - 1 && y > 0 && y <= rows - 2);
3617 /* If we are displaying a menu, allow clicks anywhere; if we are
3618 * displaying the main game interface, only allow clicks in the map
3620 if (!displayingMapInterface || (displayingMapInterface && mouseInMapSection))
3622 /* [event buttonNumber] will return 0 for left click,
3623 * 1 for right click, but this is safer */
3624 int button = ([event type] == NSLeftMouseDown) ? 1 : 2;
3627 NSUInteger eventModifiers = [event modifierFlags];
3628 byte angbandModifiers = 0;
3629 angbandModifiers |= (eventModifiers & NSShiftKeyMask) ? KC_MOD_SHIFT : 0;
3630 angbandModifiers |= (eventModifiers & NSControlKeyMask) ? KC_MOD_CONTROL : 0;
3631 angbandModifiers |= (eventModifiers & NSAlternateKeyMask) ? KC_MOD_ALT : 0;
3632 button |= (angbandModifiers & 0x0F) << 4; /* encode modifiers in the button number (see Term_mousepress()) */
3635 Term_mousepress(x, y, button);
3639 /* Pass click through to permit focus change, resize, etc. */
3640 [NSApp sendEvent:event];
3646 * Encodes an NSEvent Angband-style, or forwards it along. Returns YES if the
3647 * event was sent to Angband, NO if Cocoa (or nothing) handled it */
3648 static BOOL send_event(NSEvent *event)
3651 /* If the receiving window is not an Angband window, then do nothing */
3652 if (! contains_angband_view([[event window] contentView]))
3654 [NSApp sendEvent:event];
3658 /* Analyze the event */
3659 switch ([event type])
3663 /* Try performing a key equivalent */
3664 if ([[NSApp mainMenu] performKeyEquivalent:event]) break;
3666 unsigned modifiers = [event modifierFlags];
3668 /* Send all NSCommandKeyMasks through */
3669 if (modifiers & NSCommandKeyMask)
3671 [NSApp sendEvent:event];
3675 if (! [[event characters] length]) break;
3678 /* Extract some modifiers */
3679 int mc = !! (modifiers & NSControlKeyMask);
3680 int ms = !! (modifiers & NSShiftKeyMask);
3681 int mo = !! (modifiers & NSAlternateKeyMask);
3682 int kp = !! (modifiers & NSNumericPadKeyMask);
3685 /* Get the Angband char corresponding to this unichar */
3686 unichar c = [[event characters] characterAtIndex:0];
3689 * Have anything from the numeric keypad generate a macro
3690 * trigger so that shift or control modifiers can be passed.
3692 if (c <= 0x7F && !kp)
3698 * The rest of Hengband uses Angband 2.7's or so key handling:
3699 * so for the rest do something like the encoding that
3700 * main-win.c does: send a macro trigger with the Unicode
3701 * value encoded into printable ASCII characters.
3706 /* override special keys */
3707 switch([event keyCode]) {
3708 case kVK_Return: ch = '\r'; break;
3709 case kVK_Escape: ch = 27; break;
3710 case kVK_Tab: ch = '\t'; break;
3711 case kVK_Delete: ch = '\b'; break;
3712 case kVK_ANSI_KeypadEnter: ch = '\r'; kp = TRUE; break;
3715 /* Hide the mouse pointer */
3716 [NSCursor setHiddenUntilMouseMoves:YES];
3726 * Could use the hexsym global but some characters overlap with
3727 * those used to indicate modifiers.
3729 const char encoded[16] = {
3730 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b',
3734 /* Begin the macro trigger. */
3737 /* Send the modifiers. */
3738 if (mc) Term_keypress('C');
3739 if (ms) Term_keypress('S');
3740 if (mo) Term_keypress('O');
3741 if (kp) Term_keypress('K');
3744 Term_keypress(encoded[c & 0xF]);
3748 /* End the macro trigger. */
3755 case NSLeftMouseDown:
3756 case NSRightMouseDown:
3757 AngbandHandleEventMouseDown(event);
3760 case NSApplicationDefined:
3762 if ([event subtype] == AngbandEventWakeup)
3770 [NSApp sendEvent:event];
3777 * Check for Events, return TRUE if we process any
3779 static BOOL check_events(int wait)
3782 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
3784 /* Handles the quit_when_ready flag */
3785 if (quit_when_ready) quit_calmly();
3788 if (wait == CHECK_EVENTS_WAIT) endDate = [NSDate distantFuture];
3789 else endDate = [NSDate distantPast];
3793 if (quit_when_ready)
3795 /* send escape events until we quit */
3796 Term_keypress(0x1B);
3801 event = [NSApp nextEventMatchingMask:-1 untilDate:endDate inMode:NSDefaultRunLoopMode dequeue:YES];
3807 if (send_event(event)) break;
3813 /* Something happened */
3819 * Hook to tell the user something important
3821 static void hook_plog(const char * str)
3825 NSString *msg = NSLocalizedStringWithDefaultValue(
3826 @"Warning", AngbandMessageCatalog, [NSBundle mainBundle],
3827 @"Warning", @"Alert text for generic warning");
3828 NSString *info = [NSString stringWithCString:str
3830 encoding:NSJapaneseEUCStringEncoding
3832 encoding:NSMacOSRomanStringEncoding
3835 NSAlert *alert = [[NSAlert alloc] init];
3837 alert.messageText = msg;
3838 alert.informativeText = info;
3839 NSModalResponse result = [alert runModal];
3846 * Hook to tell the user something, and then quit
3848 static void hook_quit(const char * str)
3855 * ------------------------------------------------------------------------
3857 * ------------------------------------------------------------------------ */
3859 @implementation AngbandAppDelegate
3861 @synthesize graphicsMenu=_graphicsMenu;
3862 @synthesize commandMenu=_commandMenu;
3863 @synthesize commandMenuTagMap=_commandMenuTagMap;
3865 - (IBAction)newGame:sender
3867 /* Game is in progress */
3868 game_in_progress = TRUE;
3872 - (IBAction)editFont:sender
3874 NSFontPanel *panel = [NSFontPanel sharedFontPanel];
3875 NSFont *termFont = default_font;
3878 for (i=0; i < ANGBAND_TERM_MAX; i++) {
3879 if ([(id)angband_term[i]->data isMainWindow]) {
3880 termFont = [(id)angband_term[i]->data selectionFont];
3885 [panel setPanelFont:termFont isMultiple:NO];
3886 [panel orderFront:self];
3890 * Implent NSObject's changeFont() method to receive a notification about the
3891 * changed font. Note that, as of 10.14, changeFont() is deprecated in
3892 * NSObject - it will be removed at some point and the application delegate
3893 * will have to be declared as implementing the NSFontChanging protocol.
3895 - (void)changeFont:(id)sender
3898 for (mainTerm=0; mainTerm < ANGBAND_TERM_MAX; mainTerm++) {
3899 if ([(id)angband_term[mainTerm]->data isMainWindow]) {
3904 /* Bug #1709: Only change font for angband windows */
3905 if (mainTerm == ANGBAND_TERM_MAX) return;
3907 NSFont *oldFont = default_font;
3908 NSFont *newFont = [sender convertFont:oldFont];
3909 if (! newFont) return; /*paranoia */
3911 /* Store as the default font if we changed the first term */
3912 if (mainTerm == 0) {
3914 [default_font release];
3915 default_font = newFont;
3918 /* Record it in the preferences */
3919 NSUserDefaults *defs = [NSUserDefaults angbandDefaults];
3920 [defs setValue:[newFont fontName]
3921 forKey:[NSString stringWithFormat:@"FontName-%d", mainTerm]];
3922 [defs setFloat:[newFont pointSize]
3923 forKey:[NSString stringWithFormat:@"FontSize-%d", mainTerm]];
3926 NSDisableScreenUpdates();
3929 AngbandContext *angbandContext = angband_term[mainTerm]->data;
3930 [(id)angbandContext setSelectionFont:newFont adjustTerminal: YES];
3932 NSEnableScreenUpdates();
3934 if (mainTerm == 0 && game_in_progress) {
3935 /* Mimics the logic in setGraphicsMode(). */
3937 wakeup_event_loop();
3939 [(id)angbandContext requestRedraw];
3943 - (IBAction)openGame:sender
3945 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
3946 BOOL selectedSomething = NO;
3949 /* Get where we think the save files are */
3950 NSURL *startingDirectoryURL = [NSURL fileURLWithPath:[NSString stringWithCString:ANGBAND_DIR_SAVE encoding:NSASCIIStringEncoding] isDirectory:YES];
3952 /* Set up an open panel */
3953 NSOpenPanel* panel = [NSOpenPanel openPanel];
3954 [panel setCanChooseFiles:YES];
3955 [panel setCanChooseDirectories:NO];
3956 [panel setResolvesAliases:YES];
3957 [panel setAllowsMultipleSelection:NO];
3958 [panel setTreatsFilePackagesAsDirectories:YES];
3959 [panel setDirectoryURL:startingDirectoryURL];
3962 panelResult = [panel runModal];
3963 if (panelResult == NSOKButton)
3965 NSArray* fileURLs = [panel URLs];
3966 if ([fileURLs count] > 0 && [[fileURLs objectAtIndex:0] isFileURL])
3968 NSURL* savefileURL = (NSURL *)[fileURLs objectAtIndex:0];
3969 /* The path property doesn't do the right thing except for
3970 * URLs with the file scheme. We had getFileSystemRepresentation
3971 * here before, but that wasn't introduced until OS X 10.9. */
3972 selectedSomething = [[savefileURL path] getCString:savefile
3973 maxLength:sizeof savefile encoding:NSMacOSRomanStringEncoding];
3977 if (selectedSomething)
3979 /* Remember this so we can select it by default next time */
3980 record_current_savefile();
3982 /* Game is in progress */
3983 game_in_progress = TRUE;
3990 - (IBAction)saveGame:sender
3992 /* Hack -- Forget messages */
3996 do_cmd_save_game(FALSE);
3998 /* Record the current save file so we can select it by default next time.
3999 * It's a little sketchy that this only happens when we save through the
4000 * menu; ideally game-triggered saves would trigger it too. */
4001 record_current_savefile();
4005 * Implement NSObject's validateMenuItem() method to override enabling or
4006 * disabling a menu item. Note that, as of 10.14, validateMenuItem() is
4007 * deprecated in NSObject - it will be removed at some point and the
4008 * application delegate will have to be declared as implementing the
4009 * NSMenuItemValidation protocol.
4011 - (BOOL)validateMenuItem:(NSMenuItem *)menuItem
4013 SEL sel = [menuItem action];
4014 NSInteger tag = [menuItem tag];
4016 if( tag >= AngbandWindowMenuItemTagBase && tag < AngbandWindowMenuItemTagBase + ANGBAND_TERM_MAX )
4018 if( tag == AngbandWindowMenuItemTagBase )
4020 /* The main window should always be available and visible */
4026 * Another window is only usable after Term_init_cocoa() has
4027 * been called for it. For Angband if window_flag[i] is nonzero
4028 * then that has happened for window i. For Hengband, that is
4029 * not the case so also test angband_term[i]->data.
4031 NSInteger subwindowNumber = tag - AngbandWindowMenuItemTagBase;
4032 return (angband_term[subwindowNumber]->data != 0
4033 && window_flag[subwindowNumber] > 0);
4039 if (sel == @selector(newGame:))
4041 return ! game_in_progress;
4043 else if (sel == @selector(editFont:))
4047 else if (sel == @selector(openGame:))
4049 return ! game_in_progress;
4051 else if (sel == @selector(setRefreshRate:) &&
4052 [[menuItem parentItem] tag] == 150)
4054 NSInteger fps = [[NSUserDefaults standardUserDefaults] integerForKey:AngbandFrameRateDefaultsKey];
4055 [menuItem setState: ([menuItem tag] == fps)];
4058 else if( sel == @selector(setGraphicsMode:) )
4060 NSInteger requestedGraphicsMode = [[NSUserDefaults standardUserDefaults] integerForKey:AngbandGraphicsDefaultsKey];
4061 [menuItem setState: (tag == requestedGraphicsMode)];
4064 else if( sel == @selector(toggleSound:) )
4066 BOOL is_on = [[NSUserDefaults standardUserDefaults]
4067 boolForKey:AngbandSoundDefaultsKey];
4069 [menuItem setState: ((is_on) ? NSOnState : NSOffState)];
4072 else if( sel == @selector(sendAngbandCommand:) ||
4073 sel == @selector(saveGame:) )
4076 * we only want to be able to send commands during an active game
4077 * after the birth screens
4079 return !!game_in_progress && character_generated;
4085 - (IBAction)setRefreshRate:(NSMenuItem *)menuItem
4087 frames_per_second = [menuItem tag];
4088 [[NSUserDefaults angbandDefaults] setInteger:frames_per_second forKey:AngbandFrameRateDefaultsKey];
4091 - (void)selectWindow: (id)sender
4093 NSInteger subwindowNumber = [(NSMenuItem *)sender tag] - AngbandWindowMenuItemTagBase;
4094 AngbandContext *context = angband_term[subwindowNumber]->data;
4095 [context->primaryWindow makeKeyAndOrderFront: self];
4096 [context saveWindowVisibleToDefaults: YES];
4099 - (void)prepareWindowsMenu
4101 /* Get the window menu with default items and add a separator and item for
4102 * the main window */
4103 NSMenu *windowsMenu = [[NSApplication sharedApplication] windowsMenu];
4104 [windowsMenu addItem: [NSMenuItem separatorItem]];
4106 NSString *title1 = [NSString stringWithCString:angband_term_name[0]
4108 encoding:NSJapaneseEUCStringEncoding
4110 encoding:NSMacOSRomanStringEncoding
4113 NSMenuItem *angbandItem = [[NSMenuItem alloc] initWithTitle:title1 action: @selector(selectWindow:) keyEquivalent: @"0"];
4114 [angbandItem setTarget: self];
4115 [angbandItem setTag: AngbandWindowMenuItemTagBase];
4116 [windowsMenu addItem: angbandItem];
4117 [angbandItem release];
4119 /* Add items for the additional term windows */
4120 for( NSInteger i = 1; i < ANGBAND_TERM_MAX; i++ )
4122 NSString *title = [NSString stringWithCString:angband_term_name[i]
4124 encoding:NSJapaneseEUCStringEncoding
4126 encoding:NSMacOSRomanStringEncoding
4129 NSString *keyEquivalent = [NSString stringWithFormat: @"%ld", (long)i];
4130 NSMenuItem *windowItem = [[NSMenuItem alloc] initWithTitle: title action: @selector(selectWindow:) keyEquivalent: keyEquivalent];
4131 [windowItem setTarget: self];
4132 [windowItem setTag: AngbandWindowMenuItemTagBase + i];
4133 [windowsMenu addItem: windowItem];
4134 [windowItem release];
4138 - (void)setGraphicsMode:(NSMenuItem *)sender
4140 /* We stashed the graphics mode ID in the menu item's tag */
4141 graf_mode_req = [sender tag];
4143 /* Stash it in UserDefaults */
4144 [[NSUserDefaults angbandDefaults] setInteger:graf_mode_req forKey:AngbandGraphicsDefaultsKey];
4145 [[NSUserDefaults angbandDefaults] synchronize];
4147 if (game_in_progress)
4149 /* Hack -- Force redraw */
4152 /* Wake up the event loop so it notices the change */
4153 wakeup_event_loop();
4157 - (IBAction) toggleSound: (NSMenuItem *) sender
4159 BOOL is_on = (sender.state == NSOnState);
4161 /* Toggle the state and update the Angband global and preferences. */
4162 sender.state = (is_on) ? NSOffState : NSOnState;
4163 use_sound = (is_on) ? FALSE : TRUE;
4164 [[NSUserDefaults angbandDefaults] setBool:(! is_on)
4165 forKey:AngbandSoundDefaultsKey];
4169 * Send a command to Angband via a menu item. This places the appropriate key
4170 * down events into the queue so that it seems like the user pressed them
4171 * (instead of trying to use the term directly).
4173 - (void)sendAngbandCommand: (id)sender
4175 NSMenuItem *menuItem = (NSMenuItem *)sender;
4176 NSString *command = [self.commandMenuTagMap objectForKey: [NSNumber numberWithInteger: [menuItem tag]]];
4177 NSInteger windowNumber = [((AngbandContext *)angband_term[0]->data)->primaryWindow windowNumber];
4179 /* Send a \ to bypass keymaps */
4180 NSEvent *escape = [NSEvent keyEventWithType: NSKeyDown
4181 location: NSZeroPoint
4184 windowNumber: windowNumber
4187 charactersIgnoringModifiers: @"\\"
4190 [[NSApplication sharedApplication] postEvent: escape atStart: NO];
4192 /* Send the actual command (from the original command set) */
4193 NSEvent *keyDown = [NSEvent keyEventWithType: NSKeyDown
4194 location: NSZeroPoint
4197 windowNumber: windowNumber
4200 charactersIgnoringModifiers: command
4203 [[NSApplication sharedApplication] postEvent: keyDown atStart: NO];
4207 * Set up the command menu dynamically, based on CommandMenu.plist.
4209 - (void)prepareCommandMenu
4211 NSString *commandMenuPath = [[NSBundle mainBundle] pathForResource: @"CommandMenu" ofType: @"plist"];
4212 NSArray *commandMenuItems = [[NSArray alloc] initWithContentsOfFile: commandMenuPath];
4213 NSMutableDictionary *angbandCommands = [[NSMutableDictionary alloc] init];
4214 NSString *tblname = @"CommandMenu";
4215 NSInteger tagOffset = 0;
4217 for( NSDictionary *item in commandMenuItems )
4219 BOOL useShiftModifier = [[item valueForKey: @"ShiftModifier"] boolValue];
4220 BOOL useOptionModifier = [[item valueForKey: @"OptionModifier"] boolValue];
4221 NSUInteger keyModifiers = NSCommandKeyMask;
4222 keyModifiers |= (useShiftModifier) ? NSShiftKeyMask : 0;
4223 keyModifiers |= (useOptionModifier) ? NSAlternateKeyMask : 0;
4225 NSString *lookup = [item valueForKey: @"Title"];
4226 NSString *title = NSLocalizedStringWithDefaultValue(
4227 lookup, tblname, [NSBundle mainBundle], lookup, @"");
4228 NSString *key = [item valueForKey: @"KeyEquivalent"];
4229 NSMenuItem *menuItem = [[NSMenuItem alloc] initWithTitle: title action: @selector(sendAngbandCommand:) keyEquivalent: key];
4230 [menuItem setTarget: self];
4231 [menuItem setKeyEquivalentModifierMask: keyModifiers];
4232 [menuItem setTag: AngbandCommandMenuItemTagBase + tagOffset];
4233 [self.commandMenu addItem: menuItem];
4236 NSString *angbandCommand = [item valueForKey: @"AngbandCommand"];
4237 [angbandCommands setObject: angbandCommand forKey: [NSNumber numberWithInteger: [menuItem tag]]];
4241 [commandMenuItems release];
4243 NSDictionary *safeCommands = [[NSDictionary alloc] initWithDictionary: angbandCommands];
4244 self.commandMenuTagMap = safeCommands;
4245 [safeCommands release];
4246 [angbandCommands release];
4249 - (void)awakeFromNib
4251 [super awakeFromNib];
4253 [self prepareWindowsMenu];
4254 [self prepareCommandMenu];
4257 - (void)applicationDidFinishLaunching:sender
4259 [AngbandContext beginGame];
4261 /* Once beginGame finished, the game is over - that's how Angband works,
4262 * and we should quit */
4263 game_is_finished = TRUE;
4264 [NSApp terminate:self];
4267 - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
4269 if (p_ptr->playing == FALSE || game_is_finished == TRUE)
4271 return NSTerminateNow;
4273 else if (! inkey_flag)
4275 /* For compatibility with other ports, do not quit in this case */
4276 return NSTerminateCancel;
4281 /* player->upkeep->playing = FALSE; */
4283 /* Post an escape event so that we can return from our get-key-event
4285 wakeup_event_loop();
4286 quit_when_ready = true;
4287 /* Must return Cancel, not Later, because we need to get out of the
4288 * run loop and back to Angband's loop */
4289 return NSTerminateCancel;
4294 * Dynamically build the Graphics menu
4296 - (void)menuNeedsUpdate:(NSMenu *)menu {
4298 /* Only the graphics menu is dynamic */
4299 if (! [menu isEqual:self.graphicsMenu])
4302 /* If it's non-empty, then we've already built it. Currently graphics modes
4303 * won't change once created; if they ever can we can remove this check.
4304 * Note that the check mark does change, but that's handled in
4305 * validateMenuItem: instead of menuNeedsUpdate: */
4306 if ([menu numberOfItems] > 0)
4309 /* This is the action for all these menu items */
4310 SEL action = @selector(setGraphicsMode:);
4312 /* Add an initial Classic ASCII menu item */
4313 NSString *tblname = @"GraphicsMenu";
4314 NSString *key = @"Classic ASCII";
4315 NSString *title = NSLocalizedStringWithDefaultValue(
4316 key, tblname, [NSBundle mainBundle], key, @"");
4317 NSMenuItem *classicItem = [menu addItemWithTitle:title action:action keyEquivalent:@""];
4318 [classicItem setTag:GRAPHICS_NONE];
4320 /* Walk through the list of graphics modes */
4321 if (graphics_modes) {
4324 for (i=0; graphics_modes[i].pNext; i++)
4326 const graphics_mode *graf = &graphics_modes[i];
4328 if (graf->grafID == GRAPHICS_NONE) {
4331 /* Make the title. NSMenuItem throws on a nil title, so ensure it's
4333 key = [[NSString alloc] initWithUTF8String:graf->menuname];
4334 title = NSLocalizedStringWithDefaultValue(
4335 key, tblname, [NSBundle mainBundle], key, @"");
4338 NSMenuItem *item = [menu addItemWithTitle:title action:action keyEquivalent:@""];
4340 [item setTag:graf->grafID];
4346 * Delegate method that gets called if we're asked to open a file.
4348 - (void)application:(NSApplication *)sender openFiles:(NSArray *)filenames
4350 /* Can't open a file once we've started */
4351 if (game_in_progress) {
4352 [[NSApplication sharedApplication]
4353 replyToOpenOrPrint:NSApplicationDelegateReplyFailure];
4357 /* We can only open one file. Use the last one. */
4358 NSString *file = [filenames lastObject];
4360 [[NSApplication sharedApplication]
4361 replyToOpenOrPrint:NSApplicationDelegateReplyFailure];
4365 /* Put it in savefile */
4366 if (! [file getFileSystemRepresentation:savefile maxLength:sizeof savefile]) {
4367 [[NSApplication sharedApplication]
4368 replyToOpenOrPrint:NSApplicationDelegateReplyFailure];
4372 game_in_progress = TRUE;
4375 /* Wake us up in case this arrives while we're sitting at the Welcome
4377 wakeup_event_loop();
4379 [[NSApplication sharedApplication]
4380 replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
4385 int main(int argc, char* argv[])
4387 NSApplicationMain(argc, (void*)argv);
4391 #endif /* MACINTOSH || MACH_O_COCOA */