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 AngbandBigTileDefaultsKey = @"UseBigTiles";
45 static NSString * const AngbandFrameRateDefaultsKey = @"FramesPerSecond";
46 static NSString * const AngbandSoundDefaultsKey = @"AllowSound";
47 static NSInteger const AngbandWindowMenuItemTagBase = 1000;
48 static NSInteger const AngbandCommandMenuItemTagBase = 2000;
50 /* We can blit to a large layer or image and then scale it down during live
51 * resize, which makes resizing much faster, at the cost of some image quality
53 #ifndef USE_LIVE_RESIZE_CACHE
54 # define USE_LIVE_RESIZE_CACHE 1
57 /* Global defines etc from Angband 3.5-dev - NRM */
58 #define ANGBAND_TERM_MAX 8
60 #define MAX_COLORS 256
61 #define MSG_MAX SOUND_MAX
63 /* End Angband stuff - NRM */
65 /* Application defined event numbers */
68 AngbandEventWakeup = 1
71 /* Delay handling of pre-emptive "quit" event */
72 static BOOL quit_when_ready = FALSE;
74 /* Set to indicate the game is over and we can quit without delay */
75 static Boolean game_is_finished = FALSE;
77 /* Our frames per second (e.g. 60). A value of 0 means unthrottled. */
78 static int frames_per_second;
80 /* Force a new game or not? */
81 static bool new_game = FALSE;
86 * Load sound effects based on sound.cfg within the xtra/sound directory;
87 * bridge to Cocoa to use NSSound for simple loading and playback, avoiding
88 * I/O latency by caching all sounds at the start. Inherits full sound
89 * format support from Quicktime base/plugins.
90 * pelpel favoured a plist-based parser for the future but .cfg support
91 * improves cross-platform compatibility.
93 @interface AngbandSoundCatalog : NSObject {
96 * Stores instances of NSSound keyed by path so the same sound can be
97 * used for multiple events.
99 NSMutableDictionary *soundsByPath;
101 * Stores arrays of NSSound keyed by event number.
103 NSMutableDictionary *soundArraysByEvent;
107 * If NO, then playSound effectively becomes a do nothing operation.
109 @property (getter=isEnabled) BOOL enabled;
112 * Set up for lazy initialization in playSound(). Set enabled to NO.
117 * If self.enabled is YES and the given event has one or more sounds
118 * corresponding to it in the catalog, plays one of those sounds, chosen at
121 - (void)playSound:(int)event;
124 * Impose an arbitary limit on number of possible samples per event.
125 * Currently not declaring this as a class property for compatibility with
126 * versions of Xcode prior to 8.
131 * Return the shared sound catalog instance, creating it if it does not
132 * exist yet. Currently not declaring this as a class property for
133 * compatibility with versions of Xcode prior to 8.
135 + (AngbandSoundCatalog*)sharedSounds;
138 * Release any resouces associated with shared sounds.
140 + (void)clearSharedSounds;
144 @implementation AngbandSoundCatalog
147 if (self = [super init]) {
148 self->soundsByPath = nil;
149 self->soundArraysByEvent = nil;
155 - (void)playSound:(int)event {
156 if (! self.enabled) {
160 /* Initialize when the first sound is played. */
161 if (self->soundArraysByEvent == nil) {
162 /* Build the "sound" path */
163 char sound_dir[1024];
164 path_build(sound_dir, sizeof(sound_dir), ANGBAND_DIR_XTRA, "sound");
166 /* Find and open the config file */
168 path_build(path, sizeof(path), sound_dir, "sound.cfg");
169 FILE *fff = my_fopen(path, "r");
173 NSLog(@"The sound configuration file could not be opened.");
177 self->soundsByPath = [[NSMutableDictionary alloc] init];
178 self->soundArraysByEvent = [[NSMutableDictionary alloc] init];
181 * This loop may take a while depending on the count and size of
186 /* Lines are always of the form "name = sample [sample ...]" */
188 while (my_fgets(fff, buffer, sizeof(buffer)) == 0) {
190 char *cfg_sample_list;
196 /* Skip anything not beginning with an alphabetic character */
197 if (!buffer[0] || !isalpha((unsigned char)buffer[0])) continue;
199 /* Split the line into two: message name, and the rest */
200 search = strchr(buffer, ' ');
201 cfg_sample_list = strchr(search + 1, ' ');
202 if (!search) continue;
203 if (!cfg_sample_list) continue;
205 /* Set the message name, and terminate at first space */
209 /* Make sure this is a valid event name */
210 for (event = MSG_MAX - 1; event >= 0; event--) {
211 if (strcmp(msg_name, angband_sound_name[event]) == 0)
214 if (event < 0) continue;
217 * Advance the sample list pointer so it's at the beginning of
221 if (!cfg_sample_list[0]) continue;
223 /* Terminate the current token */
224 cur_token = cfg_sample_list;
225 search = strchr(cur_token, ' ');
228 next_token = search + 1;
234 * Now we find all the sample names and add them one by one
237 NSMutableArray *soundSamples =
238 [self->soundArraysByEvent
239 objectForKey:[NSNumber numberWithInteger:event]];
240 if (soundSamples == nil) {
241 soundSamples = [[NSMutableArray alloc] init];
242 [self->soundArraysByEvent
243 setObject:soundSamples
244 forKey:[NSNumber numberWithInteger:event]];
246 int num = (int) soundSamples.count;
248 /* Don't allow too many samples */
249 if (num >= [AngbandSoundCatalog maxSamples]) break;
251 NSString *token_string =
252 [NSString stringWithUTF8String:cur_token];
254 [self->soundsByPath objectForKey:token_string];
258 * We have to load the sound. Build the path to the
261 path_build(path, sizeof(path), sound_dir, cur_token);
263 if (stat(path, &stb) == 0) {
264 /* Load the sound into memory */
265 sound = [[NSSound alloc]
266 initWithContentsOfFile:[NSString stringWithUTF8String:path]
269 [self->soundsByPath setObject:sound
270 forKey:token_string];
275 /* Store it if we loaded it */
277 [soundSamples addObject:sound];
280 /* Figure out next token */
281 cur_token = next_token;
283 /* Try to find a space */
284 search = strchr(cur_token, ' ');
287 * If we can find one, terminate, and set new "next".
291 next_token = search + 1;
293 /* Otherwise prevent infinite looping */
306 NSMutableArray *samples =
307 [self->soundArraysByEvent
308 objectForKey:[NSNumber numberWithInteger:event]];
310 if (samples == nil || samples.count == 0) {
314 /* Choose a random event. */
315 int s = randint0((int) samples.count);
316 NSSound *sound = samples[s];
318 if ([sound isPlaying])
321 /* Play the sound. */
331 * For sharedSounds and clearSharedSounds.
333 static __strong AngbandSoundCatalog* gSharedSounds = nil;
335 + (AngbandSoundCatalog*)sharedSounds {
336 if (gSharedSounds == nil) {
337 gSharedSounds = [[AngbandSoundCatalog alloc] init];
339 return gSharedSounds;;
342 + (void)clearSharedSounds {
349 * To handle fonts where an individual glyph's bounding box can extend into
350 * neighboring columns, Term_curs_cocoa(), Term_pict_cocoa(),
351 * Term_text_cocoa(), and Term_wipe_cocoa() merely record what needs to be
352 * done with the actual drawing happening in response to the notification to
353 * flush all rows, the TERM_XTRA_FRESH case in Term_xtra_cocoa(). Can not use
354 * the TERM_XTRA_FROSH notification (the per-row flush), since with a software
355 * cursor, there are calls to Term_pict_cocoa(), Term_text_cocoa(), or
356 * Term_wipe_cocoa() to take care of the old cursor position which are not
357 * followed by a row flush.
359 enum PendingCellChangeType {
360 CELL_CHANGE_NONE = 0,
365 struct PendingTextChange {
369 * Is YES if glyph is a character that takes up two columns (i.e.
370 * Japanese kanji); otherwise it is NO.
374 struct PendingTileChange {
375 char fgdCol, fgdRow, bckCol, bckRow;
377 struct PendingCellChange {
378 union { struct PendingTextChange txc; struct PendingTileChange tic; } v;
379 enum PendingCellChangeType changeType;
382 @interface PendingTermChanges : NSObject {
385 struct PendingCellChange **changesByRow;
389 * Returns YES if nCol and nRow are a feasible size for the pending changes.
390 * Otherwise, returns NO.
392 + (BOOL)isValidSize:(int)nCol rows:(int)nRow;
395 * Initialize with zero columns and zero rows.
400 * Initialize with nCol columns and nRow rows. No changes will be marked.
402 - (id)initWithColumnsRows:(int)nCol rows:(int)nRow NS_DESIGNATED_INITIALIZER;
405 * Clears all marked changes.
410 * Changes the bounds over which changes are recorded. Has the side effect
411 * of clearing any marked changes. Will throw an exception if nCol or nRow
414 - (void)resize:(int)nCol rows:(int)nRow;
417 * Mark the cell, (iCol, iRow), as having changed text.
419 - (void)markTextChange:(int)iCol row:(int)iRow glyph:(wchar_t)g color:(int)c
420 isDoubleWidth:(BOOL)dw;
423 * Mark the cell, (iCol, iRow), as having a changed tile.
425 - (void)markTileChange:(int)iCol row:(int)iRow
426 foregroundCol:(char)fc foregroundRow:(char)fr
427 backgroundCol:(char)bc backgroundRow:(char)br;
430 * Mark the cells from (iCol, iRow) to (iCol + nCol - 1, iRow) as wiped.
432 - (void)markWipeRange:(int)iCol row:(int)iRow n:(int)nCol;
435 * Mark the location of the cursor. The cursor will be the standard size:
438 - (void)markCursor:(int)iCol row:(int)iRow;
441 * Mark the location of the cursor. The cursor will be w cells wide and
442 * h cells tall and the given location is the position of the upper left
445 - (void)markBigCursor:(int)iCol row:(int)iRow
446 cellsWide:(int)w cellsHigh:(int)h;
449 * Return the zero-based index of the first column changed for the given
450 * zero-based row index. If there are no changes in the row, the returned
451 * value will be the number of columns.
453 - (int)getFirstChangedColumnInRow:(int)iRow;
456 * Return the zero-based index of the last column changed for the given
457 * zero-based row index. If there are no changes in the row, the returned
460 - (int)getLastChangedColumnInRow:(int)iRow;
463 * Return the type of change at the given cell, (iCol, iRow).
465 - (enum PendingCellChangeType)getCellChangeType:(int)iCol row:(int)iRow;
468 * Return the nature of a text change at the given cell, (iCol, iRow).
469 * Will throw an exception if [obj getCellChangeType:iCol row:iRow] is
470 * neither CELL_CHANGE_TEXT nor CELL_CHANGE_WIPE.
472 - (struct PendingTextChange)getCellTextChange:(int)iCol row:(int)iRow;
475 * Return the nature of a tile change at the given cell, (iCol, iRow).
476 * Will throw an exception if [obj getCellChangeType:iCol row:iRow] is
477 * different than CELL_CHANGE_TILE.
479 - (struct PendingTileChange)getCellTileChange:(int)iCol row:(int)iRow;
482 * Is the number of columns for recording changes.
484 @property (readonly) int columnCount;
487 * Is the number of rows for recording changes.
489 @property (readonly) int rowCount;
492 * Will be YES if there are any pending changes to locations rendered as text.
493 * Otherwise, it will be NO.
495 @property (readonly) BOOL hasTextChanges;
498 * Will be YES if there are any pending changes to locations rendered as tiles.
499 * Otherwise, it will be NO.
501 @property (readonly) BOOL hasTileChanges;
504 * Will be YES if there are any pending wipes. Otherwise, it will be NO.
506 @property (readonly) BOOL hasWipeChanges;
509 * Is the zero-based index of the first row with changes. Will be equal to
510 * the number of rows if there are no changes.
512 @property (readonly) int firstChangedRow;
515 * Is the zero-based index of the last row with changes. Will be equal to
516 * -1 if there are no changes.
518 @property (readonly) int lastChangedRow;
521 * Is the zero-based index for the column with the upper left corner of the
522 * cursor. It will be -1 if the cursor position has not been set since the
523 * changes were cleared.
525 @property (readonly) int cursorColumn;
528 * Is the zero-based index for the row with the upper left corner of the
529 * cursor. It will be -1 if the cursor position has not been set since the
530 * changes were cleared.
532 @property (readonly) int cursorRow;
535 * Is the cursor width in number of cells.
537 @property (readonly) int cursorWidth;
540 * Is the cursor height in number of cells.
542 @property (readonly) int cursorHeight;
545 * This is a helper for the mark* messages.
547 - (void)setupForChange:(int)iCol row:(int)iRow n:(int)nCol;
550 * Throw an exception if the given range of column indices is invalid
551 * (including non-positive values for nCol).
553 - (void)checkColumnIndices:(int)iCol n:(int)nCol;
556 * Throw an exception if the given row index is invalid.
558 - (void)checkRowIndex:(int)iRow;
562 @implementation PendingTermChanges
564 + (BOOL)isValidSize:(int)nCol rows:(int)nRow
567 (size_t) nCol > SIZE_MAX / sizeof(struct PendingCellChange) ||
569 (size_t) nRow > SIZE_MAX / sizeof(struct PendingCellChange*) ||
570 (size_t) nRow > SIZE_MAX / (2 * sizeof(int))) {
578 return [self initWithColumnsRows:0 rows:0];
581 - (id)initWithColumnsRows:(int)nCol rows:(int)nRow
583 if (self = [super init]) {
584 if (! [PendingTermChanges isValidSize:nCol rows:nRow]) {
587 self->colBounds = malloc((size_t) 2 * sizeof(int) * nRow);
588 if (self->colBounds == 0 && nRow > 0) {
591 self->changesByRow = calloc(nRow, sizeof(struct PendingCellChange*));
592 if (self->changesByRow == 0 && nRow > 0) {
593 free(self->colBounds);
596 for (int i = 0; i < nRow + nRow; i += 2) {
597 self->colBounds[i] = nCol;
598 self->colBounds[i + 1] = -1;
600 self->_columnCount = nCol;
601 self->_rowCount = nRow;
602 self->_hasTextChanges = NO;
603 self->_hasTileChanges = NO;
604 self->_hasWipeChanges = NO;
605 self->_firstChangedRow = nRow;
606 self->_lastChangedRow = -1;
607 self->_cursorColumn = -1;
608 self->_cursorRow = -1;
609 self->_cursorWidth = 1;
610 self->_cursorHeight = 1;
617 if (self->changesByRow != 0) {
618 for (int i = 0; i < self.rowCount; ++i) {
619 if (self->changesByRow[i] != 0) {
620 free(self->changesByRow[i]);
621 self->changesByRow[i] = 0;
624 free(self->changesByRow);
625 self->changesByRow = 0;
627 if (self->colBounds != 0) {
628 free(self->colBounds);
635 for (int i = 0; i < self.rowCount; ++i) {
636 self->colBounds[i + i] = self.columnCount;
637 self->colBounds[i + i + 1] = -1;
638 if (self->changesByRow[i] != 0) {
639 free(self->changesByRow[i]);
640 self->changesByRow[i] = 0;
643 self->_hasTextChanges = NO;
644 self->_hasTileChanges = NO;
645 self->_hasWipeChanges = NO;
646 self->_firstChangedRow = self.rowCount;
647 self->_lastChangedRow = -1;
648 self->_cursorColumn = -1;
649 self->_cursorRow = -1;
650 self->_cursorWidth = 1;
651 self->_cursorHeight = 1;
654 - (void)resize:(int)nCol rows:(int)nRow
656 if (! [PendingTermChanges isValidSize:nCol rows:nRow]) {
657 NSException *exc = [NSException
658 exceptionWithName:@"PendingTermChangesRowsColumns"
659 reason:@"resize called with number of columns or rows that is negative or too large"
664 int *cb = malloc((size_t) 2 * sizeof(int) * nRow);
665 struct PendingCellChange** cbr =
666 calloc(nRow, sizeof(struct PendingCellChange*));
669 if ((cb == 0 || cbr == 0) && nRow > 0) {
677 NSException *exc = [NSException
678 exceptionWithName:@"OutOfMemory"
679 reason:@"resize called for PendingTermChanges"
684 for (i = 0; i < nRow; ++i) {
688 if (self->changesByRow != 0) {
689 for (i = 0; i < self.rowCount; ++i) {
690 if (self->changesByRow[i] != 0) {
691 free(self->changesByRow[i]);
692 self->changesByRow[i] = 0;
695 free(self->changesByRow);
697 if (self->colBounds != 0) {
698 free(self->colBounds);
701 self->colBounds = cb;
702 self->changesByRow = cbr;
703 self->_columnCount = nCol;
704 self->_rowCount = nRow;
705 self->_hasTextChanges = NO;
706 self->_hasTileChanges = NO;
707 self->_hasWipeChanges = NO;
708 self->_firstChangedRow = self.rowCount;
709 self->_lastChangedRow = -1;
710 self->_cursorColumn = -1;
711 self->_cursorRow = -1;
712 self->_cursorWidth = 1;
713 self->_cursorHeight = 1;
716 - (void)markTextChange:(int)iCol row:(int)iRow glyph:(wchar_t)g color:(int)c
717 isDoubleWidth:(BOOL)dw
719 [self setupForChange:iCol row:iRow n:((dw) ? 2 : 1)];
720 struct PendingCellChange *pcc = self->changesByRow[iRow] + iCol;
721 pcc->v.txc.glyph = g;
722 pcc->v.txc.color = c;
723 pcc->v.txc.doubleWidth = dw;
724 pcc->changeType = CELL_CHANGE_TEXT;
726 * Fill in a dummy since the previous character will take up two columns.
729 pcc[1].v.txc.glyph = 0;
730 pcc[1].v.txc.color = c;
731 pcc[1].v.txc.doubleWidth = NO;
732 pcc[1].changeType = CELL_CHANGE_TEXT;
734 self->_hasTextChanges = YES;
737 - (void)markTileChange:(int)iCol row:(int)iRow
738 foregroundCol:(char)fc foregroundRow:(char)fr
739 backgroundCol:(char)bc backgroundRow:(char)br
741 [self setupForChange:iCol row:iRow n:1];
742 struct PendingCellChange *pcc = self->changesByRow[iRow] + iCol;
743 pcc->v.tic.fgdCol = fc;
744 pcc->v.tic.fgdRow = fr;
745 pcc->v.tic.bckCol = bc;
746 pcc->v.tic.bckRow = br;
747 pcc->changeType = CELL_CHANGE_TILE;
748 self->_hasTileChanges = YES;
751 - (void)markWipeRange:(int)iCol row:(int)iRow n:(int)nCol
753 [self setupForChange:iCol row:iRow n:nCol];
754 struct PendingCellChange *pcc = self->changesByRow[iRow] + iCol;
755 for (int i = 0; i < nCol; ++i) {
756 pcc[i].v.txc.glyph = 0;
757 pcc[i].v.txc.color = 0;
758 pcc[i].changeType = CELL_CHANGE_WIPE;
760 self->_hasWipeChanges = YES;
763 - (void)markCursor:(int)iCol row:(int)iRow
765 /* Allow negative indices to indicate an invalid cursor. */
766 [self checkColumnIndices:((iCol >= 0) ? iCol : 0) n:1];
767 [self checkRowIndex:((iRow >= 0) ? iRow : 0)];
768 self->_cursorColumn = iCol;
769 self->_cursorRow = iRow;
770 self->_cursorWidth = 1;
771 self->_cursorHeight = 1;
774 - (void)markBigCursor:(int)iCol row:(int)iRow
775 cellsWide:(int)w cellsHigh:(int)h
777 /* Allow negative indices to indicate an invalid cursor. */
778 [self checkColumnIndices:((iCol >= 0) ? iCol : 0) n:1];
779 [self checkRowIndex:((iRow >= 0) ? iRow : 0)];
780 if (w < 1 || h < 1) {
781 NSException *exc = [NSException
782 exceptionWithName:@"InvalidCursorDimensions"
783 reason:@"markBigCursor called for PendingTermChanges"
787 self->_cursorColumn = iCol;
788 self->_cursorRow = iRow;
789 self->_cursorWidth = w;
790 self->_cursorHeight = h;
793 - (void)setupForChange:(int)iCol row:(int)iRow n:(int)nCol
795 [self checkColumnIndices:iCol n:nCol];
796 [self checkRowIndex:iRow];
797 if (self->changesByRow[iRow] == 0) {
798 self->changesByRow[iRow] =
799 malloc(self.columnCount * sizeof(struct PendingCellChange));
800 if (self->changesByRow[iRow] == 0 && self.columnCount > 0) {
801 NSException *exc = [NSException
802 exceptionWithName:@"OutOfMemory"
803 reason:@"setupForChange called for PendingTermChanges"
807 struct PendingCellChange* pcc = self->changesByRow[iRow];
808 for (int i = 0; i < self.columnCount; ++i) {
809 pcc[i].changeType = CELL_CHANGE_NONE;
812 if (self.firstChangedRow > iRow) {
813 self->_firstChangedRow = iRow;
815 if (self.lastChangedRow < iRow) {
816 self->_lastChangedRow = iRow;
818 if ([self getFirstChangedColumnInRow:iRow] > iCol) {
819 self->colBounds[iRow + iRow] = iCol;
821 if ([self getLastChangedColumnInRow:iRow] < iCol + nCol - 1) {
822 self->colBounds[iRow + iRow + 1] = iCol + nCol - 1;
826 - (int)getFirstChangedColumnInRow:(int)iRow
828 [self checkRowIndex:iRow];
829 return self->colBounds[iRow + iRow];
832 - (int)getLastChangedColumnInRow:(int)iRow
834 [self checkRowIndex:iRow];
835 return self->colBounds[iRow + iRow + 1];
838 - (enum PendingCellChangeType)getCellChangeType:(int)iCol row:(int)iRow
840 [self checkColumnIndices:iCol n:1];
841 [self checkRowIndex:iRow];
842 if (iRow < self.firstChangedRow || iRow > self.lastChangedRow) {
843 return CELL_CHANGE_NONE;
845 if (iCol < [self getFirstChangedColumnInRow:iRow] ||
846 iCol > [self getLastChangedColumnInRow:iRow]) {
847 return CELL_CHANGE_NONE;
849 return self->changesByRow[iRow][iCol].changeType;
852 - (struct PendingTextChange)getCellTextChange:(int)iCol row:(int)iRow
854 [self checkColumnIndices:iCol n:1];
855 [self checkRowIndex:iRow];
856 if (iRow < self.firstChangedRow || iRow > self.lastChangedRow ||
857 iCol < [self getFirstChangedColumnInRow:iRow] ||
858 iCol > [self getLastChangedColumnInRow:iRow] ||
859 (self->changesByRow[iRow][iCol].changeType != CELL_CHANGE_TEXT &&
860 self->changesByRow[iRow][iCol].changeType != CELL_CHANGE_WIPE)) {
861 NSException *exc = [NSException
862 exceptionWithName:@"NotTextChange"
863 reason:@"getCellTextChange called for PendingTermChanges"
867 return self->changesByRow[iRow][iCol].v.txc;
870 - (struct PendingTileChange)getCellTileChange:(int)iCol row:(int)iRow
872 [self checkColumnIndices:iCol n:1];
873 [self checkRowIndex:iRow];
874 if (iRow < self.firstChangedRow || iRow > self.lastChangedRow ||
875 iCol < [self getFirstChangedColumnInRow:iRow] ||
876 iCol > [self getLastChangedColumnInRow:iRow] ||
877 self->changesByRow[iRow][iCol].changeType != CELL_CHANGE_TILE) {
878 NSException *exc = [NSException
879 exceptionWithName:@"NotTileChange"
880 reason:@"getCellTileChange called for PendingTermChanges"
884 return self->changesByRow[iRow][iCol].v.tic;
887 - (void)checkColumnIndices:(int)iCol n:(int)nCol
890 NSException *exc = [NSException
891 exceptionWithName:@"InvalidColumnIndex"
892 reason:@"negative column index"
896 if (iCol >= self.columnCount || iCol + nCol > self.columnCount) {
897 NSException *exc = [NSException
898 exceptionWithName:@"InvalidColumnIndex"
899 reason:@"column index exceeds number of columns"
904 NSException *exc = [NSException
905 exceptionWithName:@"InvalidColumnIndex"
906 reason:@"empty column range"
912 - (void)checkRowIndex:(int)iRow
915 NSException *exc = [NSException
916 exceptionWithName:@"InvalidRowIndex"
917 reason:@"negative row index"
921 if (iRow >= self.rowCount) {
922 NSException *exc = [NSException
923 exceptionWithName:@"InvalidRowIndex"
924 reason:@"row index exceeds number of rows"
933 /* The max number of glyphs we support. Currently this only affects
934 * updateGlyphInfo() for the calculation of the tile size, fontAscender,
935 * fontDescender, nColPre, and nColPost. The rendering in drawWChar() will
936 * work for a glyph not in updateGlyphInfo()'s set, and that is used for
937 * rendering Japanese characters, though there may be clipping or clearing
938 * artifacts because it wasn't included in updateGlyphInfo()'s calculations.
940 #define GLYPH_COUNT 256
942 /* An AngbandContext represents a logical Term (i.e. what Angband thinks is
943 * a window). This typically maps to one NSView, but may map to more than one
944 * NSView (e.g. the Test and real screen saver view). */
945 @interface AngbandContext : NSObject <NSWindowDelegate>
949 /* The Angband term */
953 /* Is the last time we drew, so we can throttle drawing. */
954 CFAbsoluteTime lastRefreshTime;
957 * Whether we are currently in live resize, which affects how big we
962 /* Flags whether or not a fullscreen transition is in progress. */
963 BOOL inFullscreenTransition;
966 /* Column and row counts, by default 80 x 24 */
970 /* The size of the border between the window edge and the contents */
971 @property (readonly) NSSize borderSize;
973 /* Our array of views */
974 @property NSMutableArray *angbandViews;
976 /* The buffered image */
977 @property CGLayerRef angbandLayer;
979 /* The font of this context */
980 @property NSFont *angbandViewFont;
982 /* The size of one tile */
983 @property (readonly) NSSize tileSize;
985 /* Font's ascender and descender */
986 @property (readonly) CGFloat fontAscender;
987 @property (readonly) CGFloat fontDescender;
990 * These are the number of columns before or after, respectively, a text
991 * change that may need to be redrawn.
993 @property (readonly) int nColPre;
994 @property (readonly) int nColPost;
996 /* If this context owns a window, here it is. */
997 @property NSWindow *primaryWindow;
999 /* Is the record of changes to the contents for the next update. */
1000 @property PendingTermChanges *changes;
1002 @property (nonatomic, assign) BOOL hasSubwindowFlags;
1003 @property (nonatomic, assign) BOOL windowVisibilityChecked;
1005 - (void)drawRect:(NSRect)rect inView:(NSView *)view;
1007 /* Called at initialization to set the term */
1008 - (void)setTerm:(term *)t;
1010 /* Called when the context is going down. */
1013 /* Returns the size of the image. */
1014 - (NSSize)imageSize;
1016 /* Return the rect for a tile at given coordinates. */
1017 - (NSRect)rectInImageForTileAtX:(int)x Y:(int)y;
1019 /* Draw the given wide character into the given tile rect. */
1020 - (void)drawWChar:(wchar_t)wchar inRect:(NSRect)tile context:(CGContextRef)ctx;
1022 /* Locks focus on the Angband image, and scales the CTM appropriately. */
1023 - (CGContextRef)lockFocus;
1025 /* Locks focus on the Angband image but does NOT scale the CTM. Appropriate
1026 * for drawing hairlines. */
1027 - (CGContextRef)lockFocusUnscaled;
1029 /* Unlocks focus. */
1030 - (void)unlockFocus;
1032 /* Returns the primary window for this angband context, creating it if
1034 - (NSWindow *)makePrimaryWindow;
1036 /* Called to add a new Angband view */
1037 - (void)addAngbandView:(AngbandView *)view;
1039 /* Make the context aware that one of its views changed size */
1040 - (void)angbandViewDidScale:(AngbandView *)view;
1042 /* Handle becoming the main window */
1043 - (void)windowDidBecomeMain:(NSNotification *)notification;
1045 /* Return whether the context's primary window is ordered in or not */
1046 - (BOOL)isOrderedIn;
1048 /* Return whether the context's primary window is key */
1049 - (BOOL)isMainWindow;
1051 /* Invalidate the whole image */
1052 - (void)setNeedsDisplay:(BOOL)val;
1054 /* Invalidate part of the image, with the rect expressed in base coordinates */
1055 - (void)setNeedsDisplayInBaseRect:(NSRect)rect;
1057 /* Display (flush) our Angband views */
1058 - (void)displayIfNeeded;
1060 /* Resize context to size of contentRect, and optionally save size to
1062 - (void)resizeTerminalWithContentRect: (NSRect)contentRect saveToDefaults: (BOOL)saveToDefaults;
1065 * Change the minimum size for the window associated with the context.
1066 * termIdx is the index for the terminal: pass it so this function can be
1067 * used when self->terminal has not yet been set.
1069 - (void)setMinimumWindowSize:(int)termIdx;
1071 /* Called from the view to indicate that it is starting or ending live resize */
1072 - (void)viewWillStartLiveResize:(AngbandView *)view;
1073 - (void)viewDidEndLiveResize:(AngbandView *)view;
1074 - (void)saveWindowVisibleToDefaults: (BOOL)windowVisible;
1075 - (BOOL)windowVisibleUsingDefaults;
1079 * Gets the default font for all contexts. Currently not declaring this as
1080 * a class property for compatibility with versions of Xcode prior to 8.
1082 + (NSFont*)defaultFont;
1084 * Sets the default font for all contexts.
1086 + (void)setDefaultFont:(NSFont*)font;
1088 /* Internal method */
1089 - (AngbandView *)activeView;
1094 * Generate a mask for the subwindow flags. The mask is just a safety check to
1095 * make sure that our windows show and hide as expected. This function allows
1096 * for future changes to the set of flags without needed to update it here
1097 * (unless the underlying types change).
1099 u32b AngbandMaskForValidSubwindowFlags(void)
1101 int windowFlagBits = sizeof(*(window_flag)) * CHAR_BIT;
1102 int maxBits = MIN( 16, windowFlagBits );
1105 for( int i = 0; i < maxBits; i++ )
1107 if( window_flag_desc[i] != NULL )
1117 * Check for changes in the subwindow flags and update window visibility.
1118 * This seems to be called for every user event, so we don't
1119 * want to do any unnecessary hiding or showing of windows.
1121 static void AngbandUpdateWindowVisibility(void)
1123 /* Because this function is called frequently, we'll make the mask static.
1124 * It doesn't change between calls, as the flags themselves are hardcoded */
1125 static u32b validWindowFlagsMask = 0;
1127 if( validWindowFlagsMask == 0 )
1129 validWindowFlagsMask = AngbandMaskForValidSubwindowFlags();
1132 /* Loop through all of the subwindows and see if there is a change in the
1133 * flags. If so, show or hide the corresponding window. We don't care about
1134 * the flags themselves; we just want to know if any are set. */
1135 for( int i = 1; i < ANGBAND_TERM_MAX; i++ )
1137 AngbandContext *angbandContext =
1138 (__bridge AngbandContext*) (angband_term[i]->data);
1140 if( angbandContext == nil )
1145 /* This horrible mess of flags is so that we can try to maintain some
1146 * user visibility preference. This should allow the user a window and
1147 * have it stay closed between application launches. However, this
1148 * means that when a subwindow is turned on, it will no longer appear
1149 * automatically. Angband has no concept of user control over window
1150 * visibility, other than the subwindow flags. */
1151 if( !angbandContext.windowVisibilityChecked )
1153 if( [angbandContext windowVisibleUsingDefaults] )
1155 [angbandContext.primaryWindow orderFront: nil];
1156 angbandContext.windowVisibilityChecked = YES;
1160 [angbandContext.primaryWindow close];
1161 angbandContext.windowVisibilityChecked = NO;
1166 BOOL termHasSubwindowFlags = ((window_flag[i] & validWindowFlagsMask) > 0);
1168 if( angbandContext.hasSubwindowFlags && !termHasSubwindowFlags )
1170 [angbandContext.primaryWindow close];
1171 angbandContext.hasSubwindowFlags = NO;
1172 [angbandContext saveWindowVisibleToDefaults: NO];
1174 else if( !angbandContext.hasSubwindowFlags && termHasSubwindowFlags )
1176 [angbandContext.primaryWindow orderFront: nil];
1177 angbandContext.hasSubwindowFlags = YES;
1178 [angbandContext saveWindowVisibleToDefaults: YES];
1183 /* Make the main window key so that user events go to the right spot */
1184 AngbandContext *mainWindow =
1185 (__bridge AngbandContext*) (angband_term[0]->data);
1186 [mainWindow.primaryWindow makeKeyAndOrderFront: nil];
1191 * ------------------------------------------------------------------------
1193 * ------------------------------------------------------------------------ */
1198 static CGImageRef pict_image;
1201 * Numbers of rows and columns in a tileset,
1202 * calculated by the PICT/PNG loading code
1204 static int pict_cols = 0;
1205 static int pict_rows = 0;
1208 * Requested graphics mode (as a grafID).
1209 * The current mode is stored in current_graphics_mode.
1211 static int graf_mode_req = 0;
1214 * Helper function to check the various ways that graphics can be enabled,
1215 * guarding against NULL
1217 static BOOL graphics_are_enabled(void)
1219 return current_graphics_mode
1220 && current_graphics_mode->grafID != GRAPHICS_NONE;
1224 * Hack -- game in progress
1226 static Boolean game_in_progress = FALSE;
1229 #pragma mark Prototypes
1230 static void wakeup_event_loop(void);
1231 static void hook_plog(const char *str);
1232 static void hook_quit(const char * str);
1233 static NSString* get_lib_directory(void);
1234 static NSString* get_doc_directory(void);
1235 static NSString* AngbandCorrectedDirectoryPath(NSString *originalPath);
1236 static void prepare_paths_and_directories(void);
1237 static void handle_open_when_ready(void);
1238 static void play_sound(int event);
1239 static BOOL check_events(int wait);
1240 static BOOL send_event(NSEvent *event);
1241 static void record_current_savefile(void);
1243 static wchar_t convert_two_byte_eucjp_to_utf16_native(const char *cp);
1247 * Available values for 'wait'
1249 #define CHECK_EVENTS_DRAIN -1
1250 #define CHECK_EVENTS_NO_WAIT 0
1251 #define CHECK_EVENTS_WAIT 1
1255 * Note when "open"/"new" become valid
1257 static bool initialized = FALSE;
1259 /* Methods for getting the appropriate NSUserDefaults */
1260 @interface NSUserDefaults (AngbandDefaults)
1261 + (NSUserDefaults *)angbandDefaults;
1264 @implementation NSUserDefaults (AngbandDefaults)
1265 + (NSUserDefaults *)angbandDefaults
1267 return [NSUserDefaults standardUserDefaults];
1271 /* Methods for pulling images out of the Angband bundle (which may be separate
1272 * from the current bundle in the case of a screensaver */
1273 @interface NSImage (AngbandImages)
1274 + (NSImage *)angbandImage:(NSString *)name;
1277 /* The NSView subclass that draws our Angband image */
1278 @interface AngbandView : NSView
1280 AngbandContext *angbandContext;
1283 - (void)setAngbandContext:(AngbandContext *)context;
1284 - (AngbandContext *)angbandContext;
1288 @implementation NSImage (AngbandImages)
1290 /* Returns an image in the resource directoy of the bundle containing the
1291 * Angband view class. */
1292 + (NSImage *)angbandImage:(NSString *)name
1294 NSBundle *bundle = [NSBundle bundleForClass:[AngbandView class]];
1295 NSString *path = [bundle pathForImageResource:name];
1296 return (path) ? [[NSImage alloc] initByReferencingFile:path] : nil;
1302 @implementation AngbandContext
1304 @synthesize hasSubwindowFlags=_hasSubwindowFlags;
1305 @synthesize windowVisibilityChecked=_windowVisibilityChecked;
1307 - (BOOL)useLiveResizeOptimization
1309 /* If we have graphics turned off, text rendering is fast enough that we
1310 * don't need to use a live resize optimization. */
1311 return self->inLiveResize && graphics_are_enabled();
1316 /* We round the base size down. If we round it up, I believe we may end up
1317 * with pixels that nobody "owns" that may accumulate garbage. In general
1318 * rounding down is harmless, because any lost pixels may be sopped up by
1321 floor(self.cols * self.tileSize.width + 2 * self.borderSize.width),
1322 floor(self.rows * self.tileSize.height + 2 * self.borderSize.height));
1325 /* qsort-compatible compare function for CGSizes */
1326 static int compare_advances(const void *ap, const void *bp)
1328 const CGSize *a = ap, *b = bp;
1329 return (a->width > b->width) - (a->width < b->width);
1333 * Precompute certain metrics (tileSize, fontAscender, fontDescender, nColPre,
1334 * and nColPost) for the current font.
1336 - (void)updateGlyphInfo
1338 NSFont *screenFont = [self.angbandViewFont screenFont];
1340 /* Generate a string containing each MacRoman character */
1342 * Here and below, dynamically allocate working arrays rather than put them
1343 * on the stack in case limited stack space is an issue.
1345 unsigned char *latinString = malloc(GLYPH_COUNT);
1346 if (latinString == 0) {
1347 NSException *exc = [NSException exceptionWithName:@"OutOfMemory"
1348 reason:@"latinString in updateGlyphInfo"
1353 for (i=0; i < GLYPH_COUNT; i++) latinString[i] = (unsigned char)i;
1355 /* Turn that into unichar. Angband uses ISO Latin 1. */
1356 NSString *allCharsString = [[NSString alloc] initWithBytes:latinString length:sizeof latinString encoding:NSISOLatin1StringEncoding];
1357 unichar *unicharString = malloc(GLYPH_COUNT * sizeof(unichar));
1358 if (unicharString == 0) {
1360 NSException *exc = [NSException exceptionWithName:@"OutOfMemory"
1361 reason:@"unicharString in updateGlyphInfo"
1365 unicharString[0] = 0;
1366 [allCharsString getCharacters:unicharString range:NSMakeRange(0, MIN(GLYPH_COUNT, [allCharsString length]))];
1367 allCharsString = nil;
1371 CGGlyph *glyphArray = calloc(GLYPH_COUNT, sizeof(CGGlyph));
1372 if (glyphArray == 0) {
1373 free(unicharString);
1374 NSException *exc = [NSException exceptionWithName:@"OutOfMemory"
1375 reason:@"glyphArray in updateGlyphInfo"
1379 CTFontGetGlyphsForCharacters((CTFontRef)screenFont, unicharString,
1380 glyphArray, GLYPH_COUNT);
1381 free(unicharString);
1383 /* Get advances. Record the max advance. */
1384 CGSize *advances = malloc(GLYPH_COUNT * sizeof(CGSize));
1385 if (advances == 0) {
1387 NSException *exc = [NSException exceptionWithName:@"OutOfMemory"
1388 reason:@"advances in updateGlyphInfo"
1392 CTFontGetAdvancesForGlyphs(
1393 (CTFontRef)screenFont, kCTFontHorizontalOrientation, glyphArray,
1394 advances, GLYPH_COUNT);
1395 CGFloat *glyphWidths = malloc(GLYPH_COUNT * sizeof(CGFloat));
1396 if (glyphWidths == 0) {
1399 NSException *exc = [NSException exceptionWithName:@"OutOfMemory"
1400 reason:@"glyphWidths in updateGlyphInfo"
1404 for (i=0; i < GLYPH_COUNT; i++) {
1405 glyphWidths[i] = advances[i].width;
1408 /* For good non-mono-font support, use the median advance. Start by sorting
1410 qsort(advances, GLYPH_COUNT, sizeof *advances, compare_advances);
1412 /* Skip over any initially empty run */
1414 for (startIdx = 0; startIdx < GLYPH_COUNT; startIdx++)
1416 if (advances[startIdx].width > 0) break;
1419 /* Pick the center to find the median */
1420 CGFloat medianAdvance = 0;
1421 if (startIdx < GLYPH_COUNT)
1423 /* In case we have all zero advances for some reason */
1424 medianAdvance = advances[(startIdx + GLYPH_COUNT)/2].width;
1430 * Record the ascender and descender. Some fonts, for instance DIN
1431 * Condensed and Rockwell in 10.14, the ascent on '@' exceeds that
1432 * reported by [screenFont ascender]. Get the overall bounding box
1433 * for the glyphs and use that instead of the ascender and descender
1434 * values if the bounding box result extends farther from the baseline.
1436 CGRect bounds = CTFontGetBoundingRectsForGlyphs(
1437 (CTFontRef) screenFont, kCTFontHorizontalOrientation, glyphArray,
1439 self->_fontAscender = [screenFont ascender];
1440 if (self->_fontAscender < bounds.origin.y + bounds.size.height) {
1441 self->_fontAscender = bounds.origin.y + bounds.size.height;
1443 self->_fontDescender = [screenFont descender];
1444 if (self->_fontDescender > bounds.origin.y) {
1445 self->_fontDescender = bounds.origin.y;
1449 * Record the tile size. Round both values up to have tile boundaries
1450 * match pixel boundaries.
1452 self->_tileSize.width = ceil(medianAdvance);
1453 self->_tileSize.height = ceil(self.fontAscender - self.fontDescender);
1456 * Determine whether neighboring columns need to be redrawn when a
1457 * character changes.
1459 CGRect *boxes = malloc(GLYPH_COUNT * sizeof(CGRect));
1463 NSException *exc = [NSException exceptionWithName:@"OutOfMemory"
1464 reason:@"boxes in updateGlyphInfo"
1468 CGFloat beyond_right = 0.;
1469 CGFloat beyond_left = 0.;
1470 CTFontGetBoundingRectsForGlyphs(
1471 (CTFontRef)screenFont,
1472 kCTFontHorizontalOrientation,
1476 for (i = 0; i < GLYPH_COUNT; i++) {
1477 /* Account for the compression and offset used by drawWChar(). */
1478 CGFloat compression, offset;
1481 if (glyphWidths[i] <= self.tileSize.width) {
1483 offset = 0.5 * (self.tileSize.width - glyphWidths[i]);
1485 compression = self.tileSize.width / glyphWidths[i];
1488 v = (offset + boxes[i].origin.x) * compression;
1489 if (beyond_left > v) {
1492 v = (offset + boxes[i].origin.x + boxes[i].size.width) * compression;
1493 if (beyond_right < v) {
1498 self->_nColPre = ceil(-beyond_left / self.tileSize.width);
1499 if (beyond_right > self.tileSize.width) {
1501 ceil((beyond_right - self.tileSize.width) / self.tileSize.width);
1503 self->_nColPost = 0;
1512 NSSize size = NSMakeSize(1, 1);
1514 AngbandView *activeView = [self activeView];
1517 /* If we are in live resize, draw as big as the screen, so we can scale
1518 * nicely to any size. If we are not in live resize, then use the
1519 * bounds of the active view. */
1521 if ([self useLiveResizeOptimization] && (screen = [[activeView window] screen]) != NULL)
1523 size = [screen frame].size;
1527 size = [activeView bounds].size;
1531 CGLayerRelease(self.angbandLayer);
1533 /* Use the highest monitor scale factor on the system to work out what
1534 * scale to draw at - not the recommended method, but works where we
1535 * can't easily get the monitor the current draw is occurring on. */
1536 float angbandLayerScale = 1.0;
1537 if ([[NSScreen mainScreen] respondsToSelector:@selector(backingScaleFactor)]) {
1538 for (NSScreen *screen in [NSScreen screens]) {
1539 angbandLayerScale = fmax(angbandLayerScale, [screen backingScaleFactor]);
1543 /* Make a bitmap context as an example for our layer */
1544 CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();
1545 CGContextRef exampleCtx = CGBitmapContextCreate(NULL, 1, 1, 8 /* bits per component */, 48 /* bytesPerRow */, cs, kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Host);
1546 CGColorSpaceRelease(cs);
1548 /* Create the layer at the appropriate size */
1549 size.width = fmax(1, ceil(size.width * angbandLayerScale));
1550 size.height = fmax(1, ceil(size.height * angbandLayerScale));
1552 CGLayerCreateWithContext(exampleCtx, *(CGSize *)&size, NULL);
1554 CFRelease(exampleCtx);
1556 /* Set the new context of the layer to draw at the correct scale */
1557 CGContextRef ctx = CGLayerGetContext(self.angbandLayer);
1558 CGContextScaleCTM(ctx, angbandLayerScale, angbandLayerScale);
1561 [[NSColor blackColor] set];
1562 NSRectFill((NSRect){NSZeroPoint, [self baseSize]});
1566 - (void)requestRedraw
1568 if (! self->terminal) return;
1572 /* Activate the term */
1573 Term_activate(self->terminal);
1575 /* Redraw the contents */
1578 /* Flush the output */
1581 /* Restore the old term */
1585 - (void)setTerm:(term *)t
1590 - (void)viewWillStartLiveResize:(AngbandView *)view
1592 #if USE_LIVE_RESIZE_CACHE
1593 if (self->inLiveResize < INT_MAX) self->inLiveResize++;
1594 else [NSException raise:NSInternalInconsistencyException format:@"inLiveResize overflow"];
1596 if (self->inLiveResize == 1 && graphics_are_enabled())
1600 [self setNeedsDisplay:YES]; /* We'll need to redisplay everything anyways, so avoid creating all those little redisplay rects */
1601 [self requestRedraw];
1606 - (void)viewDidEndLiveResize:(AngbandView *)view
1608 #if USE_LIVE_RESIZE_CACHE
1609 if (self->inLiveResize > 0) self->inLiveResize--;
1610 else [NSException raise:NSInternalInconsistencyException format:@"inLiveResize underflow"];
1612 if (self->inLiveResize == 0 && graphics_are_enabled())
1616 [self setNeedsDisplay:YES]; /* We'll need to redisplay everything anyways, so avoid creating all those little redisplay rects */
1617 [self requestRedraw];
1623 * If we're trying to limit ourselves to a certain number of frames per second,
1624 * then compute how long it's been since we last drew, and then wait until the
1625 * next frame has passed. */
1628 if (frames_per_second > 0)
1630 CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
1631 CFTimeInterval timeSinceLastRefresh = now - self->lastRefreshTime;
1632 CFTimeInterval timeUntilNextRefresh = (1. / (double)frames_per_second) - timeSinceLastRefresh;
1634 if (timeUntilNextRefresh > 0)
1636 usleep((unsigned long)(timeUntilNextRefresh * 1000000.));
1639 self->lastRefreshTime = CFAbsoluteTimeGetCurrent();
1642 - (void)drawWChar:(wchar_t)wchar inRect:(NSRect)tile context:(CGContextRef)ctx
1644 CGFloat tileOffsetY = self.fontAscender;
1645 CGFloat tileOffsetX = 0.0;
1646 NSFont *screenFont = [self.angbandViewFont screenFont];
1647 UniChar unicharString[2] = {(UniChar)wchar, 0};
1649 /* Get glyph and advance */
1650 CGGlyph thisGlyphArray[1] = { 0 };
1651 CGSize advances[1] = { { 0, 0 } };
1652 CTFontGetGlyphsForCharacters((CTFontRef)screenFont, unicharString, thisGlyphArray, 1);
1653 CGGlyph glyph = thisGlyphArray[0];
1654 CTFontGetAdvancesForGlyphs((CTFontRef)screenFont, kCTFontHorizontalOrientation, thisGlyphArray, advances, 1);
1655 CGSize advance = advances[0];
1657 /* If our font is not monospaced, our tile width is deliberately not big
1658 * enough for every character. In that event, if our glyph is too wide, we
1659 * need to compress it horizontally. Compute the compression ratio.
1660 * 1.0 means no compression. */
1661 double compressionRatio;
1662 if (advance.width <= NSWidth(tile))
1664 /* Our glyph fits, so we can just draw it, possibly with an offset */
1665 compressionRatio = 1.0;
1666 tileOffsetX = (NSWidth(tile) - advance.width)/2;
1670 /* Our glyph doesn't fit, so we'll have to compress it */
1671 compressionRatio = NSWidth(tile) / advance.width;
1677 CGAffineTransform textMatrix = CGContextGetTextMatrix(ctx);
1678 CGFloat savedA = textMatrix.a;
1680 /* Set the position */
1681 textMatrix.tx = tile.origin.x + tileOffsetX;
1682 textMatrix.ty = tile.origin.y + tileOffsetY;
1684 /* Maybe squish it horizontally. */
1685 if (compressionRatio != 1.)
1687 textMatrix.a *= compressionRatio;
1690 textMatrix = CGAffineTransformScale( textMatrix, 1.0, -1.0 );
1691 CGContextSetTextMatrix(ctx, textMatrix);
1692 CGContextShowGlyphsAtPositions(ctx, &glyph, &CGPointZero, 1);
1694 /* Restore the text matrix if we messed with the compression ratio */
1695 if (compressionRatio != 1.)
1697 textMatrix.a = savedA;
1698 CGContextSetTextMatrix(ctx, textMatrix);
1701 textMatrix = CGAffineTransformScale( textMatrix, 1.0, -1.0 );
1702 CGContextSetTextMatrix(ctx, textMatrix);
1705 /* Lock and unlock focus on our image or layer, setting up the CTM
1707 - (CGContextRef)lockFocusUnscaled
1709 /* Create an NSGraphicsContext representing this CGLayer */
1710 CGContextRef ctx = CGLayerGetContext(self.angbandLayer);
1711 NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithGraphicsPort:ctx flipped:NO];
1712 [NSGraphicsContext saveGraphicsState];
1713 [NSGraphicsContext setCurrentContext:context];
1714 CGContextSaveGState(ctx);
1720 /* Restore the graphics state */
1721 CGContextRef ctx = [[NSGraphicsContext currentContext] graphicsPort];
1722 CGContextRestoreGState(ctx);
1723 [NSGraphicsContext restoreGraphicsState];
1728 /* Return the size of our layer */
1729 CGSize result = CGLayerGetSize(self.angbandLayer);
1730 return NSMakeSize(result.width, result.height);
1733 - (CGContextRef)lockFocus
1735 return [self lockFocusUnscaled];
1739 - (NSRect)rectInImageForTileAtX:(int)x Y:(int)y
1742 return NSMakeRect(x * self.tileSize.width + self.borderSize.width,
1743 flippedY * self.tileSize.height + self.borderSize.height,
1744 self.tileSize.width, self.tileSize.height);
1747 - (void)setSelectionFont:(NSFont*)font adjustTerminal: (BOOL)adjustTerminal
1749 /* Record the new font */
1750 self.angbandViewFont = font;
1752 /* Update our glyph info */
1753 [self updateGlyphInfo];
1755 if( adjustTerminal )
1757 /* Adjust terminal to fit window with new font; save the new columns
1758 * and rows since they could be changed */
1759 NSRect contentRect =
1761 contentRectForFrameRect: [self.primaryWindow frame]];
1763 [self setMinimumWindowSize:[self terminalIndex]];
1764 NSSize size = self.primaryWindow.contentMinSize;
1765 BOOL windowNeedsResizing = NO;
1766 if (contentRect.size.width < size.width) {
1767 contentRect.size.width = size.width;
1768 windowNeedsResizing = YES;
1770 if (contentRect.size.height < size.height) {
1771 contentRect.size.height = size.height;
1772 windowNeedsResizing = YES;
1774 if (windowNeedsResizing) {
1775 size.width = contentRect.size.width;
1776 size.height = contentRect.size.height;
1777 [self.primaryWindow setContentSize:size];
1779 [self resizeTerminalWithContentRect: contentRect saveToDefaults: YES];
1782 /* Update our image */
1788 if ((self = [super init]))
1790 /* Default rows and cols */
1794 /* Default border size */
1795 self->_borderSize = NSMakeSize(2, 2);
1797 /* Allocate our array of views */
1798 self->_angbandViews = [[NSMutableArray alloc] init];
1801 self->_nColPost = 0;
1804 [[PendingTermChanges alloc] initWithColumnsRows:self->_cols
1806 self->lastRefreshTime = CFAbsoluteTimeGetCurrent();
1807 self->inLiveResize = 0;
1808 self->inFullscreenTransition = NO;
1810 /* Make the image. Since we have no views, it'll just be a puny 1x1 image. */
1813 self->_windowVisibilityChecked = NO;
1819 * Destroy all the receiver's stuff. This is intended to be callable more than
1824 self->terminal = NULL;
1826 /* Disassociate ourselves from our angbandViews */
1827 [self.angbandViews makeObjectsPerformSelector:@selector(setAngbandContext:) withObject:nil];
1828 self.angbandViews = nil;
1830 /* Destroy the layer/image */
1831 CGLayerRelease(self.angbandLayer);
1832 self.angbandLayer = NULL;
1835 self.angbandViewFont = nil;
1838 [self.primaryWindow setDelegate:nil];
1839 [self.primaryWindow close];
1840 self.primaryWindow = nil;
1842 /* Pending changes */
1846 /* Usual Cocoa fare */
1853 /* From the Linux mbstowcs(3) man page:
1854 * If dest is NULL, n is ignored, and the conversion proceeds as above,
1855 * except that the converted wide characters are not written out to mem‐
1856 * ory, and that no length limit exists.
1858 static size_t Term_mbcs_cocoa(wchar_t *dest, const char *src, int n)
1863 /* Unicode code point to UTF-8
1864 * 0x0000-0x007f: 0xxxxxxx
1865 * 0x0080-0x07ff: 110xxxxx 10xxxxxx
1866 * 0x0800-0xffff: 1110xxxx 10xxxxxx 10xxxxxx
1867 * 0x10000-0x1fffff: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
1868 * Note that UTF-16 limits Unicode to 0x10ffff. This code is not
1871 for (i = 0; i < n || dest == NULL; i++) {
1872 if ((src[i] & 0x80) == 0) {
1873 if (dest != NULL) dest[count] = src[i];
1874 if (src[i] == 0) break;
1875 } else if ((src[i] & 0xe0) == 0xc0) {
1876 if (dest != NULL) dest[count] =
1877 (((unsigned char)src[i] & 0x1f) << 6)|
1878 ((unsigned char)src[i+1] & 0x3f);
1880 } else if ((src[i] & 0xf0) == 0xe0) {
1881 if (dest != NULL) dest[count] =
1882 (((unsigned char)src[i] & 0x0f) << 12) |
1883 (((unsigned char)src[i+1] & 0x3f) << 6) |
1884 ((unsigned char)src[i+2] & 0x3f);
1886 } else if ((src[i] & 0xf8) == 0xf0) {
1887 if (dest != NULL) dest[count] =
1888 (((unsigned char)src[i] & 0x0f) << 18) |
1889 (((unsigned char)src[i+1] & 0x3f) << 12) |
1890 (((unsigned char)src[i+2] & 0x3f) << 6) |
1891 ((unsigned char)src[i+3] & 0x3f);
1894 /* Found an invalid multibyte sequence */
1903 - (void)addAngbandView:(AngbandView *)view
1905 if (! [self.angbandViews containsObject:view])
1907 [self.angbandViews addObject:view];
1909 [self setNeedsDisplay:YES]; /* We'll need to redisplay everything anyways, so avoid creating all those little redisplay rects */
1910 [self requestRedraw];
1915 * For defaultFont and setDefaultFont.
1917 static __strong NSFont* gDefaultFont = nil;
1919 + (NSFont*)defaultFont
1921 return gDefaultFont;
1924 + (void)setDefaultFont:(NSFont*)font
1926 gDefaultFont = font;
1930 * We have this notion of an "active" AngbandView, which is the largest - the
1931 * idea being that in the screen saver, when the user hits Test in System
1932 * Preferences, we don't want to keep driving the AngbandView in the
1933 * background. Our active AngbandView is the widest - that's a hack all right.
1934 * Mercifully when we're just playing the game there's only one view.
1936 - (AngbandView *)activeView
1938 if ([self.angbandViews count] == 1)
1939 return [self.angbandViews objectAtIndex:0];
1941 AngbandView *result = nil;
1943 for (AngbandView *angbandView in self.angbandViews)
1945 float width = [angbandView frame].size.width;
1946 if (width > maxWidth)
1949 result = angbandView;
1955 - (void)angbandViewDidScale:(AngbandView *)view
1957 /* If we're live-resizing with graphics, we're using the live resize
1958 * optimization, so don't update the image. Otherwise do it. */
1959 if (! (self->inLiveResize && graphics_are_enabled()) && view == [self activeView])
1963 [self setNeedsDisplay:YES]; /*we'll need to redisplay everything anyways, so avoid creating all those little redisplay rects */
1964 [self requestRedraw];
1969 - (void)removeAngbandView:(AngbandView *)view
1971 if ([self.angbandViews containsObject:view])
1973 [self.angbandViews removeObject:view];
1975 [self setNeedsDisplay:YES]; /* We'll need to redisplay everything anyways, so avoid creating all those little redisplay rects */
1976 if ([self.angbandViews count]) [self requestRedraw];
1981 - (NSWindow *)makePrimaryWindow
1983 if (! self.primaryWindow)
1985 /* This has to be done after the font is set, which it already is in
1986 * term_init_cocoa() */
1987 NSSize sz = self.baseSize;
1988 NSRect contentRect = NSMakeRect( 0.0, 0.0, sz.width, sz.height );
1990 NSUInteger styleMask = NSTitledWindowMask | NSResizableWindowMask | NSMiniaturizableWindowMask;
1992 /* Make every window other than the main window closable */
1993 if ((__bridge AngbandContext*) (angband_term[0]->data) != self)
1995 styleMask |= NSClosableWindowMask;
1998 self.primaryWindow = [[NSWindow alloc] initWithContentRect:contentRect styleMask: styleMask backing:NSBackingStoreBuffered defer:YES];
2000 /* Not to be released when closed */
2001 [self.primaryWindow setReleasedWhenClosed:NO];
2002 [self.primaryWindow setExcludedFromWindowsMenu: YES]; /* we're using custom window menu handling */
2005 AngbandView *angbandView = [[AngbandView alloc] initWithFrame:contentRect];
2006 [angbandView setAngbandContext:self];
2007 [self.angbandViews addObject:angbandView];
2008 [self.primaryWindow setContentView:angbandView];
2010 /* We are its delegate */
2011 [self.primaryWindow setDelegate:self];
2013 /* Update our image, since this is probably the first angband view
2017 return self.primaryWindow;
2022 #pragma mark View/Window Passthrough
2025 * This is what our views call to get us to draw to the window
2027 - (void)drawRect:(NSRect)rect inView:(NSView *)view
2029 /* Take this opportunity to throttle so we don't flush faster than desired.
2031 BOOL viewInLiveResize = [view inLiveResize];
2032 if (! viewInLiveResize) [self throttle];
2034 /* With a GLayer, use CGContextDrawLayerInRect */
2035 CGContextRef context = [[NSGraphicsContext currentContext] graphicsPort];
2036 NSRect bounds = [view bounds];
2037 if (viewInLiveResize) CGContextSetInterpolationQuality(context, kCGInterpolationLow);
2038 CGContextSetBlendMode(context, kCGBlendModeCopy);
2039 CGContextDrawLayerInRect(context, *(CGRect *)&bounds, self.angbandLayer);
2040 if (viewInLiveResize) CGContextSetInterpolationQuality(context, kCGInterpolationDefault);
2045 return [[[self.angbandViews lastObject] window] isVisible];
2048 - (BOOL)isMainWindow
2050 return [[[self.angbandViews lastObject] window] isMainWindow];
2053 - (void)setNeedsDisplay:(BOOL)val
2055 for (NSView *angbandView in self.angbandViews)
2057 [angbandView setNeedsDisplay:val];
2061 - (void)setNeedsDisplayInBaseRect:(NSRect)rect
2063 for (NSView *angbandView in self.angbandViews)
2065 [angbandView setNeedsDisplayInRect: rect];
2069 - (void)displayIfNeeded
2071 [[self activeView] displayIfNeeded];
2074 - (int)terminalIndex
2078 for( termIndex = 0; termIndex < ANGBAND_TERM_MAX; termIndex++ )
2080 if( angband_term[termIndex] == self->terminal )
2089 - (void)resizeTerminalWithContentRect: (NSRect)contentRect saveToDefaults: (BOOL)saveToDefaults
2091 CGFloat newRows = floor(
2092 (contentRect.size.height - (self.borderSize.height * 2.0)) /
2093 self.tileSize.height);
2094 CGFloat newColumns = ceil(
2095 (contentRect.size.width - (self.borderSize.width * 2.0)) /
2096 self.tileSize.width);
2098 if (newRows < 1 || newColumns < 1) return;
2099 self->_cols = newColumns;
2100 self->_rows = newRows;
2101 [self.changes resize:self.cols rows:self.rows];
2103 if( saveToDefaults )
2105 int termIndex = [self terminalIndex];
2106 NSArray *terminals = [[NSUserDefaults standardUserDefaults] valueForKey: AngbandTerminalsDefaultsKey];
2108 if( termIndex < (int)[terminals count] )
2110 NSMutableDictionary *mutableTerm = [[NSMutableDictionary alloc] initWithDictionary: [terminals objectAtIndex: termIndex]];
2111 [mutableTerm setValue: [NSNumber numberWithInteger: self.cols]
2112 forKey: AngbandTerminalColumnsDefaultsKey];
2113 [mutableTerm setValue: [NSNumber numberWithInteger: self.rows]
2114 forKey: AngbandTerminalRowsDefaultsKey];
2116 NSMutableArray *mutableTerminals = [[NSMutableArray alloc] initWithArray: terminals];
2117 [mutableTerminals replaceObjectAtIndex: termIndex withObject: mutableTerm];
2119 [[NSUserDefaults standardUserDefaults] setValue: mutableTerminals forKey: AngbandTerminalsDefaultsKey];
2124 Term_activate( self->terminal );
2125 Term_resize( self.cols, self.rows );
2127 Term_activate( old );
2130 - (void)setMinimumWindowSize:(int)termIdx
2136 minsize.height = 24;
2142 minsize.width * self.tileSize.width + self.borderSize.width * 2.0;
2144 minsize.height * self.tileSize.height + self.borderSize.height * 2.0;
2145 [[self makePrimaryWindow] setContentMinSize:minsize];
2148 - (void)saveWindowVisibleToDefaults: (BOOL)windowVisible
2150 int termIndex = [self terminalIndex];
2151 BOOL safeVisibility = (termIndex == 0) ? YES : windowVisible; /* Ensure main term doesn't go away because of these defaults */
2152 NSArray *terminals = [[NSUserDefaults standardUserDefaults] valueForKey: AngbandTerminalsDefaultsKey];
2154 if( termIndex < (int)[terminals count] )
2156 NSMutableDictionary *mutableTerm = [[NSMutableDictionary alloc] initWithDictionary: [terminals objectAtIndex: termIndex]];
2157 [mutableTerm setValue: [NSNumber numberWithBool: safeVisibility] forKey: AngbandTerminalVisibleDefaultsKey];
2159 NSMutableArray *mutableTerminals = [[NSMutableArray alloc] initWithArray: terminals];
2160 [mutableTerminals replaceObjectAtIndex: termIndex withObject: mutableTerm];
2162 [[NSUserDefaults standardUserDefaults] setValue: mutableTerminals forKey: AngbandTerminalsDefaultsKey];
2166 - (BOOL)windowVisibleUsingDefaults
2168 int termIndex = [self terminalIndex];
2170 if( termIndex == 0 )
2175 NSArray *terminals = [[NSUserDefaults standardUserDefaults] valueForKey: AngbandTerminalsDefaultsKey];
2178 if( termIndex < (int)[terminals count] )
2180 NSDictionary *term = [terminals objectAtIndex: termIndex];
2181 NSNumber *visibleValue = [term valueForKey: AngbandTerminalVisibleDefaultsKey];
2183 if( visibleValue != nil )
2185 visible = [visibleValue boolValue];
2193 #pragma mark NSWindowDelegate Methods
2195 /*- (void)windowWillStartLiveResize: (NSNotification *)notification
2199 - (void)windowDidEndLiveResize: (NSNotification *)notification
2201 NSWindow *window = [notification object];
2202 NSRect contentRect = [window contentRectForFrameRect: [window frame]];
2203 [self resizeTerminalWithContentRect: contentRect saveToDefaults: !(self->inFullscreenTransition)];
2206 /*- (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
2210 - (void)windowWillEnterFullScreen: (NSNotification *)notification
2212 self->inFullscreenTransition = YES;
2215 - (void)windowDidEnterFullScreen: (NSNotification *)notification
2217 NSWindow *window = [notification object];
2218 NSRect contentRect = [window contentRectForFrameRect: [window frame]];
2219 self->inFullscreenTransition = NO;
2220 [self resizeTerminalWithContentRect: contentRect saveToDefaults: NO];
2223 - (void)windowWillExitFullScreen: (NSNotification *)notification
2225 self->inFullscreenTransition = YES;
2228 - (void)windowDidExitFullScreen: (NSNotification *)notification
2230 NSWindow *window = [notification object];
2231 NSRect contentRect = [window contentRectForFrameRect: [window frame]];
2232 self->inFullscreenTransition = NO;
2233 [self resizeTerminalWithContentRect: contentRect saveToDefaults: NO];
2236 - (void)windowDidBecomeMain:(NSNotification *)notification
2238 NSWindow *window = [notification object];
2240 if( window != self.primaryWindow )
2245 int termIndex = [self terminalIndex];
2246 NSMenuItem *item = [[[NSApplication sharedApplication] windowsMenu] itemWithTag: AngbandWindowMenuItemTagBase + termIndex];
2247 [item setState: NSOnState];
2249 if( [[NSFontPanel sharedFontPanel] isVisible] )
2251 [[NSFontPanel sharedFontPanel] setPanelFont:self.angbandViewFont
2256 - (void)windowDidResignMain: (NSNotification *)notification
2258 NSWindow *window = [notification object];
2260 if( window != self.primaryWindow )
2265 int termIndex = [self terminalIndex];
2266 NSMenuItem *item = [[[NSApplication sharedApplication] windowsMenu] itemWithTag: AngbandWindowMenuItemTagBase + termIndex];
2267 [item setState: NSOffState];
2270 - (void)windowWillClose: (NSNotification *)notification
2272 [self saveWindowVisibleToDefaults: NO];
2278 @implementation AngbandView
2290 - (void)drawRect:(NSRect)rect
2292 if (! angbandContext)
2294 /* Draw bright orange, 'cause this ain't right */
2295 [[NSColor orangeColor] set];
2296 NSRectFill([self bounds]);
2300 /* Tell the Angband context to draw into us */
2301 [angbandContext drawRect:rect inView:self];
2305 - (void)setAngbandContext:(AngbandContext *)context
2307 angbandContext = context;
2310 - (AngbandContext *)angbandContext
2312 return angbandContext;
2315 - (void)setFrameSize:(NSSize)size
2317 BOOL changed = ! NSEqualSizes(size, [self frame].size);
2318 [super setFrameSize:size];
2319 if (changed) [angbandContext angbandViewDidScale:self];
2322 - (void)viewWillStartLiveResize
2324 [angbandContext viewWillStartLiveResize:self];
2327 - (void)viewDidEndLiveResize
2329 [angbandContext viewDidEndLiveResize:self];
2335 * Delay handling of double-clicked savefiles
2337 Boolean open_when_ready = FALSE;
2342 * ------------------------------------------------------------------------
2343 * Some generic functions
2344 * ------------------------------------------------------------------------ */
2347 * Sets an Angband color at a given index
2349 static void set_color_for_index(int idx)
2353 /* Extract the R,G,B data */
2354 rv = angband_color_table[idx][1];
2355 gv = angband_color_table[idx][2];
2356 bv = angband_color_table[idx][3];
2358 CGContextSetRGBFillColor([[NSGraphicsContext currentContext] graphicsPort], rv/255., gv/255., bv/255., 1.);
2362 * Remember the current character in UserDefaults so we can select it by
2363 * default next time.
2365 static void record_current_savefile(void)
2367 NSString *savefileString = [[NSString stringWithCString:savefile encoding:NSMacOSRomanStringEncoding] lastPathComponent];
2370 NSUserDefaults *angbandDefs = [NSUserDefaults angbandDefaults];
2371 [angbandDefs setObject:savefileString forKey:@"SaveFile"];
2378 * Convert a two-byte EUC-JP encoded character (both *cp and (*cp + 1) are in
2379 * the range, 0xA1-0xFE, or *cp is 0x8E) to a utf16 value in the native byte
2382 static wchar_t convert_two_byte_eucjp_to_utf16_native(const char *cp)
2384 NSString* str = [[NSString alloc] initWithBytes:cp length:2
2385 encoding:NSJapaneseEUCStringEncoding];
2386 wchar_t result = [str characterAtIndex:0];
2394 * ------------------------------------------------------------------------
2395 * Support for the "z-term.c" package
2396 * ------------------------------------------------------------------------ */
2400 * Initialize a new Term
2402 static void Term_init_cocoa(term *t)
2405 AngbandContext *context = [[AngbandContext alloc] init];
2407 /* Give the term ownership of the context */
2408 t->data = (void *)CFBridgingRetain(context);
2410 /* Handle graphics */
2411 t->higher_pict = !! use_graphics;
2412 t->always_pict = FALSE;
2414 NSDisableScreenUpdates();
2417 * Figure out the frame autosave name based on the index of this term
2419 NSString *autosaveName = nil;
2421 for (termIdx = 0; termIdx < ANGBAND_TERM_MAX; termIdx++)
2423 if (angband_term[termIdx] == t)
2426 [NSString stringWithFormat:@"AngbandTerm-%d", termIdx];
2432 NSString *fontName =
2433 [[NSUserDefaults angbandDefaults]
2434 stringForKey:[NSString stringWithFormat:@"FontName-%d", termIdx]];
2435 if (! fontName) fontName = [[AngbandContext defaultFont] fontName];
2438 * Use a smaller default font for the other windows, but only if the
2439 * font hasn't been explicitly set.
2442 (termIdx > 0) ? 10.0 : [[AngbandContext defaultFont] pointSize];
2443 NSNumber *fontSizeNumber =
2444 [[NSUserDefaults angbandDefaults]
2445 valueForKey: [NSString stringWithFormat: @"FontSize-%d", termIdx]];
2447 if( fontSizeNumber != nil )
2449 fontSize = [fontSizeNumber floatValue];
2452 [context setSelectionFont:[NSFont fontWithName:fontName size:fontSize]
2453 adjustTerminal: NO];
2455 NSArray *terminalDefaults =
2456 [[NSUserDefaults standardUserDefaults]
2457 valueForKey: AngbandTerminalsDefaultsKey];
2458 NSInteger rows = 24;
2459 NSInteger columns = 80;
2461 if( termIdx < (int)[terminalDefaults count] )
2463 NSDictionary *term = [terminalDefaults objectAtIndex: termIdx];
2464 NSInteger defaultRows =
2465 [[term valueForKey: AngbandTerminalRowsDefaultsKey]
2467 NSInteger defaultColumns =
2468 [[term valueForKey: AngbandTerminalColumnsDefaultsKey]
2471 if (defaultRows > 0) rows = defaultRows;
2472 if (defaultColumns > 0) columns = defaultColumns;
2475 context.cols = columns;
2476 context.rows = rows;
2477 [context.changes resize:columns rows:rows];
2479 /* Get the window */
2480 NSWindow *window = [context makePrimaryWindow];
2482 /* Set its title and, for auxiliary terms, tentative size */
2484 [NSString stringWithCString:angband_term_name[termIdx]
2486 encoding:NSJapaneseEUCStringEncoding
2488 encoding:NSMacOSRomanStringEncoding
2491 [window setTitle:title];
2492 [context setMinimumWindowSize:termIdx];
2495 * If this is the first term, and we support full screen (Mac OS X Lion
2496 * or later), then allow it to go full screen (sweet). Allow other
2497 * terms to be FullScreenAuxilliary, so they can at least show up.
2498 * Unfortunately in Lion they don't get brought to the full screen
2499 * space; but they would only make sense on multiple displays anyways
2500 * so it's not a big loss.
2502 if ([window respondsToSelector:@selector(toggleFullScreen:)])
2504 NSWindowCollectionBehavior behavior = [window collectionBehavior];
2507 NSWindowCollectionBehaviorFullScreenPrimary :
2508 NSWindowCollectionBehaviorFullScreenAuxiliary);
2509 [window setCollectionBehavior:behavior];
2512 /* No Resume support yet, though it would not be hard to add */
2513 if ([window respondsToSelector:@selector(setRestorable:)])
2515 [window setRestorable:NO];
2518 /* default window placement */ {
2519 static NSRect overallBoundingRect;
2524 * This is a bit of a trick to allow us to display multiple
2525 * windows in the "standard default" window position in OS X:
2526 * the upper center of the screen. The term sizes set in
2527 * AngbandAppDelegate's loadPrefs() are based on a 5-wide by
2528 * 3-high grid, with the main term being 4/5 wide by 2/3 high
2529 * (hence the scaling to find what the containing rect would
2532 NSRect originalMainTermFrame = [window frame];
2533 NSRect scaledFrame = originalMainTermFrame;
2534 scaledFrame.size.width *= 5.0 / 4.0;
2535 scaledFrame.size.height *= 3.0 / 2.0;
2536 scaledFrame.size.width += 1.0; /* spacing between window columns */
2537 scaledFrame.size.height += 1.0; /* spacing between window rows */
2538 [window setFrame: scaledFrame display: NO];
2540 overallBoundingRect = [window frame];
2541 [window setFrame: originalMainTermFrame display: NO];
2544 static NSRect mainTermBaseRect;
2545 NSRect windowFrame = [window frame];
2550 * The height and width adjustments were determined
2551 * experimentally, so that the rest of the windows line up
2552 * nicely without overlapping.
2554 windowFrame.size.width += 7.0;
2555 windowFrame.size.height += 9.0;
2556 windowFrame.origin.x = NSMinX( overallBoundingRect );
2557 windowFrame.origin.y =
2558 NSMaxY( overallBoundingRect ) - NSHeight( windowFrame );
2559 mainTermBaseRect = windowFrame;
2561 else if( termIdx == 1 )
2563 windowFrame.origin.x = NSMinX( mainTermBaseRect );
2564 windowFrame.origin.y =
2565 NSMinY( mainTermBaseRect ) - NSHeight( windowFrame ) - 1.0;
2567 else if( termIdx == 2 )
2569 windowFrame.origin.x = NSMaxX( mainTermBaseRect ) + 1.0;
2570 windowFrame.origin.y =
2571 NSMaxY( mainTermBaseRect ) - NSHeight( windowFrame );
2573 else if( termIdx == 3 )
2575 windowFrame.origin.x = NSMaxX( mainTermBaseRect ) + 1.0;
2576 windowFrame.origin.y =
2577 NSMinY( mainTermBaseRect ) - NSHeight( windowFrame ) - 1.0;
2579 else if( termIdx == 4 )
2581 windowFrame.origin.x = NSMaxX( mainTermBaseRect ) + 1.0;
2582 windowFrame.origin.y = NSMinY( mainTermBaseRect );
2584 else if( termIdx == 5 )
2586 windowFrame.origin.x =
2587 NSMinX( mainTermBaseRect ) + NSWidth( windowFrame ) + 1.0;
2588 windowFrame.origin.y =
2589 NSMinY( mainTermBaseRect ) - NSHeight( windowFrame ) - 1.0;
2592 [window setFrame: windowFrame display: NO];
2595 /* Override the default frame above if the user has adjusted windows in
2597 if (autosaveName) [window setFrameAutosaveName:autosaveName];
2600 * Tell it about its term. Do this after we've sized it so that the
2601 * sizing doesn't trigger redrawing and such.
2603 [context setTerm:t];
2606 * Only order front if it's the first term. Other terms will be ordered
2607 * front from AngbandUpdateWindowVisibility(). This is to work around a
2608 * problem where Angband aggressively tells us to initialize terms that
2609 * don't do anything!
2611 if (t == angband_term[0])
2612 [context.primaryWindow makeKeyAndOrderFront: nil];
2614 NSEnableScreenUpdates();
2616 /* Set "mapped" flag */
2617 t->mapped_flag = true;
2626 static void Term_nuke_cocoa(term *t)
2629 AngbandContext *context = (__bridge AngbandContext*) (t->data);
2632 /* Tell the context to get rid of its windows, etc. */
2635 /* Balance our CFBridgingRetain from when we created it */
2645 * Returns the CGImageRef corresponding to an image with the given name in the
2646 * resource directory, transferring ownership to the caller
2648 static CGImageRef create_angband_image(NSString *path)
2650 CGImageRef decodedImage = NULL, result = NULL;
2652 /* Try using ImageIO to load the image */
2655 NSURL *url = [[NSURL alloc] initFileURLWithPath:path isDirectory:NO];
2658 NSDictionary *options = [[NSDictionary alloc] initWithObjectsAndKeys:(id)kCFBooleanTrue, kCGImageSourceShouldCache, nil];
2659 CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)url, (CFDictionaryRef)options);
2662 /* We really want the largest image, but in practice there's
2663 * only going to be one */
2664 decodedImage = CGImageSourceCreateImageAtIndex(source, 0, (CFDictionaryRef)options);
2670 /* Draw the sucker to defeat ImageIO's weird desire to cache and decode on
2671 * demand. Our images aren't that big! */
2674 size_t width = CGImageGetWidth(decodedImage), height = CGImageGetHeight(decodedImage);
2676 /* Compute our own bitmap info */
2677 CGBitmapInfo imageBitmapInfo = CGImageGetBitmapInfo(decodedImage);
2678 CGBitmapInfo contextBitmapInfo = kCGBitmapByteOrderDefault;
2680 switch (imageBitmapInfo & kCGBitmapAlphaInfoMask) {
2681 case kCGImageAlphaNone:
2682 case kCGImageAlphaNoneSkipLast:
2683 case kCGImageAlphaNoneSkipFirst:
2685 contextBitmapInfo |= kCGImageAlphaNone;
2688 /* Some alpha, use premultiplied last which is most efficient. */
2689 contextBitmapInfo |= kCGImageAlphaPremultipliedLast;
2693 /* Draw the source image flipped, since the view is flipped */
2694 CGContextRef ctx = CGBitmapContextCreate(NULL, width, height, CGImageGetBitsPerComponent(decodedImage), CGImageGetBytesPerRow(decodedImage), CGImageGetColorSpace(decodedImage), contextBitmapInfo);
2696 CGContextSetBlendMode(ctx, kCGBlendModeCopy);
2697 CGContextTranslateCTM(ctx, 0.0, height);
2698 CGContextScaleCTM(ctx, 1.0, -1.0);
2700 ctx, CGRectMake(0, 0, width, height), decodedImage);
2701 result = CGBitmapContextCreateImage(ctx);
2705 CGImageRelease(decodedImage);
2713 static errr Term_xtra_cocoa_react(void)
2715 /* Don't actually switch graphics until the game is running */
2716 if (!initialized || !game_in_progress) return (-1);
2719 AngbandContext *angbandContext =
2720 (__bridge AngbandContext*) (Term->data);
2722 /* Handle graphics */
2723 int expected_graf_mode = (current_graphics_mode) ?
2724 current_graphics_mode->grafID : GRAPHICS_NONE;
2725 if (graf_mode_req != expected_graf_mode)
2727 graphics_mode *new_mode;
2728 if (graf_mode_req != GRAPHICS_NONE) {
2729 new_mode = get_graphics_mode(graf_mode_req);
2734 /* Get rid of the old image. CGImageRelease is NULL-safe. */
2735 CGImageRelease(pict_image);
2738 /* Try creating the image if we want one */
2739 if (new_mode != NULL)
2741 NSString *img_path =
2742 [NSString stringWithFormat:@"%s/%s", new_mode->path, new_mode->file];
2743 pict_image = create_angband_image(img_path);
2745 /* If we failed to create the image, revert to ASCII. */
2749 arg_bigtile = FALSE;
2751 [[NSUserDefaults angbandDefaults]
2752 setInteger:GRAPHICS_NONE
2753 forKey:AngbandGraphicsDefaultsKey];
2755 NSString *msg = NSLocalizedStringWithDefaultValue(
2756 @"Error.TileSetLoadFailed",
2757 AngbandMessageCatalog,
2758 [NSBundle mainBundle],
2759 @"Failed to Load Tile Set",
2760 @"Alert text for failed tile set load");
2761 NSString *info = NSLocalizedStringWithDefaultValue(
2762 @"Error.TileSetRevertToASCII",
2763 AngbandMessageCatalog,
2764 [NSBundle mainBundle],
2765 @"Could not load the tile set. Switched back to ASCII.",
2766 @"Alert informative message for failed tile set load");
2767 NSAlert *alert = [[NSAlert alloc] init];
2769 alert.messageText = msg;
2770 alert.informativeText = info;
2775 /* Record what we did */
2776 use_graphics = new_mode ? new_mode->grafID : 0;
2777 ANGBAND_GRAF = (new_mode ? new_mode->graf : "ascii");
2778 current_graphics_mode = new_mode;
2781 * Enable or disable higher picts. Note: this should be done for
2784 angbandContext->terminal->higher_pict = !! use_graphics;
2786 if (pict_image && current_graphics_mode)
2789 * Compute the row and column count via the image height and
2792 pict_rows = (int)(CGImageGetHeight(pict_image) /
2793 current_graphics_mode->cell_height);
2794 pict_cols = (int)(CGImageGetWidth(pict_image) /
2795 current_graphics_mode->cell_width);
2804 if (arg_bigtile == use_bigtile)
2810 if (arg_bigtile != use_bigtile) {
2814 Term_activate(angband_term[0]);
2815 Term_resize(angband_term[0]->wid, angband_term[0]->hgt);
2825 * Draws one tile as a helper function for Term_xtra_cocoa_fresh().
2827 static void draw_image_tile(
2828 NSGraphicsContext* nsContext,
2829 CGContextRef cgContext,
2833 NSCompositingOperation op)
2835 /* Flip the source rect since the source image is flipped */
2836 CGAffineTransform flip = CGAffineTransformIdentity;
2837 flip = CGAffineTransformTranslate(flip, 0.0, CGImageGetHeight(image));
2838 flip = CGAffineTransformScale(flip, 1.0, -1.0);
2839 CGRect flippedSourceRect =
2840 CGRectApplyAffineTransform(NSRectToCGRect(srcRect), flip);
2843 * When we use high-quality resampling to draw a tile, pixels from outside
2844 * the tile may bleed in, causing graphics artifacts. Work around that.
2846 CGImageRef subimage =
2847 CGImageCreateWithImageInRect(image, flippedSourceRect);
2848 [nsContext setCompositingOperation:op];
2849 CGContextDrawImage(cgContext, NSRectToCGRect(dstRect), subimage);
2850 CGImageRelease(subimage);
2855 * This is a helper function for Term_xtra_cocoa_fresh(): look before a block
2856 * of text on a row to see if the bounds for rendering and clipping need to be
2859 static void query_before_text(
2860 PendingTermChanges *tc, int iy, int npre, int* pclip, int* prend)
2866 if (i < 0 || i < start - npre) {
2869 enum PendingCellChangeType ctype = [tc getCellChangeType:i row:iy];
2871 if (ctype == CELL_CHANGE_TILE) {
2873 * The cell has been rendered with a tile. Do not want to modify
2874 * its contents so the clipping and rendering region can not be
2878 } else if (ctype == CELL_CHANGE_NONE) {
2880 * It has not changed (or using big tile mode and it is within
2881 * a changed tile but is not the left cell for that tile) so
2882 * inquire what it is.
2887 Term_what(i, iy, a + 1, c + 1);
2888 if (use_graphics && (a[1] & 0x80) && (c[1] & 0x80)) {
2890 * It is an unchanged location rendered with a tile. Do not
2891 * want to modify its contents so the clipping and rendering
2892 * region can not be extended.
2896 if (use_bigtile && i > 0) {
2897 Term_what(i - 1, iy, a, c);
2898 if (use_graphics && (a[0] & 0x80) && (c[0] & 0x80)) {
2900 * It is the right cell of a location rendered with a tile.
2901 * Do not want to modify its contents so the clipping and
2902 * rendering region can not be exteded.
2908 * It is unchanged text. A character from the changed region
2909 * may have extended into it so render it to clear that.
2912 /* Check to see if it is the second part of a kanji character. */
2914 Term_what(i - 1, iy, a, c);
2916 [tc markTextChange:i-1 row:iy
2917 glyph:convert_two_byte_eucjp_to_utf16_native(c)
2918 color:a[0] isDoubleWidth:YES];
2923 [tc markTextChange:i row:iy
2924 glyph:c[1] color:a[1] isDoubleWidth:NO];
2929 [tc markTextChange:i row:iy
2930 glyph:c[1] color:a[1] isDoubleWidth:NO];
2935 [tc markTextChange:i row:iy
2936 glyph:c[1] color:a[1] isDoubleWidth:NO];
2943 * The cell has been wiped or had changed text rendered. Do
2944 * not need to render. Can extend the clipping rectangle into it.
2954 * This is a helper function for Term_xtra_cocoa_fresh(): look after a block
2955 * of text on a row to see if the bounds for rendering and clipping need to be
2958 static void query_after_text(
2959 PendingTermChanges *tc, int iy, int npost, int* pclip, int* prend)
2963 int ncol = tc.columnCount;
2970 enum PendingCellChangeType ctype = [tc getCellChangeType:i row:iy];
2973 * Be willing to consolidate this block with the one after it. This
2974 * logic should be sufficient to avoid redraws of the region between
2975 * changed blocks of text if angbandContext.nColPre is zero or one.
2976 * For larger values of nColPre, would need to do something more to
2977 * avoid extra redraws.
2979 if (i > end + npost && ctype != CELL_CHANGE_TEXT &&
2980 ctype != CELL_CHANGE_WIPE) {
2984 if (ctype == CELL_CHANGE_TILE) {
2986 * The cell has been rendered with a tile. Do not want to modify
2987 * its contents so the clipping and rendering region can not be
2991 } else if (ctype == CELL_CHANGE_NONE) {
2992 /* It has not changed so inquire what it is. */
2996 Term_what(i, iy, a, c);
2997 if (use_graphics && (a[0] & 0x80) && (c[0] & 0x80)) {
2999 * It is an unchanged location rendered with a tile. Do not
3000 * want to modify its contents so the clipping and rendering
3001 * region can not be extended.
3006 * It is unchanged text. A character from the changed region
3007 * may have extended into it so render it to clear that.
3010 /* Check to see if it is the first part of a kanji character. */
3012 Term_what(i + 1, iy, a + 1, c + 1);
3014 [tc markTextChange:i row:iy
3015 glyph:convert_two_byte_eucjp_to_utf16_native(c)
3016 color:a[0] isDoubleWidth:YES];
3021 [tc markTextChange:i row:iy
3022 glyph:c[0] color:a[0] isDoubleWidth:NO];
3027 [tc markTextChange:i row:iy
3028 glyph:c[0] color:a[0] isDoubleWidth:NO];
3033 [tc markTextChange:i row:iy
3034 glyph:c[0] color:a[0] isDoubleWidth:NO];
3041 * Have come to another region of changed text or another region
3042 * to wipe. Combine the regions to minimize redraws.
3054 * Draw the pending changes saved in angbandContext->changes.
3056 static void Term_xtra_cocoa_fresh(AngbandContext* angbandContext)
3058 int graf_width, graf_height, alphablend;
3060 if (angbandContext.changes.hasTileChanges) {
3061 CGImageAlphaInfo ainfo = CGImageGetAlphaInfo(pict_image);
3063 graf_width = current_graphics_mode->cell_width;
3064 graf_height = current_graphics_mode->cell_height;
3066 * As of this writing, a value of zero for
3067 * current_graphics_mode->alphablend can mean either that the tile set
3068 * doesn't have an alpha channel or it does but it only takes on values
3069 * of 0 or 255. For main-cocoa.m's purposes, the latter is rendered
3070 * using the same procedure as if alphablend was nonzero. The former
3071 * is handled differently, but alphablend doesn't distinguish it from
3072 * the latter. So ignore alphablend and directly test whether an
3073 * alpha channel is present.
3075 alphablend = (ainfo & (kCGImageAlphaPremultipliedFirst |
3076 kCGImageAlphaPremultipliedLast)) ? 1 : 0;
3083 CGContextRef ctx = [angbandContext lockFocus];
3085 if (angbandContext.changes.hasTextChanges ||
3086 angbandContext.changes.hasWipeChanges) {
3087 NSFont *selectionFont = [angbandContext.angbandViewFont screenFont];
3088 [selectionFont set];
3091 for (int iy = angbandContext.changes.firstChangedRow;
3092 iy <= angbandContext.changes.lastChangedRow;
3094 /* Skip untouched rows. */
3095 if ([angbandContext.changes getFirstChangedColumnInRow:iy] >
3096 [angbandContext.changes getLastChangedColumnInRow:iy]) {
3099 int ix = [angbandContext.changes getFirstChangedColumnInRow:iy];
3100 int ixmax = [angbandContext.changes getLastChangedColumnInRow:iy];
3109 switch ([angbandContext.changes getCellChangeType:ix row:iy]) {
3110 case CELL_CHANGE_NONE:
3114 case CELL_CHANGE_TILE:
3117 * Because changes are made to the compositing mode, save
3118 * the incoming value.
3120 NSGraphicsContext *nsContext =
3121 [NSGraphicsContext currentContext];
3122 NSCompositingOperation op = nsContext.compositingOperation;
3123 int step = (use_bigtile) ? 2 : 1;
3126 while (jx <= ixmax &&
3127 [angbandContext.changes getCellChangeType:jx row:iy]
3128 == CELL_CHANGE_TILE) {
3129 NSRect destinationRect =
3130 [angbandContext rectInImageForTileAtX:jx Y:iy];
3131 struct PendingTileChange tileIndices =
3132 [angbandContext.changes
3133 getCellTileChange:jx row:iy];
3134 NSRect sourceRect, terrainRect;
3136 destinationRect.size.width *= step;
3137 sourceRect.origin.x = graf_width * tileIndices.fgdCol;
3138 sourceRect.origin.y = graf_height * tileIndices.fgdRow;
3139 sourceRect.size.width = graf_width;
3140 sourceRect.size.height = graf_height;
3141 terrainRect.origin.x = graf_width * tileIndices.bckCol;
3142 terrainRect.origin.y = graf_height *
3144 terrainRect.size.width = graf_width;
3145 terrainRect.size.height = graf_height;
3155 * Skip drawing the foreground if it is the same
3156 * as the background.
3158 if (sourceRect.origin.x != terrainRect.origin.x ||
3159 sourceRect.origin.y != terrainRect.origin.y) {
3166 NSCompositeSourceOver);
3180 [nsContext setCompositingOperation:op];
3183 [angbandContext rectInImageForTileAtX:ix Y:iy];
3185 angbandContext.tileSize.width * (jx - ix);
3186 [angbandContext setNeedsDisplayInBaseRect:rect];
3191 case CELL_CHANGE_WIPE:
3192 case CELL_CHANGE_TEXT:
3194 * For a wiped region, treat it as if it had text (the only
3195 * loss if it was not is some extra work rendering
3196 * neighboring unchanged text).
3200 if (jx >= angbandContext.cols) {
3203 enum PendingCellChangeType ctype =
3204 [angbandContext.changes getCellChangeType:jx row:iy];
3205 if (ctype != CELL_CHANGE_TEXT &&
3206 ctype != CELL_CHANGE_WIPE) {
3213 int ieclip = jx - 1;
3215 int ierend = jx - 1;
3217 TERM_COLOR alast = 0;
3222 angbandContext.changes,
3224 angbandContext.nColPre,
3228 angbandContext.changes,
3230 angbandContext.nColPost,
3236 /* Save the state since the clipping will be modified. */
3237 CGContextSaveGState(ctx);
3239 /* Clear the area where rendering will be done. */
3240 r = [angbandContext rectInImageForTileAtX:isrend Y:iy];
3241 r.size.width = angbandContext.tileSize.width *
3242 (ierend - isrend + 1);
3243 [[NSColor blackColor] set];
3247 * Clear the current path so it does not affect clipping.
3248 * Then set the clipping rectangle. Using
3249 * CGContextSetTextDrawingMode() to include clipping does
3250 * not appear to be necessary on 10.14 and is actually
3251 * detrimental: when displaying more than one character,
3252 * only the first is visible.
3254 CGContextBeginPath(ctx);
3255 r = [angbandContext rectInImageForTileAtX:isclip Y:iy];
3256 r.size.width = angbandContext.tileSize.width *
3257 (ieclip - isclip + 1);
3258 CGContextClipToRect(ctx, r);
3262 while (k <= ierend) {
3263 if ([angbandContext.changes getCellChangeType:k row:iy]
3264 == CELL_CHANGE_WIPE) {
3265 /* Skip over since no rendering is necessary. */
3270 struct PendingTextChange textChange =
3271 [angbandContext.changes getCellTextChange:k
3273 int anew = textChange.color % MAX_COLORS;
3274 if (set_color || alast != anew) {
3277 set_color_for_index(anew);
3281 [angbandContext rectInImageForTileAtX:k Y:iy];
3282 if (textChange.doubleWidth) {
3283 rectToDraw.size.width *= 2.0;
3284 [angbandContext drawWChar:textChange.glyph
3285 inRect:rectToDraw context:ctx];
3288 [angbandContext drawWChar:textChange.glyph
3289 inRect:rectToDraw context:ctx];
3295 * Inform the context that the area in the clipping
3296 * rectangle needs to be redisplayed.
3298 [angbandContext setNeedsDisplayInBaseRect:r];
3300 CGContextRestoreGState(ctx);
3307 if (angbandContext.changes.cursorColumn >= 0 &&
3308 angbandContext.changes.cursorRow >= 0) {
3309 NSRect rect = [angbandContext
3310 rectInImageForTileAtX:angbandContext.changes.cursorColumn
3311 Y:angbandContext.changes.cursorRow];
3313 rect.size.width *= angbandContext.changes.cursorWidth;
3314 rect.size.height *= angbandContext.changes.cursorHeight;
3315 [[NSColor yellowColor] set];
3316 NSFrameRectWithWidth(rect, 1);
3317 /* Invalidate that rect */
3318 [angbandContext setNeedsDisplayInBaseRect:rect];
3321 [angbandContext unlockFocus];
3326 * Do a "special thing"
3328 static errr Term_xtra_cocoa(int n, int v)
3332 AngbandContext* angbandContext =
3333 (__bridge AngbandContext*) (Term->data);
3338 case TERM_XTRA_NOISE:
3343 case TERM_XTRA_SOUND:
3347 /* Process random events */
3348 case TERM_XTRA_BORED:
3350 * Show or hide cocoa windows based on the subwindow flags set by
3353 AngbandUpdateWindowVisibility();
3354 /* Process an event */
3355 (void)check_events(CHECK_EVENTS_NO_WAIT);
3358 /* Process pending events */
3359 case TERM_XTRA_EVENT:
3360 /* Process an event */
3361 (void)check_events(v);
3364 /* Flush all pending events (if any) */
3365 case TERM_XTRA_FLUSH:
3366 /* Hack -- flush all events */
3367 while (check_events(CHECK_EVENTS_DRAIN)) /* loop */;
3371 /* Hack -- Change the "soft level" */
3372 case TERM_XTRA_LEVEL:
3374 * Here we could activate (if requested), but I don't think
3375 * Angband should be telling us our window order (the user
3376 * should decide that), so do nothing.
3380 /* Clear the screen */
3381 case TERM_XTRA_CLEAR:
3383 [angbandContext lockFocus];
3384 [[NSColor blackColor] set];
3385 NSRect imageRect = {NSZeroPoint, [angbandContext imageSize]};
3386 NSRectFillUsingOperation(imageRect, NSCompositeCopy);
3387 [angbandContext unlockFocus];
3388 [angbandContext setNeedsDisplay:YES];
3393 /* React to changes */
3394 case TERM_XTRA_REACT:
3395 result = Term_xtra_cocoa_react();
3398 /* Delay (milliseconds) */
3399 case TERM_XTRA_DELAY:
3402 double seconds = v / 1000.;
3403 NSDate* date = [NSDate dateWithTimeIntervalSinceNow:seconds];
3407 event = [NSApp nextEventMatchingMask:-1
3409 inMode:NSDefaultRunLoopMode
3411 if (event) send_event(event);
3413 } while ([date timeIntervalSinceNow] >= 0);
3417 /* Draw the pending changes. */
3418 case TERM_XTRA_FRESH:
3419 Term_xtra_cocoa_fresh(angbandContext);
3420 [angbandContext.changes clear];
3433 static errr Term_curs_cocoa(TERM_LEN x, TERM_LEN y)
3435 AngbandContext *angbandContext = (__bridge AngbandContext*) (Term->data);
3437 [angbandContext.changes markCursor:x row:y];
3444 * Draw a cursor that's two tiles wide. For Japanese, that's used when
3445 * the cursor points at a kanji character, irregardless of whether operating
3448 static errr Term_bigcurs_cocoa(TERM_LEN x, TERM_LEN y)
3450 AngbandContext *angbandContext = (__bridge AngbandContext*) (Term->data);
3452 [angbandContext.changes markBigCursor:x row:y cellsWide:2 cellsHigh:1];
3459 * Low level graphics (Assumes valid input)
3461 * Erase "n" characters starting at (x,y)
3463 static errr Term_wipe_cocoa(TERM_LEN x, TERM_LEN y, int n)
3465 AngbandContext *angbandContext = (__bridge AngbandContext*) (Term->data);
3467 [angbandContext.changes markWipeRange:x row:y n:n];
3473 static errr Term_pict_cocoa(TERM_LEN x, TERM_LEN y, int n,
3474 TERM_COLOR *ap, concptr cp,
3475 const TERM_COLOR *tap, concptr tcp)
3477 /* Paranoia: Bail if we don't have a current graphics mode */
3478 if (! current_graphics_mode) return -1;
3480 AngbandContext* angbandContext = (__bridge AngbandContext*) (Term->data);
3481 int step = (use_bigtile) ? 2 : 1;
3484 * In bigtile mode, it is sufficient that the bounds for the modified
3485 * region only encompass the left cell for the region affected by the
3486 * tile and that only that cell has to have the details of the changes.
3488 for (int i = x; i < x + n * step; i += step) {
3489 TERM_COLOR a = *ap++;
3491 TERM_COLOR ta = *tap++;
3494 if (use_graphics && (a & 0x80) && (c & 0x80)) {
3495 [angbandContext.changes markTileChange:i row:y
3496 foregroundCol:((byte)c & 0x7F) % pict_cols
3497 foregroundRow:((byte)a & 0x7F) % pict_rows
3498 backgroundCol:((byte)tc & 0x7F) % pict_cols
3499 backgroundRow:((byte)ta & 0x7F) % pict_rows];
3508 * Low level graphics. Assumes valid input.
3510 * Draw several ("n") chars, with an attr, at a given location.
3512 static errr Term_text_cocoa(
3513 TERM_LEN x, TERM_LEN y, int n, TERM_COLOR a, concptr cp)
3515 AngbandContext* angbandContext = (__bridge AngbandContext*) (Term->data);
3523 * The second byte of the character is past the end. Ignore
3528 [angbandContext.changes markTextChange:i+x row:y
3529 glyph:convert_two_byte_eucjp_to_utf16_native(cp)
3530 color:a isDoubleWidth:YES];
3535 [angbandContext.changes markTextChange:i+x row:y
3536 glyph:*cp color:a isDoubleWidth:NO];
3541 [angbandContext.changes markTextChange:i+x row:y
3542 glyph:*cp color:a isDoubleWidth:NO];
3553 * Post a nonsense event so that our event loop wakes up
3555 static void wakeup_event_loop(void)
3557 /* Big hack - send a nonsense event to make us update */
3558 NSEvent *event = [NSEvent otherEventWithType:NSApplicationDefined location:NSZeroPoint modifierFlags:0 timestamp:0 windowNumber:0 context:NULL subtype:AngbandEventWakeup data1:0 data2:0];
3559 [NSApp postEvent:event atStart:NO];
3564 * Handle the "open_when_ready" flag
3566 static void handle_open_when_ready(void)
3568 /* Check the flag XXX XXX XXX make a function for this */
3569 if (open_when_ready && initialized && !game_in_progress)
3572 open_when_ready = FALSE;
3574 /* Game is in progress */
3575 game_in_progress = TRUE;
3577 /* Wait for a keypress */
3578 pause_line(Term->hgt - 1);
3584 * Handle quit_when_ready, by Peter Ammon,
3585 * slightly modified to check inkey_flag.
3587 static void quit_calmly(void)
3589 /* Quit immediately if game's not started */
3590 if (!game_in_progress || !character_generated) quit(NULL);
3592 /* Save the game and Quit (if it's safe) */
3595 /* Hack -- Forget messages and term */
3597 Term->mapped_flag = FALSE;
3600 do_cmd_save_game(FALSE);
3601 record_current_savefile();
3607 /* Wait until inkey_flag is set */
3613 * Returns YES if we contain an AngbandView (and hence should direct our events
3616 static BOOL contains_angband_view(NSView *view)
3618 if ([view isKindOfClass:[AngbandView class]]) return YES;
3619 for (NSView *subview in [view subviews]) {
3620 if (contains_angband_view(subview)) return YES;
3627 * Queue mouse presses if they occur in the map section of the main window.
3629 static void AngbandHandleEventMouseDown( NSEvent *event )
3632 AngbandContext *angbandContext = [[[event window] contentView] angbandContext];
3633 AngbandContext *mainAngbandContext =
3634 (__bridge AngbandContext*) (angband_term[0]->data);
3636 if (mainAngbandContext.primaryWindow &&
3637 [[event window] windowNumber] ==
3638 [mainAngbandContext.primaryWindow windowNumber])
3640 int cols, rows, x, y;
3641 Term_get_size(&cols, &rows);
3642 NSSize tileSize = angbandContext.tileSize;
3643 NSSize border = angbandContext.borderSize;
3644 NSPoint windowPoint = [event locationInWindow];
3646 /* Adjust for border; add border height because window origin is at
3648 windowPoint = NSMakePoint( windowPoint.x - border.width, windowPoint.y + border.height );
3650 NSPoint p = [[[event window] contentView] convertPoint: windowPoint fromView: nil];
3651 x = floor( p.x / tileSize.width );
3652 y = floor( p.y / tileSize.height );
3654 /* Being safe about this, since xcode doesn't seem to like the
3655 * bool_hack stuff */
3656 BOOL displayingMapInterface = ((int)inkey_flag != 0);
3658 /* Sidebar plus border == thirteen characters; top row is reserved. */
3659 /* Coordinates run from (0,0) to (cols-1, rows-1). */
3660 BOOL mouseInMapSection = (x > 13 && x <= cols - 1 && y > 0 && y <= rows - 2);
3662 /* If we are displaying a menu, allow clicks anywhere; if we are
3663 * displaying the main game interface, only allow clicks in the map
3665 if (!displayingMapInterface || (displayingMapInterface && mouseInMapSection))
3667 /* [event buttonNumber] will return 0 for left click,
3668 * 1 for right click, but this is safer */
3669 int button = ([event type] == NSLeftMouseDown) ? 1 : 2;
3672 NSUInteger eventModifiers = [event modifierFlags];
3673 byte angbandModifiers = 0;
3674 angbandModifiers |= (eventModifiers & NSShiftKeyMask) ? KC_MOD_SHIFT : 0;
3675 angbandModifiers |= (eventModifiers & NSControlKeyMask) ? KC_MOD_CONTROL : 0;
3676 angbandModifiers |= (eventModifiers & NSAlternateKeyMask) ? KC_MOD_ALT : 0;
3677 button |= (angbandModifiers & 0x0F) << 4; /* encode modifiers in the button number (see Term_mousepress()) */
3680 Term_mousepress(x, y, button);
3685 /* Pass click through to permit focus change, resize, etc. */
3686 [NSApp sendEvent:event];
3692 * Encodes an NSEvent Angband-style, or forwards it along. Returns YES if the
3693 * event was sent to Angband, NO if Cocoa (or nothing) handled it */
3694 static BOOL send_event(NSEvent *event)
3697 /* If the receiving window is not an Angband window, then do nothing */
3698 if (! contains_angband_view([[event window] contentView]))
3700 [NSApp sendEvent:event];
3704 /* Analyze the event */
3705 switch ([event type])
3709 /* Try performing a key equivalent */
3710 if ([[NSApp mainMenu] performKeyEquivalent:event]) break;
3712 unsigned modifiers = [event modifierFlags];
3714 /* Send all NSCommandKeyMasks through */
3715 if (modifiers & NSCommandKeyMask)
3717 [NSApp sendEvent:event];
3721 if (! [[event characters] length]) break;
3724 /* Extract some modifiers */
3725 int mc = !! (modifiers & NSControlKeyMask);
3726 int ms = !! (modifiers & NSShiftKeyMask);
3727 int mo = !! (modifiers & NSAlternateKeyMask);
3728 int kp = !! (modifiers & NSNumericPadKeyMask);
3731 /* Get the Angband char corresponding to this unichar */
3732 unichar c = [[event characters] characterAtIndex:0];
3735 * Have anything from the numeric keypad generate a macro
3736 * trigger so that shift or control modifiers can be passed.
3738 if (c <= 0x7F && !kp)
3744 * The rest of Hengband uses Angband 2.7's or so key handling:
3745 * so for the rest do something like the encoding that
3746 * main-win.c does: send a macro trigger with the Unicode
3747 * value encoded into printable ASCII characters.
3752 /* override special keys */
3753 switch([event keyCode]) {
3754 case kVK_Return: ch = '\r'; break;
3755 case kVK_Escape: ch = 27; break;
3756 case kVK_Tab: ch = '\t'; break;
3757 case kVK_Delete: ch = '\b'; break;
3758 case kVK_ANSI_KeypadEnter: ch = '\r'; kp = TRUE; break;
3761 /* Hide the mouse pointer */
3762 [NSCursor setHiddenUntilMouseMoves:YES];
3772 * Could use the hexsym global but some characters overlap with
3773 * those used to indicate modifiers.
3775 const char encoded[16] = {
3776 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b',
3780 /* Begin the macro trigger. */
3783 /* Send the modifiers. */
3784 if (mc) Term_keypress('C');
3785 if (ms) Term_keypress('S');
3786 if (mo) Term_keypress('O');
3787 if (kp) Term_keypress('K');
3790 Term_keypress(encoded[c & 0xF]);
3794 /* End the macro trigger. */
3801 case NSLeftMouseDown:
3802 case NSRightMouseDown:
3803 AngbandHandleEventMouseDown(event);
3806 case NSApplicationDefined:
3808 if ([event subtype] == AngbandEventWakeup)
3816 [NSApp sendEvent:event];
3823 * Check for Events, return TRUE if we process any
3825 static BOOL check_events(int wait)
3830 /* Handles the quit_when_ready flag */
3831 if (quit_when_ready) quit_calmly();
3834 if (wait == CHECK_EVENTS_WAIT) endDate = [NSDate distantFuture];
3835 else endDate = [NSDate distantPast];
3839 if (quit_when_ready)
3841 /* send escape events until we quit */
3842 Term_keypress(0x1B);
3847 event = [NSApp nextEventMatchingMask:-1 untilDate:endDate
3848 inMode:NSDefaultRunLoopMode dequeue:YES];
3853 if (send_event(event)) break;
3862 * Hook to tell the user something important
3864 static void hook_plog(const char * str)
3868 NSString *msg = NSLocalizedStringWithDefaultValue(
3869 @"Warning", AngbandMessageCatalog, [NSBundle mainBundle],
3870 @"Warning", @"Alert text for generic warning");
3871 NSString *info = [NSString stringWithCString:str
3873 encoding:NSJapaneseEUCStringEncoding
3875 encoding:NSMacOSRomanStringEncoding
3878 NSAlert *alert = [[NSAlert alloc] init];
3880 alert.messageText = msg;
3881 alert.informativeText = info;
3888 * Hook to tell the user something, and then quit
3890 static void hook_quit(const char * str)
3892 for (int i = ANGBAND_TERM_MAX - 1; i >= 0; --i) {
3893 if (angband_term[i]) {
3894 term_nuke(angband_term[i]);
3897 [AngbandSoundCatalog clearSharedSounds];
3898 [AngbandContext setDefaultFont:nil];
3904 * Return the path for Angband's lib directory and bail if it isn't found. The
3905 * lib directory should be in the bundle's resources directory, since it's
3906 * copied when built.
3908 static NSString* get_lib_directory(void)
3910 NSString *bundleLibPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: AngbandDirectoryNameLib];
3911 BOOL isDirectory = NO;
3912 BOOL libExists = [[NSFileManager defaultManager] fileExistsAtPath: bundleLibPath isDirectory: &isDirectory];
3914 if( !libExists || !isDirectory )
3916 NSLog( @"Hengband: can't find %@/ in bundle: isDirectory: %d libExists: %d", AngbandDirectoryNameLib, isDirectory, libExists );
3918 NSString *msg = NSLocalizedStringWithDefaultValue(
3919 @"Error.MissingResources",
3920 AngbandMessageCatalog,
3921 [NSBundle mainBundle],
3922 @"Missing Resources",
3923 @"Alert text for missing resources");
3924 NSString *info = NSLocalizedStringWithDefaultValue(
3925 @"Error.MissingAngbandLib",
3926 AngbandMessageCatalog,
3927 [NSBundle mainBundle],
3928 @"Hengband was unable to find required resources and must quit. Please report a bug on the Angband forums.",
3929 @"Alert informative message for missing Angband lib/ folder");
3930 NSString *quit_label = NSLocalizedStringWithDefaultValue(
3931 @"Label.Quit", AngbandMessageCatalog, [NSBundle mainBundle],
3933 NSAlert *alert = [[NSAlert alloc] init];
3936 * Note that NSCriticalAlertStyle was deprecated in 10.10. The
3937 * replacement is NSAlertStyleCritical.
3939 alert.alertStyle = NSCriticalAlertStyle;
3940 alert.messageText = msg;
3941 alert.informativeText = info;
3942 [alert addButtonWithTitle:quit_label];
3947 return bundleLibPath;
3951 * Return the path for the directory where Angband should look for its standard
3954 static NSString* get_doc_directory(void)
3956 NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
3958 #if defined(SAFE_DIRECTORY)
3959 NSString *versionedDirectory = [NSString stringWithFormat: @"%@-%s", AngbandDirectoryNameBase, VERSION_STRING];
3960 return [documents stringByAppendingPathComponent: versionedDirectory];
3962 return [documents stringByAppendingPathComponent: AngbandDirectoryNameBase];
3967 * Adjust directory paths as needed to correct for any differences needed by
3968 * Angband. init_file_paths() currently requires that all paths provided have
3969 * a trailing slash and all other platforms honor this.
3971 * \param originalPath The directory path to adjust.
3972 * \return A path suitable for Angband or nil if an error occurred.
3974 static NSString* AngbandCorrectedDirectoryPath(NSString *originalPath)
3976 if ([originalPath length] == 0) {
3980 if (![originalPath hasSuffix: @"/"]) {
3981 return [originalPath stringByAppendingString: @"/"];
3984 return originalPath;
3988 * Give Angband the base paths that should be used for the various directories
3989 * it needs. It will create any needed directories.
3991 static void prepare_paths_and_directories(void)
3993 char libpath[PATH_MAX + 1] = "\0";
3994 NSString *libDirectoryPath =
3995 AngbandCorrectedDirectoryPath(get_lib_directory());
3996 [libDirectoryPath getFileSystemRepresentation: libpath maxLength: sizeof(libpath)];
3998 char basepath[PATH_MAX + 1] = "\0";
3999 NSString *angbandDocumentsPath =
4000 AngbandCorrectedDirectoryPath(get_doc_directory());
4001 [angbandDocumentsPath getFileSystemRepresentation: basepath maxLength: sizeof(basepath)];
4003 init_file_paths(libpath, basepath);
4004 create_needed_dirs();
4008 * Play sound effects asynchronously. Select a sound from any available
4009 * for the required event, and bridge to Cocoa to play it.
4011 static void play_sound(int event)
4013 [[AngbandSoundCatalog sharedSounds] playSound:event];
4017 * ------------------------------------------------------------------------
4019 * ------------------------------------------------------------------------ */
4021 @implementation AngbandAppDelegate
4023 @synthesize graphicsMenu=_graphicsMenu;
4024 @synthesize commandMenu=_commandMenu;
4025 @synthesize commandMenuTagMap=_commandMenuTagMap;
4027 - (IBAction)newGame:sender
4029 /* Game is in progress */
4030 game_in_progress = TRUE;
4034 - (IBAction)editFont:sender
4036 NSFontPanel *panel = [NSFontPanel sharedFontPanel];
4037 NSFont *termFont = [AngbandContext defaultFont];
4040 for (i=0; i < ANGBAND_TERM_MAX; i++) {
4041 AngbandContext *context =
4042 (__bridge AngbandContext*) (angband_term[i]->data);
4043 if ([context isMainWindow]) {
4044 termFont = [context angbandViewFont];
4049 [panel setPanelFont:termFont isMultiple:NO];
4050 [panel orderFront:self];
4054 * Implement NSObject's changeFont() method to receive a notification about the
4055 * changed font. Note that, as of 10.14, changeFont() is deprecated in
4056 * NSObject - it will be removed at some point and the application delegate
4057 * will have to be declared as implementing the NSFontChanging protocol.
4059 - (void)changeFont:(id)sender
4062 for (mainTerm=0; mainTerm < ANGBAND_TERM_MAX; mainTerm++) {
4063 AngbandContext *context =
4064 (__bridge AngbandContext*) (angband_term[mainTerm]->data);
4065 if ([context isMainWindow]) {
4070 /* Bug #1709: Only change font for angband windows */
4071 if (mainTerm == ANGBAND_TERM_MAX) return;
4073 NSFont *oldFont = [AngbandContext defaultFont];
4074 NSFont *newFont = [sender convertFont:oldFont];
4075 if (! newFont) return; /*paranoia */
4077 /* Store as the default font if we changed the first term */
4078 if (mainTerm == 0) {
4079 [AngbandContext setDefaultFont:newFont];
4082 /* Record it in the preferences */
4083 NSUserDefaults *defs = [NSUserDefaults angbandDefaults];
4084 [defs setValue:[newFont fontName]
4085 forKey:[NSString stringWithFormat:@"FontName-%d", mainTerm]];
4086 [defs setFloat:[newFont pointSize]
4087 forKey:[NSString stringWithFormat:@"FontSize-%d", mainTerm]];
4089 NSDisableScreenUpdates();
4092 AngbandContext *angbandContext =
4093 (__bridge AngbandContext*) (angband_term[mainTerm]->data);
4094 [(id)angbandContext setSelectionFont:newFont adjustTerminal: YES];
4096 NSEnableScreenUpdates();
4098 if (mainTerm == 0 && game_in_progress) {
4099 /* Mimics the logic in setGraphicsMode(). */
4101 wakeup_event_loop();
4103 [(id)angbandContext requestRedraw];
4107 - (IBAction)openGame:sender
4110 BOOL selectedSomething = NO;
4113 /* Get where we think the save files are */
4114 NSURL *startingDirectoryURL =
4115 [NSURL fileURLWithPath:[NSString stringWithCString:ANGBAND_DIR_SAVE encoding:NSASCIIStringEncoding]
4118 /* Set up an open panel */
4119 NSOpenPanel* panel = [NSOpenPanel openPanel];
4120 [panel setCanChooseFiles:YES];
4121 [panel setCanChooseDirectories:NO];
4122 [panel setResolvesAliases:YES];
4123 [panel setAllowsMultipleSelection:NO];
4124 [panel setTreatsFilePackagesAsDirectories:YES];
4125 [panel setDirectoryURL:startingDirectoryURL];
4128 panelResult = [panel runModal];
4129 if (panelResult == NSOKButton)
4131 NSArray* fileURLs = [panel URLs];
4132 if ([fileURLs count] > 0 && [[fileURLs objectAtIndex:0] isFileURL])
4134 NSURL* savefileURL = (NSURL *)[fileURLs objectAtIndex:0];
4136 * The path property doesn't do the right thing except for
4137 * URLs with the file scheme. We had
4138 * getFileSystemRepresentation here before, but that wasn't
4139 * introduced until OS X 10.9.
4141 selectedSomething = [[savefileURL path]
4143 maxLength:sizeof savefile
4144 encoding:NSMacOSRomanStringEncoding];
4148 if (selectedSomething)
4150 /* Remember this so we can select it by default next time */
4151 record_current_savefile();
4153 /* Game is in progress */
4154 game_in_progress = TRUE;
4159 - (IBAction)saveGame:sender
4161 /* Hack -- Forget messages */
4165 do_cmd_save_game(FALSE);
4167 /* Record the current save file so we can select it by default next time.
4168 * It's a little sketchy that this only happens when we save through the
4169 * menu; ideally game-triggered saves would trigger it too. */
4170 record_current_savefile();
4174 * Create and initialize Angband terminal number "termIndex".
4176 - (void)linkTermData:(int)termIndex
4178 NSArray *terminalDefaults = [[NSUserDefaults standardUserDefaults]
4179 valueForKey: AngbandTerminalsDefaultsKey];
4180 NSInteger rows = 24;
4181 NSInteger columns = 80;
4183 if (termIndex < (int)[terminalDefaults count]) {
4184 NSDictionary *term = [terminalDefaults objectAtIndex:termIndex];
4185 rows = [[term valueForKey: AngbandTerminalRowsDefaultsKey]
4187 columns = [[term valueForKey: AngbandTerminalColumnsDefaultsKey]
4192 term *newterm = ZNEW(term);
4194 /* Initialize the term */
4195 term_init(newterm, columns, rows, 256 /* keypresses, for some reason? */);
4197 /* Differentiate between BS/^h, Tab/^i, etc. */
4198 /* newterm->complex_input = TRUE; */
4200 /* Use a "software" cursor */
4201 newterm->soft_cursor = TRUE;
4203 /* Disable the per-row flush notifications since they are not used. */
4204 newterm->never_frosh = TRUE;
4206 /* Erase with "white space" */
4207 newterm->attr_blank = TERM_WHITE;
4208 newterm->char_blank = ' ';
4210 /* Prepare the init/nuke hooks */
4211 newterm->init_hook = Term_init_cocoa;
4212 newterm->nuke_hook = Term_nuke_cocoa;
4214 /* Prepare the function hooks */
4215 newterm->xtra_hook = Term_xtra_cocoa;
4216 newterm->wipe_hook = Term_wipe_cocoa;
4217 newterm->curs_hook = Term_curs_cocoa;
4218 newterm->bigcurs_hook = Term_bigcurs_cocoa;
4219 newterm->text_hook = Term_text_cocoa;
4220 newterm->pict_hook = Term_pict_cocoa;
4221 /* newterm->mbcs_hook = Term_mbcs_cocoa; */
4223 /* Global pointer */
4224 angband_term[termIndex] = newterm;
4228 * Allocate the primary Angband terminal and activate it. Allocate the other
4229 * Angband terminals.
4231 - (void)initWindows {
4232 for (int i = 0; i < ANGBAND_TERM_MAX; i++) {
4233 [self linkTermData:i];
4236 Term_activate(angband_term[0]);
4240 * Load preferences from preferences file for current host+current user+
4241 * current application.
4245 NSUserDefaults *defs = [NSUserDefaults angbandDefaults];
4247 /* Make some default defaults */
4248 NSMutableArray *defaultTerms = [[NSMutableArray alloc] init];
4251 * The following default rows/cols were determined experimentally by first
4252 * finding the ideal window/font size combinations. But because of awful
4253 * temporal coupling in Term_init_cocoa(), it's impossible to set up the
4254 * defaults there, so we do it this way.
4256 for (NSUInteger i = 0; i < ANGBAND_TERM_MAX; i++) {
4292 NSDictionary *standardTerm =
4293 [NSDictionary dictionaryWithObjectsAndKeys:
4294 [NSNumber numberWithInt: rows], AngbandTerminalRowsDefaultsKey,
4295 [NSNumber numberWithInt: columns], AngbandTerminalColumnsDefaultsKey,
4296 [NSNumber numberWithBool: visible], AngbandTerminalVisibleDefaultsKey,
4298 [defaultTerms addObject: standardTerm];
4301 NSDictionary *defaults = [[NSDictionary alloc] initWithObjectsAndKeys:
4303 @"Osaka", @"FontName",
4305 @"Menlo", @"FontName",
4307 [NSNumber numberWithFloat:13.f], @"FontSize",
4308 [NSNumber numberWithInt:60], AngbandFrameRateDefaultsKey,
4309 [NSNumber numberWithBool:YES], AngbandSoundDefaultsKey,
4310 [NSNumber numberWithInt:GRAPHICS_NONE], AngbandGraphicsDefaultsKey,
4311 [NSNumber numberWithBool:YES], AngbandBigTileDefaultsKey,
4312 defaultTerms, AngbandTerminalsDefaultsKey,
4314 [defs registerDefaults:defaults];
4316 /* Preferred graphics mode */
4317 graf_mode_req = [defs integerForKey:AngbandGraphicsDefaultsKey];
4318 if (graf_mode_req != GRAPHICS_NONE &&
4319 get_graphics_mode(graf_mode_req)->grafID != GRAPHICS_NONE &&
4320 [defs boolForKey:AngbandBigTileDefaultsKey] == YES) {
4324 use_bigtile = FALSE;
4325 arg_bigtile = FALSE;
4328 /* Use sounds; set the Angband global */
4329 if ([defs boolForKey:AngbandSoundDefaultsKey] == YES) {
4331 [AngbandSoundCatalog sharedSounds].enabled = YES;
4334 [AngbandSoundCatalog sharedSounds].enabled = NO;
4338 frames_per_second = [defs integerForKey:AngbandFrameRateDefaultsKey];
4342 setDefaultFont:[NSFont fontWithName:[defs valueForKey:@"FontName-0"]
4343 size:[defs floatForKey:@"FontSize-0"]]];
4344 if (! [AngbandContext defaultFont])
4346 setDefaultFont:[NSFont fontWithName:@"Menlo" size:13.]];
4350 * Entry point for initializing Angband
4355 /* Hooks in some "z-util.c" hooks */
4356 plog_aux = hook_plog;
4357 quit_aux = hook_quit;
4359 /* Initialize file paths */
4360 prepare_paths_and_directories();
4362 /* Note the "system" */
4363 ANGBAND_SYS = "coc";
4365 /* Load possible graphics modes */
4366 init_graphics_modes();
4368 /* Load preferences */
4371 /* Prepare the windows */
4374 /* Set up game event handlers */
4375 /* init_display(); */
4377 /* Register the sound hook */
4378 /* sound_hook = play_sound; */
4380 /* Initialise game */
4383 /* Initialize some save file stuff */
4384 player_egid = getegid();
4386 /* We are now initialized */
4389 /* Handle "open_when_ready" */
4390 handle_open_when_ready();
4392 /* Handle pending events (most notably update) and flush input */
4395 /* Prompt the user */
4396 int message_row = (Term->hgt - 23) / 5 + 23;
4397 Term_erase(0, message_row, 255);
4400 "['ファイル' メニューから '新規' または '開く' を選択します]",
4401 message_row, (Term->wid - 59) / 2
4403 "[Choose 'New' or 'Open' from the 'File' menu]",
4404 message_row, (Term->wid - 45) / 2
4410 while (!game_in_progress) {
4412 NSEvent *event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:[NSDate distantFuture] inMode:NSDefaultRunLoopMode dequeue:YES];
4413 if (event) [NSApp sendEvent:event];
4418 * Play a game -- "new_game" is set by "new", "open" or the open document
4419 * even handler as appropriate
4422 play_game(new_game);
4428 * Implement NSObject's validateMenuItem() method to override enabling or
4429 * disabling a menu item. Note that, as of 10.14, validateMenuItem() is
4430 * deprecated in NSObject - it will be removed at some point and the
4431 * application delegate will have to be declared as implementing the
4432 * NSMenuItemValidation protocol.
4434 - (BOOL)validateMenuItem:(NSMenuItem *)menuItem
4436 SEL sel = [menuItem action];
4437 NSInteger tag = [menuItem tag];
4439 if( tag >= AngbandWindowMenuItemTagBase && tag < AngbandWindowMenuItemTagBase + ANGBAND_TERM_MAX )
4441 if( tag == AngbandWindowMenuItemTagBase )
4443 /* The main window should always be available and visible */
4449 * Another window is only usable after Term_init_cocoa() has
4450 * been called for it. For Angband if window_flag[i] is nonzero
4451 * then that has happened for window i. For Hengband, that is
4452 * not the case so also test angband_term[i]->data.
4454 NSInteger subwindowNumber = tag - AngbandWindowMenuItemTagBase;
4455 return (angband_term[subwindowNumber]->data != 0
4456 && window_flag[subwindowNumber] > 0);
4462 if (sel == @selector(newGame:))
4464 return ! game_in_progress;
4466 else if (sel == @selector(editFont:))
4470 else if (sel == @selector(openGame:))
4472 return ! game_in_progress;
4474 else if (sel == @selector(setRefreshRate:) &&
4475 [[menuItem parentItem] tag] == 150)
4477 NSInteger fps = [[NSUserDefaults standardUserDefaults] integerForKey:AngbandFrameRateDefaultsKey];
4478 [menuItem setState: ([menuItem tag] == fps)];
4481 else if( sel == @selector(setGraphicsMode:) )
4483 NSInteger requestedGraphicsMode = [[NSUserDefaults standardUserDefaults] integerForKey:AngbandGraphicsDefaultsKey];
4484 [menuItem setState: (tag == requestedGraphicsMode)];
4487 else if( sel == @selector(toggleSound:) )
4489 BOOL is_on = [[NSUserDefaults standardUserDefaults]
4490 boolForKey:AngbandSoundDefaultsKey];
4492 [menuItem setState: ((is_on) ? NSOnState : NSOffState)];
4495 else if( sel == @selector(sendAngbandCommand:) ||
4496 sel == @selector(saveGame:) )
4499 * we only want to be able to send commands during an active game
4500 * after the birth screens
4502 return !!game_in_progress && character_generated;
4508 - (IBAction)setRefreshRate:(NSMenuItem *)menuItem
4510 frames_per_second = [menuItem tag];
4511 [[NSUserDefaults angbandDefaults] setInteger:frames_per_second forKey:AngbandFrameRateDefaultsKey];
4514 - (void)setGraphicsMode:(NSMenuItem *)sender
4516 /* We stashed the graphics mode ID in the menu item's tag */
4517 graf_mode_req = [sender tag];
4519 /* Stash it in UserDefaults */
4520 [[NSUserDefaults angbandDefaults] setInteger:graf_mode_req forKey:AngbandGraphicsDefaultsKey];
4522 if (graf_mode_req == GRAPHICS_NONE ||
4523 get_graphics_mode(graf_mode_req) == GRAPHICS_NONE) {
4525 arg_bigtile = FALSE;
4527 } else if ([[NSUserDefaults angbandDefaults] boolForKey:AngbandBigTileDefaultsKey] == YES &&
4532 if (game_in_progress)
4534 if (arg_bigtile != use_bigtile) {
4535 Term_activate(angband_term[0]);
4536 Term_resize(angband_term[0]->wid, angband_term[0]->hgt);
4539 /* Hack -- Force redraw */
4542 /* Wake up the event loop so it notices the change */
4543 wakeup_event_loop();
4547 - (void)selectWindow: (id)sender
4549 NSInteger subwindowNumber =
4550 [(NSMenuItem *)sender tag] - AngbandWindowMenuItemTagBase;
4551 AngbandContext *context =
4552 (__bridge AngbandContext*) (angband_term[subwindowNumber]->data);
4553 [context.primaryWindow makeKeyAndOrderFront: self];
4554 [context saveWindowVisibleToDefaults: YES];
4557 - (IBAction) toggleSound: (NSMenuItem *) sender
4559 BOOL is_on = (sender.state == NSOnState);
4561 /* Toggle the state and update the Angband global and preferences. */
4563 sender.state = NSOffState;
4565 [AngbandSoundCatalog sharedSounds].enabled = NO;
4567 sender.state = NSOnState;
4569 [AngbandSoundCatalog sharedSounds].enabled = YES;
4571 [[NSUserDefaults angbandDefaults] setBool:(! is_on)
4572 forKey:AngbandSoundDefaultsKey];
4575 - (IBAction)toggleWideTiles:(NSMenuItem *) sender
4577 BOOL is_on = (sender.state == NSOnState);
4579 /* Toggle the state and update the Angband globals and preferences. */
4580 sender.state = (is_on) ? NSOffState : NSOnState;
4581 [[NSUserDefaults angbandDefaults] setBool:(! is_on)
4582 forKey:AngbandBigTileDefaultsKey];
4583 if (graphics_are_enabled()) {
4584 arg_bigtile = (is_on) ? FALSE : TRUE;
4585 /* Mimics the logic in setGraphicsMode(). */
4586 if (game_in_progress && arg_bigtile != use_bigtile) {
4587 Term_activate(angband_term[0]);
4588 Term_resize(angband_term[0]->wid, angband_term[0]->hgt);
4590 wakeup_event_loop();
4595 - (void)prepareWindowsMenu
4599 * Get the window menu with default items and add a separator and
4600 * item for the main window.
4602 NSMenu *windowsMenu = [[NSApplication sharedApplication] windowsMenu];
4603 [windowsMenu addItem: [NSMenuItem separatorItem]];
4605 NSString *title1 = [NSString stringWithCString:angband_term_name[0]
4607 encoding:NSJapaneseEUCStringEncoding
4609 encoding:NSMacOSRomanStringEncoding
4612 NSMenuItem *angbandItem = [[NSMenuItem alloc] initWithTitle:title1 action: @selector(selectWindow:) keyEquivalent: @"0"];
4613 [angbandItem setTarget: self];
4614 [angbandItem setTag: AngbandWindowMenuItemTagBase];
4615 [windowsMenu addItem: angbandItem];
4617 /* Add items for the additional term windows */
4618 for( NSInteger i = 1; i < ANGBAND_TERM_MAX; i++ )
4620 NSString *title = [NSString stringWithCString:angband_term_name[i]
4622 encoding:NSJapaneseEUCStringEncoding
4624 encoding:NSMacOSRomanStringEncoding
4627 NSString *keyEquivalent =
4628 [NSString stringWithFormat: @"%ld", (long)i];
4629 NSMenuItem *windowItem =
4630 [[NSMenuItem alloc] initWithTitle: title
4631 action: @selector(selectWindow:)
4632 keyEquivalent: keyEquivalent];
4633 [windowItem setTarget: self];
4634 [windowItem setTag: AngbandWindowMenuItemTagBase + i];
4635 [windowsMenu addItem: windowItem];
4641 * Send a command to Angband via a menu item. This places the appropriate key
4642 * down events into the queue so that it seems like the user pressed them
4643 * (instead of trying to use the term directly).
4645 - (void)sendAngbandCommand: (id)sender
4647 NSMenuItem *menuItem = (NSMenuItem *)sender;
4648 NSString *command = [self.commandMenuTagMap objectForKey: [NSNumber numberWithInteger: [menuItem tag]]];
4649 AngbandContext* context =
4650 (__bridge AngbandContext*) (angband_term[0]->data);
4651 NSInteger windowNumber = [context.primaryWindow windowNumber];
4653 /* Send a \ to bypass keymaps */
4654 NSEvent *escape = [NSEvent keyEventWithType: NSKeyDown
4655 location: NSZeroPoint
4658 windowNumber: windowNumber
4661 charactersIgnoringModifiers: @"\\"
4664 [[NSApplication sharedApplication] postEvent: escape atStart: NO];
4666 /* Send the actual command (from the original command set) */
4667 NSEvent *keyDown = [NSEvent keyEventWithType: NSKeyDown
4668 location: NSZeroPoint
4671 windowNumber: windowNumber
4674 charactersIgnoringModifiers: command
4677 [[NSApplication sharedApplication] postEvent: keyDown atStart: NO];
4681 * Set up the command menu dynamically, based on CommandMenu.plist.
4683 - (void)prepareCommandMenu
4686 NSString *commandMenuPath =
4687 [[NSBundle mainBundle] pathForResource: @"CommandMenu"
4689 NSArray *commandMenuItems =
4690 [[NSArray alloc] initWithContentsOfFile: commandMenuPath];
4691 NSMutableDictionary *angbandCommands =
4692 [[NSMutableDictionary alloc] init];
4693 NSString *tblname = @"CommandMenu";
4694 NSInteger tagOffset = 0;
4696 for( NSDictionary *item in commandMenuItems )
4698 BOOL useShiftModifier =
4699 [[item valueForKey: @"ShiftModifier"] boolValue];
4700 BOOL useOptionModifier =
4701 [[item valueForKey: @"OptionModifier"] boolValue];
4702 NSUInteger keyModifiers = NSCommandKeyMask;
4703 keyModifiers |= (useShiftModifier) ? NSShiftKeyMask : 0;
4704 keyModifiers |= (useOptionModifier) ? NSAlternateKeyMask : 0;
4706 NSString *lookup = [item valueForKey: @"Title"];
4707 NSString *title = NSLocalizedStringWithDefaultValue(
4708 lookup, tblname, [NSBundle mainBundle], lookup, @"");
4709 NSString *key = [item valueForKey: @"KeyEquivalent"];
4710 NSMenuItem *menuItem =
4711 [[NSMenuItem alloc] initWithTitle: title
4712 action: @selector(sendAngbandCommand:)
4713 keyEquivalent: key];
4714 [menuItem setTarget: self];
4715 [menuItem setKeyEquivalentModifierMask: keyModifiers];
4716 [menuItem setTag: AngbandCommandMenuItemTagBase + tagOffset];
4717 [self.commandMenu addItem: menuItem];
4719 NSString *angbandCommand = [item valueForKey: @"AngbandCommand"];
4720 [angbandCommands setObject: angbandCommand
4721 forKey: [NSNumber numberWithInteger: [menuItem tag]]];
4725 self.commandMenuTagMap = [[NSDictionary alloc]
4726 initWithDictionary: angbandCommands];
4730 - (void)awakeFromNib
4732 [super awakeFromNib];
4734 [self prepareWindowsMenu];
4735 [self prepareCommandMenu];
4738 - (void)applicationDidFinishLaunching:sender
4742 /* Once beginGame finished, the game is over - that's how Angband works,
4743 * and we should quit */
4744 game_is_finished = TRUE;
4745 [NSApp terminate:self];
4748 - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
4750 if (p_ptr->playing == FALSE || game_is_finished == TRUE)
4752 return NSTerminateNow;
4754 else if (! inkey_flag)
4756 /* For compatibility with other ports, do not quit in this case */
4757 return NSTerminateCancel;
4762 /* player->upkeep->playing = FALSE; */
4764 /* Post an escape event so that we can return from our get-key-event
4766 wakeup_event_loop();
4767 quit_when_ready = true;
4768 /* Must return Cancel, not Later, because we need to get out of the
4769 * run loop and back to Angband's loop */
4770 return NSTerminateCancel;
4775 * Dynamically build the Graphics menu
4777 - (void)menuNeedsUpdate:(NSMenu *)menu {
4779 /* Only the graphics menu is dynamic */
4780 if (! [menu isEqual:self.graphicsMenu])
4783 /* If it's non-empty, then we've already built it. Currently graphics modes
4784 * won't change once created; if they ever can we can remove this check.
4785 * Note that the check mark does change, but that's handled in
4786 * validateMenuItem: instead of menuNeedsUpdate: */
4787 if ([menu numberOfItems] > 0)
4790 /* This is the action for all these menu items */
4791 SEL action = @selector(setGraphicsMode:);
4793 /* Add an initial Classic ASCII menu item */
4794 NSString *tblname = @"GraphicsMenu";
4795 NSString *key = @"Classic ASCII";
4796 NSString *title = NSLocalizedStringWithDefaultValue(
4797 key, tblname, [NSBundle mainBundle], key, @"");
4798 NSMenuItem *classicItem = [menu addItemWithTitle:title action:action keyEquivalent:@""];
4799 [classicItem setTag:GRAPHICS_NONE];
4801 /* Walk through the list of graphics modes */
4802 if (graphics_modes) {
4805 for (i=0; graphics_modes[i].pNext; i++)
4807 const graphics_mode *graf = &graphics_modes[i];
4809 if (graf->grafID == GRAPHICS_NONE) {
4812 /* Make the title. NSMenuItem throws on a nil title, so ensure it's
4814 key = [[NSString alloc] initWithUTF8String:graf->menuname];
4815 title = NSLocalizedStringWithDefaultValue(
4816 key, tblname, [NSBundle mainBundle], key, @"");
4819 NSMenuItem *item = [menu addItemWithTitle:title action:action keyEquivalent:@""];
4820 [item setTag:graf->grafID];
4826 * Delegate method that gets called if we're asked to open a file.
4828 - (void)application:(NSApplication *)sender openFiles:(NSArray *)filenames
4830 /* Can't open a file once we've started */
4831 if (game_in_progress) {
4832 [[NSApplication sharedApplication]
4833 replyToOpenOrPrint:NSApplicationDelegateReplyFailure];
4837 /* We can only open one file. Use the last one. */
4838 NSString *file = [filenames lastObject];
4840 [[NSApplication sharedApplication]
4841 replyToOpenOrPrint:NSApplicationDelegateReplyFailure];
4845 /* Put it in savefile */
4846 if (! [file getFileSystemRepresentation:savefile maxLength:sizeof savefile]) {
4847 [[NSApplication sharedApplication]
4848 replyToOpenOrPrint:NSApplicationDelegateReplyFailure];
4852 game_in_progress = TRUE;
4854 /* Wake us up in case this arrives while we're sitting at the Welcome
4856 wakeup_event_loop();
4858 [[NSApplication sharedApplication]
4859 replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
4864 int main(int argc, char* argv[])
4866 NSApplicationMain(argc, (void*)argv);
4870 #endif /* MACINTOSH || MACH_O_COCOA */