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 * Releases the resources acquired for the catalog.
122 * If self.enabled is YES and the given event has one or more sounds
123 * corresponding to it in the catalog, plays one of those sounds, chosen at
126 - (void)playSound:(int)event;
129 * Impose an arbitary limit on number of possible samples per event.
130 * Currently not declaring this as a class property for compatibility with
131 * versions of Xcode prior to 8.
136 * Return the shared sound catalog instance, creating it if it does not
137 * exist yet. Currently not declaring this as a class property for
138 * compatibility with versions of Xcode prior to 8.
140 + (AngbandSoundCatalog*)sharedSounds;
143 * Release any resouces associated with shared sounds.
145 + (void)clearSharedSounds;
149 @implementation AngbandSoundCatalog
152 if (self = [super init]) {
153 self->soundsByPath = nil;
154 self->soundArraysByEvent = nil;
161 self->soundsByPath = nil;
162 self->soundArraysByEvent = nil;
165 - (void)playSound:(int)event {
166 if (! self.enabled) {
170 /* Initialize when the first sound is played. */
171 if (self->soundArraysByEvent == nil) {
172 /* Build the "sound" path */
173 char sound_dir[1024];
174 path_build(sound_dir, sizeof(sound_dir), ANGBAND_DIR_XTRA, "sound");
176 /* Find and open the config file */
178 path_build(path, sizeof(path), sound_dir, "sound.cfg");
179 FILE *fff = my_fopen(path, "r");
183 NSLog(@"The sound configuration file could not be opened.");
187 self->soundsByPath = [[NSMutableDictionary alloc] init];
188 self->soundArraysByEvent = [[NSMutableDictionary alloc] init];
191 * This loop may take a while depending on the count and size of
196 /* Lines are always of the form "name = sample [sample ...]" */
198 while (my_fgets(fff, buffer, sizeof(buffer)) == 0) {
200 char *cfg_sample_list;
206 /* Skip anything not beginning with an alphabetic character */
207 if (!buffer[0] || !isalpha((unsigned char)buffer[0])) continue;
209 /* Split the line into two: message name, and the rest */
210 search = strchr(buffer, ' ');
211 cfg_sample_list = strchr(search + 1, ' ');
212 if (!search) continue;
213 if (!cfg_sample_list) continue;
215 /* Set the message name, and terminate at first space */
219 /* Make sure this is a valid event name */
220 for (event = MSG_MAX - 1; event >= 0; event--) {
221 if (strcmp(msg_name, angband_sound_name[event]) == 0)
224 if (event < 0) continue;
227 * Advance the sample list pointer so it's at the beginning of
231 if (!cfg_sample_list[0]) continue;
233 /* Terminate the current token */
234 cur_token = cfg_sample_list;
235 search = strchr(cur_token, ' ');
238 next_token = search + 1;
244 * Now we find all the sample names and add them one by one
247 NSMutableArray *soundSamples =
248 [self->soundArraysByEvent
249 objectForKey:[NSNumber numberWithInteger:event]];
250 if (soundSamples == nil) {
251 soundSamples = [[NSMutableArray alloc] init];
252 [self->soundArraysByEvent
253 setObject:soundSamples
254 forKey:[NSNumber numberWithInteger:event]];
256 int num = (int) soundSamples.count;
258 /* Don't allow too many samples */
259 if (num >= [AngbandSoundCatalog maxSamples]) break;
261 NSString *token_string =
262 [NSString stringWithUTF8String:cur_token];
264 [self->soundsByPath objectForKey:token_string];
268 * We have to load the sound. Build the path to the
271 path_build(path, sizeof(path), sound_dir, cur_token);
273 if (stat(path, &stb) == 0) {
274 /* Load the sound into memory */
275 sound = [[NSSound alloc]
276 initWithContentsOfFile:[NSString stringWithUTF8String:path]
279 [self->soundsByPath setObject:sound
280 forKey:token_string];
285 /* Store it if we loaded it */
287 [soundSamples addObject:sound];
290 /* Figure out next token */
291 cur_token = next_token;
293 /* Try to find a space */
294 search = strchr(cur_token, ' ');
297 * If we can find one, terminate, and set new "next".
301 next_token = search + 1;
303 /* Otherwise prevent infinite looping */
316 NSMutableArray *samples =
317 [self->soundArraysByEvent
318 objectForKey:[NSNumber numberWithInteger:event]];
320 if (samples == nil || samples.count == 0) {
324 /* Choose a random event. */
325 int s = randint0((int) samples.count);
326 NSSound *sound = samples[s];
328 if ([sound isPlaying])
331 /* Play the sound. */
341 * For sharedSounds and clearSharedSounds.
343 static __strong AngbandSoundCatalog* gSharedSounds = nil;
345 + (AngbandSoundCatalog*)sharedSounds {
346 if (gSharedSounds == nil) {
347 gSharedSounds = [[AngbandSoundCatalog alloc] init];
349 return gSharedSounds;;
352 + (void)clearSharedSounds {
359 * To handle fonts where an individual glyph's bounding box can extend into
360 * neighboring columns, Term_curs_cocoa(), Term_pict_cocoa(),
361 * Term_text_cocoa(), and Term_wipe_cocoa() merely record what needs to be
362 * done with the actual drawing happening in response to the notification to
363 * flush all rows, the TERM_XTRA_FRESH case in Term_xtra_cocoa(). Can not use
364 * the TERM_XTRA_FROSH notification (the per-row flush), since with a software
365 * cursor, there are calls to Term_pict_cocoa(), Term_text_cocoa(), or
366 * Term_wipe_cocoa() to take care of the old cursor position which are not
367 * followed by a row flush.
369 enum PendingCellChangeType {
370 CELL_CHANGE_NONE = 0,
375 struct PendingTextChange {
379 * Is YES if glyph is a character that takes up two columns (i.e.
380 * Japanese kanji); otherwise it is NO.
384 struct PendingTileChange {
385 char fgdCol, fgdRow, bckCol, bckRow;
387 struct PendingCellChange {
388 union { struct PendingTextChange txc; struct PendingTileChange tic; } v;
389 enum PendingCellChangeType changeType;
392 @interface PendingTermChanges : NSObject {
395 struct PendingCellChange **changesByRow;
399 * Returns YES if nCol and nRow are a feasible size for the pending changes.
400 * Otherwise, returns NO.
402 + (BOOL)isValidSize:(int)nCol rows:(int)nRow;
405 * Initialize with zero columns and zero rows.
410 * Initialize with nCol columns and nRow rows. No changes will be marked.
412 - (id)initWithColumnsRows:(int)nCol rows:(int)nRow NS_DESIGNATED_INITIALIZER;
415 * Clears all marked changes.
420 * Changes the bounds over which changes are recorded. Has the side effect
421 * of clearing any marked changes. Will throw an exception if nCol or nRow
424 - (void)resize:(int)nCol rows:(int)nRow;
427 * Mark the cell, (iCol, iRow), as having changed text.
429 - (void)markTextChange:(int)iCol row:(int)iRow glyph:(wchar_t)g color:(int)c
430 isDoubleWidth:(BOOL)dw;
433 * Mark the cell, (iCol, iRow), as having a changed tile.
435 - (void)markTileChange:(int)iCol row:(int)iRow
436 foregroundCol:(char)fc foregroundRow:(char)fr
437 backgroundCol:(char)bc backgroundRow:(char)br;
440 * Mark the cells from (iCol, iRow) to (iCol + nCol - 1, iRow) as wiped.
442 - (void)markWipeRange:(int)iCol row:(int)iRow n:(int)nCol;
445 * Mark the location of the cursor. The cursor will be the standard size:
448 - (void)markCursor:(int)iCol row:(int)iRow;
451 * Mark the location of the cursor. The cursor will be w cells wide and
452 * h cells tall and the given location is the position of the upper left
455 - (void)markBigCursor:(int)iCol row:(int)iRow
456 cellsWide:(int)w cellsHigh:(int)h;
459 * Return the zero-based index of the first column changed for the given
460 * zero-based row index. If there are no changes in the row, the returned
461 * value will be the number of columns.
463 - (int)getFirstChangedColumnInRow:(int)iRow;
466 * Return the zero-based index of the last column changed for the given
467 * zero-based row index. If there are no changes in the row, the returned
470 - (int)getLastChangedColumnInRow:(int)iRow;
473 * Return the type of change at the given cell, (iCol, iRow).
475 - (enum PendingCellChangeType)getCellChangeType:(int)iCol row:(int)iRow;
478 * Return the nature of a text change at the given cell, (iCol, iRow).
479 * Will throw an exception if [obj getCellChangeType:iCol row:iRow] is
480 * neither CELL_CHANGE_TEXT nor CELL_CHANGE_WIPE.
482 - (struct PendingTextChange)getCellTextChange:(int)iCol row:(int)iRow;
485 * Return the nature of a tile change at the given cell, (iCol, iRow).
486 * Will throw an exception if [obj getCellChangeType:iCol row:iRow] is
487 * different than CELL_CHANGE_TILE.
489 - (struct PendingTileChange)getCellTileChange:(int)iCol row:(int)iRow;
492 * Is the number of columns for recording changes.
494 @property (readonly) int columnCount;
497 * Is the number of rows for recording changes.
499 @property (readonly) int rowCount;
502 * Will be YES if there are any pending changes to locations rendered as text.
503 * Otherwise, it will be NO.
505 @property (readonly) BOOL hasTextChanges;
508 * Will be YES if there are any pending changes to locations rendered as tiles.
509 * Otherwise, it will be NO.
511 @property (readonly) BOOL hasTileChanges;
514 * Will be YES if there are any pending wipes. Otherwise, it will be NO.
516 @property (readonly) BOOL hasWipeChanges;
519 * Is the zero-based index of the first row with changes. Will be equal to
520 * the number of rows if there are no changes.
522 @property (readonly) int firstChangedRow;
525 * Is the zero-based index of the last row with changes. Will be equal to
526 * -1 if there are no changes.
528 @property (readonly) int lastChangedRow;
531 * Is the zero-based index for the column with the upper left corner of the
532 * cursor. It will be -1 if the cursor position has not been set since the
533 * changes were cleared.
535 @property (readonly) int cursorColumn;
538 * Is the zero-based index for the row with the upper left corner of the
539 * cursor. It will be -1 if the cursor position has not been set since the
540 * changes were cleared.
542 @property (readonly) int cursorRow;
545 * Is the cursor width in number of cells.
547 @property (readonly) int cursorWidth;
550 * Is the cursor height in number of cells.
552 @property (readonly) int cursorHeight;
555 * This is a helper for the mark* messages.
557 - (void)setupForChange:(int)iCol row:(int)iRow n:(int)nCol;
560 * Throw an exception if the given range of column indices is invalid
561 * (including non-positive values for nCol).
563 - (void)checkColumnIndices:(int)iCol n:(int)nCol;
566 * Throw an exception if the given row index is invalid.
568 - (void)checkRowIndex:(int)iRow;
572 @implementation PendingTermChanges
574 + (BOOL)isValidSize:(int)nCol rows:(int)nRow
577 (size_t) nCol > SIZE_MAX / sizeof(struct PendingCellChange) ||
579 (size_t) nRow > SIZE_MAX / sizeof(struct PendingCellChange*) ||
580 (size_t) nRow > SIZE_MAX / (2 * sizeof(int))) {
588 return [self initWithColumnsRows:0 rows:0];
591 - (id)initWithColumnsRows:(int)nCol rows:(int)nRow
593 if (self = [super init]) {
594 if (! [PendingTermChanges isValidSize:nCol rows:nRow]) {
597 self->colBounds = malloc((size_t) 2 * sizeof(int) * nRow);
598 if (self->colBounds == 0 && nRow > 0) {
601 self->changesByRow = calloc(nRow, sizeof(struct PendingCellChange*));
602 if (self->changesByRow == 0 && nRow > 0) {
603 free(self->colBounds);
606 for (int i = 0; i < nRow + nRow; i += 2) {
607 self->colBounds[i] = nCol;
608 self->colBounds[i + 1] = -1;
610 self->_columnCount = nCol;
611 self->_rowCount = nRow;
612 self->_hasTextChanges = NO;
613 self->_hasTileChanges = NO;
614 self->_hasWipeChanges = NO;
615 self->_firstChangedRow = nRow;
616 self->_lastChangedRow = -1;
617 self->_cursorColumn = -1;
618 self->_cursorRow = -1;
619 self->_cursorWidth = 1;
620 self->_cursorHeight = 1;
627 if (self->changesByRow != 0) {
628 for (int i = 0; i < self.rowCount; ++i) {
629 if (self->changesByRow[i] != 0) {
630 free(self->changesByRow[i]);
631 self->changesByRow[i] = 0;
634 free(self->changesByRow);
635 self->changesByRow = 0;
637 if (self->colBounds != 0) {
638 free(self->colBounds);
645 for (int i = 0; i < self.rowCount; ++i) {
646 self->colBounds[i + i] = self.columnCount;
647 self->colBounds[i + i + 1] = -1;
648 if (self->changesByRow[i] != 0) {
649 free(self->changesByRow[i]);
650 self->changesByRow[i] = 0;
653 self->_hasTextChanges = NO;
654 self->_hasTileChanges = NO;
655 self->_hasWipeChanges = NO;
656 self->_firstChangedRow = self.rowCount;
657 self->_lastChangedRow = -1;
658 self->_cursorColumn = -1;
659 self->_cursorRow = -1;
660 self->_cursorWidth = 1;
661 self->_cursorHeight = 1;
664 - (void)resize:(int)nCol rows:(int)nRow
666 if (! [PendingTermChanges isValidSize:nCol rows:nRow]) {
667 NSException *exc = [NSException
668 exceptionWithName:@"PendingTermChangesRowsColumns"
669 reason:@"resize called with number of columns or rows that is negative or too large"
674 int *cb = malloc((size_t) 2 * sizeof(int) * nRow);
675 struct PendingCellChange** cbr =
676 calloc(nRow, sizeof(struct PendingCellChange*));
679 if ((cb == 0 || cbr == 0) && nRow > 0) {
687 NSException *exc = [NSException
688 exceptionWithName:@"OutOfMemory"
689 reason:@"resize called for PendingTermChanges"
694 for (i = 0; i < nRow; ++i) {
698 if (self->changesByRow != 0) {
699 for (i = 0; i < self.rowCount; ++i) {
700 if (self->changesByRow[i] != 0) {
701 free(self->changesByRow[i]);
702 self->changesByRow[i] = 0;
705 free(self->changesByRow);
707 if (self->colBounds != 0) {
708 free(self->colBounds);
711 self->colBounds = cb;
712 self->changesByRow = cbr;
713 self->_columnCount = nCol;
714 self->_rowCount = nRow;
715 self->_hasTextChanges = NO;
716 self->_hasTileChanges = NO;
717 self->_hasWipeChanges = NO;
718 self->_firstChangedRow = self.rowCount;
719 self->_lastChangedRow = -1;
720 self->_cursorColumn = -1;
721 self->_cursorRow = -1;
722 self->_cursorWidth = 1;
723 self->_cursorHeight = 1;
726 - (void)markTextChange:(int)iCol row:(int)iRow glyph:(wchar_t)g color:(int)c
727 isDoubleWidth:(BOOL)dw
729 [self setupForChange:iCol row:iRow n:((dw) ? 2 : 1)];
730 struct PendingCellChange *pcc = self->changesByRow[iRow] + iCol;
731 pcc->v.txc.glyph = g;
732 pcc->v.txc.color = c;
733 pcc->v.txc.doubleWidth = dw;
734 pcc->changeType = CELL_CHANGE_TEXT;
736 * Fill in a dummy since the previous character will take up two columns.
739 pcc[1].v.txc.glyph = 0;
740 pcc[1].v.txc.color = c;
741 pcc[1].v.txc.doubleWidth = NO;
742 pcc[1].changeType = CELL_CHANGE_TEXT;
744 self->_hasTextChanges = YES;
747 - (void)markTileChange:(int)iCol row:(int)iRow
748 foregroundCol:(char)fc foregroundRow:(char)fr
749 backgroundCol:(char)bc backgroundRow:(char)br
751 [self setupForChange:iCol row:iRow n:1];
752 struct PendingCellChange *pcc = self->changesByRow[iRow] + iCol;
753 pcc->v.tic.fgdCol = fc;
754 pcc->v.tic.fgdRow = fr;
755 pcc->v.tic.bckCol = bc;
756 pcc->v.tic.bckRow = br;
757 pcc->changeType = CELL_CHANGE_TILE;
758 self->_hasTileChanges = YES;
761 - (void)markWipeRange:(int)iCol row:(int)iRow n:(int)nCol
763 [self setupForChange:iCol row:iRow n:nCol];
764 struct PendingCellChange *pcc = self->changesByRow[iRow] + iCol;
765 for (int i = 0; i < nCol; ++i) {
766 pcc[i].v.txc.glyph = 0;
767 pcc[i].v.txc.color = 0;
768 pcc[i].changeType = CELL_CHANGE_WIPE;
770 self->_hasWipeChanges = YES;
773 - (void)markCursor:(int)iCol row:(int)iRow
775 /* Allow negative indices to indicate an invalid cursor. */
776 [self checkColumnIndices:((iCol >= 0) ? iCol : 0) n:1];
777 [self checkRowIndex:((iRow >= 0) ? iRow : 0)];
778 self->_cursorColumn = iCol;
779 self->_cursorRow = iRow;
780 self->_cursorWidth = 1;
781 self->_cursorHeight = 1;
784 - (void)markBigCursor:(int)iCol row:(int)iRow
785 cellsWide:(int)w cellsHigh:(int)h
787 /* Allow negative indices to indicate an invalid cursor. */
788 [self checkColumnIndices:((iCol >= 0) ? iCol : 0) n:1];
789 [self checkRowIndex:((iRow >= 0) ? iRow : 0)];
790 if (w < 1 || h < 1) {
791 NSException *exc = [NSException
792 exceptionWithName:@"InvalidCursorDimensions"
793 reason:@"markBigCursor called for PendingTermChanges"
797 self->_cursorColumn = iCol;
798 self->_cursorRow = iRow;
799 self->_cursorWidth = w;
800 self->_cursorHeight = h;
803 - (void)setupForChange:(int)iCol row:(int)iRow n:(int)nCol
805 [self checkColumnIndices:iCol n:nCol];
806 [self checkRowIndex:iRow];
807 if (self->changesByRow[iRow] == 0) {
808 self->changesByRow[iRow] =
809 malloc(self.columnCount * sizeof(struct PendingCellChange));
810 if (self->changesByRow[iRow] == 0 && self.columnCount > 0) {
811 NSException *exc = [NSException
812 exceptionWithName:@"OutOfMemory"
813 reason:@"setupForChange called for PendingTermChanges"
817 struct PendingCellChange* pcc = self->changesByRow[iRow];
818 for (int i = 0; i < self.columnCount; ++i) {
819 pcc[i].changeType = CELL_CHANGE_NONE;
822 if (self.firstChangedRow > iRow) {
823 self->_firstChangedRow = iRow;
825 if (self.lastChangedRow < iRow) {
826 self->_lastChangedRow = iRow;
828 if ([self getFirstChangedColumnInRow:iRow] > iCol) {
829 self->colBounds[iRow + iRow] = iCol;
831 if ([self getLastChangedColumnInRow:iRow] < iCol + nCol - 1) {
832 self->colBounds[iRow + iRow + 1] = iCol + nCol - 1;
836 - (int)getFirstChangedColumnInRow:(int)iRow
838 [self checkRowIndex:iRow];
839 return self->colBounds[iRow + iRow];
842 - (int)getLastChangedColumnInRow:(int)iRow
844 [self checkRowIndex:iRow];
845 return self->colBounds[iRow + iRow + 1];
848 - (enum PendingCellChangeType)getCellChangeType:(int)iCol row:(int)iRow
850 [self checkColumnIndices:iCol n:1];
851 [self checkRowIndex:iRow];
852 if (iRow < self.firstChangedRow || iRow > self.lastChangedRow) {
853 return CELL_CHANGE_NONE;
855 if (iCol < [self getFirstChangedColumnInRow:iRow] ||
856 iCol > [self getLastChangedColumnInRow:iRow]) {
857 return CELL_CHANGE_NONE;
859 return self->changesByRow[iRow][iCol].changeType;
862 - (struct PendingTextChange)getCellTextChange:(int)iCol row:(int)iRow
864 [self checkColumnIndices:iCol n:1];
865 [self checkRowIndex:iRow];
866 if (iRow < self.firstChangedRow || iRow > self.lastChangedRow ||
867 iCol < [self getFirstChangedColumnInRow:iRow] ||
868 iCol > [self getLastChangedColumnInRow:iRow] ||
869 (self->changesByRow[iRow][iCol].changeType != CELL_CHANGE_TEXT &&
870 self->changesByRow[iRow][iCol].changeType != CELL_CHANGE_WIPE)) {
871 NSException *exc = [NSException
872 exceptionWithName:@"NotTextChange"
873 reason:@"getCellTextChange called for PendingTermChanges"
877 return self->changesByRow[iRow][iCol].v.txc;
880 - (struct PendingTileChange)getCellTileChange:(int)iCol row:(int)iRow
882 [self checkColumnIndices:iCol n:1];
883 [self checkRowIndex:iRow];
884 if (iRow < self.firstChangedRow || iRow > self.lastChangedRow ||
885 iCol < [self getFirstChangedColumnInRow:iRow] ||
886 iCol > [self getLastChangedColumnInRow:iRow] ||
887 self->changesByRow[iRow][iCol].changeType != CELL_CHANGE_TILE) {
888 NSException *exc = [NSException
889 exceptionWithName:@"NotTileChange"
890 reason:@"getCellTileChange called for PendingTermChanges"
894 return self->changesByRow[iRow][iCol].v.tic;
897 - (void)checkColumnIndices:(int)iCol n:(int)nCol
900 NSException *exc = [NSException
901 exceptionWithName:@"InvalidColumnIndex"
902 reason:@"negative column index"
906 if (iCol >= self.columnCount || iCol + nCol > self.columnCount) {
907 NSException *exc = [NSException
908 exceptionWithName:@"InvalidColumnIndex"
909 reason:@"column index exceeds number of columns"
914 NSException *exc = [NSException
915 exceptionWithName:@"InvalidColumnIndex"
916 reason:@"empty column range"
922 - (void)checkRowIndex:(int)iRow
925 NSException *exc = [NSException
926 exceptionWithName:@"InvalidRowIndex"
927 reason:@"negative row index"
931 if (iRow >= self.rowCount) {
932 NSException *exc = [NSException
933 exceptionWithName:@"InvalidRowIndex"
934 reason:@"row index exceeds number of rows"
943 /* The max number of glyphs we support. Currently this only affects
944 * updateGlyphInfo() for the calculation of the tile size, fontAscender,
945 * fontDescender, nColPre, and nColPost. The rendering in drawWChar() will
946 * work for a glyph not in updateGlyphInfo()'s set, and that is used for
947 * rendering Japanese characters, though there may be clipping or clearing
948 * artifacts because it wasn't included in updateGlyphInfo()'s calculations.
950 #define GLYPH_COUNT 256
952 /* An AngbandContext represents a logical Term (i.e. what Angband thinks is
953 * a window). This typically maps to one NSView, but may map to more than one
954 * NSView (e.g. the Test and real screen saver view). */
955 @interface AngbandContext : NSObject <NSWindowDelegate>
959 /* The Angband term */
963 /* Is the last time we drew, so we can throttle drawing. */
964 CFAbsoluteTime lastRefreshTime;
967 * Whether we are currently in live resize, which affects how big we
972 /* Flags whether or not a fullscreen transition is in progress. */
973 BOOL inFullscreenTransition;
976 /* Column and row counts, by default 80 x 24 */
980 /* The size of the border between the window edge and the contents */
981 @property (readonly) NSSize borderSize;
983 /* Our array of views */
984 @property NSMutableArray *angbandViews;
986 /* The buffered image */
987 @property CGLayerRef angbandLayer;
989 /* The font of this context */
990 @property NSFont *angbandViewFont;
992 /* The size of one tile */
993 @property (readonly) NSSize tileSize;
995 /* Font's ascender and descender */
996 @property (readonly) CGFloat fontAscender;
997 @property (readonly) CGFloat fontDescender;
1000 * These are the number of columns before or after, respectively, a text
1001 * change that may need to be redrawn.
1003 @property (readonly) int nColPre;
1004 @property (readonly) int nColPost;
1006 /* If this context owns a window, here it is. */
1007 @property NSWindow *primaryWindow;
1009 /* Is the record of changes to the contents for the next update. */
1010 @property PendingTermChanges *changes;
1012 @property (nonatomic, assign) BOOL hasSubwindowFlags;
1013 @property (nonatomic, assign) BOOL windowVisibilityChecked;
1015 - (void)drawRect:(NSRect)rect inView:(NSView *)view;
1017 /* Called at initialization to set the term */
1018 - (void)setTerm:(term *)t;
1020 /* Called when the context is going down. */
1023 /* Returns the size of the image. */
1024 - (NSSize)imageSize;
1026 /* Return the rect for a tile at given coordinates. */
1027 - (NSRect)rectInImageForTileAtX:(int)x Y:(int)y;
1029 /* Draw the given wide character into the given tile rect. */
1030 - (void)drawWChar:(wchar_t)wchar inRect:(NSRect)tile context:(CGContextRef)ctx;
1032 /* Locks focus on the Angband image, and scales the CTM appropriately. */
1033 - (CGContextRef)lockFocus;
1035 /* Locks focus on the Angband image but does NOT scale the CTM. Appropriate
1036 * for drawing hairlines. */
1037 - (CGContextRef)lockFocusUnscaled;
1039 /* Unlocks focus. */
1040 - (void)unlockFocus;
1042 /* Returns the primary window for this angband context, creating it if
1044 - (NSWindow *)makePrimaryWindow;
1046 /* Called to add a new Angband view */
1047 - (void)addAngbandView:(AngbandView *)view;
1049 /* Make the context aware that one of its views changed size */
1050 - (void)angbandViewDidScale:(AngbandView *)view;
1052 /* Handle becoming the main window */
1053 - (void)windowDidBecomeMain:(NSNotification *)notification;
1055 /* Return whether the context's primary window is ordered in or not */
1056 - (BOOL)isOrderedIn;
1058 /* Return whether the context's primary window is key */
1059 - (BOOL)isMainWindow;
1061 /* Invalidate the whole image */
1062 - (void)setNeedsDisplay:(BOOL)val;
1064 /* Invalidate part of the image, with the rect expressed in base coordinates */
1065 - (void)setNeedsDisplayInBaseRect:(NSRect)rect;
1067 /* Display (flush) our Angband views */
1068 - (void)displayIfNeeded;
1070 /* Resize context to size of contentRect, and optionally save size to
1072 - (void)resizeTerminalWithContentRect: (NSRect)contentRect saveToDefaults: (BOOL)saveToDefaults;
1075 * Change the minimum size for the window associated with the context.
1076 * termIdx is the index for the terminal: pass it so this function can be
1077 * used when self->terminal has not yet been set.
1079 - (void)setMinimumWindowSize:(int)termIdx;
1081 /* Called from the view to indicate that it is starting or ending live resize */
1082 - (void)viewWillStartLiveResize:(AngbandView *)view;
1083 - (void)viewDidEndLiveResize:(AngbandView *)view;
1084 - (void)saveWindowVisibleToDefaults: (BOOL)windowVisible;
1085 - (BOOL)windowVisibleUsingDefaults;
1089 * Gets the default font for all contexts. Currently not declaring this as
1090 * a class property for compatibility with versions of Xcode prior to 8.
1092 + (NSFont*)defaultFont;
1094 * Sets the default font for all contexts.
1096 + (void)setDefaultFont:(NSFont*)font;
1098 /* Internal method */
1099 - (AngbandView *)activeView;
1104 * Generate a mask for the subwindow flags. The mask is just a safety check to
1105 * make sure that our windows show and hide as expected. This function allows
1106 * for future changes to the set of flags without needed to update it here
1107 * (unless the underlying types change).
1109 u32b AngbandMaskForValidSubwindowFlags(void)
1111 int windowFlagBits = sizeof(*(window_flag)) * CHAR_BIT;
1112 int maxBits = MIN( 16, windowFlagBits );
1115 for( int i = 0; i < maxBits; i++ )
1117 if( window_flag_desc[i] != NULL )
1127 * Check for changes in the subwindow flags and update window visibility.
1128 * This seems to be called for every user event, so we don't
1129 * want to do any unnecessary hiding or showing of windows.
1131 static void AngbandUpdateWindowVisibility(void)
1133 /* Because this function is called frequently, we'll make the mask static.
1134 * It doesn't change between calls, as the flags themselves are hardcoded */
1135 static u32b validWindowFlagsMask = 0;
1137 if( validWindowFlagsMask == 0 )
1139 validWindowFlagsMask = AngbandMaskForValidSubwindowFlags();
1142 /* Loop through all of the subwindows and see if there is a change in the
1143 * flags. If so, show or hide the corresponding window. We don't care about
1144 * the flags themselves; we just want to know if any are set. */
1145 for( int i = 1; i < ANGBAND_TERM_MAX; i++ )
1147 AngbandContext *angbandContext =
1148 (__bridge AngbandContext*) (angband_term[i]->data);
1150 if( angbandContext == nil )
1155 /* This horrible mess of flags is so that we can try to maintain some
1156 * user visibility preference. This should allow the user a window and
1157 * have it stay closed between application launches. However, this
1158 * means that when a subwindow is turned on, it will no longer appear
1159 * automatically. Angband has no concept of user control over window
1160 * visibility, other than the subwindow flags. */
1161 if( !angbandContext.windowVisibilityChecked )
1163 if( [angbandContext windowVisibleUsingDefaults] )
1165 [angbandContext.primaryWindow orderFront: nil];
1166 angbandContext.windowVisibilityChecked = YES;
1170 [angbandContext.primaryWindow close];
1171 angbandContext.windowVisibilityChecked = NO;
1176 BOOL termHasSubwindowFlags = ((window_flag[i] & validWindowFlagsMask) > 0);
1178 if( angbandContext.hasSubwindowFlags && !termHasSubwindowFlags )
1180 [angbandContext.primaryWindow close];
1181 angbandContext.hasSubwindowFlags = NO;
1182 [angbandContext saveWindowVisibleToDefaults: NO];
1184 else if( !angbandContext.hasSubwindowFlags && termHasSubwindowFlags )
1186 [angbandContext.primaryWindow orderFront: nil];
1187 angbandContext.hasSubwindowFlags = YES;
1188 [angbandContext saveWindowVisibleToDefaults: YES];
1193 /* Make the main window key so that user events go to the right spot */
1194 AngbandContext *mainWindow =
1195 (__bridge AngbandContext*) (angband_term[0]->data);
1196 [mainWindow.primaryWindow makeKeyAndOrderFront: nil];
1201 * ------------------------------------------------------------------------
1203 * ------------------------------------------------------------------------ */
1208 static CGImageRef pict_image;
1211 * Numbers of rows and columns in a tileset,
1212 * calculated by the PICT/PNG loading code
1214 static int pict_cols = 0;
1215 static int pict_rows = 0;
1218 * Requested graphics mode (as a grafID).
1219 * The current mode is stored in current_graphics_mode.
1221 static int graf_mode_req = 0;
1224 * Helper function to check the various ways that graphics can be enabled,
1225 * guarding against NULL
1227 static BOOL graphics_are_enabled(void)
1229 return current_graphics_mode
1230 && current_graphics_mode->grafID != GRAPHICS_NONE;
1234 * Hack -- game in progress
1236 static Boolean game_in_progress = FALSE;
1239 #pragma mark Prototypes
1240 static void wakeup_event_loop(void);
1241 static void hook_plog(const char *str);
1242 static void hook_quit(const char * str);
1243 static NSString* get_lib_directory(void);
1244 static NSString* get_doc_directory(void);
1245 static NSString* AngbandCorrectedDirectoryPath(NSString *originalPath);
1246 static void prepare_paths_and_directories(void);
1247 static void handle_open_when_ready(void);
1248 static void play_sound(int event);
1249 static BOOL check_events(int wait);
1250 static BOOL send_event(NSEvent *event);
1251 static void record_current_savefile(void);
1253 static wchar_t convert_two_byte_eucjp_to_utf16_native(const char *cp);
1257 * Available values for 'wait'
1259 #define CHECK_EVENTS_DRAIN -1
1260 #define CHECK_EVENTS_NO_WAIT 0
1261 #define CHECK_EVENTS_WAIT 1
1265 * Note when "open"/"new" become valid
1267 static bool initialized = FALSE;
1269 /* Methods for getting the appropriate NSUserDefaults */
1270 @interface NSUserDefaults (AngbandDefaults)
1271 + (NSUserDefaults *)angbandDefaults;
1274 @implementation NSUserDefaults (AngbandDefaults)
1275 + (NSUserDefaults *)angbandDefaults
1277 return [NSUserDefaults standardUserDefaults];
1281 /* Methods for pulling images out of the Angband bundle (which may be separate
1282 * from the current bundle in the case of a screensaver */
1283 @interface NSImage (AngbandImages)
1284 + (NSImage *)angbandImage:(NSString *)name;
1287 /* The NSView subclass that draws our Angband image */
1288 @interface AngbandView : NSView
1290 AngbandContext *angbandContext;
1293 - (void)setAngbandContext:(AngbandContext *)context;
1294 - (AngbandContext *)angbandContext;
1298 @implementation NSImage (AngbandImages)
1300 /* Returns an image in the resource directoy of the bundle containing the
1301 * Angband view class. */
1302 + (NSImage *)angbandImage:(NSString *)name
1304 NSBundle *bundle = [NSBundle bundleForClass:[AngbandView class]];
1305 NSString *path = [bundle pathForImageResource:name];
1306 return (path) ? [[NSImage alloc] initByReferencingFile:path] : nil;
1312 @implementation AngbandContext
1314 @synthesize hasSubwindowFlags=_hasSubwindowFlags;
1315 @synthesize windowVisibilityChecked=_windowVisibilityChecked;
1317 - (BOOL)useLiveResizeOptimization
1319 /* If we have graphics turned off, text rendering is fast enough that we
1320 * don't need to use a live resize optimization. */
1321 return self->inLiveResize && graphics_are_enabled();
1326 /* We round the base size down. If we round it up, I believe we may end up
1327 * with pixels that nobody "owns" that may accumulate garbage. In general
1328 * rounding down is harmless, because any lost pixels may be sopped up by
1331 floor(self.cols * self.tileSize.width + 2 * self.borderSize.width),
1332 floor(self.rows * self.tileSize.height + 2 * self.borderSize.height));
1335 /* qsort-compatible compare function for CGSizes */
1336 static int compare_advances(const void *ap, const void *bp)
1338 const CGSize *a = ap, *b = bp;
1339 return (a->width > b->width) - (a->width < b->width);
1343 * Precompute certain metrics (tileSize, fontAscender, fontDescender, nColPre,
1344 * and nColPost) for the current font.
1346 - (void)updateGlyphInfo
1348 NSFont *screenFont = [self.angbandViewFont screenFont];
1350 /* Generate a string containing each MacRoman character */
1352 * Here and below, dynamically allocate working arrays rather than put them
1353 * on the stack in case limited stack space is an issue.
1355 unsigned char *latinString = malloc(GLYPH_COUNT);
1356 if (latinString == 0) {
1357 NSException *exc = [NSException exceptionWithName:@"OutOfMemory"
1358 reason:@"latinString in updateGlyphInfo"
1363 for (i=0; i < GLYPH_COUNT; i++) latinString[i] = (unsigned char)i;
1365 /* Turn that into unichar. Angband uses ISO Latin 1. */
1366 NSString *allCharsString = [[NSString alloc] initWithBytes:latinString length:sizeof latinString encoding:NSISOLatin1StringEncoding];
1367 unichar *unicharString = malloc(GLYPH_COUNT * sizeof(unichar));
1368 if (unicharString == 0) {
1370 NSException *exc = [NSException exceptionWithName:@"OutOfMemory"
1371 reason:@"unicharString in updateGlyphInfo"
1375 unicharString[0] = 0;
1376 [allCharsString getCharacters:unicharString range:NSMakeRange(0, MIN(GLYPH_COUNT, [allCharsString length]))];
1377 allCharsString = nil;
1381 CGGlyph *glyphArray = calloc(GLYPH_COUNT, sizeof(CGGlyph));
1382 if (glyphArray == 0) {
1383 free(unicharString);
1384 NSException *exc = [NSException exceptionWithName:@"OutOfMemory"
1385 reason:@"glyphArray in updateGlyphInfo"
1389 CTFontGetGlyphsForCharacters((CTFontRef)screenFont, unicharString,
1390 glyphArray, GLYPH_COUNT);
1391 free(unicharString);
1393 /* Get advances. Record the max advance. */
1394 CGSize *advances = malloc(GLYPH_COUNT * sizeof(CGSize));
1395 if (advances == 0) {
1397 NSException *exc = [NSException exceptionWithName:@"OutOfMemory"
1398 reason:@"advances in updateGlyphInfo"
1402 CTFontGetAdvancesForGlyphs(
1403 (CTFontRef)screenFont, kCTFontHorizontalOrientation, glyphArray,
1404 advances, GLYPH_COUNT);
1405 CGFloat *glyphWidths = malloc(GLYPH_COUNT * sizeof(CGFloat));
1406 if (glyphWidths == 0) {
1409 NSException *exc = [NSException exceptionWithName:@"OutOfMemory"
1410 reason:@"glyphWidths in updateGlyphInfo"
1414 for (i=0; i < GLYPH_COUNT; i++) {
1415 glyphWidths[i] = advances[i].width;
1418 /* For good non-mono-font support, use the median advance. Start by sorting
1420 qsort(advances, GLYPH_COUNT, sizeof *advances, compare_advances);
1422 /* Skip over any initially empty run */
1424 for (startIdx = 0; startIdx < GLYPH_COUNT; startIdx++)
1426 if (advances[startIdx].width > 0) break;
1429 /* Pick the center to find the median */
1430 CGFloat medianAdvance = 0;
1431 if (startIdx < GLYPH_COUNT)
1433 /* In case we have all zero advances for some reason */
1434 medianAdvance = advances[(startIdx + GLYPH_COUNT)/2].width;
1440 * Record the ascender and descender. Some fonts, for instance DIN
1441 * Condensed and Rockwell in 10.14, the ascent on '@' exceeds that
1442 * reported by [screenFont ascender]. Get the overall bounding box
1443 * for the glyphs and use that instead of the ascender and descender
1444 * values if the bounding box result extends farther from the baseline.
1446 CGRect bounds = CTFontGetBoundingRectsForGlyphs(
1447 (CTFontRef) screenFont, kCTFontHorizontalOrientation, glyphArray,
1449 self->_fontAscender = [screenFont ascender];
1450 if (self->_fontAscender < bounds.origin.y + bounds.size.height) {
1451 self->_fontAscender = bounds.origin.y + bounds.size.height;
1453 self->_fontDescender = [screenFont descender];
1454 if (self->_fontDescender > bounds.origin.y) {
1455 self->_fontDescender = bounds.origin.y;
1459 * Record the tile size. Round both values up to have tile boundaries
1460 * match pixel boundaries.
1462 self->_tileSize.width = ceil(medianAdvance);
1463 self->_tileSize.height = ceil(self.fontAscender - self.fontDescender);
1466 * Determine whether neighboring columns need to be redrawn when a
1467 * character changes.
1469 CGRect *boxes = malloc(GLYPH_COUNT * sizeof(CGRect));
1473 NSException *exc = [NSException exceptionWithName:@"OutOfMemory"
1474 reason:@"boxes in updateGlyphInfo"
1478 CGFloat beyond_right = 0.;
1479 CGFloat beyond_left = 0.;
1480 CTFontGetBoundingRectsForGlyphs(
1481 (CTFontRef)screenFont,
1482 kCTFontHorizontalOrientation,
1486 for (i = 0; i < GLYPH_COUNT; i++) {
1487 /* Account for the compression and offset used by drawWChar(). */
1488 CGFloat compression, offset;
1491 if (glyphWidths[i] <= self.tileSize.width) {
1493 offset = 0.5 * (self.tileSize.width - glyphWidths[i]);
1495 compression = self.tileSize.width / glyphWidths[i];
1498 v = (offset + boxes[i].origin.x) * compression;
1499 if (beyond_left > v) {
1502 v = (offset + boxes[i].origin.x + boxes[i].size.width) * compression;
1503 if (beyond_right < v) {
1508 self->_nColPre = ceil(-beyond_left / self.tileSize.width);
1509 if (beyond_right > self.tileSize.width) {
1511 ceil((beyond_right - self.tileSize.width) / self.tileSize.width);
1513 self->_nColPost = 0;
1522 NSSize size = NSMakeSize(1, 1);
1524 AngbandView *activeView = [self activeView];
1527 /* If we are in live resize, draw as big as the screen, so we can scale
1528 * nicely to any size. If we are not in live resize, then use the
1529 * bounds of the active view. */
1531 if ([self useLiveResizeOptimization] && (screen = [[activeView window] screen]) != NULL)
1533 size = [screen frame].size;
1537 size = [activeView bounds].size;
1541 CGLayerRelease(self.angbandLayer);
1543 /* Use the highest monitor scale factor on the system to work out what
1544 * scale to draw at - not the recommended method, but works where we
1545 * can't easily get the monitor the current draw is occurring on. */
1546 float angbandLayerScale = 1.0;
1547 if ([[NSScreen mainScreen] respondsToSelector:@selector(backingScaleFactor)]) {
1548 for (NSScreen *screen in [NSScreen screens]) {
1549 angbandLayerScale = fmax(angbandLayerScale, [screen backingScaleFactor]);
1553 /* Make a bitmap context as an example for our layer */
1554 CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();
1555 CGContextRef exampleCtx = CGBitmapContextCreate(NULL, 1, 1, 8 /* bits per component */, 48 /* bytesPerRow */, cs, kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Host);
1556 CGColorSpaceRelease(cs);
1558 /* Create the layer at the appropriate size */
1559 size.width = fmax(1, ceil(size.width * angbandLayerScale));
1560 size.height = fmax(1, ceil(size.height * angbandLayerScale));
1562 CGLayerCreateWithContext(exampleCtx, *(CGSize *)&size, NULL);
1564 CFRelease(exampleCtx);
1566 /* Set the new context of the layer to draw at the correct scale */
1567 CGContextRef ctx = CGLayerGetContext(self.angbandLayer);
1568 CGContextScaleCTM(ctx, angbandLayerScale, angbandLayerScale);
1571 [[NSColor blackColor] set];
1572 NSRectFill((NSRect){NSZeroPoint, [self baseSize]});
1576 - (void)requestRedraw
1578 if (! self->terminal) return;
1582 /* Activate the term */
1583 Term_activate(self->terminal);
1585 /* Redraw the contents */
1588 /* Flush the output */
1591 /* Restore the old term */
1595 - (void)setTerm:(term *)t
1600 - (void)viewWillStartLiveResize:(AngbandView *)view
1602 #if USE_LIVE_RESIZE_CACHE
1603 if (self->inLiveResize < INT_MAX) self->inLiveResize++;
1604 else [NSException raise:NSInternalInconsistencyException format:@"inLiveResize overflow"];
1606 if (self->inLiveResize == 1 && graphics_are_enabled())
1610 [self setNeedsDisplay:YES]; /* We'll need to redisplay everything anyways, so avoid creating all those little redisplay rects */
1611 [self requestRedraw];
1616 - (void)viewDidEndLiveResize:(AngbandView *)view
1618 #if USE_LIVE_RESIZE_CACHE
1619 if (self->inLiveResize > 0) self->inLiveResize--;
1620 else [NSException raise:NSInternalInconsistencyException format:@"inLiveResize underflow"];
1622 if (self->inLiveResize == 0 && graphics_are_enabled())
1626 [self setNeedsDisplay:YES]; /* We'll need to redisplay everything anyways, so avoid creating all those little redisplay rects */
1627 [self requestRedraw];
1633 * If we're trying to limit ourselves to a certain number of frames per second,
1634 * then compute how long it's been since we last drew, and then wait until the
1635 * next frame has passed. */
1638 if (frames_per_second > 0)
1640 CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
1641 CFTimeInterval timeSinceLastRefresh = now - self->lastRefreshTime;
1642 CFTimeInterval timeUntilNextRefresh = (1. / (double)frames_per_second) - timeSinceLastRefresh;
1644 if (timeUntilNextRefresh > 0)
1646 usleep((unsigned long)(timeUntilNextRefresh * 1000000.));
1649 self->lastRefreshTime = CFAbsoluteTimeGetCurrent();
1652 - (void)drawWChar:(wchar_t)wchar inRect:(NSRect)tile context:(CGContextRef)ctx
1654 CGFloat tileOffsetY = self.fontAscender;
1655 CGFloat tileOffsetX = 0.0;
1656 NSFont *screenFont = [self.angbandViewFont screenFont];
1657 UniChar unicharString[2] = {(UniChar)wchar, 0};
1659 /* Get glyph and advance */
1660 CGGlyph thisGlyphArray[1] = { 0 };
1661 CGSize advances[1] = { { 0, 0 } };
1662 CTFontGetGlyphsForCharacters((CTFontRef)screenFont, unicharString, thisGlyphArray, 1);
1663 CGGlyph glyph = thisGlyphArray[0];
1664 CTFontGetAdvancesForGlyphs((CTFontRef)screenFont, kCTFontHorizontalOrientation, thisGlyphArray, advances, 1);
1665 CGSize advance = advances[0];
1667 /* If our font is not monospaced, our tile width is deliberately not big
1668 * enough for every character. In that event, if our glyph is too wide, we
1669 * need to compress it horizontally. Compute the compression ratio.
1670 * 1.0 means no compression. */
1671 double compressionRatio;
1672 if (advance.width <= NSWidth(tile))
1674 /* Our glyph fits, so we can just draw it, possibly with an offset */
1675 compressionRatio = 1.0;
1676 tileOffsetX = (NSWidth(tile) - advance.width)/2;
1680 /* Our glyph doesn't fit, so we'll have to compress it */
1681 compressionRatio = NSWidth(tile) / advance.width;
1687 CGAffineTransform textMatrix = CGContextGetTextMatrix(ctx);
1688 CGFloat savedA = textMatrix.a;
1690 /* Set the position */
1691 textMatrix.tx = tile.origin.x + tileOffsetX;
1692 textMatrix.ty = tile.origin.y + tileOffsetY;
1694 /* Maybe squish it horizontally. */
1695 if (compressionRatio != 1.)
1697 textMatrix.a *= compressionRatio;
1700 textMatrix = CGAffineTransformScale( textMatrix, 1.0, -1.0 );
1701 CGContextSetTextMatrix(ctx, textMatrix);
1702 CGContextShowGlyphsAtPositions(ctx, &glyph, &CGPointZero, 1);
1704 /* Restore the text matrix if we messed with the compression ratio */
1705 if (compressionRatio != 1.)
1707 textMatrix.a = savedA;
1708 CGContextSetTextMatrix(ctx, textMatrix);
1711 textMatrix = CGAffineTransformScale( textMatrix, 1.0, -1.0 );
1712 CGContextSetTextMatrix(ctx, textMatrix);
1715 /* Lock and unlock focus on our image or layer, setting up the CTM
1717 - (CGContextRef)lockFocusUnscaled
1719 /* Create an NSGraphicsContext representing this CGLayer */
1720 CGContextRef ctx = CGLayerGetContext(self.angbandLayer);
1721 NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithGraphicsPort:ctx flipped:NO];
1722 [NSGraphicsContext saveGraphicsState];
1723 [NSGraphicsContext setCurrentContext:context];
1724 CGContextSaveGState(ctx);
1730 /* Restore the graphics state */
1731 CGContextRef ctx = [[NSGraphicsContext currentContext] graphicsPort];
1732 CGContextRestoreGState(ctx);
1733 [NSGraphicsContext restoreGraphicsState];
1738 /* Return the size of our layer */
1739 CGSize result = CGLayerGetSize(self.angbandLayer);
1740 return NSMakeSize(result.width, result.height);
1743 - (CGContextRef)lockFocus
1745 return [self lockFocusUnscaled];
1749 - (NSRect)rectInImageForTileAtX:(int)x Y:(int)y
1752 return NSMakeRect(x * self.tileSize.width + self.borderSize.width,
1753 flippedY * self.tileSize.height + self.borderSize.height,
1754 self.tileSize.width, self.tileSize.height);
1757 - (void)setSelectionFont:(NSFont*)font adjustTerminal: (BOOL)adjustTerminal
1759 /* Record the new font */
1760 self.angbandViewFont = font;
1762 /* Update our glyph info */
1763 [self updateGlyphInfo];
1765 if( adjustTerminal )
1767 /* Adjust terminal to fit window with new font; save the new columns
1768 * and rows since they could be changed */
1769 NSRect contentRect =
1771 contentRectForFrameRect: [self.primaryWindow frame]];
1773 [self setMinimumWindowSize:[self terminalIndex]];
1774 NSSize size = self.primaryWindow.contentMinSize;
1775 BOOL windowNeedsResizing = NO;
1776 if (contentRect.size.width < size.width) {
1777 contentRect.size.width = size.width;
1778 windowNeedsResizing = YES;
1780 if (contentRect.size.height < size.height) {
1781 contentRect.size.height = size.height;
1782 windowNeedsResizing = YES;
1784 if (windowNeedsResizing) {
1785 size.width = contentRect.size.width;
1786 size.height = contentRect.size.height;
1787 [self.primaryWindow setContentSize:size];
1789 [self resizeTerminalWithContentRect: contentRect saveToDefaults: YES];
1792 /* Update our image */
1798 if ((self = [super init]))
1800 /* Default rows and cols */
1804 /* Default border size */
1805 self->_borderSize = NSMakeSize(2, 2);
1807 /* Allocate our array of views */
1808 self->_angbandViews = [[NSMutableArray alloc] init];
1811 self->_nColPost = 0;
1814 [[PendingTermChanges alloc] initWithColumnsRows:self->_cols
1816 self->lastRefreshTime = CFAbsoluteTimeGetCurrent();
1817 self->inLiveResize = 0;
1818 self->inFullscreenTransition = NO;
1820 /* Make the image. Since we have no views, it'll just be a puny 1x1 image. */
1823 self->_windowVisibilityChecked = NO;
1829 * Destroy all the receiver's stuff. This is intended to be callable more than
1834 self->terminal = NULL;
1836 /* Disassociate ourselves from our angbandViews */
1837 [self.angbandViews makeObjectsPerformSelector:@selector(setAngbandContext:) withObject:nil];
1838 self.angbandViews = nil;
1840 /* Destroy the layer/image */
1841 CGLayerRelease(self.angbandLayer);
1842 self.angbandLayer = NULL;
1845 self.angbandViewFont = nil;
1848 [self.primaryWindow setDelegate:nil];
1849 [self.primaryWindow close];
1850 self.primaryWindow = nil;
1852 /* Pending changes */
1856 /* Usual Cocoa fare */
1863 /* From the Linux mbstowcs(3) man page:
1864 * If dest is NULL, n is ignored, and the conversion proceeds as above,
1865 * except that the converted wide characters are not written out to mem‐
1866 * ory, and that no length limit exists.
1868 static size_t Term_mbcs_cocoa(wchar_t *dest, const char *src, int n)
1873 /* Unicode code point to UTF-8
1874 * 0x0000-0x007f: 0xxxxxxx
1875 * 0x0080-0x07ff: 110xxxxx 10xxxxxx
1876 * 0x0800-0xffff: 1110xxxx 10xxxxxx 10xxxxxx
1877 * 0x10000-0x1fffff: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
1878 * Note that UTF-16 limits Unicode to 0x10ffff. This code is not
1881 for (i = 0; i < n || dest == NULL; i++) {
1882 if ((src[i] & 0x80) == 0) {
1883 if (dest != NULL) dest[count] = src[i];
1884 if (src[i] == 0) break;
1885 } else if ((src[i] & 0xe0) == 0xc0) {
1886 if (dest != NULL) dest[count] =
1887 (((unsigned char)src[i] & 0x1f) << 6)|
1888 ((unsigned char)src[i+1] & 0x3f);
1890 } else if ((src[i] & 0xf0) == 0xe0) {
1891 if (dest != NULL) dest[count] =
1892 (((unsigned char)src[i] & 0x0f) << 12) |
1893 (((unsigned char)src[i+1] & 0x3f) << 6) |
1894 ((unsigned char)src[i+2] & 0x3f);
1896 } else if ((src[i] & 0xf8) == 0xf0) {
1897 if (dest != NULL) dest[count] =
1898 (((unsigned char)src[i] & 0x0f) << 18) |
1899 (((unsigned char)src[i+1] & 0x3f) << 12) |
1900 (((unsigned char)src[i+2] & 0x3f) << 6) |
1901 ((unsigned char)src[i+3] & 0x3f);
1904 /* Found an invalid multibyte sequence */
1913 - (void)addAngbandView:(AngbandView *)view
1915 if (! [self.angbandViews containsObject:view])
1917 [self.angbandViews addObject:view];
1919 [self setNeedsDisplay:YES]; /* We'll need to redisplay everything anyways, so avoid creating all those little redisplay rects */
1920 [self requestRedraw];
1925 * For defaultFont and setDefaultFont.
1927 static __strong NSFont* gDefaultFont = nil;
1929 + (NSFont*)defaultFont
1931 return gDefaultFont;
1934 + (void)setDefaultFont:(NSFont*)font
1936 gDefaultFont = font;
1940 * We have this notion of an "active" AngbandView, which is the largest - the
1941 * idea being that in the screen saver, when the user hits Test in System
1942 * Preferences, we don't want to keep driving the AngbandView in the
1943 * background. Our active AngbandView is the widest - that's a hack all right.
1944 * Mercifully when we're just playing the game there's only one view.
1946 - (AngbandView *)activeView
1948 if ([self.angbandViews count] == 1)
1949 return [self.angbandViews objectAtIndex:0];
1951 AngbandView *result = nil;
1953 for (AngbandView *angbandView in self.angbandViews)
1955 float width = [angbandView frame].size.width;
1956 if (width > maxWidth)
1959 result = angbandView;
1965 - (void)angbandViewDidScale:(AngbandView *)view
1967 /* If we're live-resizing with graphics, we're using the live resize
1968 * optimization, so don't update the image. Otherwise do it. */
1969 if (! (self->inLiveResize && graphics_are_enabled()) && view == [self activeView])
1973 [self setNeedsDisplay:YES]; /*we'll need to redisplay everything anyways, so avoid creating all those little redisplay rects */
1974 [self requestRedraw];
1979 - (void)removeAngbandView:(AngbandView *)view
1981 if ([self.angbandViews containsObject:view])
1983 [self.angbandViews removeObject:view];
1985 [self setNeedsDisplay:YES]; /* We'll need to redisplay everything anyways, so avoid creating all those little redisplay rects */
1986 if ([self.angbandViews count]) [self requestRedraw];
1991 - (NSWindow *)makePrimaryWindow
1993 if (! self.primaryWindow)
1995 /* This has to be done after the font is set, which it already is in
1996 * term_init_cocoa() */
1997 NSSize sz = self.baseSize;
1998 NSRect contentRect = NSMakeRect( 0.0, 0.0, sz.width, sz.height );
2000 NSUInteger styleMask = NSTitledWindowMask | NSResizableWindowMask | NSMiniaturizableWindowMask;
2002 /* Make every window other than the main window closable */
2003 if ((__bridge AngbandContext*) (angband_term[0]->data) != self)
2005 styleMask |= NSClosableWindowMask;
2008 self.primaryWindow = [[NSWindow alloc] initWithContentRect:contentRect styleMask: styleMask backing:NSBackingStoreBuffered defer:YES];
2010 /* Not to be released when closed */
2011 [self.primaryWindow setReleasedWhenClosed:NO];
2012 [self.primaryWindow setExcludedFromWindowsMenu: YES]; /* we're using custom window menu handling */
2015 AngbandView *angbandView = [[AngbandView alloc] initWithFrame:contentRect];
2016 [angbandView setAngbandContext:self];
2017 [self.angbandViews addObject:angbandView];
2018 [self.primaryWindow setContentView:angbandView];
2020 /* We are its delegate */
2021 [self.primaryWindow setDelegate:self];
2023 /* Update our image, since this is probably the first angband view
2027 return self.primaryWindow;
2032 #pragma mark View/Window Passthrough
2035 * This is what our views call to get us to draw to the window
2037 - (void)drawRect:(NSRect)rect inView:(NSView *)view
2039 /* Take this opportunity to throttle so we don't flush faster than desired.
2041 BOOL viewInLiveResize = [view inLiveResize];
2042 if (! viewInLiveResize) [self throttle];
2044 /* With a GLayer, use CGContextDrawLayerInRect */
2045 CGContextRef context = [[NSGraphicsContext currentContext] graphicsPort];
2046 NSRect bounds = [view bounds];
2047 if (viewInLiveResize) CGContextSetInterpolationQuality(context, kCGInterpolationLow);
2048 CGContextSetBlendMode(context, kCGBlendModeCopy);
2049 CGContextDrawLayerInRect(context, *(CGRect *)&bounds, self.angbandLayer);
2050 if (viewInLiveResize) CGContextSetInterpolationQuality(context, kCGInterpolationDefault);
2055 return [[[self.angbandViews lastObject] window] isVisible];
2058 - (BOOL)isMainWindow
2060 return [[[self.angbandViews lastObject] window] isMainWindow];
2063 - (void)setNeedsDisplay:(BOOL)val
2065 for (NSView *angbandView in self.angbandViews)
2067 [angbandView setNeedsDisplay:val];
2071 - (void)setNeedsDisplayInBaseRect:(NSRect)rect
2073 for (NSView *angbandView in self.angbandViews)
2075 [angbandView setNeedsDisplayInRect: rect];
2079 - (void)displayIfNeeded
2081 [[self activeView] displayIfNeeded];
2084 - (int)terminalIndex
2088 for( termIndex = 0; termIndex < ANGBAND_TERM_MAX; termIndex++ )
2090 if( angband_term[termIndex] == self->terminal )
2099 - (void)resizeTerminalWithContentRect: (NSRect)contentRect saveToDefaults: (BOOL)saveToDefaults
2101 CGFloat newRows = floor(
2102 (contentRect.size.height - (self.borderSize.height * 2.0)) /
2103 self.tileSize.height);
2104 CGFloat newColumns = ceil(
2105 (contentRect.size.width - (self.borderSize.width * 2.0)) /
2106 self.tileSize.width);
2108 if (newRows < 1 || newColumns < 1) return;
2109 self->_cols = newColumns;
2110 self->_rows = newRows;
2111 [self.changes resize:self.cols rows:self.rows];
2113 if( saveToDefaults )
2115 int termIndex = [self terminalIndex];
2116 NSArray *terminals = [[NSUserDefaults standardUserDefaults] valueForKey: AngbandTerminalsDefaultsKey];
2118 if( termIndex < (int)[terminals count] )
2120 NSMutableDictionary *mutableTerm = [[NSMutableDictionary alloc] initWithDictionary: [terminals objectAtIndex: termIndex]];
2121 [mutableTerm setValue: [NSNumber numberWithInteger: self.cols]
2122 forKey: AngbandTerminalColumnsDefaultsKey];
2123 [mutableTerm setValue: [NSNumber numberWithInteger: self.rows]
2124 forKey: AngbandTerminalRowsDefaultsKey];
2126 NSMutableArray *mutableTerminals = [[NSMutableArray alloc] initWithArray: terminals];
2127 [mutableTerminals replaceObjectAtIndex: termIndex withObject: mutableTerm];
2129 [[NSUserDefaults standardUserDefaults] setValue: mutableTerminals forKey: AngbandTerminalsDefaultsKey];
2134 Term_activate( self->terminal );
2135 Term_resize( self.cols, self.rows );
2137 Term_activate( old );
2140 - (void)setMinimumWindowSize:(int)termIdx
2146 minsize.height = 24;
2152 minsize.width * self.tileSize.width + self.borderSize.width * 2.0;
2154 minsize.height * self.tileSize.height + self.borderSize.height * 2.0;
2155 [[self makePrimaryWindow] setContentMinSize:minsize];
2158 - (void)saveWindowVisibleToDefaults: (BOOL)windowVisible
2160 int termIndex = [self terminalIndex];
2161 BOOL safeVisibility = (termIndex == 0) ? YES : windowVisible; /* Ensure main term doesn't go away because of these defaults */
2162 NSArray *terminals = [[NSUserDefaults standardUserDefaults] valueForKey: AngbandTerminalsDefaultsKey];
2164 if( termIndex < (int)[terminals count] )
2166 NSMutableDictionary *mutableTerm = [[NSMutableDictionary alloc] initWithDictionary: [terminals objectAtIndex: termIndex]];
2167 [mutableTerm setValue: [NSNumber numberWithBool: safeVisibility] forKey: AngbandTerminalVisibleDefaultsKey];
2169 NSMutableArray *mutableTerminals = [[NSMutableArray alloc] initWithArray: terminals];
2170 [mutableTerminals replaceObjectAtIndex: termIndex withObject: mutableTerm];
2172 [[NSUserDefaults standardUserDefaults] setValue: mutableTerminals forKey: AngbandTerminalsDefaultsKey];
2176 - (BOOL)windowVisibleUsingDefaults
2178 int termIndex = [self terminalIndex];
2180 if( termIndex == 0 )
2185 NSArray *terminals = [[NSUserDefaults standardUserDefaults] valueForKey: AngbandTerminalsDefaultsKey];
2188 if( termIndex < (int)[terminals count] )
2190 NSDictionary *term = [terminals objectAtIndex: termIndex];
2191 NSNumber *visibleValue = [term valueForKey: AngbandTerminalVisibleDefaultsKey];
2193 if( visibleValue != nil )
2195 visible = [visibleValue boolValue];
2203 #pragma mark NSWindowDelegate Methods
2205 /*- (void)windowWillStartLiveResize: (NSNotification *)notification
2209 - (void)windowDidEndLiveResize: (NSNotification *)notification
2211 NSWindow *window = [notification object];
2212 NSRect contentRect = [window contentRectForFrameRect: [window frame]];
2213 [self resizeTerminalWithContentRect: contentRect saveToDefaults: !(self->inFullscreenTransition)];
2216 /*- (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
2220 - (void)windowWillEnterFullScreen: (NSNotification *)notification
2222 self->inFullscreenTransition = YES;
2225 - (void)windowDidEnterFullScreen: (NSNotification *)notification
2227 NSWindow *window = [notification object];
2228 NSRect contentRect = [window contentRectForFrameRect: [window frame]];
2229 self->inFullscreenTransition = NO;
2230 [self resizeTerminalWithContentRect: contentRect saveToDefaults: NO];
2233 - (void)windowWillExitFullScreen: (NSNotification *)notification
2235 self->inFullscreenTransition = YES;
2238 - (void)windowDidExitFullScreen: (NSNotification *)notification
2240 NSWindow *window = [notification object];
2241 NSRect contentRect = [window contentRectForFrameRect: [window frame]];
2242 self->inFullscreenTransition = NO;
2243 [self resizeTerminalWithContentRect: contentRect saveToDefaults: NO];
2246 - (void)windowDidBecomeMain:(NSNotification *)notification
2248 NSWindow *window = [notification object];
2250 if( window != self.primaryWindow )
2255 int termIndex = [self terminalIndex];
2256 NSMenuItem *item = [[[NSApplication sharedApplication] windowsMenu] itemWithTag: AngbandWindowMenuItemTagBase + termIndex];
2257 [item setState: NSOnState];
2259 if( [[NSFontPanel sharedFontPanel] isVisible] )
2261 [[NSFontPanel sharedFontPanel] setPanelFont:self.angbandViewFont
2266 - (void)windowDidResignMain: (NSNotification *)notification
2268 NSWindow *window = [notification object];
2270 if( window != self.primaryWindow )
2275 int termIndex = [self terminalIndex];
2276 NSMenuItem *item = [[[NSApplication sharedApplication] windowsMenu] itemWithTag: AngbandWindowMenuItemTagBase + termIndex];
2277 [item setState: NSOffState];
2280 - (void)windowWillClose: (NSNotification *)notification
2282 [self saveWindowVisibleToDefaults: NO];
2288 @implementation AngbandView
2300 - (void)drawRect:(NSRect)rect
2302 if (! angbandContext)
2304 /* Draw bright orange, 'cause this ain't right */
2305 [[NSColor orangeColor] set];
2306 NSRectFill([self bounds]);
2310 /* Tell the Angband context to draw into us */
2311 [angbandContext drawRect:rect inView:self];
2315 - (void)setAngbandContext:(AngbandContext *)context
2317 angbandContext = context;
2320 - (AngbandContext *)angbandContext
2322 return angbandContext;
2325 - (void)setFrameSize:(NSSize)size
2327 BOOL changed = ! NSEqualSizes(size, [self frame].size);
2328 [super setFrameSize:size];
2329 if (changed) [angbandContext angbandViewDidScale:self];
2332 - (void)viewWillStartLiveResize
2334 [angbandContext viewWillStartLiveResize:self];
2337 - (void)viewDidEndLiveResize
2339 [angbandContext viewDidEndLiveResize:self];
2345 * Delay handling of double-clicked savefiles
2347 Boolean open_when_ready = FALSE;
2352 * ------------------------------------------------------------------------
2353 * Some generic functions
2354 * ------------------------------------------------------------------------ */
2357 * Sets an Angband color at a given index
2359 static void set_color_for_index(int idx)
2363 /* Extract the R,G,B data */
2364 rv = angband_color_table[idx][1];
2365 gv = angband_color_table[idx][2];
2366 bv = angband_color_table[idx][3];
2368 CGContextSetRGBFillColor([[NSGraphicsContext currentContext] graphicsPort], rv/255., gv/255., bv/255., 1.);
2372 * Remember the current character in UserDefaults so we can select it by
2373 * default next time.
2375 static void record_current_savefile(void)
2377 NSString *savefileString = [[NSString stringWithCString:savefile encoding:NSMacOSRomanStringEncoding] lastPathComponent];
2380 NSUserDefaults *angbandDefs = [NSUserDefaults angbandDefaults];
2381 [angbandDefs setObject:savefileString forKey:@"SaveFile"];
2388 * Convert a two-byte EUC-JP encoded character (both *cp and (*cp + 1) are in
2389 * the range, 0xA1-0xFE, or *cp is 0x8E) to a utf16 value in the native byte
2392 static wchar_t convert_two_byte_eucjp_to_utf16_native(const char *cp)
2394 NSString* str = [[NSString alloc] initWithBytes:cp length:2
2395 encoding:NSJapaneseEUCStringEncoding];
2396 wchar_t result = [str characterAtIndex:0];
2404 * ------------------------------------------------------------------------
2405 * Support for the "z-term.c" package
2406 * ------------------------------------------------------------------------ */
2410 * Initialize a new Term
2412 static void Term_init_cocoa(term *t)
2415 AngbandContext *context = [[AngbandContext alloc] init];
2417 /* Give the term ownership of the context */
2418 t->data = (void *)CFBridgingRetain(context);
2420 /* Handle graphics */
2421 t->higher_pict = !! use_graphics;
2422 t->always_pict = FALSE;
2424 NSDisableScreenUpdates();
2427 * Figure out the frame autosave name based on the index of this term
2429 NSString *autosaveName = nil;
2431 for (termIdx = 0; termIdx < ANGBAND_TERM_MAX; termIdx++)
2433 if (angband_term[termIdx] == t)
2436 [NSString stringWithFormat:@"AngbandTerm-%d", termIdx];
2442 NSString *fontName =
2443 [[NSUserDefaults angbandDefaults]
2444 stringForKey:[NSString stringWithFormat:@"FontName-%d", termIdx]];
2445 if (! fontName) fontName = [[AngbandContext defaultFont] fontName];
2448 * Use a smaller default font for the other windows, but only if the
2449 * font hasn't been explicitly set.
2452 (termIdx > 0) ? 10.0 : [[AngbandContext defaultFont] pointSize];
2453 NSNumber *fontSizeNumber =
2454 [[NSUserDefaults angbandDefaults]
2455 valueForKey: [NSString stringWithFormat: @"FontSize-%d", termIdx]];
2457 if( fontSizeNumber != nil )
2459 fontSize = [fontSizeNumber floatValue];
2462 [context setSelectionFont:[NSFont fontWithName:fontName size:fontSize]
2463 adjustTerminal: NO];
2465 NSArray *terminalDefaults =
2466 [[NSUserDefaults standardUserDefaults]
2467 valueForKey: AngbandTerminalsDefaultsKey];
2468 NSInteger rows = 24;
2469 NSInteger columns = 80;
2471 if( termIdx < (int)[terminalDefaults count] )
2473 NSDictionary *term = [terminalDefaults objectAtIndex: termIdx];
2474 NSInteger defaultRows =
2475 [[term valueForKey: AngbandTerminalRowsDefaultsKey]
2477 NSInteger defaultColumns =
2478 [[term valueForKey: AngbandTerminalColumnsDefaultsKey]
2481 if (defaultRows > 0) rows = defaultRows;
2482 if (defaultColumns > 0) columns = defaultColumns;
2485 context.cols = columns;
2486 context.rows = rows;
2487 [context.changes resize:columns rows:rows];
2489 /* Get the window */
2490 NSWindow *window = [context makePrimaryWindow];
2492 /* Set its title and, for auxiliary terms, tentative size */
2494 [NSString stringWithCString:angband_term_name[termIdx]
2496 encoding:NSJapaneseEUCStringEncoding
2498 encoding:NSMacOSRomanStringEncoding
2501 [window setTitle:title];
2502 [context setMinimumWindowSize:termIdx];
2505 * If this is the first term, and we support full screen (Mac OS X Lion
2506 * or later), then allow it to go full screen (sweet). Allow other
2507 * terms to be FullScreenAuxilliary, so they can at least show up.
2508 * Unfortunately in Lion they don't get brought to the full screen
2509 * space; but they would only make sense on multiple displays anyways
2510 * so it's not a big loss.
2512 if ([window respondsToSelector:@selector(toggleFullScreen:)])
2514 NSWindowCollectionBehavior behavior = [window collectionBehavior];
2517 NSWindowCollectionBehaviorFullScreenPrimary :
2518 NSWindowCollectionBehaviorFullScreenAuxiliary);
2519 [window setCollectionBehavior:behavior];
2522 /* No Resume support yet, though it would not be hard to add */
2523 if ([window respondsToSelector:@selector(setRestorable:)])
2525 [window setRestorable:NO];
2528 /* default window placement */ {
2529 static NSRect overallBoundingRect;
2534 * This is a bit of a trick to allow us to display multiple
2535 * windows in the "standard default" window position in OS X:
2536 * the upper center of the screen. The term sizes set in
2537 * AngbandAppDelegate's loadPrefs() are based on a 5-wide by
2538 * 3-high grid, with the main term being 4/5 wide by 2/3 high
2539 * (hence the scaling to find what the containing rect would
2542 NSRect originalMainTermFrame = [window frame];
2543 NSRect scaledFrame = originalMainTermFrame;
2544 scaledFrame.size.width *= 5.0 / 4.0;
2545 scaledFrame.size.height *= 3.0 / 2.0;
2546 scaledFrame.size.width += 1.0; /* spacing between window columns */
2547 scaledFrame.size.height += 1.0; /* spacing between window rows */
2548 [window setFrame: scaledFrame display: NO];
2550 overallBoundingRect = [window frame];
2551 [window setFrame: originalMainTermFrame display: NO];
2554 static NSRect mainTermBaseRect;
2555 NSRect windowFrame = [window frame];
2560 * The height and width adjustments were determined
2561 * experimentally, so that the rest of the windows line up
2562 * nicely without overlapping.
2564 windowFrame.size.width += 7.0;
2565 windowFrame.size.height += 9.0;
2566 windowFrame.origin.x = NSMinX( overallBoundingRect );
2567 windowFrame.origin.y =
2568 NSMaxY( overallBoundingRect ) - NSHeight( windowFrame );
2569 mainTermBaseRect = windowFrame;
2571 else if( termIdx == 1 )
2573 windowFrame.origin.x = NSMinX( mainTermBaseRect );
2574 windowFrame.origin.y =
2575 NSMinY( mainTermBaseRect ) - NSHeight( windowFrame ) - 1.0;
2577 else if( termIdx == 2 )
2579 windowFrame.origin.x = NSMaxX( mainTermBaseRect ) + 1.0;
2580 windowFrame.origin.y =
2581 NSMaxY( mainTermBaseRect ) - NSHeight( windowFrame );
2583 else if( termIdx == 3 )
2585 windowFrame.origin.x = NSMaxX( mainTermBaseRect ) + 1.0;
2586 windowFrame.origin.y =
2587 NSMinY( mainTermBaseRect ) - NSHeight( windowFrame ) - 1.0;
2589 else if( termIdx == 4 )
2591 windowFrame.origin.x = NSMaxX( mainTermBaseRect ) + 1.0;
2592 windowFrame.origin.y = NSMinY( mainTermBaseRect );
2594 else if( termIdx == 5 )
2596 windowFrame.origin.x =
2597 NSMinX( mainTermBaseRect ) + NSWidth( windowFrame ) + 1.0;
2598 windowFrame.origin.y =
2599 NSMinY( mainTermBaseRect ) - NSHeight( windowFrame ) - 1.0;
2602 [window setFrame: windowFrame display: NO];
2605 /* Override the default frame above if the user has adjusted windows in
2607 if (autosaveName) [window setFrameAutosaveName:autosaveName];
2610 * Tell it about its term. Do this after we've sized it so that the
2611 * sizing doesn't trigger redrawing and such.
2613 [context setTerm:t];
2616 * Only order front if it's the first term. Other terms will be ordered
2617 * front from AngbandUpdateWindowVisibility(). This is to work around a
2618 * problem where Angband aggressively tells us to initialize terms that
2619 * don't do anything!
2621 if (t == angband_term[0])
2622 [context.primaryWindow makeKeyAndOrderFront: nil];
2624 NSEnableScreenUpdates();
2626 /* Set "mapped" flag */
2627 t->mapped_flag = true;
2636 static void Term_nuke_cocoa(term *t)
2639 AngbandContext *context = (__bridge AngbandContext*) (t->data);
2642 /* Tell the context to get rid of its windows, etc. */
2645 /* Balance our CFBridgingRetain from when we created it */
2655 * Returns the CGImageRef corresponding to an image with the given name in the
2656 * resource directory, transferring ownership to the caller
2658 static CGImageRef create_angband_image(NSString *path)
2660 CGImageRef decodedImage = NULL, result = NULL;
2662 /* Try using ImageIO to load the image */
2665 NSURL *url = [[NSURL alloc] initFileURLWithPath:path isDirectory:NO];
2668 NSDictionary *options = [[NSDictionary alloc] initWithObjectsAndKeys:(id)kCFBooleanTrue, kCGImageSourceShouldCache, nil];
2669 CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)url, (CFDictionaryRef)options);
2672 /* We really want the largest image, but in practice there's
2673 * only going to be one */
2674 decodedImage = CGImageSourceCreateImageAtIndex(source, 0, (CFDictionaryRef)options);
2680 /* Draw the sucker to defeat ImageIO's weird desire to cache and decode on
2681 * demand. Our images aren't that big! */
2684 size_t width = CGImageGetWidth(decodedImage), height = CGImageGetHeight(decodedImage);
2686 /* Compute our own bitmap info */
2687 CGBitmapInfo imageBitmapInfo = CGImageGetBitmapInfo(decodedImage);
2688 CGBitmapInfo contextBitmapInfo = kCGBitmapByteOrderDefault;
2690 switch (imageBitmapInfo & kCGBitmapAlphaInfoMask) {
2691 case kCGImageAlphaNone:
2692 case kCGImageAlphaNoneSkipLast:
2693 case kCGImageAlphaNoneSkipFirst:
2695 contextBitmapInfo |= kCGImageAlphaNone;
2698 /* Some alpha, use premultiplied last which is most efficient. */
2699 contextBitmapInfo |= kCGImageAlphaPremultipliedLast;
2703 /* Draw the source image flipped, since the view is flipped */
2704 CGContextRef ctx = CGBitmapContextCreate(NULL, width, height, CGImageGetBitsPerComponent(decodedImage), CGImageGetBytesPerRow(decodedImage), CGImageGetColorSpace(decodedImage), contextBitmapInfo);
2706 CGContextSetBlendMode(ctx, kCGBlendModeCopy);
2707 CGContextTranslateCTM(ctx, 0.0, height);
2708 CGContextScaleCTM(ctx, 1.0, -1.0);
2710 ctx, CGRectMake(0, 0, width, height), decodedImage);
2711 result = CGBitmapContextCreateImage(ctx);
2715 CGImageRelease(decodedImage);
2723 static errr Term_xtra_cocoa_react(void)
2725 /* Don't actually switch graphics until the game is running */
2726 if (!initialized || !game_in_progress) return (-1);
2729 AngbandContext *angbandContext =
2730 (__bridge AngbandContext*) (Term->data);
2732 /* Handle graphics */
2733 int expected_graf_mode = (current_graphics_mode) ?
2734 current_graphics_mode->grafID : GRAPHICS_NONE;
2735 if (graf_mode_req != expected_graf_mode)
2737 graphics_mode *new_mode;
2738 if (graf_mode_req != GRAPHICS_NONE) {
2739 new_mode = get_graphics_mode(graf_mode_req);
2744 /* Get rid of the old image. CGImageRelease is NULL-safe. */
2745 CGImageRelease(pict_image);
2748 /* Try creating the image if we want one */
2749 if (new_mode != NULL)
2751 NSString *img_path =
2752 [NSString stringWithFormat:@"%s/%s", new_mode->path, new_mode->file];
2753 pict_image = create_angband_image(img_path);
2755 /* If we failed to create the image, revert to ASCII. */
2759 arg_bigtile = FALSE;
2761 [[NSUserDefaults angbandDefaults]
2762 setInteger:GRAPHICS_NONE
2763 forKey:AngbandGraphicsDefaultsKey];
2765 NSString *msg = NSLocalizedStringWithDefaultValue(
2766 @"Error.TileSetLoadFailed",
2767 AngbandMessageCatalog,
2768 [NSBundle mainBundle],
2769 @"Failed to Load Tile Set",
2770 @"Alert text for failed tile set load");
2771 NSString *info = NSLocalizedStringWithDefaultValue(
2772 @"Error.TileSetRevertToASCII",
2773 AngbandMessageCatalog,
2774 [NSBundle mainBundle],
2775 @"Could not load the tile set. Switched back to ASCII.",
2776 @"Alert informative message for failed tile set load");
2777 NSAlert *alert = [[NSAlert alloc] init];
2779 alert.messageText = msg;
2780 alert.informativeText = info;
2785 /* Record what we did */
2786 use_graphics = new_mode ? new_mode->grafID : 0;
2787 ANGBAND_GRAF = (new_mode ? new_mode->graf : "ascii");
2788 current_graphics_mode = new_mode;
2791 * Enable or disable higher picts. Note: this should be done for
2794 angbandContext->terminal->higher_pict = !! use_graphics;
2796 if (pict_image && current_graphics_mode)
2799 * Compute the row and column count via the image height and
2802 pict_rows = (int)(CGImageGetHeight(pict_image) /
2803 current_graphics_mode->cell_height);
2804 pict_cols = (int)(CGImageGetWidth(pict_image) /
2805 current_graphics_mode->cell_width);
2814 if (arg_bigtile == use_bigtile)
2820 if (arg_bigtile != use_bigtile) {
2824 Term_activate(angband_term[0]);
2825 Term_resize(angband_term[0]->wid, angband_term[0]->hgt);
2835 * Draws one tile as a helper function for Term_xtra_cocoa_fresh().
2837 static void draw_image_tile(
2838 NSGraphicsContext* nsContext,
2839 CGContextRef cgContext,
2843 NSCompositingOperation op)
2845 /* Flip the source rect since the source image is flipped */
2846 CGAffineTransform flip = CGAffineTransformIdentity;
2847 flip = CGAffineTransformTranslate(flip, 0.0, CGImageGetHeight(image));
2848 flip = CGAffineTransformScale(flip, 1.0, -1.0);
2849 CGRect flippedSourceRect =
2850 CGRectApplyAffineTransform(NSRectToCGRect(srcRect), flip);
2853 * When we use high-quality resampling to draw a tile, pixels from outside
2854 * the tile may bleed in, causing graphics artifacts. Work around that.
2856 CGImageRef subimage =
2857 CGImageCreateWithImageInRect(image, flippedSourceRect);
2858 [nsContext setCompositingOperation:op];
2859 CGContextDrawImage(cgContext, NSRectToCGRect(dstRect), subimage);
2860 CGImageRelease(subimage);
2865 * This is a helper function for Term_xtra_cocoa_fresh(): look before a block
2866 * of text on a row to see if the bounds for rendering and clipping need to be
2869 static void query_before_text(
2870 PendingTermChanges *tc, int iy, int npre, int* pclip, int* prend)
2876 if (i < 0 || i < start - npre) {
2879 enum PendingCellChangeType ctype = [tc getCellChangeType:i row:iy];
2881 if (ctype == CELL_CHANGE_TILE) {
2883 * The cell has been rendered with a tile. Do not want to modify
2884 * its contents so the clipping and rendering region can not be
2888 } else if (ctype == CELL_CHANGE_NONE) {
2890 * It has not changed (or using big tile mode and it is within
2891 * a changed tile but is not the left cell for that tile) so
2892 * inquire what it is.
2897 Term_what(i, iy, a + 1, c + 1);
2898 if (use_graphics && (a[1] & 0x80) && (c[1] & 0x80)) {
2900 * It is an unchanged location rendered with a tile. Do not
2901 * want to modify its contents so the clipping and rendering
2902 * region can not be extended.
2906 if (use_bigtile && i > 0) {
2907 Term_what(i - 1, iy, a, c);
2908 if (use_graphics && (a[0] & 0x80) && (c[0] & 0x80)) {
2910 * It is the right cell of a location rendered with a tile.
2911 * Do not want to modify its contents so the clipping and
2912 * rendering region can not be exteded.
2918 * It is unchanged text. A character from the changed region
2919 * may have extended into it so render it to clear that.
2922 /* Check to see if it is the second part of a kanji character. */
2924 Term_what(i - 1, iy, a, c);
2926 [tc markTextChange:i-1 row:iy
2927 glyph:convert_two_byte_eucjp_to_utf16_native(c)
2928 color:a[0] isDoubleWidth:YES];
2933 [tc markTextChange:i row:iy
2934 glyph:c[1] color:a[1] isDoubleWidth:NO];
2939 [tc markTextChange:i row:iy
2940 glyph:c[1] color:a[1] isDoubleWidth:NO];
2945 [tc markTextChange:i row:iy
2946 glyph:c[1] color:a[1] isDoubleWidth:NO];
2953 * The cell has been wiped or had changed text rendered. Do
2954 * not need to render. Can extend the clipping rectangle into it.
2964 * This is a helper function for Term_xtra_cocoa_fresh(): look after a block
2965 * of text on a row to see if the bounds for rendering and clipping need to be
2968 static void query_after_text(
2969 PendingTermChanges *tc, int iy, int npost, int* pclip, int* prend)
2973 int ncol = tc.columnCount;
2980 enum PendingCellChangeType ctype = [tc getCellChangeType:i row:iy];
2983 * Be willing to consolidate this block with the one after it. This
2984 * logic should be sufficient to avoid redraws of the region between
2985 * changed blocks of text if angbandContext.nColPre is zero or one.
2986 * For larger values of nColPre, would need to do something more to
2987 * avoid extra redraws.
2989 if (i > end + npost && ctype != CELL_CHANGE_TEXT &&
2990 ctype != CELL_CHANGE_WIPE) {
2994 if (ctype == CELL_CHANGE_TILE) {
2996 * The cell has been rendered with a tile. Do not want to modify
2997 * its contents so the clipping and rendering region can not be
3001 } else if (ctype == CELL_CHANGE_NONE) {
3002 /* It has not changed so inquire what it is. */
3006 Term_what(i, iy, a, c);
3007 if (use_graphics && (a[0] & 0x80) && (c[0] & 0x80)) {
3009 * It is an unchanged location rendered with a tile. Do not
3010 * want to modify its contents so the clipping and rendering
3011 * region can not be extended.
3016 * It is unchanged text. A character from the changed region
3017 * may have extended into it so render it to clear that.
3020 /* Check to see if it is the first part of a kanji character. */
3022 Term_what(i + 1, iy, a + 1, c + 1);
3024 [tc markTextChange:i row:iy
3025 glyph:convert_two_byte_eucjp_to_utf16_native(c)
3026 color:a[0] isDoubleWidth:YES];
3031 [tc markTextChange:i row:iy
3032 glyph:c[0] color:a[0] isDoubleWidth:NO];
3037 [tc markTextChange:i row:iy
3038 glyph:c[0] color:a[0] isDoubleWidth:NO];
3043 [tc markTextChange:i row:iy
3044 glyph:c[0] color:a[0] isDoubleWidth:NO];
3051 * Have come to another region of changed text or another region
3052 * to wipe. Combine the regions to minimize redraws.
3064 * Draw the pending changes saved in angbandContext->changes.
3066 static void Term_xtra_cocoa_fresh(AngbandContext* angbandContext)
3068 int graf_width, graf_height, alphablend;
3070 if (angbandContext.changes.hasTileChanges) {
3071 CGImageAlphaInfo ainfo = CGImageGetAlphaInfo(pict_image);
3073 graf_width = current_graphics_mode->cell_width;
3074 graf_height = current_graphics_mode->cell_height;
3076 * As of this writing, a value of zero for
3077 * current_graphics_mode->alphablend can mean either that the tile set
3078 * doesn't have an alpha channel or it does but it only takes on values
3079 * of 0 or 255. For main-cocoa.m's purposes, the latter is rendered
3080 * using the same procedure as if alphablend was nonzero. The former
3081 * is handled differently, but alphablend doesn't distinguish it from
3082 * the latter. So ignore alphablend and directly test whether an
3083 * alpha channel is present.
3085 alphablend = (ainfo & (kCGImageAlphaPremultipliedFirst |
3086 kCGImageAlphaPremultipliedLast)) ? 1 : 0;
3093 CGContextRef ctx = [angbandContext lockFocus];
3095 if (angbandContext.changes.hasTextChanges ||
3096 angbandContext.changes.hasWipeChanges) {
3097 NSFont *selectionFont = [angbandContext.angbandViewFont screenFont];
3098 [selectionFont set];
3101 for (int iy = angbandContext.changes.firstChangedRow;
3102 iy <= angbandContext.changes.lastChangedRow;
3104 /* Skip untouched rows. */
3105 if ([angbandContext.changes getFirstChangedColumnInRow:iy] >
3106 [angbandContext.changes getLastChangedColumnInRow:iy]) {
3109 int ix = [angbandContext.changes getFirstChangedColumnInRow:iy];
3110 int ixmax = [angbandContext.changes getLastChangedColumnInRow:iy];
3119 switch ([angbandContext.changes getCellChangeType:ix row:iy]) {
3120 case CELL_CHANGE_NONE:
3124 case CELL_CHANGE_TILE:
3127 * Because changes are made to the compositing mode, save
3128 * the incoming value.
3130 NSGraphicsContext *nsContext =
3131 [NSGraphicsContext currentContext];
3132 NSCompositingOperation op = nsContext.compositingOperation;
3133 int step = (use_bigtile) ? 2 : 1;
3136 while (jx <= ixmax &&
3137 [angbandContext.changes getCellChangeType:jx row:iy]
3138 == CELL_CHANGE_TILE) {
3139 NSRect destinationRect =
3140 [angbandContext rectInImageForTileAtX:jx Y:iy];
3141 struct PendingTileChange tileIndices =
3142 [angbandContext.changes
3143 getCellTileChange:jx row:iy];
3144 NSRect sourceRect, terrainRect;
3146 destinationRect.size.width *= step;
3147 sourceRect.origin.x = graf_width * tileIndices.fgdCol;
3148 sourceRect.origin.y = graf_height * tileIndices.fgdRow;
3149 sourceRect.size.width = graf_width;
3150 sourceRect.size.height = graf_height;
3151 terrainRect.origin.x = graf_width * tileIndices.bckCol;
3152 terrainRect.origin.y = graf_height *
3154 terrainRect.size.width = graf_width;
3155 terrainRect.size.height = graf_height;
3165 * Skip drawing the foreground if it is the same
3166 * as the background.
3168 if (sourceRect.origin.x != terrainRect.origin.x ||
3169 sourceRect.origin.y != terrainRect.origin.y) {
3176 NSCompositeSourceOver);
3190 [nsContext setCompositingOperation:op];
3193 [angbandContext rectInImageForTileAtX:ix Y:iy];
3195 angbandContext.tileSize.width * (jx - ix);
3196 [angbandContext setNeedsDisplayInBaseRect:rect];
3201 case CELL_CHANGE_WIPE:
3202 case CELL_CHANGE_TEXT:
3204 * For a wiped region, treat it as if it had text (the only
3205 * loss if it was not is some extra work rendering
3206 * neighboring unchanged text).
3210 if (jx >= angbandContext.cols) {
3213 enum PendingCellChangeType ctype =
3214 [angbandContext.changes getCellChangeType:jx row:iy];
3215 if (ctype != CELL_CHANGE_TEXT &&
3216 ctype != CELL_CHANGE_WIPE) {
3223 int ieclip = jx - 1;
3225 int ierend = jx - 1;
3227 TERM_COLOR alast = 0;
3232 angbandContext.changes,
3234 angbandContext.nColPre,
3238 angbandContext.changes,
3240 angbandContext.nColPost,
3246 /* Save the state since the clipping will be modified. */
3247 CGContextSaveGState(ctx);
3249 /* Clear the area where rendering will be done. */
3250 r = [angbandContext rectInImageForTileAtX:isrend Y:iy];
3251 r.size.width = angbandContext.tileSize.width *
3252 (ierend - isrend + 1);
3253 [[NSColor blackColor] set];
3257 * Clear the current path so it does not affect clipping.
3258 * Then set the clipping rectangle. Using
3259 * CGContextSetTextDrawingMode() to include clipping does
3260 * not appear to be necessary on 10.14 and is actually
3261 * detrimental: when displaying more than one character,
3262 * only the first is visible.
3264 CGContextBeginPath(ctx);
3265 r = [angbandContext rectInImageForTileAtX:isclip Y:iy];
3266 r.size.width = angbandContext.tileSize.width *
3267 (ieclip - isclip + 1);
3268 CGContextClipToRect(ctx, r);
3272 while (k <= ierend) {
3273 if ([angbandContext.changes getCellChangeType:k row:iy]
3274 == CELL_CHANGE_WIPE) {
3275 /* Skip over since no rendering is necessary. */
3280 struct PendingTextChange textChange =
3281 [angbandContext.changes getCellTextChange:k
3283 int anew = textChange.color % MAX_COLORS;
3284 if (set_color || alast != anew) {
3287 set_color_for_index(anew);
3291 [angbandContext rectInImageForTileAtX:k Y:iy];
3292 if (textChange.doubleWidth) {
3293 rectToDraw.size.width *= 2.0;
3294 [angbandContext drawWChar:textChange.glyph
3295 inRect:rectToDraw context:ctx];
3298 [angbandContext drawWChar:textChange.glyph
3299 inRect:rectToDraw context:ctx];
3305 * Inform the context that the area in the clipping
3306 * rectangle needs to be redisplayed.
3308 [angbandContext setNeedsDisplayInBaseRect:r];
3310 CGContextRestoreGState(ctx);
3317 if (angbandContext.changes.cursorColumn >= 0 &&
3318 angbandContext.changes.cursorRow >= 0) {
3319 NSRect rect = [angbandContext
3320 rectInImageForTileAtX:angbandContext.changes.cursorColumn
3321 Y:angbandContext.changes.cursorRow];
3323 rect.size.width *= angbandContext.changes.cursorWidth;
3324 rect.size.height *= angbandContext.changes.cursorHeight;
3325 [[NSColor yellowColor] set];
3326 NSFrameRectWithWidth(rect, 1);
3327 /* Invalidate that rect */
3328 [angbandContext setNeedsDisplayInBaseRect:rect];
3331 [angbandContext unlockFocus];
3336 * Do a "special thing"
3338 static errr Term_xtra_cocoa(int n, int v)
3342 AngbandContext* angbandContext =
3343 (__bridge AngbandContext*) (Term->data);
3348 case TERM_XTRA_NOISE:
3353 case TERM_XTRA_SOUND:
3357 /* Process random events */
3358 case TERM_XTRA_BORED:
3360 * Show or hide cocoa windows based on the subwindow flags set by
3363 AngbandUpdateWindowVisibility();
3364 /* Process an event */
3365 (void)check_events(CHECK_EVENTS_NO_WAIT);
3368 /* Process pending events */
3369 case TERM_XTRA_EVENT:
3370 /* Process an event */
3371 (void)check_events(v);
3374 /* Flush all pending events (if any) */
3375 case TERM_XTRA_FLUSH:
3376 /* Hack -- flush all events */
3377 while (check_events(CHECK_EVENTS_DRAIN)) /* loop */;
3381 /* Hack -- Change the "soft level" */
3382 case TERM_XTRA_LEVEL:
3384 * Here we could activate (if requested), but I don't think
3385 * Angband should be telling us our window order (the user
3386 * should decide that), so do nothing.
3390 /* Clear the screen */
3391 case TERM_XTRA_CLEAR:
3393 [angbandContext lockFocus];
3394 [[NSColor blackColor] set];
3395 NSRect imageRect = {NSZeroPoint, [angbandContext imageSize]};
3396 NSRectFillUsingOperation(imageRect, NSCompositeCopy);
3397 [angbandContext unlockFocus];
3398 [angbandContext setNeedsDisplay:YES];
3403 /* React to changes */
3404 case TERM_XTRA_REACT:
3405 result = Term_xtra_cocoa_react();
3408 /* Delay (milliseconds) */
3409 case TERM_XTRA_DELAY:
3412 double seconds = v / 1000.;
3413 NSDate* date = [NSDate dateWithTimeIntervalSinceNow:seconds];
3417 event = [NSApp nextEventMatchingMask:-1
3419 inMode:NSDefaultRunLoopMode
3421 if (event) send_event(event);
3423 } while ([date timeIntervalSinceNow] >= 0);
3427 /* Draw the pending changes. */
3428 case TERM_XTRA_FRESH:
3429 Term_xtra_cocoa_fresh(angbandContext);
3430 [angbandContext.changes clear];
3443 static errr Term_curs_cocoa(TERM_LEN x, TERM_LEN y)
3445 AngbandContext *angbandContext = (__bridge AngbandContext*) (Term->data);
3447 [angbandContext.changes markCursor:x row:y];
3454 * Draw a cursor that's two tiles wide. For Japanese, that's used when
3455 * the cursor points at a kanji character, irregardless of whether operating
3458 static errr Term_bigcurs_cocoa(TERM_LEN x, TERM_LEN y)
3460 AngbandContext *angbandContext = (__bridge AngbandContext*) (Term->data);
3462 [angbandContext.changes markBigCursor:x row:y cellsWide:2 cellsHigh:1];
3469 * Low level graphics (Assumes valid input)
3471 * Erase "n" characters starting at (x,y)
3473 static errr Term_wipe_cocoa(TERM_LEN x, TERM_LEN y, int n)
3475 AngbandContext *angbandContext = (__bridge AngbandContext*) (Term->data);
3477 [angbandContext.changes markWipeRange:x row:y n:n];
3483 static errr Term_pict_cocoa(TERM_LEN x, TERM_LEN y, int n,
3484 TERM_COLOR *ap, concptr cp,
3485 const TERM_COLOR *tap, concptr tcp)
3487 /* Paranoia: Bail if we don't have a current graphics mode */
3488 if (! current_graphics_mode) return -1;
3490 AngbandContext* angbandContext = (__bridge AngbandContext*) (Term->data);
3491 int step = (use_bigtile) ? 2 : 1;
3494 * In bigtile mode, it is sufficient that the bounds for the modified
3495 * region only encompass the left cell for the region affected by the
3496 * tile and that only that cell has to have the details of the changes.
3498 for (int i = x; i < x + n * step; i += step) {
3499 TERM_COLOR a = *ap++;
3501 TERM_COLOR ta = *tap++;
3504 if (use_graphics && (a & 0x80) && (c & 0x80)) {
3505 [angbandContext.changes markTileChange:i row:y
3506 foregroundCol:((byte)c & 0x7F) % pict_cols
3507 foregroundRow:((byte)a & 0x7F) % pict_rows
3508 backgroundCol:((byte)tc & 0x7F) % pict_cols
3509 backgroundRow:((byte)ta & 0x7F) % pict_rows];
3518 * Low level graphics. Assumes valid input.
3520 * Draw several ("n") chars, with an attr, at a given location.
3522 static errr Term_text_cocoa(
3523 TERM_LEN x, TERM_LEN y, int n, TERM_COLOR a, concptr cp)
3525 AngbandContext* angbandContext = (__bridge AngbandContext*) (Term->data);
3533 * The second byte of the character is past the end. Ignore
3538 [angbandContext.changes markTextChange:i+x row:y
3539 glyph:convert_two_byte_eucjp_to_utf16_native(cp)
3540 color:a isDoubleWidth:YES];
3545 [angbandContext.changes markTextChange:i+x row:y
3546 glyph:*cp color:a isDoubleWidth:NO];
3551 [angbandContext.changes markTextChange:i+x row:y
3552 glyph:*cp color:a isDoubleWidth:NO];
3563 * Post a nonsense event so that our event loop wakes up
3565 static void wakeup_event_loop(void)
3567 /* Big hack - send a nonsense event to make us update */
3568 NSEvent *event = [NSEvent otherEventWithType:NSApplicationDefined location:NSZeroPoint modifierFlags:0 timestamp:0 windowNumber:0 context:NULL subtype:AngbandEventWakeup data1:0 data2:0];
3569 [NSApp postEvent:event atStart:NO];
3574 * Handle the "open_when_ready" flag
3576 static void handle_open_when_ready(void)
3578 /* Check the flag XXX XXX XXX make a function for this */
3579 if (open_when_ready && initialized && !game_in_progress)
3582 open_when_ready = FALSE;
3584 /* Game is in progress */
3585 game_in_progress = TRUE;
3587 /* Wait for a keypress */
3588 pause_line(Term->hgt - 1);
3594 * Handle quit_when_ready, by Peter Ammon,
3595 * slightly modified to check inkey_flag.
3597 static void quit_calmly(void)
3599 /* Quit immediately if game's not started */
3600 if (!game_in_progress || !character_generated) quit(NULL);
3602 /* Save the game and Quit (if it's safe) */
3605 /* Hack -- Forget messages and term */
3607 Term->mapped_flag = FALSE;
3610 do_cmd_save_game(FALSE);
3611 record_current_savefile();
3617 /* Wait until inkey_flag is set */
3623 * Returns YES if we contain an AngbandView (and hence should direct our events
3626 static BOOL contains_angband_view(NSView *view)
3628 if ([view isKindOfClass:[AngbandView class]]) return YES;
3629 for (NSView *subview in [view subviews]) {
3630 if (contains_angband_view(subview)) return YES;
3637 * Queue mouse presses if they occur in the map section of the main window.
3639 static void AngbandHandleEventMouseDown( NSEvent *event )
3642 AngbandContext *angbandContext = [[[event window] contentView] angbandContext];
3643 AngbandContext *mainAngbandContext =
3644 (__bridge AngbandContext*) (angband_term[0]->data);
3646 if (mainAngbandContext.primaryWindow &&
3647 [[event window] windowNumber] ==
3648 [mainAngbandContext.primaryWindow windowNumber])
3650 int cols, rows, x, y;
3651 Term_get_size(&cols, &rows);
3652 NSSize tileSize = angbandContext.tileSize;
3653 NSSize border = angbandContext.borderSize;
3654 NSPoint windowPoint = [event locationInWindow];
3656 /* Adjust for border; add border height because window origin is at
3658 windowPoint = NSMakePoint( windowPoint.x - border.width, windowPoint.y + border.height );
3660 NSPoint p = [[[event window] contentView] convertPoint: windowPoint fromView: nil];
3661 x = floor( p.x / tileSize.width );
3662 y = floor( p.y / tileSize.height );
3664 /* Being safe about this, since xcode doesn't seem to like the
3665 * bool_hack stuff */
3666 BOOL displayingMapInterface = ((int)inkey_flag != 0);
3668 /* Sidebar plus border == thirteen characters; top row is reserved. */
3669 /* Coordinates run from (0,0) to (cols-1, rows-1). */
3670 BOOL mouseInMapSection = (x > 13 && x <= cols - 1 && y > 0 && y <= rows - 2);
3672 /* If we are displaying a menu, allow clicks anywhere; if we are
3673 * displaying the main game interface, only allow clicks in the map
3675 if (!displayingMapInterface || (displayingMapInterface && mouseInMapSection))
3677 /* [event buttonNumber] will return 0 for left click,
3678 * 1 for right click, but this is safer */
3679 int button = ([event type] == NSLeftMouseDown) ? 1 : 2;
3682 NSUInteger eventModifiers = [event modifierFlags];
3683 byte angbandModifiers = 0;
3684 angbandModifiers |= (eventModifiers & NSShiftKeyMask) ? KC_MOD_SHIFT : 0;
3685 angbandModifiers |= (eventModifiers & NSControlKeyMask) ? KC_MOD_CONTROL : 0;
3686 angbandModifiers |= (eventModifiers & NSAlternateKeyMask) ? KC_MOD_ALT : 0;
3687 button |= (angbandModifiers & 0x0F) << 4; /* encode modifiers in the button number (see Term_mousepress()) */
3690 Term_mousepress(x, y, button);
3695 /* Pass click through to permit focus change, resize, etc. */
3696 [NSApp sendEvent:event];
3702 * Encodes an NSEvent Angband-style, or forwards it along. Returns YES if the
3703 * event was sent to Angband, NO if Cocoa (or nothing) handled it */
3704 static BOOL send_event(NSEvent *event)
3707 /* If the receiving window is not an Angband window, then do nothing */
3708 if (! contains_angband_view([[event window] contentView]))
3710 [NSApp sendEvent:event];
3714 /* Analyze the event */
3715 switch ([event type])
3719 /* Try performing a key equivalent */
3720 if ([[NSApp mainMenu] performKeyEquivalent:event]) break;
3722 unsigned modifiers = [event modifierFlags];
3724 /* Send all NSCommandKeyMasks through */
3725 if (modifiers & NSCommandKeyMask)
3727 [NSApp sendEvent:event];
3731 if (! [[event characters] length]) break;
3734 /* Extract some modifiers */
3735 int mc = !! (modifiers & NSControlKeyMask);
3736 int ms = !! (modifiers & NSShiftKeyMask);
3737 int mo = !! (modifiers & NSAlternateKeyMask);
3738 int kp = !! (modifiers & NSNumericPadKeyMask);
3741 /* Get the Angband char corresponding to this unichar */
3742 unichar c = [[event characters] characterAtIndex:0];
3745 * Have anything from the numeric keypad generate a macro
3746 * trigger so that shift or control modifiers can be passed.
3748 if (c <= 0x7F && !kp)
3754 * The rest of Hengband uses Angband 2.7's or so key handling:
3755 * so for the rest do something like the encoding that
3756 * main-win.c does: send a macro trigger with the Unicode
3757 * value encoded into printable ASCII characters.
3762 /* override special keys */
3763 switch([event keyCode]) {
3764 case kVK_Return: ch = '\r'; break;
3765 case kVK_Escape: ch = 27; break;
3766 case kVK_Tab: ch = '\t'; break;
3767 case kVK_Delete: ch = '\b'; break;
3768 case kVK_ANSI_KeypadEnter: ch = '\r'; kp = TRUE; break;
3771 /* Hide the mouse pointer */
3772 [NSCursor setHiddenUntilMouseMoves:YES];
3782 * Could use the hexsym global but some characters overlap with
3783 * those used to indicate modifiers.
3785 const char encoded[16] = {
3786 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b',
3790 /* Begin the macro trigger. */
3793 /* Send the modifiers. */
3794 if (mc) Term_keypress('C');
3795 if (ms) Term_keypress('S');
3796 if (mo) Term_keypress('O');
3797 if (kp) Term_keypress('K');
3800 Term_keypress(encoded[c & 0xF]);
3804 /* End the macro trigger. */
3811 case NSLeftMouseDown:
3812 case NSRightMouseDown:
3813 AngbandHandleEventMouseDown(event);
3816 case NSApplicationDefined:
3818 if ([event subtype] == AngbandEventWakeup)
3826 [NSApp sendEvent:event];
3833 * Check for Events, return TRUE if we process any
3835 static BOOL check_events(int wait)
3840 /* Handles the quit_when_ready flag */
3841 if (quit_when_ready) quit_calmly();
3844 if (wait == CHECK_EVENTS_WAIT) endDate = [NSDate distantFuture];
3845 else endDate = [NSDate distantPast];
3849 if (quit_when_ready)
3851 /* send escape events until we quit */
3852 Term_keypress(0x1B);
3857 event = [NSApp nextEventMatchingMask:-1 untilDate:endDate
3858 inMode:NSDefaultRunLoopMode dequeue:YES];
3863 if (send_event(event)) break;
3872 * Hook to tell the user something important
3874 static void hook_plog(const char * str)
3878 NSString *msg = NSLocalizedStringWithDefaultValue(
3879 @"Warning", AngbandMessageCatalog, [NSBundle mainBundle],
3880 @"Warning", @"Alert text for generic warning");
3881 NSString *info = [NSString stringWithCString:str
3883 encoding:NSJapaneseEUCStringEncoding
3885 encoding:NSMacOSRomanStringEncoding
3888 NSAlert *alert = [[NSAlert alloc] init];
3890 alert.messageText = msg;
3891 alert.informativeText = info;
3898 * Hook to tell the user something, and then quit
3900 static void hook_quit(const char * str)
3907 * Return the path for Angband's lib directory and bail if it isn't found. The
3908 * lib directory should be in the bundle's resources directory, since it's
3909 * copied when built.
3911 static NSString* get_lib_directory(void)
3913 NSString *bundleLibPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: AngbandDirectoryNameLib];
3914 BOOL isDirectory = NO;
3915 BOOL libExists = [[NSFileManager defaultManager] fileExistsAtPath: bundleLibPath isDirectory: &isDirectory];
3917 if( !libExists || !isDirectory )
3919 NSLog( @"Hengband: can't find %@/ in bundle: isDirectory: %d libExists: %d", AngbandDirectoryNameLib, isDirectory, libExists );
3921 NSString *msg = NSLocalizedStringWithDefaultValue(
3922 @"Error.MissingResources",
3923 AngbandMessageCatalog,
3924 [NSBundle mainBundle],
3925 @"Missing Resources",
3926 @"Alert text for missing resources");
3927 NSString *info = NSLocalizedStringWithDefaultValue(
3928 @"Error.MissingAngbandLib",
3929 AngbandMessageCatalog,
3930 [NSBundle mainBundle],
3931 @"Hengband was unable to find required resources and must quit. Please report a bug on the Angband forums.",
3932 @"Alert informative message for missing Angband lib/ folder");
3933 NSString *quit_label = NSLocalizedStringWithDefaultValue(
3934 @"Label.Quit", AngbandMessageCatalog, [NSBundle mainBundle],
3936 NSAlert *alert = [[NSAlert alloc] init];
3939 * Note that NSCriticalAlertStyle was deprecated in 10.10. The
3940 * replacement is NSAlertStyleCritical.
3942 alert.alertStyle = NSCriticalAlertStyle;
3943 alert.messageText = msg;
3944 alert.informativeText = info;
3945 [alert addButtonWithTitle:quit_label];
3950 return bundleLibPath;
3954 * Return the path for the directory where Angband should look for its standard
3957 static NSString* get_doc_directory(void)
3959 NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
3961 #if defined(SAFE_DIRECTORY)
3962 NSString *versionedDirectory = [NSString stringWithFormat: @"%@-%s", AngbandDirectoryNameBase, VERSION_STRING];
3963 return [documents stringByAppendingPathComponent: versionedDirectory];
3965 return [documents stringByAppendingPathComponent: AngbandDirectoryNameBase];
3970 * Adjust directory paths as needed to correct for any differences needed by
3971 * Angband. init_file_paths() currently requires that all paths provided have
3972 * a trailing slash and all other platforms honor this.
3974 * \param originalPath The directory path to adjust.
3975 * \return A path suitable for Angband or nil if an error occurred.
3977 static NSString* AngbandCorrectedDirectoryPath(NSString *originalPath)
3979 if ([originalPath length] == 0) {
3983 if (![originalPath hasSuffix: @"/"]) {
3984 return [originalPath stringByAppendingString: @"/"];
3987 return originalPath;
3991 * Give Angband the base paths that should be used for the various directories
3992 * it needs. It will create any needed directories.
3994 static void prepare_paths_and_directories(void)
3996 char libpath[PATH_MAX + 1] = "\0";
3997 NSString *libDirectoryPath =
3998 AngbandCorrectedDirectoryPath(get_lib_directory());
3999 [libDirectoryPath getFileSystemRepresentation: libpath maxLength: sizeof(libpath)];
4001 char basepath[PATH_MAX + 1] = "\0";
4002 NSString *angbandDocumentsPath =
4003 AngbandCorrectedDirectoryPath(get_doc_directory());
4004 [angbandDocumentsPath getFileSystemRepresentation: basepath maxLength: sizeof(basepath)];
4006 init_file_paths(libpath, basepath);
4007 create_needed_dirs();
4011 * Play sound effects asynchronously. Select a sound from any available
4012 * for the required event, and bridge to Cocoa to play it.
4014 static void play_sound(int event)
4016 [[AngbandSoundCatalog sharedSounds] playSound:event];
4020 * ------------------------------------------------------------------------
4022 * ------------------------------------------------------------------------ */
4024 @implementation AngbandAppDelegate
4026 @synthesize graphicsMenu=_graphicsMenu;
4027 @synthesize commandMenu=_commandMenu;
4028 @synthesize commandMenuTagMap=_commandMenuTagMap;
4030 - (IBAction)newGame:sender
4032 /* Game is in progress */
4033 game_in_progress = TRUE;
4037 - (IBAction)editFont:sender
4039 NSFontPanel *panel = [NSFontPanel sharedFontPanel];
4040 NSFont *termFont = [AngbandContext defaultFont];
4043 for (i=0; i < ANGBAND_TERM_MAX; i++) {
4044 AngbandContext *context =
4045 (__bridge AngbandContext*) (angband_term[i]->data);
4046 if ([context isMainWindow]) {
4047 termFont = [context angbandViewFont];
4052 [panel setPanelFont:termFont isMultiple:NO];
4053 [panel orderFront:self];
4057 * Implement NSObject's changeFont() method to receive a notification about the
4058 * changed font. Note that, as of 10.14, changeFont() is deprecated in
4059 * NSObject - it will be removed at some point and the application delegate
4060 * will have to be declared as implementing the NSFontChanging protocol.
4062 - (void)changeFont:(id)sender
4065 for (mainTerm=0; mainTerm < ANGBAND_TERM_MAX; mainTerm++) {
4066 AngbandContext *context =
4067 (__bridge AngbandContext*) (angband_term[mainTerm]->data);
4068 if ([context isMainWindow]) {
4073 /* Bug #1709: Only change font for angband windows */
4074 if (mainTerm == ANGBAND_TERM_MAX) return;
4076 NSFont *oldFont = [AngbandContext defaultFont];
4077 NSFont *newFont = [sender convertFont:oldFont];
4078 if (! newFont) return; /*paranoia */
4080 /* Store as the default font if we changed the first term */
4081 if (mainTerm == 0) {
4082 [AngbandContext setDefaultFont:newFont];
4085 /* Record it in the preferences */
4086 NSUserDefaults *defs = [NSUserDefaults angbandDefaults];
4087 [defs setValue:[newFont fontName]
4088 forKey:[NSString stringWithFormat:@"FontName-%d", mainTerm]];
4089 [defs setFloat:[newFont pointSize]
4090 forKey:[NSString stringWithFormat:@"FontSize-%d", mainTerm]];
4092 NSDisableScreenUpdates();
4095 AngbandContext *angbandContext =
4096 (__bridge AngbandContext*) (angband_term[mainTerm]->data);
4097 [(id)angbandContext setSelectionFont:newFont adjustTerminal: YES];
4099 NSEnableScreenUpdates();
4101 if (mainTerm == 0 && game_in_progress) {
4102 /* Mimics the logic in setGraphicsMode(). */
4104 wakeup_event_loop();
4106 [(id)angbandContext requestRedraw];
4110 - (IBAction)openGame:sender
4113 BOOL selectedSomething = NO;
4116 /* Get where we think the save files are */
4117 NSURL *startingDirectoryURL =
4118 [NSURL fileURLWithPath:[NSString stringWithCString:ANGBAND_DIR_SAVE encoding:NSASCIIStringEncoding]
4121 /* Set up an open panel */
4122 NSOpenPanel* panel = [NSOpenPanel openPanel];
4123 [panel setCanChooseFiles:YES];
4124 [panel setCanChooseDirectories:NO];
4125 [panel setResolvesAliases:YES];
4126 [panel setAllowsMultipleSelection:NO];
4127 [panel setTreatsFilePackagesAsDirectories:YES];
4128 [panel setDirectoryURL:startingDirectoryURL];
4131 panelResult = [panel runModal];
4132 if (panelResult == NSOKButton)
4134 NSArray* fileURLs = [panel URLs];
4135 if ([fileURLs count] > 0 && [[fileURLs objectAtIndex:0] isFileURL])
4137 NSURL* savefileURL = (NSURL *)[fileURLs objectAtIndex:0];
4139 * The path property doesn't do the right thing except for
4140 * URLs with the file scheme. We had
4141 * getFileSystemRepresentation here before, but that wasn't
4142 * introduced until OS X 10.9.
4144 selectedSomething = [[savefileURL path]
4146 maxLength:sizeof savefile
4147 encoding:NSMacOSRomanStringEncoding];
4151 if (selectedSomething)
4153 /* Remember this so we can select it by default next time */
4154 record_current_savefile();
4156 /* Game is in progress */
4157 game_in_progress = TRUE;
4162 - (IBAction)saveGame:sender
4164 /* Hack -- Forget messages */
4168 do_cmd_save_game(FALSE);
4170 /* Record the current save file so we can select it by default next time.
4171 * It's a little sketchy that this only happens when we save through the
4172 * menu; ideally game-triggered saves would trigger it too. */
4173 record_current_savefile();
4177 * Create and initialize Angband terminal number "termIndex".
4179 - (void)linkTermData:(int)termIndex
4181 NSArray *terminalDefaults = [[NSUserDefaults standardUserDefaults]
4182 valueForKey: AngbandTerminalsDefaultsKey];
4183 NSInteger rows = 24;
4184 NSInteger columns = 80;
4186 if (termIndex < (int)[terminalDefaults count]) {
4187 NSDictionary *term = [terminalDefaults objectAtIndex:termIndex];
4188 rows = [[term valueForKey: AngbandTerminalRowsDefaultsKey]
4190 columns = [[term valueForKey: AngbandTerminalColumnsDefaultsKey]
4195 term *newterm = ZNEW(term);
4197 /* Initialize the term */
4198 term_init(newterm, columns, rows, 256 /* keypresses, for some reason? */);
4200 /* Differentiate between BS/^h, Tab/^i, etc. */
4201 /* newterm->complex_input = TRUE; */
4203 /* Use a "software" cursor */
4204 newterm->soft_cursor = TRUE;
4206 /* Disable the per-row flush notifications since they are not used. */
4207 newterm->never_frosh = TRUE;
4209 /* Erase with "white space" */
4210 newterm->attr_blank = TERM_WHITE;
4211 newterm->char_blank = ' ';
4213 /* Prepare the init/nuke hooks */
4214 newterm->init_hook = Term_init_cocoa;
4215 newterm->nuke_hook = Term_nuke_cocoa;
4217 /* Prepare the function hooks */
4218 newterm->xtra_hook = Term_xtra_cocoa;
4219 newterm->wipe_hook = Term_wipe_cocoa;
4220 newterm->curs_hook = Term_curs_cocoa;
4221 newterm->bigcurs_hook = Term_bigcurs_cocoa;
4222 newterm->text_hook = Term_text_cocoa;
4223 newterm->pict_hook = Term_pict_cocoa;
4224 /* newterm->mbcs_hook = Term_mbcs_cocoa; */
4226 /* Global pointer */
4227 angband_term[termIndex] = newterm;
4231 * Allocate the primary Angband terminal and activate it. Allocate the other
4232 * Angband terminals.
4234 - (void)initWindows {
4235 for (int i = 0; i < ANGBAND_TERM_MAX; i++) {
4236 [self linkTermData:i];
4239 Term_activate(angband_term[0]);
4243 * Load preferences from preferences file for current host+current user+
4244 * current application.
4248 NSUserDefaults *defs = [NSUserDefaults angbandDefaults];
4250 /* Make some default defaults */
4251 NSMutableArray *defaultTerms = [[NSMutableArray alloc] init];
4254 * The following default rows/cols were determined experimentally by first
4255 * finding the ideal window/font size combinations. But because of awful
4256 * temporal coupling in Term_init_cocoa(), it's impossible to set up the
4257 * defaults there, so we do it this way.
4259 for (NSUInteger i = 0; i < ANGBAND_TERM_MAX; i++) {
4295 NSDictionary *standardTerm =
4296 [NSDictionary dictionaryWithObjectsAndKeys:
4297 [NSNumber numberWithInt: rows], AngbandTerminalRowsDefaultsKey,
4298 [NSNumber numberWithInt: columns], AngbandTerminalColumnsDefaultsKey,
4299 [NSNumber numberWithBool: visible], AngbandTerminalVisibleDefaultsKey,
4301 [defaultTerms addObject: standardTerm];
4304 NSDictionary *defaults = [[NSDictionary alloc] initWithObjectsAndKeys:
4306 @"Osaka", @"FontName",
4308 @"Menlo", @"FontName",
4310 [NSNumber numberWithFloat:13.f], @"FontSize",
4311 [NSNumber numberWithInt:60], AngbandFrameRateDefaultsKey,
4312 [NSNumber numberWithBool:YES], AngbandSoundDefaultsKey,
4313 [NSNumber numberWithInt:GRAPHICS_NONE], AngbandGraphicsDefaultsKey,
4314 [NSNumber numberWithBool:YES], AngbandBigTileDefaultsKey,
4315 defaultTerms, AngbandTerminalsDefaultsKey,
4317 [defs registerDefaults:defaults];
4319 /* Preferred graphics mode */
4320 graf_mode_req = [defs integerForKey:AngbandGraphicsDefaultsKey];
4321 if (graf_mode_req != GRAPHICS_NONE &&
4322 get_graphics_mode(graf_mode_req)->grafID != GRAPHICS_NONE &&
4323 [defs boolForKey:AngbandBigTileDefaultsKey] == YES) {
4327 use_bigtile = FALSE;
4328 arg_bigtile = FALSE;
4331 /* Use sounds; set the Angband global */
4332 if ([defs boolForKey:AngbandSoundDefaultsKey] == YES) {
4334 [AngbandSoundCatalog sharedSounds].enabled = YES;
4337 [AngbandSoundCatalog sharedSounds].enabled = NO;
4341 frames_per_second = [defs integerForKey:AngbandFrameRateDefaultsKey];
4345 setDefaultFont:[NSFont fontWithName:[defs valueForKey:@"FontName-0"]
4346 size:[defs floatForKey:@"FontSize-0"]]];
4347 if (! [AngbandContext defaultFont])
4349 setDefaultFont:[NSFont fontWithName:@"Menlo" size:13.]];
4353 * Entry point for initializing Angband
4358 /* Hooks in some "z-util.c" hooks */
4359 plog_aux = hook_plog;
4360 quit_aux = hook_quit;
4362 /* Initialize file paths */
4363 prepare_paths_and_directories();
4365 /* Note the "system" */
4366 ANGBAND_SYS = "coc";
4368 /* Load possible graphics modes */
4369 init_graphics_modes();
4371 /* Load preferences */
4374 /* Prepare the windows */
4377 /* Set up game event handlers */
4378 /* init_display(); */
4380 /* Register the sound hook */
4381 /* sound_hook = play_sound; */
4383 /* Initialise game */
4386 /* Initialize some save file stuff */
4387 player_egid = getegid();
4389 /* We are now initialized */
4392 /* Handle "open_when_ready" */
4393 handle_open_when_ready();
4395 /* Handle pending events (most notably update) and flush input */
4398 /* Prompt the user */
4399 int message_row = (Term->hgt - 23) / 5 + 23;
4400 Term_erase(0, message_row, 255);
4403 "['ファイル' メニューから '新' または '開く' を選択します]",
4404 message_row, (Term->wid - 57) / 2
4406 "[Choose 'New' or 'Open' from the 'File' menu]",
4407 message_row, (Term->wid - 45) / 2
4413 while (!game_in_progress) {
4415 NSEvent *event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:[NSDate distantFuture] inMode:NSDefaultRunLoopMode dequeue:YES];
4416 if (event) [NSApp sendEvent:event];
4421 * Play a game -- "new_game" is set by "new", "open" or the open document
4422 * even handler as appropriate
4425 play_game(new_game);
4431 * Implement NSObject's validateMenuItem() method to override enabling or
4432 * disabling a menu item. Note that, as of 10.14, validateMenuItem() is
4433 * deprecated in NSObject - it will be removed at some point and the
4434 * application delegate will have to be declared as implementing the
4435 * NSMenuItemValidation protocol.
4437 - (BOOL)validateMenuItem:(NSMenuItem *)menuItem
4439 SEL sel = [menuItem action];
4440 NSInteger tag = [menuItem tag];
4442 if( tag >= AngbandWindowMenuItemTagBase && tag < AngbandWindowMenuItemTagBase + ANGBAND_TERM_MAX )
4444 if( tag == AngbandWindowMenuItemTagBase )
4446 /* The main window should always be available and visible */
4452 * Another window is only usable after Term_init_cocoa() has
4453 * been called for it. For Angband if window_flag[i] is nonzero
4454 * then that has happened for window i. For Hengband, that is
4455 * not the case so also test angband_term[i]->data.
4457 NSInteger subwindowNumber = tag - AngbandWindowMenuItemTagBase;
4458 return (angband_term[subwindowNumber]->data != 0
4459 && window_flag[subwindowNumber] > 0);
4465 if (sel == @selector(newGame:))
4467 return ! game_in_progress;
4469 else if (sel == @selector(editFont:))
4473 else if (sel == @selector(openGame:))
4475 return ! game_in_progress;
4477 else if (sel == @selector(setRefreshRate:) &&
4478 [[menuItem parentItem] tag] == 150)
4480 NSInteger fps = [[NSUserDefaults standardUserDefaults] integerForKey:AngbandFrameRateDefaultsKey];
4481 [menuItem setState: ([menuItem tag] == fps)];
4484 else if( sel == @selector(setGraphicsMode:) )
4486 NSInteger requestedGraphicsMode = [[NSUserDefaults standardUserDefaults] integerForKey:AngbandGraphicsDefaultsKey];
4487 [menuItem setState: (tag == requestedGraphicsMode)];
4490 else if( sel == @selector(toggleSound:) )
4492 BOOL is_on = [[NSUserDefaults standardUserDefaults]
4493 boolForKey:AngbandSoundDefaultsKey];
4495 [menuItem setState: ((is_on) ? NSOnState : NSOffState)];
4498 else if( sel == @selector(sendAngbandCommand:) ||
4499 sel == @selector(saveGame:) )
4502 * we only want to be able to send commands during an active game
4503 * after the birth screens
4505 return !!game_in_progress && character_generated;
4511 - (IBAction)setRefreshRate:(NSMenuItem *)menuItem
4513 frames_per_second = [menuItem tag];
4514 [[NSUserDefaults angbandDefaults] setInteger:frames_per_second forKey:AngbandFrameRateDefaultsKey];
4517 - (void)setGraphicsMode:(NSMenuItem *)sender
4519 /* We stashed the graphics mode ID in the menu item's tag */
4520 graf_mode_req = [sender tag];
4522 /* Stash it in UserDefaults */
4523 [[NSUserDefaults angbandDefaults] setInteger:graf_mode_req forKey:AngbandGraphicsDefaultsKey];
4525 if (graf_mode_req == GRAPHICS_NONE ||
4526 get_graphics_mode(graf_mode_req) == GRAPHICS_NONE) {
4528 arg_bigtile = FALSE;
4530 } else if ([[NSUserDefaults angbandDefaults] boolForKey:AngbandBigTileDefaultsKey] == YES &&
4535 if (game_in_progress)
4537 if (arg_bigtile != use_bigtile) {
4538 Term_activate(angband_term[0]);
4539 Term_resize(angband_term[0]->wid, angband_term[0]->hgt);
4542 /* Hack -- Force redraw */
4545 /* Wake up the event loop so it notices the change */
4546 wakeup_event_loop();
4550 - (void)selectWindow: (id)sender
4552 NSInteger subwindowNumber =
4553 [(NSMenuItem *)sender tag] - AngbandWindowMenuItemTagBase;
4554 AngbandContext *context =
4555 (__bridge AngbandContext*) (angband_term[subwindowNumber]->data);
4556 [context.primaryWindow makeKeyAndOrderFront: self];
4557 [context saveWindowVisibleToDefaults: YES];
4560 - (IBAction) toggleSound: (NSMenuItem *) sender
4562 BOOL is_on = (sender.state == NSOnState);
4564 /* Toggle the state and update the Angband global and preferences. */
4566 sender.state = NSOffState;
4568 [AngbandSoundCatalog sharedSounds].enabled = NO;
4570 sender.state = NSOnState;
4572 [AngbandSoundCatalog sharedSounds].enabled = YES;
4574 [[NSUserDefaults angbandDefaults] setBool:(! is_on)
4575 forKey:AngbandSoundDefaultsKey];
4578 - (IBAction)toggleWideTiles:(NSMenuItem *) sender
4580 BOOL is_on = (sender.state == NSOnState);
4582 /* Toggle the state and update the Angband globals and preferences. */
4583 sender.state = (is_on) ? NSOffState : NSOnState;
4584 [[NSUserDefaults angbandDefaults] setBool:(! is_on)
4585 forKey:AngbandBigTileDefaultsKey];
4586 if (graphics_are_enabled()) {
4587 arg_bigtile = (is_on) ? FALSE : TRUE;
4588 /* Mimics the logic in setGraphicsMode(). */
4589 if (game_in_progress && arg_bigtile != use_bigtile) {
4590 Term_activate(angband_term[0]);
4591 Term_resize(angband_term[0]->wid, angband_term[0]->hgt);
4593 wakeup_event_loop();
4598 - (void)prepareWindowsMenu
4602 * Get the window menu with default items and add a separator and
4603 * item for the main window.
4605 NSMenu *windowsMenu = [[NSApplication sharedApplication] windowsMenu];
4606 [windowsMenu addItem: [NSMenuItem separatorItem]];
4608 NSString *title1 = [NSString stringWithCString:angband_term_name[0]
4610 encoding:NSJapaneseEUCStringEncoding
4612 encoding:NSMacOSRomanStringEncoding
4615 NSMenuItem *angbandItem = [[NSMenuItem alloc] initWithTitle:title1 action: @selector(selectWindow:) keyEquivalent: @"0"];
4616 [angbandItem setTarget: self];
4617 [angbandItem setTag: AngbandWindowMenuItemTagBase];
4618 [windowsMenu addItem: angbandItem];
4620 /* Add items for the additional term windows */
4621 for( NSInteger i = 1; i < ANGBAND_TERM_MAX; i++ )
4623 NSString *title = [NSString stringWithCString:angband_term_name[i]
4625 encoding:NSJapaneseEUCStringEncoding
4627 encoding:NSMacOSRomanStringEncoding
4630 NSString *keyEquivalent =
4631 [NSString stringWithFormat: @"%ld", (long)i];
4632 NSMenuItem *windowItem =
4633 [[NSMenuItem alloc] initWithTitle: title
4634 action: @selector(selectWindow:)
4635 keyEquivalent: keyEquivalent];
4636 [windowItem setTarget: self];
4637 [windowItem setTag: AngbandWindowMenuItemTagBase + i];
4638 [windowsMenu addItem: windowItem];
4644 * Send a command to Angband via a menu item. This places the appropriate key
4645 * down events into the queue so that it seems like the user pressed them
4646 * (instead of trying to use the term directly).
4648 - (void)sendAngbandCommand: (id)sender
4650 NSMenuItem *menuItem = (NSMenuItem *)sender;
4651 NSString *command = [self.commandMenuTagMap objectForKey: [NSNumber numberWithInteger: [menuItem tag]]];
4652 AngbandContext* context =
4653 (__bridge AngbandContext*) (angband_term[0]->data);
4654 NSInteger windowNumber = [context.primaryWindow windowNumber];
4656 /* Send a \ to bypass keymaps */
4657 NSEvent *escape = [NSEvent keyEventWithType: NSKeyDown
4658 location: NSZeroPoint
4661 windowNumber: windowNumber
4664 charactersIgnoringModifiers: @"\\"
4667 [[NSApplication sharedApplication] postEvent: escape atStart: NO];
4669 /* Send the actual command (from the original command set) */
4670 NSEvent *keyDown = [NSEvent keyEventWithType: NSKeyDown
4671 location: NSZeroPoint
4674 windowNumber: windowNumber
4677 charactersIgnoringModifiers: command
4680 [[NSApplication sharedApplication] postEvent: keyDown atStart: NO];
4684 * Set up the command menu dynamically, based on CommandMenu.plist.
4686 - (void)prepareCommandMenu
4689 NSString *commandMenuPath =
4690 [[NSBundle mainBundle] pathForResource: @"CommandMenu"
4692 NSArray *commandMenuItems =
4693 [[NSArray alloc] initWithContentsOfFile: commandMenuPath];
4694 NSMutableDictionary *angbandCommands =
4695 [[NSMutableDictionary alloc] init];
4696 NSString *tblname = @"CommandMenu";
4697 NSInteger tagOffset = 0;
4699 for( NSDictionary *item in commandMenuItems )
4701 BOOL useShiftModifier =
4702 [[item valueForKey: @"ShiftModifier"] boolValue];
4703 BOOL useOptionModifier =
4704 [[item valueForKey: @"OptionModifier"] boolValue];
4705 NSUInteger keyModifiers = NSCommandKeyMask;
4706 keyModifiers |= (useShiftModifier) ? NSShiftKeyMask : 0;
4707 keyModifiers |= (useOptionModifier) ? NSAlternateKeyMask : 0;
4709 NSString *lookup = [item valueForKey: @"Title"];
4710 NSString *title = NSLocalizedStringWithDefaultValue(
4711 lookup, tblname, [NSBundle mainBundle], lookup, @"");
4712 NSString *key = [item valueForKey: @"KeyEquivalent"];
4713 NSMenuItem *menuItem =
4714 [[NSMenuItem alloc] initWithTitle: title
4715 action: @selector(sendAngbandCommand:)
4716 keyEquivalent: key];
4717 [menuItem setTarget: self];
4718 [menuItem setKeyEquivalentModifierMask: keyModifiers];
4719 [menuItem setTag: AngbandCommandMenuItemTagBase + tagOffset];
4720 [self.commandMenu addItem: menuItem];
4722 NSString *angbandCommand = [item valueForKey: @"AngbandCommand"];
4723 [angbandCommands setObject: angbandCommand
4724 forKey: [NSNumber numberWithInteger: [menuItem tag]]];
4728 self.commandMenuTagMap = [[NSDictionary alloc]
4729 initWithDictionary: angbandCommands];
4733 - (void)awakeFromNib
4735 [super awakeFromNib];
4737 [self prepareWindowsMenu];
4738 [self prepareCommandMenu];
4741 - (void)applicationDidFinishLaunching:sender
4745 /* Once beginGame finished, the game is over - that's how Angband works,
4746 * and we should quit */
4747 game_is_finished = TRUE;
4748 [NSApp terminate:self];
4751 - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
4753 if (p_ptr->playing == FALSE || game_is_finished == TRUE)
4755 return NSTerminateNow;
4757 else if (! inkey_flag)
4759 /* For compatibility with other ports, do not quit in this case */
4760 return NSTerminateCancel;
4765 /* player->upkeep->playing = FALSE; */
4767 /* Post an escape event so that we can return from our get-key-event
4769 wakeup_event_loop();
4770 quit_when_ready = true;
4771 /* Must return Cancel, not Later, because we need to get out of the
4772 * run loop and back to Angband's loop */
4773 return NSTerminateCancel;
4778 * Dynamically build the Graphics menu
4780 - (void)menuNeedsUpdate:(NSMenu *)menu {
4782 /* Only the graphics menu is dynamic */
4783 if (! [menu isEqual:self.graphicsMenu])
4786 /* If it's non-empty, then we've already built it. Currently graphics modes
4787 * won't change once created; if they ever can we can remove this check.
4788 * Note that the check mark does change, but that's handled in
4789 * validateMenuItem: instead of menuNeedsUpdate: */
4790 if ([menu numberOfItems] > 0)
4793 /* This is the action for all these menu items */
4794 SEL action = @selector(setGraphicsMode:);
4796 /* Add an initial Classic ASCII menu item */
4797 NSString *tblname = @"GraphicsMenu";
4798 NSString *key = @"Classic ASCII";
4799 NSString *title = NSLocalizedStringWithDefaultValue(
4800 key, tblname, [NSBundle mainBundle], key, @"");
4801 NSMenuItem *classicItem = [menu addItemWithTitle:title action:action keyEquivalent:@""];
4802 [classicItem setTag:GRAPHICS_NONE];
4804 /* Walk through the list of graphics modes */
4805 if (graphics_modes) {
4808 for (i=0; graphics_modes[i].pNext; i++)
4810 const graphics_mode *graf = &graphics_modes[i];
4812 if (graf->grafID == GRAPHICS_NONE) {
4815 /* Make the title. NSMenuItem throws on a nil title, so ensure it's
4817 key = [[NSString alloc] initWithUTF8String:graf->menuname];
4818 title = NSLocalizedStringWithDefaultValue(
4819 key, tblname, [NSBundle mainBundle], key, @"");
4822 NSMenuItem *item = [menu addItemWithTitle:title action:action keyEquivalent:@""];
4823 [item setTag:graf->grafID];
4829 * Delegate method that gets called if we're asked to open a file.
4831 - (void)application:(NSApplication *)sender openFiles:(NSArray *)filenames
4833 /* Can't open a file once we've started */
4834 if (game_in_progress) {
4835 [[NSApplication sharedApplication]
4836 replyToOpenOrPrint:NSApplicationDelegateReplyFailure];
4840 /* We can only open one file. Use the last one. */
4841 NSString *file = [filenames lastObject];
4843 [[NSApplication sharedApplication]
4844 replyToOpenOrPrint:NSApplicationDelegateReplyFailure];
4848 /* Put it in savefile */
4849 if (! [file getFileSystemRepresentation:savefile maxLength:sizeof savefile]) {
4850 [[NSApplication sharedApplication]
4851 replyToOpenOrPrint:NSApplicationDelegateReplyFailure];
4855 game_in_progress = TRUE;
4857 /* Wake us up in case this arrives while we're sitting at the Welcome
4859 wakeup_event_loop();
4861 [[NSApplication sharedApplication]
4862 replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
4867 int main(int argc, char* argv[])
4869 NSApplicationMain(argc, (void*)argv);
4873 #endif /* MACINTOSH || MACH_O_COCOA */