OSDN Git Service

Be more consistent about the format of comments.
[hengbandforosx/hengbandosx.git] / src / main-cocoa.m
1 /**
2  * \file main-cocoa.m
3  * \brief OS X front end
4  *
5  * Copyright (c) 2011 Peter Ammon
6  *
7  * This work is free software; you can redistribute it and/or modify it
8  * under the terms of either:
9  *
10  * a) the GNU General Public License as published by the Free Software
11  *    Foundation, version 2, or
12  *
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.
17  */
18
19 #include "angband.h"
20 /* This is not included in angband.h in Hengband. */
21 #include "grafmode.h"
22
23 #if defined(MACH_O_COCOA)
24
25 /* Mac headers */
26 #import "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
30 #define kVK_Tab    0x30
31 #define kVK_Delete 0x33
32 #define kVK_Escape 0x35
33 #define kVK_ANSI_KeypadEnter 0x4C
34
35 static NSString * const AngbandDirectoryNameLib = @"lib";
36 static NSString * const AngbandDirectoryNameBase = @VERSION_NAME;
37
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;
49
50 /* Global defines etc from Angband 3.5-dev - NRM */
51 #define ANGBAND_TERM_MAX 8
52
53 #define MAX_COLORS 256
54 #define MSG_MAX SOUND_MAX
55
56 /* End Angband stuff - NRM */
57
58 /* Application defined event numbers */
59 enum
60 {
61     AngbandEventWakeup = 1
62 };
63
64 /* Delay handling of pre-emptive "quit" event */
65 static BOOL quit_when_ready = FALSE;
66
67 /* Set to indicate the game is over and we can quit without delay */
68 static Boolean game_is_finished = FALSE;
69
70 /* Our frames per second (e.g. 60). A value of 0 means unthrottled. */
71 static int frames_per_second;
72
73 /* Force a new game or not? */
74 static bool new_game = FALSE;
75
76 @class AngbandView;
77
78 #ifdef JP
79 static wchar_t convert_two_byte_eucjp_to_utf16_native(const char *cp);
80 #endif
81
82 /**
83  * Load sound effects based on sound.cfg within the xtra/sound directory;
84  * bridge to Cocoa to use NSSound for simple loading and playback, avoiding
85  * I/O latency by caching all sounds at the start.  Inherits full sound
86  * format support from Quicktime base/plugins.
87  * pelpel favoured a plist-based parser for the future but .cfg support
88  * improves cross-platform compatibility.
89  */
90 @interface AngbandSoundCatalog : NSObject {
91 @private
92     /**
93      * Stores instances of NSSound keyed by path so the same sound can be
94      * used for multiple events.
95      */
96     NSMutableDictionary *soundsByPath;
97     /**
98      * Stores arrays of NSSound keyed by event number.
99      */
100     NSMutableDictionary *soundArraysByEvent;
101 }
102
103 /**
104  * If NO, then playSound effectively becomes a do nothing operation.
105  */
106 @property (getter=isEnabled) BOOL enabled;
107
108 /**
109  * Set up for lazy initialization in playSound().  Set enabled to NO.
110  */
111 - (id)init;
112
113 /**
114  * If self.enabled is YES and the given event has one or more sounds
115  * corresponding to it in the catalog, plays one of those sounds, chosen at
116  * random.
117  */
118 - (void)playSound:(int)event;
119
120 /**
121  * Impose an arbitrary limit on the number of possible samples per event.
122  * Currently not declaring this as a class property for compatibility with
123  * versions of Xcode prior to 8.
124  */
125 + (int)maxSamples;
126
127 /**
128  * Return the shared sound catalog instance, creating it if it does not
129  * exist yet.  Currently not declaring this as a class property for
130  * compatibility with versions of Xcode prior to 8.
131  */
132 + (AngbandSoundCatalog*)sharedSounds;
133
134 /**
135  * Release any resources associated with shared sounds.
136  */
137 + (void)clearSharedSounds;
138
139 @end
140
141 @implementation AngbandSoundCatalog
142
143 - (id)init {
144     if (self = [super init]) {
145         self->soundsByPath = nil;
146         self->soundArraysByEvent = nil;
147         self->_enabled = NO;
148     }
149     return self;
150 }
151
152 - (void)playSound:(int)event {
153     if (! self.enabled) {
154         return;
155     }
156
157     /* Initialize when the first sound is played. */
158     if (self->soundArraysByEvent == nil) {
159         /* Build the "sound" path */
160         char sound_dir[1024];
161         path_build(sound_dir, sizeof(sound_dir), ANGBAND_DIR_XTRA, "sound");
162
163         /* Find and open the config file */
164         char path[1024];
165         path_build(path, sizeof(path), sound_dir, "sound.cfg");
166         FILE *fff = my_fopen(path, "r");
167
168         /* Handle errors */
169         if (!fff) {
170             NSLog(@"The sound configuration file could not be opened.");
171             return;
172         }
173
174         self->soundsByPath = [[NSMutableDictionary alloc] init];
175         self->soundArraysByEvent = [[NSMutableDictionary alloc] init];
176         @autoreleasepool {
177             /*
178              * This loop may take a while depending on the count and size of
179              * samples to load.
180              */
181
182             /* Parse the file */
183             /* Lines are always of the form "name = sample [sample ...]" */
184             char buffer[2048];
185             while (my_fgets(fff, buffer, sizeof(buffer)) == 0) {
186                 char *msg_name;
187                 char *cfg_sample_list;
188                 char *search;
189                 char *cur_token;
190                 char *next_token;
191                 int event;
192
193                 /* Skip anything not beginning with an alphabetic character */
194                 if (!buffer[0] || !isalpha((unsigned char)buffer[0])) continue;
195
196                 /* Split the line into two: message name, and the rest */
197                 search = strchr(buffer, ' ');
198                 cfg_sample_list = strchr(search + 1, ' ');
199                 if (!search) continue;
200                 if (!cfg_sample_list) continue;
201
202                 /* Set the message name, and terminate at first space */
203                 msg_name = buffer;
204                 search[0] = '\0';
205
206                 /* Make sure this is a valid event name */
207                 for (event = MSG_MAX - 1; event >= 0; event--) {
208                     if (strcmp(msg_name, angband_sound_name[event]) == 0)
209                         break;
210                 }
211                 if (event < 0) continue;
212
213                 /*
214                  * Advance the sample list pointer so it's at the beginning of
215                  * text.
216                  */
217                 cfg_sample_list++;
218                 if (!cfg_sample_list[0]) continue;
219
220                 /* Terminate the current token */
221                 cur_token = cfg_sample_list;
222                 search = strchr(cur_token, ' ');
223                 if (search) {
224                     search[0] = '\0';
225                     next_token = search + 1;
226                 } else {
227                     next_token = NULL;
228                 }
229
230                 /*
231                  * Now we find all the sample names and add them one by one
232                  */
233                 while (cur_token) {
234                     NSMutableArray *soundSamples =
235                         [self->soundArraysByEvent
236                              objectForKey:[NSNumber numberWithInteger:event]];
237                     if (soundSamples == nil) {
238                         soundSamples = [[NSMutableArray alloc] init];
239                         [self->soundArraysByEvent
240                              setObject:soundSamples
241                              forKey:[NSNumber numberWithInteger:event]];
242                     }
243                     int num = (int) soundSamples.count;
244
245                     /* Don't allow too many samples */
246                     if (num >= [AngbandSoundCatalog maxSamples]) break;
247
248                     NSString *token_string =
249                         [NSString stringWithUTF8String:cur_token];
250                     NSSound *sound =
251                         [self->soundsByPath objectForKey:token_string];
252
253                     if (! sound) {
254                         /*
255                          * We have to load the sound. Build the path to the
256                          * sample.
257                          */
258                         path_build(path, sizeof(path), sound_dir, cur_token);
259                         struct stat stb;
260                         if (stat(path, &stb) == 0) {
261                             /* Load the sound into memory */
262                             sound = [[NSSound alloc]
263                                          initWithContentsOfFile:[NSString stringWithUTF8String:path]
264                                          byReference:YES];
265                             if (sound) {
266                                 [self->soundsByPath setObject:sound
267                                             forKey:token_string];
268                             }
269                         }
270                     }
271
272                     /* Store it if we loaded it */
273                     if (sound) {
274                         [soundSamples addObject:sound];
275                     }
276
277                     /* Figure out next token */
278                     cur_token = next_token;
279                     if (next_token) {
280                          /* Try to find a space */
281                          search = strchr(cur_token, ' ');
282
283                          /*
284                           * If we can find one, terminate, and set new "next".
285                           */
286                          if (search) {
287                              search[0] = '\0';
288                              next_token = search + 1;
289                          } else {
290                              /* Otherwise prevent infinite looping */
291                              next_token = NULL;
292                          }
293                     }
294                 }
295             }
296         }
297
298         /* Close the file */
299         my_fclose(fff);
300     }
301
302     @autoreleasepool {
303         NSMutableArray *samples =
304             [self->soundArraysByEvent
305                  objectForKey:[NSNumber numberWithInteger:event]];
306
307         if (samples == nil || samples.count == 0) {
308             return;
309         }
310
311         /* Choose a random event. */
312         int s = randint0((int) samples.count);
313         NSSound *sound = samples[s];
314
315         if ([sound isPlaying])
316             [sound stop];
317
318         /* Play the sound. */
319         [sound play];
320     }
321 }
322
323 + (int)maxSamples {
324     return 16;
325 }
326
327 /**
328  * For sharedSounds and clearSharedSounds.
329  */
330 static __strong AngbandSoundCatalog* gSharedSounds = nil;
331
332 + (AngbandSoundCatalog*)sharedSounds {
333     if (gSharedSounds == nil) {
334         gSharedSounds = [[AngbandSoundCatalog alloc] init];
335     }
336     return gSharedSounds;
337 }
338
339 + (void)clearSharedSounds {
340     gSharedSounds = nil;
341 }
342
343 @end
344
345 /**
346  * Each location in the terminal either stores a character, a tile,
347  * padding for a big tile, or padding for a big character (for example a
348  * kanji that takes two columns).  These structures represent that.  Note
349  * that tiles do not overlap with each other (excepting the double-height
350  * tiles, i.e. from the Shockbolt set; that's handled as a special case).
351  * Characters can overlap horizontally:  that is for handling fonts that
352  * aren't fixed width.
353  */
354 struct TerminalCellChar {
355     wchar_t glyph;
356     int attr;
357 };
358 struct TerminalCellTile {
359     /*
360      * These are the coordinates, within the tile set, for the foreground
361      * tile and background tile.
362      */
363     char fgdCol, fgdRow, bckCol, bckRow;
364 };
365 struct TerminalCellPadding {
366        /*
367         * If the cell at (x, y) is padding, the cell at (x - hoff, y - voff)
368         * has the attributes affecting the padded region.
369         */
370     unsigned char hoff, voff;
371 };
372 struct TerminalCell {
373     union {
374         struct TerminalCellChar ch;
375         struct TerminalCellTile ti;
376         struct TerminalCellPadding pd;
377     } v;
378     /*
379      * Used for big characters or tiles which are hscl x vscl cells.
380      * The upper left corner of the big tile or character is marked as
381      * TERM_CELL_TILE or TERM_CELL_CHAR.  The remainder are marked as
382      * TERM_CELL_TILE_PADDING or TERM_CELL_CHAR_PADDING and have hscl and
383      * vscl set to matcn what's in the upper left corner.  Big tiles are
384      * tiles scaled up to occupy more space.  Big characters, on the other
385      * hand, are characters that naturally take up more space than standard
386      * for the font with the assumption that vscl will be one for any big
387      * character and hscl will hold the number of columns it occupies (likely
388      * just 2, i.e. for Japanese kanji).
389      */
390     unsigned char hscl;
391     unsigned char vscl;
392     /*
393      * Hold the offsets, as fractions of the tile size expressed as the
394      * rational numbers hoff_n / hoff_d and voff_n / voff_d, within the tile
395      * or character.  For something that is not a big tile or character, these
396      * will be 0, 0, 1, and 1.  For a big tile or character, these will be
397      * set when the tile or character is changed to be 0, 0, hscl, and vscl
398      * for the upper left corner and i, j, hscl, vscl for the padding element
399      * at (i, j) relative to the upper left corner.  For a big tile or
400      * character that is partially overwritten, these are not modified in the
401      * parts that are not overwritten while hscl, vscl, and, for padding,
402      * v.pd.hoff and v.pd.voff are.
403      */
404     unsigned char hoff_n;
405     unsigned char voff_n;
406     unsigned char hoff_d;
407     unsigned char voff_d;
408     /*
409      * Is either TERM_CELL_CHAR, TERM_CELL_CHAR_PADDING, TERM_CELL_TILE, or
410      * TERM_CELL_TILE_PADDING.
411      */
412     unsigned char form;
413 };
414 #define TERM_CELL_CHAR (0x1)
415 #define TERM_CELL_CHAR_PADDING (0x2)
416 #define TERM_CELL_TILE (0x4)
417 #define TERM_CELL_TILE_PADDING (0x8)
418
419 struct TerminalCellBlock {
420     int ulcol, ulrow, w, h;
421 };
422
423 struct TerminalCellLocation {
424     int col, row;
425 };
426
427 typedef int (*TerminalCellPredicate)(const struct TerminalCell*);
428
429 static int isTileTop(const struct TerminalCell *c)
430 {
431     return (c->form == TERM_CELL_TILE ||
432             (c->form == TERM_CELL_TILE_PADDING && c->v.pd.voff == 0)) ? 1 : 0;
433 }
434
435 static int isPartiallyOverwrittenBigChar(const struct TerminalCell *c)
436 {
437     if ((c->form & (TERM_CELL_CHAR | TERM_CELL_CHAR_PADDING)) != 0) {
438         /*
439          * When the tile is set in Term_pict_cocoa, hoff_d is the same as hscl
440          * and voff_d is the same as vscl.  hoff_d and voff_d aren't modified
441          * after that, but hscl and vscl are in response to partial overwrites.
442          * If they're diffent, an overwrite has occurred.
443          */
444         return ((c->hoff_d > 1 || c->voff_d > 1) &&
445                 (c->hoff_d != c->hscl || c->voff_d != c->vscl)) ? 1 : 0;
446     }
447     return 0;
448 }
449
450 static int isCharNoPartial(const struct TerminalCell *c)
451 {
452     return ((c->form & (TERM_CELL_CHAR | TERM_CELL_CHAR_PADDING)) != 0 &&
453             ! isPartiallyOverwrittenBigChar(c)) ? 1 : 0;
454 }
455
456 /**
457  * Since the drawing is decoupled from Angband's calls to the text_hook,
458  * pict_hook, wipe_hook, curs_hook, and bigcurs_hook callbacks of a terminal,
459  * maintain a version of the Terminal contents.
460  */
461 @interface TerminalContents : NSObject {
462 @private
463     struct TerminalCell *cells;
464 }
465
466 /**
467  * Initialize with zero columns and zero rows.
468  */
469 - (id)init;
470
471 /**
472  * Initialize with nCol columns and nRow rows.  All elements will be set to
473  * blanks.
474  */
475 - (id)initWithColumns:(int)nCol rows:(int)nRow NS_DESIGNATED_INITIALIZER;
476
477 /**
478  * Resize to be nCol by nRow.  Current contents still within the new bounds
479  * are preserved.  Added areas are filled with blanks.
480  */
481 - (void)resizeWithColumns:(int)nCol rows:(int)nRow;
482
483 /**
484  * Get the contents of a given cell.
485  */
486 - (const struct TerminalCell*)getCellAtColumn:(int)icol row:(int)irow;
487
488 /**
489  * Scans the row, irow, starting at the column, icol0, and stopping before the
490  * column, icol1.  Returns the column index for the first cell that's within
491  * the given type mask, tm.  If all of the cells in that range are not within
492  * the given type mask, returns icol1.
493  */
494 - (int)scanForTypeMaskInRow:(int)irow mask:(unsigned int)tm col0:(int)icol0
495                        col1:(int)icol1;
496
497 /**
498  * Scans the w x h block whose upper left corner is at (icol, irow).  The
499  * scan starts at (icol + pcurs->col, irow + pcurs->row) and proceeds from
500  * left to right and top to bottom.  At exit, pcurs will have the location
501  * (relative to icol, irow) of the first cell encountered that's within the
502  * given type mask, tm.  If no such cell was found, pcurs->col will be w
503  * and pcurs->row will be h.
504  */
505 - (void)scanForTypeMaskInBlockAtColumn:(int)icol row:(int)irow width:(int)w
506                                 height:(int)h mask:(unsigned int)tm
507                                 cursor:(struct TerminalCellLocation*)pcurs;
508
509 /**
510  * Scans the row, irow, starting at the column, icol0, and stopping before the
511  * column, icol1.  Returns the column index for the first cell that
512  * func(cell_address) != rval.  If all of the cells in the range satisfy the
513  * predicate, returns icol1.
514  */
515 - (int)scanForPredicateInRow:(int)irow
516                    predicate:(TerminalCellPredicate)func
517                      desired:(int)rval
518                         col0:(int)icol0
519                         col1:(int)icol1;
520
521 /**
522  * Change the contents to have the given string of n characters appear with
523  * the leftmost character at (icol, irow).
524  */
525 - (void)setUniformAttributeTextRunAtColumn:(int)icol
526                                        row:(int)irow
527                                          n:(int)n
528                                     glyphs:(const char*)g
529                                  attribute:(int)a;
530
531 /**
532  * Change the contents to have a tile scaled to w x h appear with its upper
533  * left corner at (icol, irow).
534  */
535 - (void)setTileAtColumn:(int)icol
536                     row:(int)irow
537        foregroundColumn:(char)fgdCol
538           foregroundRow:(char)fgdRow
539        backgroundColumn:(char)bckCol
540           backgroundRow:(char)bckRow
541               tileWidth:(int)w
542              tileHeight:(int)h;
543
544 /**
545  * Wipe the w x h block whose upper left corner is at (icol, irow).
546  */
547 - (void)wipeBlockAtColumn:(int)icol row:(int)irow width:(int)w height:(int)h;
548
549 /**
550  * Wipe all the contents.
551  */
552 - (void)wipe;
553
554 /**
555  * Wipe any tiles.
556  */
557 - (void)wipeTiles;
558
559 /**
560  * Thie is a helper function for wipeBlockAtColumn.
561  */
562 - (void)wipeBlockAuxAtColumn:(int)icol row:(int)irow width:(int)w
563                       height:(int)h;
564
565 /**
566  * This is a helper function for checkForBigStuffOverwriteAtColumn.
567  */
568 - (void) splitBlockAtColumn:(int)icol row:(int)irow n:(int)nsub
569                      blocks:(const struct TerminalCellBlock*)b;
570
571 /**
572  * This is a helper function for setUniformAttributeTextRunAtColumn,
573  * setTileAtColumn, and wipeBlockAtColumn.  If a modification could partially
574  * overwrite a big character or tile, make adjustments so what's left can
575  * be handled appropriately in rendering.
576  */
577 - (void)checkForBigStuffOverwriteAtColumn:(int)icol row:(int)irow
578                                     width:(int)w height:(int)h;
579
580 /**
581  * Position the upper left corner of the cursor at (icol, irow) and have it
582  * encompass w x h cells.
583  */
584 - (void)setCursorAtColumn:(int)icol row:(int)irow width:(int)w height:(int)h;
585
586 /**
587  * Remove the cursor.  cursorColumn and cursorRow will be -1 until
588  * setCursorAtColumn is called.
589  */
590 - (void)removeCursor;
591
592 /**
593  * Verify that everying is consistent.
594  */
595 - (void)assertInvariants;
596
597 /**
598  * Is the number of columns.
599  */
600 @property (readonly) int columnCount;
601
602 /**
603  * Is the number of rows.
604  */
605 @property (readonly) int rowCount;
606
607 /**
608  * Is the column index for the upper left corner of the cursor.  It will be -1
609  * if the cursor is disabled.
610  */
611 @property (readonly) int cursorColumn;
612
613 /**
614  * Is the row index for the upper left corner of the cursor.  It will be -1
615  * if the cursor is disabled.
616  */
617 @property (readonly) int cursorRow;
618
619 /**
620  * Is the cursor width in number of cells.
621  */
622 @property (readonly) int cursorWidth;
623
624 /**
625  * Is the cursor height in number of cells.
626  */
627 @property (readonly) int cursorHeight;
628
629 /**
630  * Return the character to be used for blanks.
631  */
632 + (wchar_t)getBlankChar;
633
634 /**
635  * Return the attribute to be used for blanks.
636  */
637 + (int)getBlankAttribute;
638
639 @end
640
641 @implementation TerminalContents
642
643 - (id)init
644 {
645     return [self initWithColumns:0 rows:0];
646 }
647
648 - (id)initWithColumns:(int)nCol rows:(int)nRow
649 {
650     if (self = [super init]) {
651         self->cells = malloc(nCol * nRow * sizeof(struct TerminalCell));
652         self->_columnCount = nCol;
653         self->_rowCount = nRow;
654         self->_cursorColumn = -1;
655         self->_cursorRow = -1;
656         self->_cursorWidth = 1;
657         self->_cursorHeight = 1;
658         [self wipe];
659     }
660     return self;
661 }
662
663 - (void)dealloc
664 {
665     if (self->cells != 0) {
666         free(self->cells);
667         self->cells = 0;
668     }
669 }
670
671 - (void)resizeWithColumns:(int)nCol rows:(int)nRow
672 {
673     /*
674      * Potential issue: big tiles or characters can become clipped by the
675      * resize.  That will only matter if drawing occurs before the contents
676      * are updated by Angband.  Even then, unless the drawing mode is used
677      * where AppKit doesn't clip to the window bounds, the only artifact will
678      * be clipping when drawn which is acceptable and doesn't require
679      * additional logic to either filter out the clipped big stuff here or
680      * to just clear it when drawing.
681      */
682     struct TerminalCell *newCells =
683         malloc(nCol * nRow * sizeof(struct TerminalCell));
684     struct TerminalCell *cellsOutCursor = newCells;
685     const struct TerminalCell *cellsInCursor = self->cells;
686     int nColCommon = (nCol < self.columnCount) ? nCol : self.columnCount;
687     int nRowCommon = (nRow < self.rowCount) ? nRow : self.rowCount;
688     wchar_t blank = [TerminalContents getBlankChar];
689     int blank_attr = [TerminalContents getBlankAttribute];
690     int i;
691
692     for (i = 0; i < nRowCommon; ++i) {
693         (void) memcpy(
694             cellsOutCursor,
695             cellsInCursor,
696             nColCommon * sizeof(struct TerminalCell));
697         cellsInCursor += self.columnCount;
698         for (int j = nColCommon; j < nCol; ++j) {
699             cellsOutCursor[j].v.ch.glyph = blank;
700             cellsOutCursor[j].v.ch.attr = blank_attr;
701             cellsOutCursor[j].hscl = 1;
702             cellsOutCursor[j].vscl = 1;
703             cellsOutCursor[j].hoff_n = 0;
704             cellsOutCursor[j].voff_n = 0;
705             cellsOutCursor[j].hoff_d = 1;
706             cellsOutCursor[j].voff_d = 1;
707             cellsOutCursor[j].form = TERM_CELL_CHAR;
708         }
709         cellsOutCursor += nCol;
710     }
711     while (cellsOutCursor != newCells + nCol * nRow) {
712         cellsOutCursor->v.ch.glyph = blank;
713         cellsOutCursor->v.ch.attr = blank_attr;
714         cellsOutCursor->hscl = 1;
715         cellsOutCursor->vscl = 1;
716         cellsOutCursor->hoff_n = 0;
717         cellsOutCursor->voff_n = 0;
718         cellsOutCursor->hoff_d = 1;
719         cellsOutCursor->voff_d = 1;
720         cellsOutCursor->form = TERM_CELL_CHAR;
721         ++cellsOutCursor;
722     }
723
724     free(self->cells);
725     self->cells = newCells;
726     self->_columnCount = nCol;
727     self->_rowCount = nRow;
728     if (self->_cursorColumn >= nCol || self->_cursorRow >= nRow) {
729         self->_cursorColumn = -1;
730         self->_cursorRow = -1;
731     } else {
732         if (self->_cursorColumn + self->_cursorWidth > nCol) {
733             self->_cursorWidth = nCol - self->_cursorColumn;
734         }
735         if (self->_cursorRow + self->_cursorHeight > nRow) {
736             self->_cursorHeight = nRow - self->_cursorRow;
737         }
738     }
739 }
740
741 - (const struct TerminalCell*)getCellAtColumn:(int)icol row:(int)irow
742 {
743     return self->cells + icol + irow * self.columnCount;
744 }
745
746 - (int)scanForTypeMaskInRow:(int)irow mask:(unsigned int)tm col0:(int)icol0
747                        col1:(int)icol1
748 {
749     int i = icol0;
750     const struct TerminalCell *cellsRow =
751         self->cells + irow * self.columnCount;
752
753     while (1) {
754         if (i >= icol1) {
755             return icol1;
756         }
757         if ((cellsRow[i].form & tm) != 0) {
758             return i;
759         }
760         ++i;
761     }
762 }
763
764 - (void)scanForTypeMaskInBlockAtColumn:(int)icol row:(int)irow width:(int)w
765                                 height:(int)h mask:(unsigned int)tm
766                                 cursor:(struct TerminalCellLocation*)pcurs
767 {
768     const struct TerminalCell *cellsRow =
769         self->cells + (irow + pcurs->row) * self.columnCount;
770     while (1) {
771         if (pcurs->col == w) {
772             if (pcurs->row >= h - 1) {
773                 pcurs->row = h;
774                 return;
775             }
776             ++pcurs->row;
777             pcurs->col = 0;
778             cellsRow += self.columnCount;
779         }
780
781         if ((cellsRow[icol + pcurs->col].form & tm) != 0) {
782             return;
783         }
784
785         ++pcurs->col;
786     }
787 }
788
789 - (int)scanForPredicateInRow:(int)irow
790                    predicate:(TerminalCellPredicate)func
791                      desired:(int)rval
792                         col0:(int)icol0
793                         col1:(int)icol1
794 {
795     int i = icol0;
796     const struct TerminalCell *cellsRow =
797         self->cells + irow * self.columnCount;
798
799     while (1) {
800         if (i >= icol1) {
801             return icol1;
802         }
803         if (func(cellsRow + i) != rval) {
804             return i;
805         }
806         ++i;
807     }
808 }
809
810 - (void)setUniformAttributeTextRunAtColumn:(int)icol
811                                        row:(int)irow
812                                          n:(int)n
813                                     glyphs:(const char*)g
814                                  attribute:(int)a
815 {
816     [self checkForBigStuffOverwriteAtColumn:icol row:irow width:n height:1];
817
818     struct TerminalCell *cellsRow = self->cells + irow * self.columnCount;
819     int i = icol;
820
821     while (i < icol + n) {
822 #ifdef JP
823         if (iskanji(*g)) {
824             if (i == n - 1) {
825                 /*
826                  * The second byte of the character is past the end.  Ignore
827                  * the character.
828                  */
829                 break;
830             }
831             cellsRow[i].v.ch.glyph = convert_two_byte_eucjp_to_utf16_native(g);
832             cellsRow[i].v.ch.attr = a;
833             cellsRow[i].hscl = 2;
834             cellsRow[i].vscl = 1;
835             cellsRow[i].hoff_n = 0;
836             cellsRow[i].voff_n = 0;
837             cellsRow[i].hoff_d = 2;
838             cellsRow[i].voff_d = 1;
839             cellsRow[i].form = TERM_CELL_CHAR;
840             ++i;
841             cellsRow[i].v.pd.hoff = 1;
842             cellsRow[i].v.pd.voff = 0;
843             cellsRow[i].hscl = 2;
844             cellsRow[i].vscl = 1;
845             cellsRow[i].hoff_n = 1;
846             cellsRow[i].voff_n = 0;
847             cellsRow[i].hoff_d = 2;
848             cellsRow[i].voff_d = 1;
849             cellsRow[i].form = TERM_CELL_CHAR_PADDING;
850             ++i;
851             g += 2;
852         } else {
853             cellsRow[i].v.ch.glyph = *g++;
854             cellsRow[i].v.ch.attr = a;
855             cellsRow[i].hscl = 1;
856             cellsRow[i].vscl = 1;
857             cellsRow[i].hoff_n = 0;
858             cellsRow[i].voff_n = 0;
859             cellsRow[i].hoff_d = 1;
860             cellsRow[i].voff_d = 1;
861             cellsRow[i].form = TERM_CELL_CHAR;
862             ++i;
863         }
864 #else
865         cellsRow[i].v.ch.glyph = *g++;
866         cellsRow[i].v.ch.attr = a;
867         cellsRow[i].hscl = 1;
868         cellsRow[i].vscl = 1;
869         cellsRow[i].hoff_n = 0;
870         cellsRow[i].voff_n = 0;
871         cellsRow[i].hoff_d = 1;
872         cellsRow[i].voff_d = 1;
873         cellsRow[i].form = TERM_CELL_CHAR;
874         ++i;
875 #endif /* JP */
876     }
877 }
878
879 - (void)setTileAtColumn:(int)icol
880                     row:(int)irow
881        foregroundColumn:(char)fgdCol
882           foregroundRow:(char)fgdRow
883        backgroundColumn:(char)bckCol
884           backgroundRow:(char)bckRow
885               tileWidth:(int)w
886              tileHeight:(int)h
887 {
888     [self checkForBigStuffOverwriteAtColumn:icol row:irow width:w height:h];
889
890     struct TerminalCell *cellsRow = self->cells + irow * self.columnCount;
891
892     cellsRow[icol].v.ti.fgdCol = fgdCol;
893     cellsRow[icol].v.ti.fgdRow = fgdRow;
894     cellsRow[icol].v.ti.bckCol = bckCol;
895     cellsRow[icol].v.ti.bckRow = bckRow;
896     cellsRow[icol].hscl = w;
897     cellsRow[icol].vscl = h;
898     cellsRow[icol].hoff_n = 0;
899     cellsRow[icol].voff_n = 0;
900     cellsRow[icol].hoff_d = w;
901     cellsRow[icol].voff_d = h;
902     cellsRow[icol].form = TERM_CELL_TILE;
903
904     int ic;
905     for (ic = icol + 1; ic < icol + w; ++ic) {
906         cellsRow[ic].v.pd.hoff = ic - icol;
907         cellsRow[ic].v.pd.voff = 0;
908         cellsRow[ic].hscl = w;
909         cellsRow[ic].vscl = h;
910         cellsRow[ic].hoff_n = ic - icol;
911         cellsRow[ic].voff_n = 0;
912         cellsRow[ic].hoff_d = w;
913         cellsRow[ic].voff_d = h;
914         cellsRow[ic].form = TERM_CELL_TILE_PADDING;
915     }
916     cellsRow += self.columnCount;
917     for (int ir = irow + 1; ir < irow + h; ++ir) {
918         for (ic = icol; ic < icol + w; ++ic) {
919             cellsRow[ic].v.pd.hoff = ic - icol;
920             cellsRow[ic].v.pd.voff = ir - irow;
921             cellsRow[ic].hscl = w;
922             cellsRow[ic].vscl = h;
923             cellsRow[ic].hoff_n = ic - icol;
924             cellsRow[ic].voff_n = ir - irow;
925             cellsRow[ic].hoff_d = w;
926             cellsRow[ic].voff_d = h;
927             cellsRow[ic].form = TERM_CELL_TILE_PADDING;
928         }
929         cellsRow += self.columnCount;
930     }
931 }
932
933 - (void)wipeBlockAtColumn:(int)icol row:(int)irow width:(int)w height:(int)h
934 {
935     [self checkForBigStuffOverwriteAtColumn:icol row:irow width:w height:h];
936     [self wipeBlockAuxAtColumn:icol row:irow width:w height:h];
937 }
938
939 - (void)wipe
940 {
941     wchar_t blank = [TerminalContents getBlankChar];
942     int blank_attr = [TerminalContents getBlankAttribute];
943     struct TerminalCell *cellCursor = self->cells +
944         self.columnCount * self.rowCount;
945
946     while (cellCursor != self->cells) {
947         --cellCursor;
948         cellCursor->v.ch.glyph = blank;
949         cellCursor->v.ch.attr = blank_attr;
950         cellCursor->hscl = 1;
951         cellCursor->vscl = 1;
952         cellCursor->hoff_n = 0;
953         cellCursor->voff_n = 0;
954         cellCursor->hoff_d = 1;
955         cellCursor->voff_d = 1;
956         cellCursor->form = TERM_CELL_CHAR;
957     }
958 }
959
960 - (void)wipeTiles
961 {
962     wchar_t blank = [TerminalContents getBlankChar];
963     int blank_attr = [TerminalContents getBlankAttribute];
964     struct TerminalCell *cellCursor = self->cells +
965         self.columnCount * self.rowCount;
966
967     while (cellCursor != self->cells) {
968         --cellCursor;
969         if ((cellCursor->form &
970              (TERM_CELL_TILE | TERM_CELL_TILE_PADDING)) != 0) {
971             cellCursor->v.ch.glyph = blank;
972             cellCursor->v.ch.attr = blank_attr;
973             cellCursor->hscl = 1;
974             cellCursor->vscl = 1;
975             cellCursor->hoff_n = 0;
976             cellCursor->voff_n = 0;
977             cellCursor->hoff_d = 1;
978             cellCursor->voff_d = 1;
979             cellCursor->form = TERM_CELL_CHAR;
980         }
981     }
982 }
983
984 - (void)wipeBlockAuxAtColumn:(int)icol row:(int)irow width:(int)w
985                       height:(int)h
986 {
987     struct TerminalCell *cellsRow = self->cells + irow * self.columnCount;
988     wchar_t blank = [TerminalContents getBlankChar];
989     int blank_attr = [TerminalContents getBlankAttribute];
990
991     for (int ir = irow; ir < irow + h; ++ir) {
992         for (int ic = icol; ic < icol + w; ++ic) {
993             cellsRow[ic].v.ch.glyph = blank;
994             cellsRow[ic].v.ch.attr = blank_attr;
995             cellsRow[ic].hscl = 1;
996             cellsRow[ic].vscl = 1;
997             cellsRow[ic].hoff_n = 0;
998             cellsRow[ic].voff_n = 0;
999             cellsRow[ic].hoff_d = 1;
1000             cellsRow[ic].voff_d = 1;
1001             cellsRow[ic].form = TERM_CELL_CHAR;
1002         }
1003         cellsRow += self.columnCount;
1004     }
1005 }
1006
1007 - (void) splitBlockAtColumn:(int)icol row:(int)irow n:(int)nsub
1008                      blocks:(const struct TerminalCellBlock*)b
1009 {
1010     const struct TerminalCell *pulold = [self getCellAtColumn:icol row:irow];
1011
1012     for (int isub = 0; isub < nsub; ++isub) {
1013         struct TerminalCell* cellsRow =
1014             self->cells + b[isub].ulrow * self.columnCount;
1015
1016         /*
1017          * Copy the data from the upper left corner of the big block to
1018          * the upper left corner of the piece.
1019          */
1020         if (b[isub].ulcol != icol || b[isub].ulrow != irow) {
1021             if (pulold->form == TERM_CELL_CHAR) {
1022                 cellsRow[b[isub].ulcol].v.ch = pulold->v.ch;
1023                 cellsRow[b[isub].ulcol].form = TERM_CELL_CHAR;
1024             } else {
1025                 cellsRow[b[isub].ulcol].v.ti = pulold->v.ti;
1026                 cellsRow[b[isub].ulcol].form = TERM_CELL_TILE;
1027             }
1028         }
1029         cellsRow[b[isub].ulcol].hscl = b[isub].w;
1030         cellsRow[b[isub].ulcol].vscl = b[isub].h;
1031
1032         /*
1033          * Point the padding elements in the piece to the new upper left
1034          * corner.
1035          */
1036         int ic;
1037         for (ic = b[isub].ulcol + 1; ic < b[isub].ulcol + b[isub].w; ++ic) {
1038             cellsRow[ic].v.pd.hoff = ic - b[isub].ulcol;
1039             cellsRow[ic].v.pd.voff = 0;
1040             cellsRow[ic].hscl = b[isub].w;
1041             cellsRow[ic].vscl = b[isub].h;
1042         }
1043         cellsRow += self.columnCount;
1044         for (int ir = b[isub].ulrow + 1;
1045              ir < b[isub].ulrow + b[isub].h;
1046              ++ir) {
1047             for (ic = b[isub].ulcol; ic < b[isub].ulcol + b[isub].w; ++ic) {
1048                 cellsRow[ic].v.pd.hoff = ic - b[isub].ulcol;
1049                 cellsRow[ic].v.pd.voff = ir - b[isub].ulrow;
1050                 cellsRow[ic].hscl = b[isub].w;
1051                 cellsRow[ic].vscl = b[isub].h;
1052             }
1053             cellsRow += self.columnCount;
1054         }
1055     }
1056 }
1057
1058 - (void)checkForBigStuffOverwriteAtColumn:(int)icol row:(int)irow
1059                                     width:(int)w height:(int)h
1060 {
1061     int ire = irow + h, ice = icol + w;
1062
1063     for (int ir = irow; ir < ire; ++ir) {
1064         for (int ic = icol; ic < ice; ++ic) {
1065             const struct TerminalCell *pcell =
1066                 [self getCellAtColumn:ic row:ir];
1067
1068             if ((pcell->form & (TERM_CELL_CHAR | TERM_CELL_TILE)) != 0 &&
1069                 (pcell->hscl > 1 || pcell->vscl > 1)) {
1070                 /*
1071                  * Lost chunk including upper left corner.  Split into at most
1072                  * two new blocks.
1073                  */
1074                 /*
1075                  * Tolerate blocks that were clipped by a resize at some point.
1076                  */
1077                 int wb = (ic + pcell->hscl <= self.columnCount) ?
1078                     pcell->hscl : self.columnCount - ic;
1079                 int hb = (ir + pcell->vscl <= self.rowCount) ?
1080                     pcell->vscl : self.rowCount - ir;
1081                 struct TerminalCellBlock blocks[2];
1082                 int nsub = 0, ww, hw;
1083
1084                 if (ice < ic + wb) {
1085                     /* Have something to the right not overwritten. */
1086                     blocks[nsub].ulcol = ice;
1087                     blocks[nsub].ulrow = ir;
1088                     blocks[nsub].w = ic + wb - ice;
1089                     blocks[nsub].h = (ire < ir + hb) ? ire - ir : hb;
1090                     ++nsub;
1091                     ww = ice - ic;
1092                 } else {
1093                     ww = wb;
1094                 }
1095                 if (ire < ir + hb) {
1096                     /* Have something below not overwritten. */
1097                     blocks[nsub].ulcol = ic;
1098                     blocks[nsub].ulrow = ire;
1099                     blocks[nsub].w = wb;
1100                     blocks[nsub].h = ir + hb - ire;
1101                     ++nsub;
1102                     hw = ire - ir;
1103                 } else {
1104                     hw = hb;
1105                 }
1106                 if (nsub > 0) {
1107                     [self splitBlockAtColumn:ic row:ir n:nsub blocks:blocks];
1108                 }
1109                 /*
1110                  * Wipe the part of the block that's destined to be overwritten
1111                  * so it doesn't receive further consideration in this loop.
1112                  * For efficiency, would like to have the loop skip over it or
1113                  * fill it with the desired content, but this is easier to
1114                  * implement.
1115                  */
1116                 [self wipeBlockAuxAtColumn:ic row:ir width:ww height:hw];
1117             } else if ((pcell->form & (TERM_CELL_CHAR_PADDING |
1118                                        TERM_CELL_TILE_PADDING)) != 0) {
1119                 /*
1120                  * Lost a chunk that doesn't cover the upper left corner.  In
1121                  * general will split into up to four new blocks (one above,
1122                  * one to the left, one to the right, and one below).
1123                  */
1124                 int pcol = ic - pcell->v.pd.hoff;
1125                 int prow = ir - pcell->v.pd.voff;
1126                 const struct TerminalCell *pcell2 =
1127                     [self getCellAtColumn:pcol row:prow];
1128
1129                 /*
1130                  * Tolerate blocks that were clipped by a resize at some point.
1131                  */
1132                 int wb = (pcol + pcell2->hscl <= self.columnCount) ?
1133                     pcell2->hscl : self.columnCount - pcol;
1134                 int hb = (prow + pcell2->vscl <= self.rowCount) ?
1135                     pcell2->vscl : self.rowCount - prow;
1136                 struct TerminalCellBlock blocks[4];
1137                 int nsub = 0, ww, hw;
1138
1139                 if (prow < ir) {
1140                     /* Have something above not overwritten. */
1141                     blocks[nsub].ulcol = pcol;
1142                     blocks[nsub].ulrow = prow;
1143                     blocks[nsub].w = wb;
1144                     blocks[nsub].h = ir - prow;
1145                     ++nsub;
1146                 }
1147                 if (pcol < ic) {
1148                     /* Have something to the left not overwritten. */
1149                     blocks[nsub].ulcol = pcol;
1150                     blocks[nsub].ulrow = ir;
1151                     blocks[nsub].w = ic - pcol;
1152                     blocks[nsub].h =
1153                         (ire < prow + hb) ? ire - ir : prow + hb - ir;
1154                     ++nsub;
1155                 }
1156                 if (ice < pcol + wb) {
1157                     /* Have something to the right not overwritten. */
1158                     blocks[nsub].ulcol = ice;
1159                     blocks[nsub].ulrow = ir;
1160                     blocks[nsub].w = pcol + wb - ice;
1161                     blocks[nsub].h =
1162                         (ire < prow + hb) ? ire - ir : prow + hb - ir;
1163                     ++nsub;
1164                     ww = ice - ic;
1165                 } else {
1166                     ww = pcol + wb - ic;
1167                 }
1168                 if (ire < prow + hb) {
1169                     /* Have something below not overwritten. */
1170                     blocks[nsub].ulcol = pcol;
1171                     blocks[nsub].ulrow = ire;
1172                     blocks[nsub].w = wb;
1173                     blocks[nsub].h = prow + hb - ire;
1174                     ++nsub;
1175                     hw = ire - ir;
1176                 } else {
1177                     hw = prow + hb - ir;
1178                 }
1179
1180                 [self splitBlockAtColumn:pcol row:prow n:nsub blocks:blocks];
1181                 /* Same rationale for wiping as above. */
1182                 [self wipeBlockAuxAtColumn:ic row:ir width:ww height:hw];
1183             }
1184         }
1185     }
1186 }
1187
1188 - (void)setCursorAtColumn:(int)icol row:(int)irow width:(int)w height:(int)h
1189 {
1190     self->_cursorColumn = icol;
1191     self->_cursorRow = irow;
1192     self->_cursorWidth = w;
1193     self->_cursorHeight = h;
1194 }
1195
1196 - (void)removeCursor
1197 {
1198     self->_cursorColumn = -1;
1199     self->_cursorHeight = -1;
1200     self->_cursorWidth = 1;
1201     self->_cursorHeight = 1;
1202 }
1203
1204 - (void)assertInvariants
1205 {
1206     const struct TerminalCell *cellsRow = self->cells;
1207
1208     /*
1209      * The comments with the definition for TerminalCell define the
1210      * relationships of hoff_n, voff_n, hoff_d, voff_d, hscl, and vscl
1211      * asserted here.
1212      */
1213     for (int ir = 0; ir < self.rowCount; ++ir) {
1214         for (int ic = 0; ic < self.columnCount; ++ic) {
1215             switch (cellsRow[ic].form) {
1216             case TERM_CELL_CHAR:
1217                 assert(cellsRow[ic].hscl > 0 && cellsRow[ic].vscl > 0);
1218                 assert(cellsRow[ic].hoff_n < cellsRow[ic].hoff_d &&
1219                        cellsRow[ic].voff_n < cellsRow[ic].voff_d);
1220                 if (cellsRow[ic].hscl == cellsRow[ic].hoff_d) {
1221                     assert(cellsRow[ic].hoff_n == 0);
1222                 }
1223                 if (cellsRow[ic].vscl == cellsRow[ic].voff_d) {
1224                     assert(cellsRow[ic].voff_n == 0);
1225                 }
1226                 /*
1227                  * Verify that the padding elements have the correct tag
1228                  * and point back to this cell.
1229                  */
1230                 if (cellsRow[ic].hscl > 1 || cellsRow[ic].vscl > 1) {
1231                     const struct TerminalCell *cellsRow2 = cellsRow;
1232
1233                     for (int ir2 = ir; ir2 < ir + cellsRow[ic].vscl; ++ir2) {
1234                         for (int ic2 = ic;
1235                              ic2 < ic + cellsRow[ic].hscl;
1236                              ++ic2) {
1237                             if (ir2 == ir && ic2 == ic) {
1238                                 continue;
1239                             }
1240                             assert(cellsRow2[ic2].form ==
1241                                    TERM_CELL_CHAR_PADDING);
1242                             assert(ic2 - cellsRow2[ic2].v.pd.hoff == ic &&
1243                                    ir2 - cellsRow2[ic2].v.pd.voff == ir);
1244                         }
1245                         cellsRow2 += self.columnCount;
1246                     }
1247                 }
1248                 break;
1249
1250             case TERM_CELL_TILE:
1251                 assert(cellsRow[ic].hscl > 0 && cellsRow[ic].vscl > 0);
1252                 assert(cellsRow[ic].hoff_n < cellsRow[ic].hoff_d &&
1253                        cellsRow[ic].voff_n < cellsRow[ic].voff_d);
1254                 if (cellsRow[ic].hscl == cellsRow[ic].hoff_d) {
1255                     assert(cellsRow[ic].hoff_n == 0);
1256                 }
1257                 if (cellsRow[ic].vscl == cellsRow[ic].voff_d) {
1258                     assert(cellsRow[ic].voff_n == 0);
1259                 }
1260                 /*
1261                  * Verify that the padding elements have the correct tag
1262                  * and point back to this cell.
1263                  */
1264                 if (cellsRow[ic].hscl > 1 || cellsRow[ic].vscl > 1) {
1265                     const struct TerminalCell *cellsRow2 = cellsRow;
1266
1267                     for (int ir2 = ir; ir2 < ir + cellsRow[ic].vscl; ++ir2) {
1268                         for (int ic2 = ic;
1269                              ic2 < ic + cellsRow[ic].hscl;
1270                              ++ic2) {
1271                             if (ir2 == ir && ic2 == ic) {
1272                                 continue;
1273                             }
1274                             assert(cellsRow2[ic2].form ==
1275                                    TERM_CELL_TILE_PADDING);
1276                             assert(ic2 - cellsRow2[ic2].v.pd.hoff == ic &&
1277                                    ir2 - cellsRow2[ic2].v.pd.voff == ir);
1278                         }
1279                         cellsRow2 += self.columnCount;
1280                     }
1281                 }
1282                 break;
1283
1284             case TERM_CELL_CHAR_PADDING:
1285                 assert(cellsRow[ic].hscl > 0 && cellsRow[ic].vscl > 0);
1286                 assert(cellsRow[ic].hoff_n < cellsRow[ic].hoff_d &&
1287                        cellsRow[ic].voff_n < cellsRow[ic].voff_d);
1288                 assert(cellsRow[ic].hoff_n > 0 || cellsRow[ic].voff_n > 0);
1289                 if (cellsRow[ic].hscl == cellsRow[ic].hoff_d) {
1290                     assert(cellsRow[ic].hoff_n == cellsRow[ic].v.pd.hoff);
1291                 }
1292                 if (cellsRow[ic].vscl == cellsRow[ic].voff_d) {
1293                     assert(cellsRow[ic].voff_n == cellsRow[ic].v.pd.voff);
1294                 }
1295                 assert(ic >= cellsRow[ic].v.pd.hoff &&
1296                        ir >= cellsRow[ic].v.pd.voff);
1297                 /*
1298                  * Verify that it's padding for something that can point
1299                  * back to it.
1300                  */
1301                 {
1302                     const struct TerminalCell *parent =
1303                         [self getCellAtColumn:(ic - cellsRow[ic].v.pd.hoff)
1304                               row:(ir - cellsRow[ic].v.pd.voff)];
1305
1306                     assert(parent->form == TERM_CELL_CHAR);
1307                     assert(parent->hscl > cellsRow[ic].v.pd.hoff &&
1308                            parent->vscl > cellsRow[ic].v.pd.voff);
1309                     assert(parent->hscl == cellsRow[ic].hscl &&
1310                            parent->vscl == cellsRow[ic].vscl);
1311                     assert(parent->hoff_d == cellsRow[ic].hoff_d &&
1312                            parent->voff_d == cellsRow[ic].voff_d);
1313                 }
1314                 break;
1315
1316             case TERM_CELL_TILE_PADDING:
1317                 assert(cellsRow[ic].hscl > 0 && cellsRow[ic].vscl > 0);
1318                 assert(cellsRow[ic].hoff_n < cellsRow[ic].hoff_d &&
1319                        cellsRow[ic].voff_n < cellsRow[ic].voff_d);
1320                 assert(cellsRow[ic].hoff_n > 0 || cellsRow[ic].voff_n > 0);
1321                 if (cellsRow[ic].hscl == cellsRow[ic].hoff_d) {
1322                     assert(cellsRow[ic].hoff_n == cellsRow[ic].v.pd.hoff);
1323                 }
1324                 if (cellsRow[ic].vscl == cellsRow[ic].voff_d) {
1325                     assert(cellsRow[ic].voff_n == cellsRow[ic].v.pd.voff);
1326                 }
1327                 assert(ic >= cellsRow[ic].v.pd.hoff &&
1328                        ir >= cellsRow[ic].v.pd.voff);
1329                 /*
1330                  * Verify that it's padding for something that can point
1331                  * back to it.
1332                  */
1333                 {
1334                     const struct TerminalCell *parent =
1335                         [self getCellAtColumn:(ic - cellsRow[ic].v.pd.hoff)
1336                               row:(ir - cellsRow[ic].v.pd.voff)];
1337
1338                     assert(parent->form == TERM_CELL_TILE);
1339                     assert(parent->hscl > cellsRow[ic].v.pd.hoff &&
1340                            parent->vscl > cellsRow[ic].v.pd.voff);
1341                     assert(parent->hscl == cellsRow[ic].hscl &&
1342                            parent->vscl == cellsRow[ic].vscl);
1343                     assert(parent->hoff_d == cellsRow[ic].hoff_d &&
1344                            parent->voff_d == cellsRow[ic].voff_d);
1345                 }
1346                 break;
1347
1348             default:
1349                 assert(0);
1350             }
1351         }
1352         cellsRow += self.columnCount;
1353     }
1354 }
1355
1356 + (wchar_t)getBlankChar
1357 {
1358     return L' ';
1359 }
1360
1361 + (int)getBlankAttribute
1362 {
1363     return 0;
1364 }
1365
1366 @end
1367
1368 /**
1369  * TerminalChanges is used to track changes made via the text_hook, pict_hook,
1370  * wipe_hook, curs_hook, and bigcurs_hook callbacks on the terminal since the
1371  * last call to xtra_hook for TERM_XTRA_FRESH.  The locations marked as changed
1372  * can then be used to make bounding rectangles for the regions that need to
1373  * be redisplayed.
1374  */
1375 @interface TerminalChanges : NSObject {
1376     int* colBounds;
1377     /*
1378      * Outside of firstChangedRow, lastChangedRow and what's in colBounds, the
1379      * contents of this are handled lazily.
1380      */
1381     BOOL* marks;
1382 }
1383
1384 /**
1385  * Initialize with zero columns and zero rows.
1386  */
1387 - (id)init;
1388
1389 /**
1390  * Initialize with nCol columns and nRow rows.  No changes will be marked.
1391  */
1392 - (id)initWithColumns:(int)nCol rows:(int)nRow NS_DESIGNATED_INITIALIZER;
1393
1394 /**
1395  * Resize to be nCol by nRow.  Current contents still within the new bounds
1396  * are preserved.  Added areas are marked as unchanged.
1397  */
1398 - (void)resizeWithColumns:(int)nCol rows:(int)nRow;
1399
1400 /**
1401  * Clears all marked changes.
1402  */
1403 - (void)clear;
1404
1405 - (BOOL)isChangedAtColumn:(int)icol row:(int)irow;
1406
1407 /**
1408  * Scans the row, irow, starting at the column, icol0, and stopping before the
1409  * column, icol1.  Returns the column index for the first cell that is
1410  * changed.  The returned index will be equal to icol1 if all of the cells in
1411  * the range are unchanged.
1412  */
1413 - (int)scanForChangedInRow:(int)irow col0:(int)icol0 col1:(int)icol1;
1414
1415 /**
1416  * Scans the row, irow, starting at the column, icol0, and stopping before the
1417  * column, icol1.  returns the column index for the first cell that has not
1418  * changed.  The returned index will be equal to icol1 if all of the cells in
1419  * the range have changed.
1420  */
1421 - (int)scanForUnchangedInRow:(int)irow col0:(int)icol0 col1:(int)icol1;
1422
1423 - (void)markChangedAtColumn:(int)icol row:(int)irow;
1424
1425 - (void)markChangedRangeAtColumn:(int)icol row:(int)irow width:(int)w;
1426
1427 /**
1428  * Marks the block as changed who's upper left hand corner is at (icol, irow).
1429  */
1430 - (void)markChangedBlockAtColumn:(int)icol
1431                              row:(int)irow
1432                            width:(int)w
1433                           height:(int)h;
1434
1435 /**
1436  * Returns the index of the first changed column in the given row.  That index
1437  * will be equal to the number of columns if there are no changes in the row.
1438  */
1439 - (int)getFirstChangedColumnInRow:(int)irow;
1440
1441 /**
1442  * Returns the index of the last changed column in the given row.  That index
1443  * will be equal to -1 if there are no changes in the row.
1444  */
1445 - (int)getLastChangedColumnInRow:(int)irow;
1446
1447 /**
1448  * Is the number of columns.
1449  */
1450 @property (readonly) int columnCount;
1451
1452 /**
1453  * Is the number of rows.
1454  */
1455 @property (readonly) int rowCount;
1456
1457 /**
1458  * Is the index of the first row with changes.  Will be equal to the number
1459  * of rows if there are no changes.
1460  */
1461 @property (readonly) int firstChangedRow;
1462
1463 /**
1464  * Is the index of the last row with changes.  Will be equal to -1 if there
1465  * are no changes.
1466  */
1467 @property (readonly) int lastChangedRow;
1468
1469 @end
1470
1471 @implementation TerminalChanges
1472
1473 - (id)init
1474 {
1475     return [self initWithColumns:0 rows:0];
1476 }
1477
1478 - (id)initWithColumns:(int)nCol rows:(int)nRow
1479 {
1480     if (self = [super init]) {
1481         self->colBounds = malloc(2 * nRow * sizeof(int));
1482         self->marks = malloc(nCol * nRow * sizeof(BOOL));
1483         self->_columnCount = nCol;
1484         self->_rowCount = nRow;
1485         [self clear];
1486     }
1487     return self;
1488 }
1489
1490 - (void)dealloc
1491 {
1492     if (self->marks != 0) {
1493         free(self->marks);
1494         self->marks = 0;
1495     }
1496     if (self->colBounds != 0) {
1497         free(self->colBounds);
1498         self->colBounds = 0;
1499     }
1500 }
1501
1502 - (void)resizeWithColumns:(int)nCol rows:(int)nRow
1503 {
1504     int* newColBounds = malloc(2 * nRow * sizeof(int));
1505     BOOL* newMarks = malloc(nCol * nRow * sizeof(BOOL));
1506     int nRowCommon = (nRow < self.rowCount) ? nRow : self.rowCount;
1507
1508     if (self.firstChangedRow <= self.lastChangedRow &&
1509         self.firstChangedRow < nRowCommon) {
1510         BOOL* marksOutCursor = newMarks + self.firstChangedRow * nCol;
1511         const BOOL* marksInCursor =
1512             self->marks + self.firstChangedRow * self.columnCount;
1513         int nColCommon = (nCol < self.columnCount) ? nCol : self.columnCount;
1514
1515         if (self.lastChangedRow >= nRowCommon) {
1516             self->_lastChangedRow = nRowCommon - 1;
1517         }
1518         for (int i = self.firstChangedRow; i <= self.lastChangedRow; ++i) {
1519             if (self->colBounds[i + i] < nColCommon) {
1520                 newColBounds[i + i] = self->colBounds[i + i];
1521                 newColBounds[i + i + 1] =
1522                     (self->colBounds[i + i + 1] < nColCommon) ?
1523                     self->colBounds[i + i + 1] : nColCommon - 1;
1524                 (void) memcpy(
1525                     marksOutCursor + self->colBounds[i + i],
1526                     marksInCursor + self->colBounds[i + i],
1527                     (newColBounds[i + i + 1] - newColBounds[i + i] + 1) *
1528                         sizeof(BOOL));
1529                 marksInCursor += self.columnCount;
1530                 marksOutCursor += nCol;
1531             } else {
1532                 self->colBounds[i + i] = nCol;
1533                 self->colBounds[i + i + 1] = -1;
1534             }
1535         }
1536     } else {
1537         self->_firstChangedRow = nRow;
1538         self->_lastChangedRow = -1;
1539     }
1540
1541     free(self->colBounds);
1542     self->colBounds = newColBounds;
1543     free(self->marks);
1544     self->marks = newMarks;
1545     self->_columnCount = nCol;
1546     self->_rowCount = nRow;
1547 }
1548
1549 - (void)clear
1550 {
1551     self->_firstChangedRow = self.rowCount;
1552     self->_lastChangedRow = -1;
1553 }
1554
1555 - (BOOL)isChangedAtColumn:(int)icol row:(int)irow
1556 {
1557     if (irow < self.firstChangedRow || irow > self.lastChangedRow) {
1558         return NO;
1559     }
1560     if (icol < self->colBounds[irow + irow] ||
1561         icol > self->colBounds[irow + irow + 1]) {
1562         return NO;
1563     }
1564     return self->marks[icol + irow * self.columnCount];
1565 }
1566
1567 - (int)scanForChangedInRow:(int)irow col0:(int)icol0 col1:(int)icol1
1568 {
1569     if (irow < self.firstChangedRow || irow > self.lastChangedRow ||
1570         icol0 > self->colBounds[irow + irow + 1]) {
1571         return icol1;
1572     }
1573
1574     int i = (icol0 > self->colBounds[irow + irow]) ?
1575         icol0 : self->colBounds[irow + irow];
1576     int i1 = (icol1 <= self->colBounds[irow + irow + 1]) ?
1577         icol1 : self->colBounds[irow + irow + 1] + 1;
1578     const BOOL* marksCursor = self->marks + irow * self.columnCount;
1579     while (1) {
1580         if (i >= i1) {
1581             return icol1;
1582         }
1583         if (marksCursor[i]) {
1584             return i;
1585         }
1586         ++i;
1587     }
1588 }
1589
1590 - (int)scanForUnchangedInRow:(int)irow col0:(int)icol0 col1:(int)icol1
1591 {
1592     if (irow < self.firstChangedRow || irow > self.lastChangedRow ||
1593         icol0 < self->colBounds[irow + irow] ||
1594         icol0 > self->colBounds[irow + irow + 1]) {
1595         return icol0;
1596     }
1597
1598     int i = icol0;
1599     int i1 = (icol1 <= self->colBounds[irow + irow + 1]) ?
1600         icol1 : self->colBounds[irow + irow + 1] + 1;
1601     const BOOL* marksCursor = self->marks + irow * self.columnCount;
1602     while (1) {
1603         if (i >= i1 || ! marksCursor[i]) {
1604             return i;
1605         }
1606         ++i;
1607     }
1608 }
1609
1610 - (void)markChangedAtColumn:(int)icol row:(int)irow
1611 {
1612     [self markChangedBlockAtColumn:icol row:irow width:1 height:1];
1613 }
1614
1615 - (void)markChangedRangeAtColumn:(int)icol row:(int)irow width:(int)w
1616 {
1617     [self markChangedBlockAtColumn:icol row:irow width:w height:1];
1618 }
1619
1620 - (void)markChangedBlockAtColumn:(int)icol
1621                              row:(int)irow
1622                            width:(int)w
1623                           height:(int)h
1624 {
1625     if (irow + h <= self.firstChangedRow) {
1626         /* All prior marked regions are on rows after the requested block. */
1627         if (self.firstChangedRow > self.lastChangedRow) {
1628             self->_lastChangedRow = irow + h - 1;
1629         } else {
1630             for (int i = irow + h; i < self.firstChangedRow; ++i) {
1631                 self->colBounds[i + i] = self.columnCount;
1632                 self->colBounds[i + i + 1] = -1;
1633             }
1634         }
1635         self->_firstChangedRow = irow;
1636
1637         BOOL* marksCursor = self->marks + irow * self.columnCount;
1638         for (int i = irow; i < irow + h; ++i) {
1639             self->colBounds[i + i] = icol;
1640             self->colBounds[i + i + 1] = icol + w - 1;
1641             for (int j = icol; j < icol + w; ++j) {
1642                 marksCursor[j] = YES;
1643             }
1644             marksCursor += self.columnCount;
1645         }
1646     } else if (irow > self.lastChangedRow) {
1647         /* All prior marked regions are on rows before the requested block. */
1648         int i;
1649
1650         for (i = self.lastChangedRow + 1; i < irow; ++i) {
1651             self->colBounds[i + i] = self.columnCount;
1652             self->colBounds[i + i + 1] = -1;
1653         }
1654         self->_lastChangedRow = irow + h - 1;
1655
1656         BOOL* marksCursor = self->marks + irow * self.columnCount;
1657         for (i = irow; i < irow + h; ++i) {
1658             self->colBounds[i + i] = icol;
1659             self->colBounds[i + i + 1] = icol + w - 1;
1660             for (int j = icol; j < icol + w; ++j) {
1661                 marksCursor[j] = YES;
1662             }
1663             marksCursor += self.columnCount;
1664         }
1665     } else {
1666         /*
1667          * There's overlap between the rows of the requested block and prior
1668          * marked regions.
1669          */
1670         BOOL* marksCursor = self->marks + irow * self.columnCount;
1671         int irow0, h0;
1672
1673         if (irow < self.firstChangedRow) {
1674             /* Handle any leading rows where there's no overlap. */
1675             for (int i = irow; i < self.firstChangedRow; ++i) {
1676                 self->colBounds[i + i] = icol;
1677                 self->colBounds[i + i + 1] = icol + w - 1;
1678                 for (int j = icol; j < icol + w; ++j) {
1679                     marksCursor[j] = YES;
1680                 }
1681                 marksCursor += self.columnCount;
1682             }
1683             irow0 = self.firstChangedRow;
1684             h0 = irow + h - self.firstChangedRow;
1685             self->_firstChangedRow = irow;
1686         } else {
1687             irow0 = irow;
1688             h0 = h;
1689         }
1690
1691         /* Handle potentially overlapping rows */
1692         if (irow0 + h0 > self.lastChangedRow + 1) {
1693             h0 = self.lastChangedRow + 1 - irow0;
1694             self->_lastChangedRow = irow + h - 1;
1695         }
1696
1697         int i;
1698         for (i = irow0; i < irow0 + h0; ++i) {
1699             if (icol + w <= self->colBounds[i + i]) {
1700                 int j;
1701
1702                 for (j = icol; j < icol + w; ++j) {
1703                     marksCursor[j] = YES;
1704                 }
1705                 if (self->colBounds[i + i] > self->colBounds[i + i + 1]) {
1706                     self->colBounds[i + i + 1] = icol + w - 1;
1707                 } else {
1708                     for (j = icol + w; j < self->colBounds[i + i]; ++j) {
1709                         marksCursor[j] = NO;
1710                     }
1711                 }
1712                 self->colBounds[i + i] = icol;
1713             } else if (icol > self->colBounds[i + i + 1]) {
1714                 int j;
1715
1716                 for (j = self->colBounds[i + i + 1] + 1; j < icol; ++j) {
1717                     marksCursor[j] = NO;
1718                 }
1719                 for (j = icol; j < icol + w; ++j) {
1720                     marksCursor[j] = YES;
1721                 }
1722                 self->colBounds[i + i + 1] = icol + w - 1;
1723             } else {
1724                 if (icol < self->colBounds[i + i]) {
1725                     self->colBounds[i + i] = icol;
1726                 }
1727                 if (icol + w > self->colBounds[i + i + 1]) {
1728                     self->colBounds[i + i + 1] = icol + w - 1;
1729                 }
1730                 for (int j = icol; j < icol + w; ++j) {
1731                     marksCursor[j] = YES;
1732                 }
1733             }
1734             marksCursor += self.columnCount;
1735         }
1736
1737         /* Handle any trailing rows where there's no overlap. */
1738         for (i = irow0 + h0; i < irow + h; ++i) {
1739             self->colBounds[i + i] = icol;
1740             self->colBounds[i + i + 1] = icol + w - 1;
1741             for (int j = icol; j < icol + w; ++j) {
1742                 marksCursor[j] = YES;
1743             }
1744             marksCursor += self.columnCount;
1745         }
1746     }
1747 }
1748
1749 - (int)getFirstChangedColumnInRow:(int)irow
1750 {
1751     if (irow < self.firstChangedRow || irow > self.lastChangedRow) {
1752         return self.columnCount;
1753     }
1754     return self->colBounds[irow + irow];
1755 }
1756
1757 - (int)getLastChangedColumnInRow:(int)irow
1758 {
1759     if (irow < self.firstChangedRow || irow > self.lastChangedRow) {
1760         return -1;
1761     }
1762     return self->colBounds[irow + irow + 1];
1763 }
1764
1765 @end
1766
1767
1768 /**
1769  * Draws one tile as a helper function for AngbandContext's drawRect.
1770  */
1771 static void draw_image_tile(
1772     NSGraphicsContext* nsContext,
1773     CGContextRef cgContext,
1774     CGImageRef image,
1775     NSRect srcRect,
1776     NSRect dstRect,
1777     NSCompositingOperation op)
1778 {
1779     /* Flip the source rect since the source image is flipped */
1780     CGAffineTransform flip = CGAffineTransformIdentity;
1781     flip = CGAffineTransformTranslate(flip, 0.0, CGImageGetHeight(image));
1782     flip = CGAffineTransformScale(flip, 1.0, -1.0);
1783     CGRect flippedSourceRect =
1784         CGRectApplyAffineTransform(NSRectToCGRect(srcRect), flip);
1785
1786     /*
1787      * When we use high-quality resampling to draw a tile, pixels from outside
1788      * the tile may bleed in, causing graphics artifacts. Work around that.
1789      */
1790     CGImageRef subimage =
1791         CGImageCreateWithImageInRect(image, flippedSourceRect);
1792     [nsContext setCompositingOperation:op];
1793     CGContextDrawImage(cgContext, NSRectToCGRect(dstRect), subimage);
1794     CGImageRelease(subimage);
1795 }
1796
1797
1798 /* The max number of glyphs we support.  Currently this only affects
1799  * updateGlyphInfo() for the calculation of the tile size, fontAscender,
1800  * fontDescender, nColPre, and nColPost.  The rendering in drawWChar() will
1801  * work for a glyph not in updateGlyphInfo()'s set, and that is used for
1802  * rendering Japanese characters, though there may be clipping or clearing
1803  * artifacts because it wasn't included in updateGlyphInfo()'s calculations.
1804  */
1805 #define GLYPH_COUNT 256
1806
1807 /*
1808  * An AngbandContext represents a logical Term (i.e. what Angband thinks is
1809  * a window).
1810  */
1811 @interface AngbandContext : NSObject <NSWindowDelegate>
1812 {
1813 @public
1814
1815     /* The Angband term */
1816     term *terminal;
1817
1818 @private
1819     /* Is the last time we drew, so we can throttle drawing. */
1820     CFAbsoluteTime lastRefreshTime;
1821
1822     /* Flags whether or not a fullscreen transition is in progress. */
1823     BOOL inFullscreenTransition;
1824
1825     /* Our view */
1826     AngbandView *angbandView;
1827 }
1828
1829 /* Column and row counts, by default 80 x 24 */
1830 @property (readonly) int cols;
1831 @property (readonly) int rows;
1832
1833 /* The size of the border between the window edge and the contents */
1834 @property (readonly) NSSize borderSize;
1835
1836 /* The font of this context */
1837 @property NSFont *angbandViewFont;
1838
1839 /* The size of one tile */
1840 @property (readonly) NSSize tileSize;
1841
1842 /* Font's ascender and descender */
1843 @property (readonly) CGFloat fontAscender;
1844 @property (readonly) CGFloat fontDescender;
1845
1846 /*
1847  * These are the number of columns before or after, respectively, a text
1848  * change that may need to be redrawn.
1849  */
1850 @property (readonly) int nColPre;
1851 @property (readonly) int nColPost;
1852
1853 /* If this context owns a window, here it is. */
1854 @property NSWindow *primaryWindow;
1855
1856 /* Holds our version of the contents of the terminal. */
1857 @property TerminalContents *contents;
1858
1859 /*
1860  * Marks which locations have been changed by the text_hook, pict_hook,
1861  * wipe_hook, curs_hook, and bigcurs_hhok callbacks on the terminal since
1862  * the last call to xtra_hook with TERM_XTRA_FRESH.
1863  */
1864 @property TerminalChanges *changes;
1865
1866 @property (nonatomic, assign) BOOL hasSubwindowFlags;
1867 @property (nonatomic, assign) BOOL windowVisibilityChecked;
1868
1869 - (void)resizeWithColumns:(int)nCol rows:(int)nRow;
1870
1871 /**
1872  * Based on what has been marked as changed, inform AppKit of the bounding
1873  * rectangles for the changed areas.
1874  */
1875 - (void)computeInvalidRects;
1876
1877 - (void)drawRect:(NSRect)rect inView:(NSView *)view;
1878
1879 /* Called at initialization to set the term */
1880 - (void)setTerm:(term *)t;
1881
1882 /* Called when the context is going down. */
1883 - (void)dispose;
1884
1885 /*
1886  * Return the rect in view coordinates for the block of cells whose upper
1887  * left corner is (x,y).
1888  */
1889 - (NSRect)viewRectForCellBlockAtX:(int)x y:(int)y width:(int)w height:(int)h;
1890
1891 /* Draw the given wide character into the given tile rect. */
1892 - (void)drawWChar:(wchar_t)wchar inRect:(NSRect)tile screenFont:(NSFont*)font
1893           context:(CGContextRef)ctx;
1894
1895 /*
1896  * Returns the primary window for this angband context, creating it if
1897  * necessary
1898  */
1899 - (NSWindow *)makePrimaryWindow;
1900
1901 /* Handle becoming the main window */
1902 - (void)windowDidBecomeMain:(NSNotification *)notification;
1903
1904 /* Return whether the context's primary window is ordered in or not */
1905 - (BOOL)isOrderedIn;
1906
1907 /*
1908  * Return whether the context's primary window is the main window.
1909  * Since the terminals other than terminal 0 are configured as panels in
1910  * Hengband, this will only be true for terminal 0.
1911  */
1912 - (BOOL)isMainWindow;
1913
1914 /*
1915  * Return whether the context's primary window is the destination for key
1916  * input.
1917  */
1918 - (BOOL)isKeyWindow;
1919
1920 /* Invalidate the whole image */
1921 - (void)setNeedsDisplay:(BOOL)val;
1922
1923 /* Invalidate part of the image, with the rect expressed in view coordinates */
1924 - (void)setNeedsDisplayInRect:(NSRect)rect;
1925
1926 /* Display (flush) our Angband views */
1927 - (void)displayIfNeeded;
1928
1929 /* Resize context to size of contentRect, and optionally save size to
1930  * defaults */
1931 - (void)resizeTerminalWithContentRect: (NSRect)contentRect saveToDefaults: (BOOL)saveToDefaults;
1932
1933 /*
1934  * Change the minimum size and size increments for the window associated with
1935  * the context.  termIdx is the index for the terminal:  pass it so this
1936  * function can be used when self->terminal has not yet been set.
1937  */
1938 - (void)constrainWindowSize:(int)termIdx;
1939
1940 - (void)saveWindowVisibleToDefaults: (BOOL)windowVisible;
1941 - (BOOL)windowVisibleUsingDefaults;
1942
1943 /* Class methods */
1944 /**
1945  * Gets the default font for all contexts.  Currently not declaring this as
1946  * a class property for compatibility with versions of Xcode prior to 8.
1947  */
1948 + (NSFont*)defaultFont;
1949 /**
1950  * Sets the default font for all contexts.
1951  */
1952 + (void)setDefaultFont:(NSFont*)font;
1953
1954 /* Internal methods */
1955 /* Set the title for the primary window. */
1956 - (void)setDefaultTitle:(int)termIdx;
1957
1958 @end
1959
1960 /**
1961  * Generate a mask for the subwindow flags. The mask is just a safety check to
1962  * make sure that our windows show and hide as expected.  This function allows
1963  * for future changes to the set of flags without needed to update it here
1964  * (unless the underlying types change).
1965  */
1966 u32b AngbandMaskForValidSubwindowFlags(void)
1967 {
1968     int windowFlagBits = sizeof(*(window_flag)) * CHAR_BIT;
1969     int maxBits = MIN( 16, windowFlagBits );
1970     u32b mask = 0;
1971
1972     for( int i = 0; i < maxBits; i++ )
1973     {
1974         if( window_flag_desc[i] != NULL )
1975         {
1976             mask |= (1 << i);
1977         }
1978     }
1979
1980     return mask;
1981 }
1982
1983 /**
1984  * Check for changes in the subwindow flags and update window visibility.
1985  * This seems to be called for every user event, so we don't
1986  * want to do any unnecessary hiding or showing of windows.
1987  */
1988 static void AngbandUpdateWindowVisibility(void)
1989 {
1990     /*
1991      * Because this function is called frequently, we'll make the mask static.
1992      * It doesn't change between calls, as the flags themselves are hardcoded
1993      */
1994     static u32b validWindowFlagsMask = 0;
1995
1996     if( validWindowFlagsMask == 0 )
1997     {
1998         validWindowFlagsMask = AngbandMaskForValidSubwindowFlags();
1999     }
2000
2001     /*
2002      * Loop through all of the subwindows and see if there is a change in the
2003      * flags. If so, show or hide the corresponding window. We don't care about
2004      * the flags themselves; we just want to know if any are set.
2005      */
2006     for( int i = 1; i < ANGBAND_TERM_MAX; i++ )
2007     {
2008         AngbandContext *angbandContext =
2009             (__bridge AngbandContext*) (angband_term[i]->data);
2010
2011         if( angbandContext == nil )
2012         {
2013             continue;
2014         }
2015
2016         /*
2017          * This horrible mess of flags is so that we can try to maintain some
2018          * user visibility preference. This should allow the user a window and
2019          * have it stay closed between application launches. However, this
2020          * means that when a subwindow is turned on, it will no longer appear
2021          * automatically. Angband has no concept of user control over window
2022          * visibility, other than the subwindow flags.
2023          */
2024         if( !angbandContext.windowVisibilityChecked )
2025         {
2026             if( [angbandContext windowVisibleUsingDefaults] )
2027             {
2028                 [angbandContext.primaryWindow orderFront: nil];
2029                 angbandContext.windowVisibilityChecked = YES;
2030             }
2031             else
2032             {
2033                 [angbandContext.primaryWindow close];
2034                 angbandContext.windowVisibilityChecked = NO;
2035             }
2036         }
2037         else
2038         {
2039             BOOL termHasSubwindowFlags = ((window_flag[i] & validWindowFlagsMask) > 0);
2040
2041             if( angbandContext.hasSubwindowFlags && !termHasSubwindowFlags )
2042             {
2043                 [angbandContext.primaryWindow close];
2044                 angbandContext.hasSubwindowFlags = NO;
2045                 [angbandContext saveWindowVisibleToDefaults: NO];
2046             }
2047             else if( !angbandContext.hasSubwindowFlags && termHasSubwindowFlags )
2048             {
2049                 [angbandContext.primaryWindow orderFront: nil];
2050                 angbandContext.hasSubwindowFlags = YES;
2051                 [angbandContext saveWindowVisibleToDefaults: YES];
2052             }
2053         }
2054     }
2055
2056     /* Make the main window key so that user events go to the right spot */
2057     AngbandContext *mainWindow =
2058         (__bridge AngbandContext*) (angband_term[0]->data);
2059     [mainWindow.primaryWindow makeKeyAndOrderFront: nil];
2060 }
2061
2062 /**
2063  * ------------------------------------------------------------------------
2064  * Graphics support
2065  * ------------------------------------------------------------------------ */
2066
2067 /**
2068  * The tile image
2069  */
2070 static CGImageRef pict_image;
2071
2072 /**
2073  * Numbers of rows and columns in a tileset,
2074  * calculated by the PICT/PNG loading code
2075  */
2076 static int pict_cols = 0;
2077 static int pict_rows = 0;
2078
2079 /**
2080  * Requested graphics mode (as a grafID).
2081  * The current mode is stored in current_graphics_mode.
2082  */
2083 static int graf_mode_req = 0;
2084
2085 /**
2086  * Helper function to check the various ways that graphics can be enabled,
2087  * guarding against NULL
2088  */
2089 static BOOL graphics_are_enabled(void)
2090 {
2091     return current_graphics_mode
2092         && current_graphics_mode->grafID != GRAPHICS_NONE;
2093 }
2094
2095 /**
2096  * Like graphics_are_enabled(), but test the requested graphics mode.
2097  */
2098 static BOOL graphics_will_be_enabled(void)
2099 {
2100     if (graf_mode_req == GRAPHICS_NONE) {
2101         return NO;
2102     }
2103
2104     graphics_mode *new_mode = get_graphics_mode(graf_mode_req);
2105     return new_mode && new_mode->grafID != GRAPHICS_NONE;
2106 }
2107
2108 /**
2109  * Hack -- game in progress
2110  */
2111 static Boolean game_in_progress = FALSE;
2112
2113
2114 #pragma mark Prototypes
2115 static BOOL redraw_for_tiles_or_term0_font(void);
2116 static void wakeup_event_loop(void);
2117 static void hook_plog(const char *str);
2118 static void hook_quit(const char * str);
2119 static NSString* get_lib_directory(void);
2120 static NSString* get_doc_directory(void);
2121 static NSString* AngbandCorrectedDirectoryPath(NSString *originalPath);
2122 static void prepare_paths_and_directories(void);
2123 static void load_prefs(void);
2124 static void init_windows(void);
2125 static void handle_open_when_ready(void);
2126 static void play_sound(int event);
2127 static BOOL check_events(int wait);
2128 static BOOL send_event(NSEvent *event);
2129 static void set_color_for_index(int idx);
2130 static void record_current_savefile(void);
2131
2132 /**
2133  * Available values for 'wait'
2134  */
2135 #define CHECK_EVENTS_DRAIN -1
2136 #define CHECK_EVENTS_NO_WAIT    0
2137 #define CHECK_EVENTS_WAIT 1
2138
2139
2140 /**
2141  * Note when "open"/"new" become valid
2142  */
2143 static bool initialized = FALSE;
2144
2145 /* Methods for getting the appropriate NSUserDefaults */
2146 @interface NSUserDefaults (AngbandDefaults)
2147 + (NSUserDefaults *)angbandDefaults;
2148 @end
2149
2150 @implementation NSUserDefaults (AngbandDefaults)
2151 + (NSUserDefaults *)angbandDefaults
2152 {
2153     return [NSUserDefaults standardUserDefaults];
2154 }
2155 @end
2156
2157 /*
2158  * Methods for pulling images out of the Angband bundle (which may be separate
2159  * from the current bundle in the case of a screensaver
2160  */
2161 @interface NSImage (AngbandImages)
2162 + (NSImage *)angbandImage:(NSString *)name;
2163 @end
2164
2165 /* The NSView subclass that draws our Angband image */
2166 @interface AngbandView : NSView {
2167 @private
2168     NSBitmapImageRep *cacheForResize;
2169     NSRect cacheBounds;
2170 }
2171
2172 @property (nonatomic, weak) AngbandContext *angbandContext;
2173
2174 @end
2175
2176 @implementation NSImage (AngbandImages)
2177
2178 /*
2179  * Returns an image in the resource directoy of the bundle containing the
2180  * Angband view class.
2181  */
2182 + (NSImage *)angbandImage:(NSString *)name
2183 {
2184     NSBundle *bundle = [NSBundle bundleForClass:[AngbandView class]];
2185     NSString *path = [bundle pathForImageResource:name];
2186     return (path) ? [[NSImage alloc] initByReferencingFile:path] : nil;
2187 }
2188
2189 @end
2190
2191
2192 @implementation AngbandContext
2193
2194 - (NSSize)baseSize
2195 {
2196     /*
2197      * We round the base size down. If we round it up, I believe we may end up
2198      * with pixels that nobody "owns" that may accumulate garbage. In general
2199      * rounding down is harmless, because any lost pixels may be sopped up by
2200      * the border.
2201      */
2202     return NSMakeSize(
2203         floor(self.cols * self.tileSize.width + 2 * self.borderSize.width),
2204         floor(self.rows * self.tileSize.height + 2 * self.borderSize.height));
2205 }
2206
2207 /* qsort-compatible compare function for CGSizes */
2208 static int compare_advances(const void *ap, const void *bp)
2209 {
2210     const CGSize *a = ap, *b = bp;
2211     return (a->width > b->width) - (a->width < b->width);
2212 }
2213
2214 /**
2215  * Precompute certain metrics (tileSize, fontAscender, fontDescender, nColPre,
2216  * and nColPost) for the current font.
2217  */
2218 - (void)updateGlyphInfo
2219 {
2220     NSFont *screenFont = [self.angbandViewFont screenFont];
2221
2222     /* Generate a string containing each MacRoman character */
2223     /*
2224      * Here and below, dynamically allocate working arrays rather than put them
2225      * on the stack in case limited stack space is an issue.
2226      */
2227     unsigned char *latinString = malloc(GLYPH_COUNT);
2228     if (latinString == 0) {
2229         NSException *exc = [NSException exceptionWithName:@"OutOfMemory"
2230                                         reason:@"latinString in updateGlyphInfo"
2231                                         userInfo:nil];
2232         @throw exc;
2233     }
2234     size_t i;
2235     for (i=0; i < GLYPH_COUNT; i++) latinString[i] = (unsigned char)i;
2236
2237     /* Turn that into unichar. Angband uses ISO Latin 1. */
2238     NSString *allCharsString = [[NSString alloc] initWithBytes:latinString
2239         length:GLYPH_COUNT encoding:NSISOLatin1StringEncoding];
2240     unichar *unicharString = malloc(GLYPH_COUNT * sizeof(unichar));
2241     if (unicharString == 0) {
2242         free(latinString);
2243         NSException *exc = [NSException exceptionWithName:@"OutOfMemory"
2244                                         reason:@"unicharString in updateGlyphInfo"
2245                                         userInfo:nil];
2246         @throw exc;
2247     }
2248     unicharString[0] = 0;
2249     [allCharsString getCharacters:unicharString range:NSMakeRange(0, MIN(GLYPH_COUNT, [allCharsString length]))];
2250     allCharsString = nil;
2251     free(latinString);
2252
2253     /* Get glyphs */
2254     CGGlyph *glyphArray = calloc(GLYPH_COUNT, sizeof(CGGlyph));
2255     if (glyphArray == 0) {
2256         free(unicharString);
2257         NSException *exc = [NSException exceptionWithName:@"OutOfMemory"
2258                                         reason:@"glyphArray in updateGlyphInfo"
2259                                         userInfo:nil];
2260         @throw exc;
2261     }
2262     CTFontGetGlyphsForCharacters((CTFontRef)screenFont, unicharString,
2263                                  glyphArray, GLYPH_COUNT);
2264     free(unicharString);
2265
2266     /* Get advances. Record the max advance. */
2267     CGSize *advances = malloc(GLYPH_COUNT * sizeof(CGSize));
2268     if (advances == 0) {
2269         free(glyphArray);
2270         NSException *exc = [NSException exceptionWithName:@"OutOfMemory"
2271                                         reason:@"advances in updateGlyphInfo"
2272                                         userInfo:nil];
2273         @throw exc;
2274     }
2275     CTFontGetAdvancesForGlyphs(
2276         (CTFontRef)screenFont, kCTFontHorizontalOrientation, glyphArray,
2277         advances, GLYPH_COUNT);
2278     CGFloat *glyphWidths = malloc(GLYPH_COUNT * sizeof(CGFloat));
2279     if (glyphWidths == 0) {
2280         free(glyphArray);
2281         free(advances);
2282         NSException *exc = [NSException exceptionWithName:@"OutOfMemory"
2283                                         reason:@"glyphWidths in updateGlyphInfo"
2284                                         userInfo:nil];
2285         @throw exc;
2286     }
2287     for (i=0; i < GLYPH_COUNT; i++) {
2288         glyphWidths[i] = advances[i].width;
2289     }
2290
2291     /*
2292      * For good non-mono-font support, use the median advance. Start by sorting
2293      * all advances.
2294      */
2295     qsort(advances, GLYPH_COUNT, sizeof *advances, compare_advances);
2296
2297     /* Skip over any initially empty run */
2298     size_t startIdx;
2299     for (startIdx = 0; startIdx < GLYPH_COUNT; startIdx++)
2300     {
2301         if (advances[startIdx].width > 0) break;
2302     }
2303
2304     /* Pick the center to find the median */
2305     CGFloat medianAdvance = 0;
2306     /* In case we have all zero advances for some reason */
2307     if (startIdx < GLYPH_COUNT)
2308     {
2309         medianAdvance = advances[(startIdx + GLYPH_COUNT)/2].width;
2310     }
2311
2312     free(advances);
2313
2314     /*
2315      * Record the ascender and descender.  Some fonts, for instance DIN
2316      * Condensed and Rockwell in 10.14, the ascent on '@' exceeds that
2317      * reported by [screenFont ascender].  Get the overall bounding box
2318      * for the glyphs and use that instead of the ascender and descender
2319      * values if the bounding box result extends farther from the baseline.
2320      */
2321     CGRect bounds = CTFontGetBoundingRectsForGlyphs(
2322         (CTFontRef) screenFont, kCTFontHorizontalOrientation, glyphArray,
2323         NULL, GLYPH_COUNT);
2324     self->_fontAscender = [screenFont ascender];
2325     if (self->_fontAscender < bounds.origin.y + bounds.size.height) {
2326         self->_fontAscender = bounds.origin.y + bounds.size.height;
2327     }
2328     self->_fontDescender = [screenFont descender];
2329     if (self->_fontDescender > bounds.origin.y) {
2330         self->_fontDescender = bounds.origin.y;
2331     }
2332
2333     /*
2334      * Record the tile size.  Round both values up to have tile boundaries
2335      * match pixel boundaries.
2336      */
2337     self->_tileSize.width = ceil(medianAdvance);
2338     self->_tileSize.height = ceil(self.fontAscender - self.fontDescender);
2339
2340     /*
2341      * Determine whether neighboring columns need to be redrawn when a
2342      * character changes.
2343      */
2344     CGRect *boxes = malloc(GLYPH_COUNT * sizeof(CGRect));
2345     if (boxes == 0) {
2346         free(glyphWidths);
2347         free(glyphArray);
2348         NSException *exc = [NSException exceptionWithName:@"OutOfMemory"
2349                                         reason:@"boxes in updateGlyphInfo"
2350                                         userInfo:nil];
2351         @throw exc;
2352     }
2353     CGFloat beyond_right = 0.;
2354     CGFloat beyond_left = 0.;
2355     CTFontGetBoundingRectsForGlyphs(
2356         (CTFontRef)screenFont,
2357         kCTFontHorizontalOrientation,
2358         glyphArray,
2359         boxes,
2360         GLYPH_COUNT);
2361     for (i = 0; i < GLYPH_COUNT; i++) {
2362         /* Account for the compression and offset used by drawWChar(). */
2363         CGFloat compression, offset;
2364         CGFloat v;
2365
2366         if (glyphWidths[i] <= self.tileSize.width) {
2367             compression = 1.;
2368             offset = 0.5 * (self.tileSize.width - glyphWidths[i]);
2369         } else {
2370             compression = self.tileSize.width / glyphWidths[i];
2371             offset = 0.;
2372         }
2373         v = (offset + boxes[i].origin.x) * compression;
2374         if (beyond_left > v) {
2375             beyond_left = v;
2376         }
2377         v = (offset + boxes[i].origin.x + boxes[i].size.width) * compression;
2378         if (beyond_right < v) {
2379             beyond_right = v;
2380         }
2381     }
2382     free(boxes);
2383     self->_nColPre = ceil(-beyond_left / self.tileSize.width);
2384     if (beyond_right > self.tileSize.width) {
2385         self->_nColPost =
2386             ceil((beyond_right - self.tileSize.width) / self.tileSize.width);
2387     } else {
2388         self->_nColPost = 0;
2389     }
2390
2391     free(glyphWidths);
2392     free(glyphArray);
2393 }
2394
2395
2396 - (void)requestRedraw
2397 {
2398     if (! self->terminal) return;
2399     
2400     term *old = Term;
2401     
2402     /* Activate the term */
2403     Term_activate(self->terminal);
2404     
2405     /* Redraw the contents */
2406     Term_redraw();
2407     
2408     /* Flush the output */
2409     Term_fresh();
2410     
2411     /* Restore the old term */
2412     Term_activate(old);
2413 }
2414
2415 - (void)setTerm:(term *)t
2416 {
2417     self->terminal = t;
2418 }
2419
2420 /**
2421  * If we're trying to limit ourselves to a certain number of frames per second,
2422  * then compute how long it's been since we last drew, and then wait until the
2423  * next frame has passed. */
2424 - (void)throttle
2425 {
2426     if (frames_per_second > 0)
2427     {
2428         CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
2429         CFTimeInterval timeSinceLastRefresh = now - self->lastRefreshTime;
2430         CFTimeInterval timeUntilNextRefresh = (1. / (double)frames_per_second) - timeSinceLastRefresh;
2431         
2432         if (timeUntilNextRefresh > 0)
2433         {
2434             usleep((unsigned long)(timeUntilNextRefresh * 1000000.));
2435         }
2436     }
2437     self->lastRefreshTime = CFAbsoluteTimeGetCurrent();
2438 }
2439
2440 - (void)drawWChar:(wchar_t)wchar inRect:(NSRect)tile screenFont:(NSFont*)font
2441           context:(CGContextRef)ctx
2442 {
2443     CGFloat tileOffsetY = self.fontAscender;
2444     CGFloat tileOffsetX = 0.0;
2445     UniChar unicharString[2] = {(UniChar)wchar, 0};
2446
2447     /* Get glyph and advance */
2448     CGGlyph thisGlyphArray[1] = { 0 };
2449     CGSize advances[1] = { { 0, 0 } };
2450     CTFontGetGlyphsForCharacters(
2451         (CTFontRef)font, unicharString, thisGlyphArray, 1);
2452     CGGlyph glyph = thisGlyphArray[0];
2453     CTFontGetAdvancesForGlyphs(
2454         (CTFontRef)font, kCTFontHorizontalOrientation, thisGlyphArray,
2455         advances, 1);
2456     CGSize advance = advances[0];
2457
2458     /*
2459      * If our font is not monospaced, our tile width is deliberately not big
2460      * enough for every character. In that event, if our glyph is too wide, we
2461      * need to compress it horizontally. Compute the compression ratio.
2462      * 1.0 means no compression.
2463      */
2464     double compressionRatio;
2465     if (advance.width <= NSWidth(tile))
2466     {
2467         /* Our glyph fits, so we can just draw it, possibly with an offset */
2468         compressionRatio = 1.0;
2469         tileOffsetX = (NSWidth(tile) - advance.width)/2;
2470     }
2471     else
2472     {
2473         /* Our glyph doesn't fit, so we'll have to compress it */
2474         compressionRatio = NSWidth(tile) / advance.width;
2475         tileOffsetX = 0;
2476     }
2477
2478     /* Now draw it */
2479     CGAffineTransform textMatrix = CGContextGetTextMatrix(ctx);
2480     CGFloat savedA = textMatrix.a;
2481
2482     /* Set the position */
2483     textMatrix.tx = tile.origin.x + tileOffsetX;
2484     textMatrix.ty = tile.origin.y + tileOffsetY;
2485
2486     /* Maybe squish it horizontally. */
2487     if (compressionRatio != 1.)
2488     {
2489         textMatrix.a *= compressionRatio;
2490     }
2491
2492     CGContextSetTextMatrix(ctx, textMatrix);
2493     CGContextShowGlyphsAtPositions(ctx, &glyph, &CGPointZero, 1);
2494
2495     /* Restore the text matrix if we messed with the compression ratio */
2496     if (compressionRatio != 1.)
2497     {
2498         textMatrix.a = savedA;
2499     }
2500
2501     CGContextSetTextMatrix(ctx, textMatrix);
2502 }
2503
2504 - (NSRect)viewRectForCellBlockAtX:(int)x y:(int)y width:(int)w height:(int)h
2505 {
2506     return NSMakeRect(
2507         x * self.tileSize.width + self.borderSize.width,
2508         y * self.tileSize.height + self.borderSize.height,
2509         w * self.tileSize.width, h * self.tileSize.height);
2510 }
2511
2512 - (void)setSelectionFont:(NSFont*)font adjustTerminal: (BOOL)adjustTerminal
2513 {
2514     /* Record the new font */
2515     self.angbandViewFont = font;
2516
2517     /* Update our glyph info */
2518     [self updateGlyphInfo];
2519
2520     if( adjustTerminal )
2521     {
2522         /*
2523          * Adjust terminal to fit window with new font; save the new columns
2524          * and rows since they could be changed
2525          */
2526         NSRect contentRect =
2527             [self.primaryWindow
2528                  contentRectForFrameRect: [self.primaryWindow frame]];
2529
2530         [self constrainWindowSize:[self terminalIndex]];
2531         NSSize size = self.primaryWindow.contentMinSize;
2532         BOOL windowNeedsResizing = NO;
2533         if (contentRect.size.width < size.width) {
2534             contentRect.size.width = size.width;
2535             windowNeedsResizing = YES;
2536         }
2537         if (contentRect.size.height < size.height) {
2538             contentRect.size.height = size.height;
2539             windowNeedsResizing = YES;
2540         }
2541         if (windowNeedsResizing) {
2542             size.width = contentRect.size.width;
2543             size.height = contentRect.size.height;
2544             [self.primaryWindow setContentSize:size];
2545         }
2546         [self resizeTerminalWithContentRect: contentRect saveToDefaults: YES];
2547     }
2548 }
2549
2550 - (id)init
2551 {
2552     if ((self = [super init]))
2553     {
2554         /* Default rows and cols */
2555         self->_cols = 80;
2556         self->_rows = 24;
2557
2558         /* Default border size */
2559         self->_borderSize = NSMakeSize(2, 2);
2560
2561         self->_nColPre = 0;
2562         self->_nColPost = 0;
2563
2564         self->_contents =
2565             [[TerminalContents alloc] initWithColumns:self->_cols
2566                                       rows:self->_rows];
2567         self->_changes =
2568             [[TerminalChanges alloc] initWithColumns:self->_cols
2569                                      rows:self->_rows];
2570         self->lastRefreshTime = CFAbsoluteTimeGetCurrent();
2571         self->inFullscreenTransition = NO;
2572
2573         self->_windowVisibilityChecked = NO;
2574     }
2575     return self;
2576 }
2577
2578 /**
2579  * Destroy all the receiver's stuff. This is intended to be callable more than
2580  * once.
2581  */
2582 - (void)dispose
2583 {
2584     self->terminal = NULL;
2585
2586     /* Disassociate ourselves from our view. */
2587     [self->angbandView setAngbandContext:nil];
2588     self->angbandView = nil;
2589
2590     /* Font */
2591     self.angbandViewFont = nil;
2592
2593     /* Window */
2594     [self.primaryWindow setDelegate:nil];
2595     [self.primaryWindow close];
2596     self.primaryWindow = nil;
2597
2598     /* Contents and pending changes */
2599     self.contents = nil;
2600     self.changes = nil;
2601 }
2602
2603 /* Usual Cocoa fare */
2604 - (void)dealloc
2605 {
2606     [self dispose];
2607 }
2608
2609 - (void)resizeWithColumns:(int)nCol rows:(int)nRow
2610 {
2611     [self.contents resizeWithColumns:nCol rows:nRow];
2612     [self.changes resizeWithColumns:nCol rows:nRow];
2613     self->_cols = nCol;
2614     self->_rows = nRow;
2615 }
2616
2617 /**
2618  * For defaultFont and setDefaultFont.
2619  */
2620 static __strong NSFont* gDefaultFont = nil;
2621
2622 + (NSFont*)defaultFont
2623 {
2624     return gDefaultFont;
2625 }
2626
2627 + (void)setDefaultFont:(NSFont*)font
2628 {
2629     gDefaultFont = font;
2630 }
2631
2632 - (void)setDefaultTitle:(int)termIdx
2633 {
2634     NSMutableString *title =
2635         [NSMutableString stringWithCString:angband_term_name[termIdx]
2636 #ifdef JP
2637                          encoding:NSJapaneseEUCStringEncoding
2638 #else
2639                          encoding:NSMacOSRomanStringEncoding
2640 #endif
2641         ];
2642     [title appendFormat:@" %dx%d", self.cols, self.rows];
2643     [[self makePrimaryWindow] setTitle:title];
2644 }
2645
2646 - (NSWindow *)makePrimaryWindow
2647 {
2648     if (! self.primaryWindow)
2649     {
2650         /*
2651          * This has to be done after the font is set, which it already is in
2652          * term_init_cocoa()
2653          */
2654         NSSize sz = self.baseSize;
2655         NSRect contentRect = NSMakeRect( 0.0, 0.0, sz.width, sz.height );
2656
2657         NSUInteger styleMask = NSTitledWindowMask | NSResizableWindowMask | NSMiniaturizableWindowMask;
2658
2659         /*
2660          * Make every window other than the main window closable, also create
2661          * them as utility panels to get the thinner title bar and other
2662          * attributes that already match up with how those windows are used.
2663          */
2664         if ((__bridge AngbandContext*) (angband_term[0]->data) != self)
2665         {
2666             NSPanel *panel =
2667                 [[NSPanel alloc] initWithContentRect:contentRect
2668                                  styleMask:(styleMask | NSClosableWindowMask |
2669                                             NSUtilityWindowMask)
2670                                  backing:NSBackingStoreBuffered defer:YES];
2671
2672             panel.floatingPanel = NO;
2673             self.primaryWindow = panel;
2674         } else {
2675             self.primaryWindow =
2676                 [[NSWindow alloc] initWithContentRect:contentRect
2677                                   styleMask:styleMask
2678                                   backing:NSBackingStoreBuffered defer:YES];
2679         }
2680
2681         /* Not to be released when closed */
2682         [self.primaryWindow setReleasedWhenClosed:NO];
2683         [self.primaryWindow setExcludedFromWindowsMenu: YES]; /* we're using custom window menu handling */
2684
2685         /* Make the view */
2686         self->angbandView = [[AngbandView alloc] initWithFrame:contentRect];
2687         [angbandView setAngbandContext:self];
2688         [angbandView setNeedsDisplay:YES];
2689         [self.primaryWindow setContentView:angbandView];
2690
2691         /* We are its delegate */
2692         [self.primaryWindow setDelegate:self];
2693     }
2694     return self.primaryWindow;
2695 }
2696
2697
2698 - (void)computeInvalidRects
2699 {
2700     for (int irow = self.changes.firstChangedRow;
2701          irow <= self.changes.lastChangedRow;
2702          ++irow) {
2703         int icol = [self.changes scanForChangedInRow:irow
2704                         col0:0 col1:self.cols];
2705
2706         while (icol < self.cols) {
2707             /* Find the end of the changed region. */
2708             int jcol =
2709                 [self.changes scanForUnchangedInRow:irow col0:(icol + 1)
2710                      col1:self.cols];
2711
2712             /*
2713              * If the last column is a character, extend the region drawn
2714              * because characters can exceed the horizontal bounds of the cell
2715              * and those parts will need to be cleared.  Don't extend into a
2716              * tile because the clipping is set while drawing to never
2717              * extend text into a tile.  For a big character that's been
2718              * partially overwritten, allow what comes after the point
2719              * where the overwrite occurred to influence the stuff before
2720              * but not vice versa.  If extending the region reaches another
2721              * changed block, find the end of that block and repeat the
2722              * process.
2723              */
2724             /*
2725              * A value of zero means checking for a character immediately
2726              * prior to the column, isrch.  A value of one means checking for
2727              * something past the end that could either influence the changed
2728              * region (within nColPre of it and no intervening tile) or be
2729              * influenced by it (within nColPost of it and no intervening
2730              * tile or partially overwritten big character).  A value of two
2731              * means checking for something past the end which is both changed
2732              * and could affect the part of the unchanged region that has to
2733              * be redrawn because it is affected by the prior changed region
2734              * Values of three and four are like one and two, respectively,
2735              * but indicate that a partially overwritten big character was
2736              * found.
2737              */
2738             int stage = 0;
2739             int isrch = jcol;
2740             int irng0 = jcol;
2741             int irng1 = jcol;
2742             while (1) {
2743                 if (stage == 0) {
2744                     const struct TerminalCell *pcell =
2745                         [self.contents getCellAtColumn:(isrch - 1) row:irow];
2746                     if ((pcell->form &
2747                          (TERM_CELL_TILE | TERM_CELL_TILE_PADDING)) != 0) {
2748                         break;
2749                     } else {
2750                         irng0 = isrch + self.nColPre;
2751                         if (irng0 > self.cols) {
2752                             irng0 = self.cols;
2753                         }
2754                         irng1 = isrch + self.nColPost;
2755                         if (irng1 > self.cols) {
2756                             irng1 = self.cols;
2757                         }
2758                         if (isrch < irng0 || isrch < irng1) {
2759                             stage = isPartiallyOverwrittenBigChar(pcell) ?
2760                                 3 : 1;
2761                         } else {
2762                             break;
2763                         }
2764                     }
2765                 }
2766
2767                 if (stage == 1) {
2768                     const struct TerminalCell *pcell =
2769                         [self.contents getCellAtColumn:isrch row:irow];
2770
2771                     if ((pcell->form &
2772                          (TERM_CELL_TILE | TERM_CELL_TILE_PADDING)) != 0) {
2773                         /*
2774                          * Check if still in the region that could be
2775                          * influenced by the changed region.  If so,
2776                          * everything up to the tile will be redrawn anyways
2777                          * so combine the regions if the tile has changed
2778                          * as well.  Otherwise, terminate the search since
2779                          * the tile doesn't allow influence to propagate
2780                          * through it and don't want to affect what's in the
2781                          * tile.
2782                          */
2783                         if (isrch < irng1) {
2784                             if ([self.changes isChangedAtColumn:isrch
2785                                      row:irow]) {
2786                                 jcol = [self.changes scanForUnchangedInRow:irow
2787                                             col0:(isrch + 1) col1:self.cols];
2788                                 if (jcol < self.cols) {
2789                                     stage = 0;
2790                                     isrch = jcol;
2791                                     continue;
2792                                 }
2793                             }
2794                         }
2795                         break;
2796                     } else {
2797                         /*
2798                          * With a changed character, combine the regions (if
2799                          * still in the region affected by the changed region
2800                          * am going to redraw everything up to this new region
2801                          * anyway; if only in the region that can affect the
2802                          * changed region, this changed text could influence
2803                          * the current changed region).
2804                          */
2805                         if ([self.changes isChangedAtColumn:isrch row:irow]) {
2806                             jcol = [self.changes scanForUnchangedInRow:irow
2807                                         col0:(isrch + 1) col1:self.cols];
2808                             if (jcol < self.cols) {
2809                                 stage = 0;
2810                                 isrch = jcol;
2811                                 continue;
2812                             }
2813                             break;
2814                         }
2815
2816                         if (isrch < irng1) {
2817                             /*
2818                              * Can be affected by the changed region so
2819                              * has to be redrawn.
2820                              */
2821                             ++jcol;
2822                         }
2823                         ++isrch;
2824                         if (isrch >= irng1) {
2825                             irng0 = jcol + self.nColPre;
2826                             if (irng0 > self.cols) {
2827                                 irng0 = self.cols;
2828                             }
2829                             if (isrch >= irng0) {
2830                                 break;
2831                             }
2832                             stage = isPartiallyOverwrittenBigChar(pcell) ?
2833                                 4 : 2;
2834                         } else if (isPartiallyOverwrittenBigChar(pcell)) {
2835                             stage = 3;
2836                         }
2837                     }
2838                 }
2839
2840                 if (stage == 2) {
2841                     /*
2842                      * Looking for a later changed region that could influence
2843                      * the region that has to be redrawn.  The region that has
2844                      * to be redrawn ends just before jcol.
2845                      */
2846                     const struct TerminalCell *pcell =
2847                         [self.contents getCellAtColumn:isrch row:irow];
2848
2849                     if ((pcell->form &
2850                          (TERM_CELL_TILE | TERM_CELL_TILE_PADDING)) != 0) {
2851                         /* Can not spread influence through a tile. */
2852                         break;
2853                     }
2854                     if ([self.changes isChangedAtColumn:isrch row:irow]) {
2855                         /*
2856                          * Found one.  Combine with the one ending just before
2857                          * jcol.
2858                          */
2859                         jcol = [self.changes scanForUnchangedInRow:irow
2860                                     col0:(isrch + 1) col1:self.cols];
2861                         if (jcol < self.cols) {
2862                             stage = 0;
2863                             isrch = jcol;
2864                             continue;
2865                         }
2866                         break;
2867                     }
2868
2869                     ++isrch;
2870                     if (isrch >= irng0) {
2871                         break;
2872                     }
2873                     if (isPartiallyOverwrittenBigChar(pcell)) {
2874                         stage = 4;
2875                     }
2876                 }
2877
2878                 if (stage == 3) {
2879                     const struct TerminalCell *pcell =
2880                         [self.contents getCellAtColumn:isrch row:irow];
2881
2882                     /*
2883                      * Have encountered a partially overwritten big character
2884                      * but still may be in the region that could be influenced
2885                      * by the changed region.  That influence can not extend
2886                      * past the past the padding for the partially overwritten
2887                      * character.
2888                      */
2889                     if ((pcell->form & (TERM_CELL_CHAR | TERM_CELL_TILE |
2890                                         TERM_CELL_TILE_PADDING)) != 0) {
2891                         if (isrch < irng1) {
2892                             /*
2893                              * Still can be affected by the changed region
2894                              * so everything up to isrch will be redrawn
2895                              * anyways.  If this location has changed,
2896                              * merge the changed regions.
2897                              */
2898                             if ([self.changes isChangedAtColumn:isrch
2899                                      row:irow]) {
2900                                 jcol = [self.changes scanForUnchangedInRow:irow
2901                                             col0:(isrch + 1) col1:self.cols];
2902                                 if (jcol < self.cols) {
2903                                     stage = 0;
2904                                     isrch = jcol;
2905                                     continue;
2906                                 }
2907                                 break;
2908                             }
2909                         }
2910                         if ((pcell->form &
2911                              (TERM_CELL_TILE | TERM_CELL_TILE_PADDING)) != 0) {
2912                             /*
2913                              * It's a tile.  That blocks influence in either
2914                              * direction.
2915                              */
2916                             break;
2917                         }
2918
2919                         /*
2920                          * The partially overwritten big character was
2921                          * overwritten by a character.  Check to see if it
2922                          * can either influence the unchanged region that
2923                          * has to redrawn or the changed region prior to
2924                          * that.
2925                          */
2926                         if (isrch >= irng0) {
2927                             break;
2928                         }
2929                         stage = 4;
2930                     } else {
2931                         if (isrch < irng1) {
2932                             /*
2933                              * Can be affected by the changed region so has to
2934                              * be redrawn.
2935                              */
2936                             ++jcol;
2937                         }
2938                         ++isrch;
2939                         if (isrch >= irng1) {
2940                             irng0 = jcol + self.nColPre;
2941                             if (irng0 > self.cols) {
2942                                 irng0 = self.cols;
2943                             }
2944                             if (isrch >= irng0) {
2945                                 break;
2946                             }
2947                             stage = 4;
2948                         }
2949                     }
2950                 }
2951
2952                 if (stage == 4) {
2953                     /*
2954                      * Have already encountered a partially overwritten big
2955                      * character.  Looking for a later changed region that
2956                      * could influence the region that has to be redrawn
2957                      * The region that has to be redrawn ends just before jcol.
2958                      */
2959                     const struct TerminalCell *pcell =
2960                         [self.contents getCellAtColumn:isrch row:irow];
2961
2962                     if ((pcell->form &
2963                          (TERM_CELL_TILE | TERM_CELL_TILE_PADDING)) != 0) {
2964                         /* Can not spread influence through a tile. */
2965                         break;
2966                     }
2967                     if (pcell->form == TERM_CELL_CHAR) {
2968                         if ([self.changes isChangedAtColumn:isrch row:irow]) {
2969                             /*
2970                              * Found a changed region.  Combine with the one
2971                              * ending just before jcol.
2972                              */
2973                             jcol = [self.changes scanForUnchangedInRow:irow
2974                                         col0:(isrch + 1) col1:self.cols];
2975                             if (jcol < self.cols) {
2976                                 stage = 0;
2977                                 isrch = jcol;
2978                                 continue;
2979                             }
2980                             break;
2981                         }
2982                     }
2983                     ++isrch;
2984                     if (isrch >= irng0) {
2985                         break;
2986                     }
2987                 }
2988             }
2989
2990             /*
2991              * Check to see if there's characters before the changed region
2992              * that would have to be redrawn because it's influenced by the
2993              * changed region.  Do not have to check for merging with a prior
2994              * region because of the screening already done.
2995              */
2996             if (self.nColPre > 0 &&
2997                 ([self.contents getCellAtColumn:icol row:irow]->form &
2998                  (TERM_CELL_CHAR | TERM_CELL_CHAR_PADDING)) != 0) {
2999                 int irng = icol - self.nColPre;
3000
3001                 if (irng < 0) {
3002                     irng = 0;
3003                 }
3004                 while (icol > irng &&
3005                        ([self.contents getCellAtColumn:(icol - 1)
3006                              row:irow]->form &
3007                         (TERM_CELL_CHAR | TERM_CELL_CHAR_PADDING)) != 0) {
3008                     --icol;
3009                 }
3010             }
3011
3012             NSRect r = [self viewRectForCellBlockAtX:icol y:irow
3013                              width:(jcol - icol) height:1];
3014             [self setNeedsDisplayInRect:r];
3015
3016             icol = [self.changes scanForChangedInRow:irow col0:jcol
3017                         col1:self.cols];
3018         }
3019     }
3020 }
3021
3022
3023 #pragma mark View/Window Passthrough
3024
3025 /*
3026  * This is a qsort-compatible compare function for NSRect, to get them in
3027  * ascending order by y origin.
3028  */
3029 static int compare_nsrect_yorigin_greater(const void *ap, const void *bp)
3030 {
3031     const NSRect *arp = ap;
3032     const NSRect *brp = bp;
3033     return (arp->origin.y > brp->origin.y) - (arp->origin.y < brp->origin.y);
3034 }
3035
3036 /**
3037  * This is a helper function for drawRect.
3038  */
3039 - (void)renderTileRunInRow:(int)irow col0:(int)icol0 col1:(int)icol1
3040                      nsctx:(NSGraphicsContext*)nsctx ctx:(CGContextRef)ctx
3041                  grafWidth:(int)graf_width grafHeight:(int)graf_height
3042                overdrawRow:(int)overdraw_row overdrawMax:(int)overdraw_max
3043 {
3044     /* Save the compositing mode since it is modified below. */
3045     NSCompositingOperation op = nsctx.compositingOperation;
3046
3047     while (icol0 < icol1) {
3048         const struct TerminalCell *pcell =
3049             [self.contents getCellAtColumn:icol0 row:irow];
3050         NSRect destinationRect =
3051             [self viewRectForCellBlockAtX:icol0 y:irow
3052                   width:pcell->hscl height:pcell->vscl];
3053         NSRect fgdRect = NSMakeRect(
3054             graf_width * (pcell->v.ti.fgdCol +
3055                           pcell->hoff_n / (1.0 * pcell->hoff_d)),
3056             graf_height * (pcell->v.ti.fgdRow +
3057                            pcell->voff_n / (1.0 * pcell->voff_d)),
3058             graf_width * pcell->hscl / (1.0 * pcell->hoff_d),
3059             graf_height * pcell->vscl / (1.0 * pcell->voff_d));
3060         NSRect bckRect = NSMakeRect(
3061             graf_width * (pcell->v.ti.bckCol +
3062                           pcell->hoff_n / (1.0 * pcell->hoff_d)),
3063             graf_height * (pcell->v.ti.bckRow +
3064                            pcell->voff_n / (1.0 * pcell->voff_d)),
3065             graf_width * pcell->hscl / (1.0 * pcell->hoff_d),
3066             graf_height * pcell->vscl / (1.0 * pcell->voff_d));
3067         int dbl_height_bck = overdraw_row && (irow > 2) &&
3068             (pcell->v.ti.bckRow >= overdraw_row &&
3069              pcell->v.ti.bckRow <= overdraw_max);
3070         int dbl_height_fgd = overdraw_row && (irow > 2) &&
3071             (pcell->v.ti.fgdRow >= overdraw_row) &&
3072             (pcell->v.ti.fgdRow <= overdraw_max);
3073         int aligned_row = 0, aligned_col = 0;
3074         int is_first_piece = 0, simple_upper = 0;
3075
3076         /* Initialize stuff for handling a double-height tile. */
3077         if (dbl_height_bck || dbl_height_fgd) {
3078             if (self->terminal == angband_term[0]) {
3079                 aligned_col = ((icol0 - COL_MAP) / pcell->hoff_d) *
3080                     pcell->hoff_d + COL_MAP;
3081             } else {
3082                 aligned_col = (icol0 / pcell->hoff_d) * pcell->hoff_d;
3083             }
3084             aligned_row = ((irow - ROW_MAP) / pcell->voff_d) *
3085                 pcell->voff_d + ROW_MAP;
3086
3087             /*
3088              * If the lower half has been broken into multiple pieces, only
3089              * do the work of rendering whatever is necessary for the upper
3090              * half when drawing the first piece (the one closest to the
3091              * upper left corner).
3092              */
3093             struct TerminalCellLocation curs = { 0, 0 };
3094
3095             [self.contents scanForTypeMaskInBlockAtColumn:aligned_col
3096                  row:aligned_row width:pcell->hoff_d height:pcell->voff_d
3097                  mask:TERM_CELL_TILE cursor:&curs];
3098             if (curs.col + aligned_col == icol0 &&
3099                 curs.row + aligned_row == irow) {
3100                 is_first_piece = 1;
3101
3102                 /*
3103                  * Hack:  lookup the previous row to determine how much of the
3104                  * tile there is shown to apply it the upper half of the
3105                  * double-height tile.  That will do the right thing if there
3106                  * is a menu displayed in that row but isn't right if there's
3107                  * an object/creature/feature there that doesn't have a
3108                  * mapping to the tile set and is rendered with a character.
3109                  */
3110                 curs.col = 0;
3111                 curs.row = 0;
3112                 [self.contents scanForTypeMaskInBlockAtColumn:aligned_col
3113                      row:(aligned_row - pcell->voff_d) width:pcell->hoff_d
3114                      height:pcell->voff_d mask:TERM_CELL_TILE cursor:&curs];
3115                 if (curs.col == 0 && curs.row == 0) {
3116                     const struct TerminalCell *pcell2 =
3117                         [self.contents
3118                              getCellAtColumn:(aligned_col + curs.col)
3119                              row:(aligned_row + curs.row - pcell->voff_d)];
3120
3121                     if (pcell2->hscl == pcell2->hoff_d &&
3122                         pcell2->vscl == pcell2->voff_d) {
3123                         /*
3124                          * The tile in the previous row hasn't been clipped
3125                          * or partially overwritten.  Use a streamlined
3126                          * rendering procedure.
3127                          */
3128                         simple_upper = 1;
3129                     }
3130                 }
3131             }
3132         }
3133
3134         /*
3135          * Draw the background.  For a double-height tile, this is only the
3136          * the lower half.
3137          */
3138         draw_image_tile(
3139             nsctx, ctx, pict_image, bckRect, destinationRect, NSCompositeCopy);
3140         if (dbl_height_bck && is_first_piece) {
3141             /* Combine upper half with previously drawn row. */
3142             if (simple_upper) {
3143                 const struct TerminalCell *pcell2 =
3144                     [self.contents getCellAtColumn:aligned_col
3145                          row:(aligned_row - pcell->voff_d)];
3146                 NSRect drect2 =
3147                     [self viewRectForCellBlockAtX:aligned_col
3148                           y:(aligned_row - pcell->voff_d)
3149                           width:pcell2->hscl height:pcell2->vscl];
3150                 NSRect brect2 = NSMakeRect(
3151                     graf_width * pcell->v.ti.bckCol,
3152                     graf_height * (pcell->v.ti.bckRow - 1),
3153                     graf_width, graf_height);
3154
3155                 draw_image_tile(nsctx, ctx, pict_image, brect2, drect2,
3156                                 NSCompositeSourceOver);
3157             } else {
3158                 struct TerminalCellLocation curs = { 0, 0 };
3159
3160                 [self.contents scanForTypeMaskInBlockAtColumn:aligned_col
3161                      row:(aligned_row - pcell->voff_d) width:pcell->hoff_d
3162                      height:pcell->voff_d mask:TERM_CELL_TILE
3163                      cursor:&curs];
3164                 while (curs.col < pcell->hoff_d &&
3165                        curs.row < pcell->voff_d) {
3166                     const struct TerminalCell *pcell2 =
3167                         [self.contents getCellAtColumn:(aligned_col + curs.col)
3168                              row:(aligned_row + curs.row - pcell->voff_d)];
3169                     NSRect drect2 =
3170                         [self viewRectForCellBlockAtX:(aligned_col + curs.col)
3171                               y:(aligned_row + curs.row - pcell->voff_d)
3172                               width:pcell2->hscl height:pcell2->vscl];
3173                     /*
3174                      * Column and row in the tile set are from the
3175                      * double-height tile at *pcell, but the offsets within
3176                      * that and size are from what's visible for *pcell2.
3177                      */
3178                     NSRect brect2 = NSMakeRect(
3179                         graf_width * (pcell->v.ti.bckCol +
3180                                       pcell2->hoff_n / (1.0 * pcell2->hoff_d)),
3181                         graf_height * (pcell->v.ti.bckRow - 1 +
3182                                        pcell2->voff_n /
3183                                        (1.0 * pcell2->voff_d)),
3184                         graf_width * pcell2->hscl / (1.0 * pcell2->hoff_d),
3185                         graf_height * pcell2->vscl / (1.0 * pcell2->voff_d));
3186
3187                     draw_image_tile(nsctx, ctx, pict_image, brect2, drect2,
3188                                     NSCompositeSourceOver);
3189                     curs.col += pcell2->hscl;
3190                     [self.contents
3191                          scanForTypeMaskInBlockAtColumn:aligned_col
3192                          row:(aligned_row - pcell->voff_d)
3193                          width:pcell->hoff_d height:pcell->voff_d
3194                          mask:TERM_CELL_TILE cursor:&curs];
3195                 }
3196             }
3197         }
3198
3199         /* Skip drawing the foreground if it is the same as the background. */
3200         if (fgdRect.origin.x != bckRect.origin.x ||
3201             fgdRect.origin.y != bckRect.origin.y) {
3202             if (is_first_piece && dbl_height_fgd) {
3203                 if (simple_upper) {
3204                     if (pcell->hoff_n == 0 && pcell->voff_n == 0 &&
3205                         pcell->hscl == pcell->hoff_d) {
3206                         /*
3207                          * Render upper and lower parts as one since they
3208                          * are contiguous.
3209                          */
3210                         fgdRect.origin.y -= graf_height;
3211                         fgdRect.size.height += graf_height;
3212                         destinationRect.origin.y -=
3213                             destinationRect.size.height;
3214                         destinationRect.size.height +=
3215                             destinationRect.size.height;
3216                     } else {
3217                         /* Not contiguous.  Render the upper half. */
3218                         NSRect drect2 =
3219                             [self viewRectForCellBlockAtX:aligned_col
3220                                   y:(aligned_row - pcell->voff_d)
3221                                   width:pcell->hoff_d height:pcell->voff_d];
3222                         NSRect frect2 = NSMakeRect(
3223                             graf_width * pcell->v.ti.fgdCol,
3224                             graf_height * (pcell->v.ti.fgdRow - 1),
3225                             graf_width, graf_height);
3226
3227                         draw_image_tile(
3228                             nsctx, ctx, pict_image, frect2, drect2,
3229                             NSCompositeSourceOver);
3230                     }
3231                 } else {
3232                     /* Render the upper half pieces. */
3233                     struct TerminalCellLocation curs = { 0, 0 };
3234
3235                     while (1) {
3236                         [self.contents
3237                              scanForTypeMaskInBlockAtColumn:aligned_col
3238                              row:(aligned_row - pcell->voff_d)
3239                              width:pcell->hoff_d height:pcell->voff_d
3240                              mask:TERM_CELL_TILE cursor:&curs];
3241
3242                         if (curs.col >= pcell->hoff_d ||
3243                             curs.row >= pcell->voff_d) {
3244                             break;
3245                         }
3246
3247                         const struct TerminalCell *pcell2 =
3248                             [self.contents
3249                                  getCellAtColumn:(aligned_col + curs.col)
3250                                  row:(aligned_row + curs.row - pcell->voff_d)];
3251                         NSRect drect2 =
3252                             [self viewRectForCellBlockAtX:(aligned_col + curs.col)
3253                                   y:(aligned_row + curs.row - pcell->voff_d)
3254                                   width:pcell2->hscl height:pcell2->vscl];
3255                         NSRect frect2 = NSMakeRect(
3256                             graf_width * (pcell->v.ti.fgdCol +
3257                                           pcell2->hoff_n /
3258                                           (1.0 * pcell2->hoff_d)),
3259                             graf_height * (pcell->v.ti.fgdRow - 1 +
3260                                            pcell2->voff_n /
3261                                            (1.0 * pcell2->voff_d)),
3262                             graf_width * pcell2->hscl / (1.0 * pcell2->hoff_d),
3263                             graf_height * pcell2->vscl /
3264                                 (1.0 * pcell2->voff_d));
3265
3266                         draw_image_tile(nsctx, ctx, pict_image, frect2, drect2,
3267                                         NSCompositeSourceOver);
3268                         curs.col += pcell2->hscl;
3269                     }
3270                 }
3271             }
3272             /*
3273              * Render the foreground (if a double height tile and the bottom
3274              * part is contiguous with the upper part this also render the
3275              * upper part.
3276              */
3277             draw_image_tile(
3278                 nsctx, ctx, pict_image, fgdRect, destinationRect,
3279                 NSCompositeSourceOver);
3280         }
3281         icol0 = [self.contents scanForTypeMaskInRow:irow mask:TERM_CELL_TILE
3282                      col0:(icol0+pcell->hscl) col1:icol1];
3283     }
3284
3285     /* Restore the compositing mode. */
3286     nsctx.compositingOperation = op;
3287 }
3288
3289 /**
3290  * This is what our views call to get us to draw to the window
3291  */
3292 - (void)drawRect:(NSRect)rect inView:(NSView *)view
3293 {
3294     /*
3295      * Take this opportunity to throttle so we don't flush faster than desired.
3296      */
3297     [self throttle];
3298
3299     CGFloat bottomY =
3300         self.borderSize.height + self.tileSize.height * self.rows;
3301     CGFloat rightX =
3302         self.borderSize.width + self.tileSize.width * self.cols;
3303
3304     const NSRect *invalidRects;
3305     NSInteger invalidCount;
3306     [view getRectsBeingDrawn:&invalidRects count:&invalidCount];
3307
3308     /*
3309      * If the non-border areas need rendering, set some things up so they can
3310      * be reused for each invalid rectangle.
3311      */
3312     NSGraphicsContext *nsctx = nil;
3313     CGContextRef ctx = 0;
3314     NSFont* screenFont = nil;
3315     int graf_width = 0, graf_height = 0;
3316     int overdraw_row = 0, overdraw_max = 0;
3317     wchar_t blank = 0;
3318     if (rect.origin.x < rightX &&
3319         rect.origin.x + rect.size.width > self.borderSize.width &&
3320         rect.origin.y < bottomY &&
3321         rect.origin.y + rect.size.height > self.borderSize.height) {
3322         nsctx = [NSGraphicsContext currentContext];
3323         ctx = [nsctx graphicsPort];
3324         screenFont = [self.angbandViewFont screenFont];
3325         [screenFont set];
3326         blank = [TerminalContents getBlankChar];
3327         if (use_graphics) {
3328             graf_width = current_graphics_mode->cell_width;
3329             graf_height = current_graphics_mode->cell_height;
3330             overdraw_row = current_graphics_mode->overdrawRow;
3331             overdraw_max = current_graphics_mode->overdrawMax;
3332         }
3333     }
3334
3335     /*
3336      * With double height tiles, need to have rendered prior rows (i.e.
3337      * smaller y) before the current one.  Since the invalid rectanges are
3338      * processed in order, ensure that by sorting the invalid rectangles in
3339      * increasing order of y origin (AppKit guarantees the invalid rectanges
3340      * are non-overlapping).
3341      */
3342     NSRect* sortedRects = 0;
3343     const NSRect* workingRects;
3344     if (overdraw_row && invalidCount > 1) {
3345         sortedRects = malloc(invalidCount * sizeof(NSRect));
3346         if (sortedRects == 0) {
3347             NSException *exc = [NSException exceptionWithName:@"OutOfMemory"
3348                                             reason:@"sorted rects in drawRect"
3349                                             userInfo:nil];
3350             @throw exc;
3351         }
3352         (void) memcpy(
3353             sortedRects, invalidRects, invalidCount * sizeof(NSRect));
3354         qsort(sortedRects, invalidCount, sizeof(NSRect),
3355               compare_nsrect_yorigin_greater);
3356         workingRects = sortedRects;
3357     } else {
3358         workingRects = invalidRects;
3359     }
3360
3361     /*
3362      * Use -2 for unknown.  Use -1 for Cocoa's blackColor.  All others are the
3363      * Angband color index.
3364      */
3365     int alast = -2;
3366     int redrawCursor = 0;
3367
3368     for (NSInteger irect = 0; irect < invalidCount; ++irect) {
3369         NSRect modRect, clearRect;
3370         CGFloat edge;
3371         int iRowFirst, iRowLast;
3372         int iColFirst, iColLast;
3373
3374         /* Handle the top border. */
3375         if (workingRects[irect].origin.y < self.borderSize.height) {
3376             edge =
3377                 workingRects[irect].origin.y + workingRects[irect].size.height;
3378             if (edge <= self.borderSize.height) {
3379                 if (alast != -1) {
3380                     [[NSColor blackColor] set];
3381                     alast = -1;
3382                 }
3383                 NSRectFill(workingRects[irect]);
3384                 continue;
3385             }
3386             clearRect = workingRects[irect];
3387             clearRect.size.height =
3388                 self.borderSize.height - workingRects[irect].origin.y;
3389             if (alast != -1) {
3390                 [[NSColor blackColor] set];
3391                 alast = -1;
3392             }
3393             NSRectFill(clearRect);
3394             modRect.origin.x = workingRects[irect].origin.x;
3395             modRect.origin.y = self.borderSize.height;
3396             modRect.size.width = workingRects[irect].size.width;
3397             modRect.size.height = edge - self.borderSize.height;
3398         } else {
3399             modRect = workingRects[irect];
3400         }
3401
3402         /* Handle the left border. */
3403         if (modRect.origin.x < self.borderSize.width) {
3404             edge = modRect.origin.x + modRect.size.width;
3405             if (edge <= self.borderSize.width) {
3406                 if (alast != -1) {
3407                     alast = -1;
3408                     [[NSColor blackColor] set];
3409                 }
3410                 NSRectFill(modRect);
3411                 continue;
3412             }
3413             clearRect = modRect;
3414             clearRect.size.width = self.borderSize.width - clearRect.origin.x;
3415             if (alast != -1) {
3416                 alast = -1;
3417                 [[NSColor blackColor] set];
3418             }
3419             NSRectFill(clearRect);
3420             modRect.origin.x = self.borderSize.width;
3421             modRect.size.width = edge - self.borderSize.width;
3422         }
3423
3424         iRowFirst = floor((modRect.origin.y - self.borderSize.height) /
3425                           self.tileSize.height);
3426         iColFirst = floor((modRect.origin.x - self.borderSize.width) /
3427                           self.tileSize.width);
3428         edge = modRect.origin.y + modRect.size.height;
3429         if (edge <= bottomY) {
3430             iRowLast =
3431                 ceil((edge - self.borderSize.height) / self.tileSize.height);
3432         } else {
3433             iRowLast = self.rows;
3434         }
3435         edge = modRect.origin.x + modRect.size.width;
3436         if (edge <= rightX) {
3437             iColLast =
3438                 ceil((edge - self.borderSize.width) / self.tileSize.width);
3439         } else {
3440             iColLast = self.cols;
3441         }
3442
3443         if (self.contents.cursorColumn != -1 &&
3444             self.contents.cursorRow != -1 &&
3445             self.contents.cursorColumn + self.contents.cursorWidth - 1 >=
3446             iColFirst &&
3447             self.contents.cursorColumn < iColLast &&
3448             self.contents.cursorRow + self.contents.cursorHeight - 1 >=
3449             iRowFirst &&
3450             self.contents.cursorRow < iRowLast) {
3451             redrawCursor = 1;
3452         }
3453
3454         for (int irow = iRowFirst; irow < iRowLast; ++irow) {
3455             int icol =
3456                 [self.contents scanForTypeMaskInRow:irow
3457                      mask:(TERM_CELL_CHAR | TERM_CELL_TILE)
3458                      col0:iColFirst col1:iColLast];
3459
3460             while (1) {
3461                 if (icol >= iColLast) {
3462                     break;
3463                 }
3464
3465                 if ([self.contents getCellAtColumn:icol row:irow]->form ==
3466                     TERM_CELL_TILE) {
3467                     /*
3468                      * It is a tile.  Identify how far the run of tiles goes.
3469                      */
3470                     int jcol = [self.contents scanForPredicateInRow:irow
3471                                     predicate:isTileTop desired:1
3472                                     col0:(icol + 1) col1:iColLast];
3473
3474                     [self renderTileRunInRow:irow col0:icol col1:jcol
3475                           nsctx:nsctx ctx:ctx
3476                           grafWidth:graf_width grafHeight:graf_height
3477                           overdrawRow:overdraw_row overdrawMax:overdraw_max];
3478                     icol = jcol;
3479                 } else {
3480                     /*
3481                      * It is a character.  Identify how far the run of
3482                      * characters goes.
3483                      */
3484                     int jcol = [self.contents scanForPredicateInRow:irow
3485                                     predicate:isCharNoPartial desired:1
3486                                     col0:(icol + 1) col1:iColLast];
3487                     int jcol2;
3488
3489                     if (jcol < iColLast &&
3490                         isPartiallyOverwrittenBigChar(
3491                             [self.contents getCellAtColumn:jcol row:irow])) {
3492                         jcol2 = [self.contents scanForTypeMaskInRow:irow
3493                                      mask:~TERM_CELL_CHAR_PADDING
3494                                      col0:(jcol + 1) col1:iColLast];
3495                     } else {
3496                         jcol2 = jcol;
3497                     }
3498
3499                     /*
3500                      * Set up clipping rectangle for text.  Save the
3501                      * graphics context so the clipping rectangle can be
3502                      * forgotten.  Use CGContextBeginPath to clear the current
3503                      * path so it does not affect clipping.  Do not call
3504                      * CGContextSetTextDrawingMode() to include clipping since
3505                      * that does not appear to necessary on 10.14 and is
3506                      * actually detrimental:  when displaying more than one
3507                      * character, only the first is visible.
3508                      */
3509                     CGContextSaveGState(ctx);
3510                     CGContextBeginPath(ctx);
3511                     NSRect r = [self viewRectForCellBlockAtX:icol y:irow
3512                                      width:(jcol2 - icol) height:1];
3513                     CGContextClipToRect(ctx, r);
3514
3515                     /*
3516                      * See if the region to be rendered needs to be expanded:
3517                      * adjacent text that could influence what's in the clipped
3518                      * region.
3519                      */
3520                     int isrch = icol;
3521                     int irng = icol - self.nColPost;
3522                     if (irng < 1) {
3523                         irng = 1;
3524                     }
3525
3526                     while (1) {
3527                         if (isrch <= irng) {
3528                             break;
3529                         }
3530
3531                         const struct TerminalCell *pcell2 =
3532                             [self.contents getCellAtColumn:(isrch - 1)
3533                                  row:irow];
3534                         if (pcell2->form == TERM_CELL_CHAR) {
3535                             --isrch;
3536                             if (pcell2->v.ch.glyph != blank) {
3537                                 icol = isrch;
3538                             }
3539                         } else if (pcell2->form == TERM_CELL_CHAR_PADDING) {
3540                             /*
3541                              * Only extend the rendering if this is padding
3542                              * for a character that hasn't been partially
3543                              * overwritten.
3544                              */
3545                             if (! isPartiallyOverwrittenBigChar(pcell2)) {
3546                                 if (isrch - pcell2->v.pd.hoff >= 0) {
3547                                     const struct TerminalCell* pcell3 =
3548                                         [self.contents
3549                                              getCellAtColumn:(isrch - pcell2->v.pd.hoff)
3550                                              row:irow];
3551
3552                                     if (pcell3->v.ch.glyph != blank) {
3553                                         icol = isrch - pcell2->v.pd.hoff;
3554                                         isrch = icol - 1;
3555                                     } else {
3556                                         isrch = isrch - pcell2->v.pd.hoff - 1;
3557                                     }
3558                                 } else {
3559                                     /* Should not happen, corrupt offset. */
3560                                     --isrch;
3561                                 }
3562                             } else {
3563                                 break;
3564                             }
3565                         } else {
3566                             /*
3567                              * Tiles or tile padding block anything before
3568                              * them from rendering after them.
3569                              */
3570                             break;
3571                         }
3572                     }
3573
3574                     isrch = jcol2;
3575                     irng = jcol2 + self.nColPre;
3576                     if (irng > self.cols) {
3577                         irng = self.cols;
3578                     }
3579                     while (1) {
3580                         if (isrch >= irng) {
3581                             break;
3582                         }
3583
3584                         const struct TerminalCell *pcell2 =
3585                             [self.contents getCellAtColumn:isrch row:irow];
3586                         if (pcell2->form == TERM_CELL_CHAR) {
3587                             if (pcell2->v.ch.glyph != blank) {
3588                                 jcol2 = isrch;
3589                             }
3590                             ++isrch;
3591                         } else if (pcell2->form == TERM_CELL_CHAR_PADDING) {
3592                             ++isrch;
3593                         } else {
3594                             break;
3595                         }
3596                     }
3597
3598                     /* Render text. */
3599                     /* Clear where rendering will be done. */
3600                     if (alast != -1) {
3601                         [[NSColor blackColor] set];
3602                         alast = -1;
3603                     }
3604                     r = [self viewRectForCellBlockAtX:icol y:irow
3605                               width:(jcol - icol) height:1];
3606                     NSRectFill(r);
3607
3608                     while (icol < jcol) {
3609                         const struct TerminalCell *pcell =
3610                             [self.contents getCellAtColumn:icol row:irow];
3611
3612                         /*
3613                          * For blanks, clearing was all that was necessary.
3614                          * Don't redraw them.
3615                          */
3616                         if (pcell->v.ch.glyph != blank) {
3617                             int a = pcell->v.ch.attr % MAX_COLORS;
3618
3619                             if (alast != a) {
3620                                 alast = a;
3621                                 set_color_for_index(a);
3622                             }
3623                             r = [self viewRectForCellBlockAtX:icol
3624                                       y:irow width:pcell->hscl
3625                                       height:1];
3626                             [self drawWChar:pcell->v.ch.glyph inRect:r
3627                                   screenFont:screenFont context:ctx];
3628                         }
3629                         icol += pcell->hscl;
3630                     }
3631
3632                     /*
3633                      * Forget the clipping rectangle.  As a side effect, lose
3634                      * the color.
3635                      */
3636                     CGContextRestoreGState(ctx);
3637                     alast = -2;
3638                 }
3639                 icol =
3640                     [self.contents scanForTypeMaskInRow:irow
3641                          mask:(TERM_CELL_CHAR | TERM_CELL_TILE)
3642                          col0:icol col1:iColLast];
3643             }
3644         }
3645
3646         /* Handle the right border. */
3647         edge = modRect.origin.x + modRect.size.width;
3648         if (edge > rightX) {
3649             if (modRect.origin.x >= rightX) {
3650                 if (alast != -1) {
3651                     alast = -1;
3652                     [[NSColor blackColor] set];
3653                 }
3654                 NSRectFill(modRect);
3655                 continue;
3656             }
3657             clearRect = modRect;
3658             clearRect.origin.x = rightX;
3659             clearRect.size.width = edge - rightX;
3660             if (alast != -1) {
3661                 alast = -1;
3662                 [[NSColor blackColor] set];
3663             }
3664             NSRectFill(clearRect);
3665             modRect.size.width = edge - modRect.origin.x;
3666         }
3667
3668         /* Handle the bottom border. */
3669         edge = modRect.origin.y + modRect.size.height;
3670         if (edge > bottomY) {
3671             if (modRect.origin.y < bottomY) {
3672                 modRect.origin.y = bottomY;
3673                 modRect.size.height = edge - bottomY;
3674             }
3675             if (alast != -1) {
3676                 alast = -1;
3677                 [[NSColor blackColor] set];
3678             }
3679             NSRectFill(modRect);
3680         }
3681     }
3682
3683     if (redrawCursor) {
3684         NSRect r = [self viewRectForCellBlockAtX:self.contents.cursorColumn
3685                          y:self.contents.cursorRow
3686                          width:self.contents.cursorWidth
3687                          height:self.contents.cursorHeight];
3688         [[NSColor yellowColor] set];
3689         NSFrameRectWithWidth(r, 1);
3690     }
3691
3692     free(sortedRects);
3693 }
3694
3695 - (BOOL)isOrderedIn
3696 {
3697     return [[self->angbandView window] isVisible];
3698 }
3699
3700 - (BOOL)isMainWindow
3701 {
3702     return [[self->angbandView window] isMainWindow];
3703 }
3704
3705 - (BOOL)isKeyWindow
3706 {
3707     return [[self->angbandView window] isKeyWindow];
3708 }
3709
3710 - (void)setNeedsDisplay:(BOOL)val
3711 {
3712     [self->angbandView setNeedsDisplay:val];
3713 }
3714
3715 - (void)setNeedsDisplayInRect:(NSRect)rect
3716 {
3717     [self->angbandView setNeedsDisplayInRect:rect];
3718 }
3719
3720 - (void)displayIfNeeded
3721 {
3722     [self->angbandView displayIfNeeded];
3723 }
3724
3725 - (int)terminalIndex
3726 {
3727         int termIndex = 0;
3728
3729         for( termIndex = 0; termIndex < ANGBAND_TERM_MAX; termIndex++ )
3730         {
3731                 if( angband_term[termIndex] == self->terminal )
3732                 {
3733                         break;
3734                 }
3735         }
3736
3737         return termIndex;
3738 }
3739
3740 - (void)resizeTerminalWithContentRect: (NSRect)contentRect saveToDefaults: (BOOL)saveToDefaults
3741 {
3742     CGFloat newRows = floor(
3743         (contentRect.size.height - (self.borderSize.height * 2.0)) /
3744         self.tileSize.height);
3745     CGFloat newColumns = floor(
3746         (contentRect.size.width - (self.borderSize.width * 2.0)) /
3747         self.tileSize.width);
3748
3749     if (newRows < 1 || newColumns < 1) return;
3750     [self resizeWithColumns:newColumns rows:newRows];
3751
3752     int termIndex = [self terminalIndex];
3753     [self setDefaultTitle:termIndex];
3754
3755     if( saveToDefaults )
3756     {
3757         NSArray *terminals = [[NSUserDefaults standardUserDefaults] valueForKey: AngbandTerminalsDefaultsKey];
3758
3759         if( termIndex < (int)[terminals count] )
3760         {
3761             NSMutableDictionary *mutableTerm = [[NSMutableDictionary alloc] initWithDictionary: [terminals objectAtIndex: termIndex]];
3762             [mutableTerm setValue: [NSNumber numberWithInteger: self.cols]
3763                          forKey: AngbandTerminalColumnsDefaultsKey];
3764             [mutableTerm setValue: [NSNumber numberWithInteger: self.rows]
3765                          forKey: AngbandTerminalRowsDefaultsKey];
3766
3767             NSMutableArray *mutableTerminals = [[NSMutableArray alloc] initWithArray: terminals];
3768             [mutableTerminals replaceObjectAtIndex: termIndex withObject: mutableTerm];
3769
3770             [[NSUserDefaults standardUserDefaults] setValue: mutableTerminals forKey: AngbandTerminalsDefaultsKey];
3771         }
3772     }
3773
3774     term *old = Term;
3775     Term_activate( self->terminal );
3776     Term_resize( self.cols, self.rows );
3777     Term_redraw();
3778     Term_activate( old );
3779 }
3780
3781 - (void)constrainWindowSize:(int)termIdx
3782 {
3783     NSSize minsize;
3784
3785     if (termIdx == 0) {
3786         minsize.width = 80;
3787         minsize.height = 24;
3788     } else {
3789         minsize.width = 1;
3790         minsize.height = 1;
3791     }
3792     minsize.width =
3793         minsize.width * self.tileSize.width + self.borderSize.width * 2.0;
3794     minsize.height =
3795         minsize.height * self.tileSize.height + self.borderSize.height * 2.0;
3796     [[self makePrimaryWindow] setContentMinSize:minsize];
3797     self.primaryWindow.contentResizeIncrements = self.tileSize;
3798 }
3799
3800 - (void)saveWindowVisibleToDefaults: (BOOL)windowVisible
3801 {
3802         int termIndex = [self terminalIndex];
3803         BOOL safeVisibility = (termIndex == 0) ? YES : windowVisible; /* Ensure main term doesn't go away because of these defaults */
3804         NSArray *terminals = [[NSUserDefaults standardUserDefaults] valueForKey: AngbandTerminalsDefaultsKey];
3805
3806         if( termIndex < (int)[terminals count] )
3807         {
3808                 NSMutableDictionary *mutableTerm = [[NSMutableDictionary alloc] initWithDictionary: [terminals objectAtIndex: termIndex]];
3809                 [mutableTerm setValue: [NSNumber numberWithBool: safeVisibility] forKey: AngbandTerminalVisibleDefaultsKey];
3810
3811                 NSMutableArray *mutableTerminals = [[NSMutableArray alloc] initWithArray: terminals];
3812                 [mutableTerminals replaceObjectAtIndex: termIndex withObject: mutableTerm];
3813
3814                 [[NSUserDefaults standardUserDefaults] setValue: mutableTerminals forKey: AngbandTerminalsDefaultsKey];
3815         }
3816 }
3817
3818 - (BOOL)windowVisibleUsingDefaults
3819 {
3820         int termIndex = [self terminalIndex];
3821
3822         if( termIndex == 0 )
3823         {
3824                 return YES;
3825         }
3826
3827         NSArray *terminals = [[NSUserDefaults standardUserDefaults] valueForKey: AngbandTerminalsDefaultsKey];
3828         BOOL visible = NO;
3829
3830         if( termIndex < (int)[terminals count] )
3831         {
3832                 NSDictionary *term = [terminals objectAtIndex: termIndex];
3833                 NSNumber *visibleValue = [term valueForKey: AngbandTerminalVisibleDefaultsKey];
3834
3835                 if( visibleValue != nil )
3836                 {
3837                         visible = [visibleValue boolValue];
3838                 }
3839         }
3840
3841         return visible;
3842 }
3843
3844 #pragma mark -
3845 #pragma mark NSWindowDelegate Methods
3846
3847 /*- (void)windowWillStartLiveResize: (NSNotification *)notification
3848
3849 }*/ 
3850
3851 - (void)windowDidEndLiveResize: (NSNotification *)notification
3852 {
3853     NSWindow *window = [notification object];
3854     NSRect contentRect = [window contentRectForFrameRect: [window frame]];
3855     [self resizeTerminalWithContentRect: contentRect saveToDefaults: !(self->inFullscreenTransition)];
3856 }
3857
3858 /*- (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
3859 {
3860 } */
3861
3862 - (void)windowWillEnterFullScreen: (NSNotification *)notification
3863 {
3864     self->inFullscreenTransition = YES;
3865 }
3866
3867 - (void)windowDidEnterFullScreen: (NSNotification *)notification
3868 {
3869     NSWindow *window = [notification object];
3870     NSRect contentRect = [window contentRectForFrameRect: [window frame]];
3871     self->inFullscreenTransition = NO;
3872     [self resizeTerminalWithContentRect: contentRect saveToDefaults: NO];
3873 }
3874
3875 - (void)windowWillExitFullScreen: (NSNotification *)notification
3876 {
3877     self->inFullscreenTransition = YES;
3878 }
3879
3880 - (void)windowDidExitFullScreen: (NSNotification *)notification
3881 {
3882     NSWindow *window = [notification object];
3883     NSRect contentRect = [window contentRectForFrameRect: [window frame]];
3884     self->inFullscreenTransition = NO;
3885     [self resizeTerminalWithContentRect: contentRect saveToDefaults: NO];
3886 }
3887
3888 - (void)windowDidBecomeMain:(NSNotification *)notification
3889 {
3890     NSWindow *window = [notification object];
3891
3892     if( window != self.primaryWindow )
3893     {
3894         return;
3895     }
3896
3897     int termIndex = [self terminalIndex];
3898     NSMenuItem *item = [[[NSApplication sharedApplication] windowsMenu] itemWithTag: AngbandWindowMenuItemTagBase + termIndex];
3899     [item setState: NSOnState];
3900
3901     if( [[NSFontPanel sharedFontPanel] isVisible] )
3902     {
3903         [[NSFontPanel sharedFontPanel] setPanelFont:self.angbandViewFont
3904                                        isMultiple: NO];
3905     }
3906 }
3907
3908 - (void)windowDidResignMain: (NSNotification *)notification
3909 {
3910     NSWindow *window = [notification object];
3911
3912     if( window != self.primaryWindow )
3913     {
3914         return;
3915     }
3916
3917     int termIndex = [self terminalIndex];
3918     NSMenuItem *item = [[[NSApplication sharedApplication] windowsMenu] itemWithTag: AngbandWindowMenuItemTagBase + termIndex];
3919     [item setState: NSOffState];
3920 }
3921
3922 - (void)windowWillClose: (NSNotification *)notification
3923 {
3924     /*
3925      * If closing only because the application is terminating, don't update
3926      * the visible state for when the application is relaunched.
3927      */
3928     if (! quit_when_ready) {
3929         [self saveWindowVisibleToDefaults: NO];
3930     }
3931 }
3932
3933 @end
3934
3935
3936 @implementation AngbandView
3937
3938 - (BOOL)isOpaque
3939 {
3940     return YES;
3941 }
3942
3943 - (BOOL)isFlipped
3944 {
3945     return YES;
3946 }
3947
3948 - (void)drawRect:(NSRect)rect
3949 {
3950     if ([self inLiveResize]) {
3951         /*
3952          * Always anchor the cached area to the upper left corner of the view.
3953          * Any parts on the right or bottom that can't be drawn from the cached
3954          * area are simply cleared.  Will fill them with appropriate content
3955          * when resizing is done.
3956          */
3957         const NSRect *rects;
3958         NSInteger count;
3959
3960         [self getRectsBeingDrawn:&rects count:&count];
3961         if (count > 0) {
3962             NSRect viewRect = [self visibleRect];
3963
3964             [[NSColor blackColor] set];
3965             while (count-- > 0) {
3966                 CGFloat drawTop = rects[count].origin.y - viewRect.origin.y;
3967                 CGFloat drawBottom = drawTop + rects[count].size.height;
3968                 CGFloat drawLeft = rects[count].origin.x - viewRect.origin.x;
3969                 CGFloat drawRight = drawLeft + rects[count].size.width;
3970                 /*
3971                  * modRect and clrRect, like rects[count], are in the view
3972                  * coordinates with y flipped.  cacheRect is in the bitmap
3973                  * coordinates and y is not flipped.
3974                  */
3975                 NSRect modRect, clrRect, cacheRect;
3976
3977                 /*
3978                  * Clip by bottom edge of cached area.  Clear what's below
3979                  * that.
3980                  */
3981                 if (drawTop >= self->cacheBounds.size.height) {
3982                     NSRectFill(rects[count]);
3983                     continue;
3984                 }
3985                 modRect.origin.x = rects[count].origin.x;
3986                 modRect.origin.y = rects[count].origin.y;
3987                 modRect.size.width = rects[count].size.width;
3988                 cacheRect.origin.y = drawTop;
3989                 if (drawBottom > self->cacheBounds.size.height) {
3990                     CGFloat excess =
3991                         drawBottom - self->cacheBounds.size.height;
3992
3993                     modRect.size.height = rects[count].size.height - excess;
3994                     cacheRect.origin.y = 0;
3995                     clrRect.origin.x = modRect.origin.x;
3996                     clrRect.origin.y = modRect.origin.y + modRect.size.height;
3997                     clrRect.size.width = modRect.size.width;
3998                     clrRect.size.height = excess;
3999                     NSRectFill(clrRect);
4000                 } else {
4001                     modRect.size.height = rects[count].size.height;
4002                     cacheRect.origin.y = self->cacheBounds.size.height -
4003                         rects[count].size.height;
4004                 }
4005                 cacheRect.size.height = modRect.size.height;
4006
4007                 /*
4008                  * Clip by right edge of cached area.  Clear what's to the
4009                  * right of that and copy the remainder from the cache.
4010                  */
4011                 if (drawLeft >= self->cacheBounds.size.width) {
4012                     NSRectFill(modRect);
4013                     continue;
4014                 }
4015                 cacheRect.origin.x = drawLeft;
4016                 if (drawRight > self->cacheBounds.size.width) {
4017                     CGFloat excess = drawRight - self->cacheBounds.size.width;
4018
4019                     modRect.size.width -= excess;
4020                     cacheRect.size.width =
4021                         self->cacheBounds.size.width - drawLeft;
4022                     clrRect.origin.x = modRect.origin.x + modRect.size.width;
4023                     clrRect.origin.y = modRect.origin.y;
4024                     clrRect.size.width = excess;
4025                     clrRect.size.height = modRect.size.height;
4026                     NSRectFill(clrRect);
4027                 } else {
4028                     cacheRect.size.width = drawRight - drawLeft;
4029                 }
4030                 [self->cacheForResize drawInRect:modRect fromRect:cacheRect
4031                      operation:NSCompositeCopy fraction:1.0
4032                      respectFlipped:YES hints:nil];
4033             }
4034         }
4035     } else if (! self.angbandContext) {
4036         /* Draw bright orange, 'cause this ain't right */
4037         [[NSColor orangeColor] set];
4038         NSRectFill([self bounds]);
4039     } else {
4040         /* Tell the Angband context to draw into us */
4041         [self.angbandContext drawRect:rect inView:self];
4042     }
4043 }
4044
4045 /**
4046  * Override NSView's method to set up a cache that's used in drawRect to
4047  * handle drawing during a resize.
4048  */
4049 - (void)viewWillStartLiveResize
4050 {
4051     [super viewWillStartLiveResize];
4052     self->cacheBounds = [self visibleRect];
4053     self->cacheForResize =
4054         [self bitmapImageRepForCachingDisplayInRect:self->cacheBounds];
4055     if (self->cacheForResize != nil) {
4056         [self cacheDisplayInRect:self->cacheBounds
4057               toBitmapImageRep:self->cacheForResize];
4058     } else {
4059         self->cacheBounds.size.width = 0.;
4060         self->cacheBounds.size.height = 0.;
4061     }
4062 }
4063
4064 /**
4065  * Override NSView's method to release the cache set up in
4066  * viewWillStartLiveResize.
4067  */
4068 - (void)viewDidEndLiveResize
4069 {
4070     [super viewDidEndLiveResize];
4071     self->cacheForResize = nil;
4072     [self setNeedsDisplay:YES];
4073 }
4074
4075 @end
4076
4077 /**
4078  * Delay handling of double-clicked savefiles
4079  */
4080 Boolean open_when_ready = FALSE;
4081
4082
4083
4084 /**
4085  * ------------------------------------------------------------------------
4086  * Some generic functions
4087  * ------------------------------------------------------------------------ */
4088
4089 /**
4090  * Sets an Angband color at a given index
4091  */
4092 static void set_color_for_index(int idx)
4093 {
4094     u16b rv, gv, bv;
4095     
4096     /* Extract the R,G,B data */
4097     rv = angband_color_table[idx][1];
4098     gv = angband_color_table[idx][2];
4099     bv = angband_color_table[idx][3];
4100     
4101     CGContextSetRGBFillColor([[NSGraphicsContext currentContext] graphicsPort], rv/255., gv/255., bv/255., 1.);
4102 }
4103
4104 /**
4105  * Remember the current character in UserDefaults so we can select it by
4106  * default next time.
4107  */
4108 static void record_current_savefile(void)
4109 {
4110     NSString *savefileString = [[NSString stringWithCString:savefile encoding:NSMacOSRomanStringEncoding] lastPathComponent];
4111     if (savefileString)
4112     {
4113         NSUserDefaults *angbandDefs = [NSUserDefaults angbandDefaults];
4114         [angbandDefs setObject:savefileString forKey:@"SaveFile"];
4115     }
4116 }
4117
4118
4119 #ifdef JP
4120 /**
4121  * Convert a two-byte EUC-JP encoded character (both *cp and (*cp + 1) are in
4122  * the range, 0xA1-0xFE, or *cp is 0x8E) to a utf16 value in the native byte
4123  * ordering.
4124  */
4125 static wchar_t convert_two_byte_eucjp_to_utf16_native(const char *cp)
4126 {
4127     NSString* str = [[NSString alloc] initWithBytes:cp length:2
4128                                       encoding:NSJapaneseEUCStringEncoding];
4129     wchar_t result = [str characterAtIndex:0];
4130     str = nil;
4131     return result;
4132 }
4133 #endif /* JP */
4134
4135
4136 /**
4137  * ------------------------------------------------------------------------
4138  * Support for the "z-term.c" package
4139  * ------------------------------------------------------------------------ */
4140
4141
4142 /**
4143  * Initialize a new Term
4144  */
4145 static void Term_init_cocoa(term *t)
4146 {
4147     @autoreleasepool {
4148         AngbandContext *context = [[AngbandContext alloc] init];
4149
4150         /* Give the term ownership of the context */
4151         t->data = (void *)CFBridgingRetain(context);
4152
4153         /* Handle graphics */
4154         t->higher_pict = !! use_graphics;
4155         t->always_pict = FALSE;
4156
4157         NSDisableScreenUpdates();
4158
4159         /*
4160          * Figure out the frame autosave name based on the index of this term
4161          */
4162         NSString *autosaveName = nil;
4163         int termIdx;
4164         for (termIdx = 0; termIdx < ANGBAND_TERM_MAX; termIdx++)
4165         {
4166             if (angband_term[termIdx] == t)
4167             {
4168                 autosaveName =
4169                     [NSString stringWithFormat:@"AngbandTerm-%d", termIdx];
4170                 break;
4171             }
4172         }
4173
4174         /* Set its font. */
4175         NSString *fontName =
4176             [[NSUserDefaults angbandDefaults]
4177                 stringForKey:[NSString stringWithFormat:@"FontName-%d", termIdx]];
4178         if (! fontName) fontName = [[AngbandContext defaultFont] fontName];
4179
4180         /*
4181          * Use a smaller default font for the other windows, but only if the
4182          * font hasn't been explicitly set.
4183          */
4184         float fontSize =
4185             (termIdx > 0) ? 10.0 : [[AngbandContext defaultFont] pointSize];
4186         NSNumber *fontSizeNumber =
4187             [[NSUserDefaults angbandDefaults]
4188                 valueForKey: [NSString stringWithFormat: @"FontSize-%d", termIdx]];
4189
4190         if( fontSizeNumber != nil )
4191         {
4192             fontSize = [fontSizeNumber floatValue];
4193         }
4194
4195         [context setSelectionFont:[NSFont fontWithName:fontName size:fontSize]
4196                  adjustTerminal: NO];
4197
4198         NSArray *terminalDefaults =
4199             [[NSUserDefaults standardUserDefaults]
4200                 valueForKey: AngbandTerminalsDefaultsKey];
4201         NSInteger rows = 24;
4202         NSInteger columns = 80;
4203
4204         if( termIdx < (int)[terminalDefaults count] )
4205         {
4206             NSDictionary *term = [terminalDefaults objectAtIndex: termIdx];
4207             NSInteger defaultRows =
4208                 [[term valueForKey: AngbandTerminalRowsDefaultsKey]
4209                     integerValue];
4210             NSInteger defaultColumns =
4211                 [[term valueForKey: AngbandTerminalColumnsDefaultsKey]
4212                     integerValue];
4213
4214             if (defaultRows > 0) rows = defaultRows;
4215             if (defaultColumns > 0) columns = defaultColumns;
4216         }
4217
4218         [context resizeWithColumns:columns rows:rows];
4219
4220         /* Get the window */
4221         NSWindow *window = [context makePrimaryWindow];
4222
4223         /* Set its title and, for auxiliary terms, tentative size */
4224         [context setDefaultTitle:termIdx];
4225         [context constrainWindowSize:termIdx];
4226
4227         /*
4228          * If this is the first term, and we support full screen (Mac OS X Lion
4229          * or later), then allow it to go full screen (sweet). Allow other
4230          * terms to be FullScreenAuxilliary, so they can at least show up.
4231          * Unfortunately in Lion they don't get brought to the full screen
4232          * space; but they would only make sense on multiple displays anyways
4233          * so it's not a big loss.
4234          */
4235         if ([window respondsToSelector:@selector(toggleFullScreen:)])
4236         {
4237             NSWindowCollectionBehavior behavior = [window collectionBehavior];
4238             behavior |=
4239                 (termIdx == 0 ?
4240                  NSWindowCollectionBehaviorFullScreenPrimary :
4241                  NSWindowCollectionBehaviorFullScreenAuxiliary);
4242             [window setCollectionBehavior:behavior];
4243         }
4244
4245         /* No Resume support yet, though it would not be hard to add */
4246         if ([window respondsToSelector:@selector(setRestorable:)])
4247         {
4248             [window setRestorable:NO];
4249         }
4250
4251         /* default window placement */ {
4252             static NSRect overallBoundingRect;
4253
4254             if( termIdx == 0 )
4255             {
4256                 /*
4257                  * This is a bit of a trick to allow us to display multiple
4258                  * windows in the "standard default" window position in OS X:
4259                  * the upper center of the screen.  The term sizes set in
4260                  * load_prefs() are based on a 5-wide by 3-high grid, with the
4261                  * main term being 4/5 wide by 2/3 high (hence the scaling to
4262                  * find what the containing rect would be).
4263                  */
4264                 NSRect originalMainTermFrame = [window frame];
4265                 NSRect scaledFrame = originalMainTermFrame;
4266                 scaledFrame.size.width *= 5.0 / 4.0;
4267                 scaledFrame.size.height *= 3.0 / 2.0;
4268                 scaledFrame.size.width += 1.0; /* spacing between window columns */
4269                 scaledFrame.size.height += 1.0; /* spacing between window rows */
4270                 [window setFrame: scaledFrame  display: NO];
4271                 [window center];
4272                 overallBoundingRect = [window frame];
4273                 [window setFrame: originalMainTermFrame display: NO];
4274             }
4275
4276             static NSRect mainTermBaseRect;
4277             NSRect windowFrame = [window frame];
4278
4279             if( termIdx == 0 )
4280             {
4281                 /*
4282                  * The height and width adjustments were determined
4283                  * experimentally, so that the rest of the windows line up
4284                  * nicely without overlapping.
4285                  */
4286                 windowFrame.size.width += 7.0;
4287                 windowFrame.size.height += 9.0;
4288                 windowFrame.origin.x = NSMinX( overallBoundingRect );
4289                 windowFrame.origin.y =
4290                     NSMaxY( overallBoundingRect ) - NSHeight( windowFrame );
4291                 mainTermBaseRect = windowFrame;
4292             }
4293             else if( termIdx == 1 )
4294             {
4295                 windowFrame.origin.x = NSMinX( mainTermBaseRect );
4296                 windowFrame.origin.y =
4297                     NSMinY( mainTermBaseRect ) - NSHeight( windowFrame ) - 1.0;
4298             }
4299             else if( termIdx == 2 )
4300             {
4301                 windowFrame.origin.x = NSMaxX( mainTermBaseRect ) + 1.0;
4302                 windowFrame.origin.y =
4303                     NSMaxY( mainTermBaseRect ) - NSHeight( windowFrame );
4304             }
4305             else if( termIdx == 3 )
4306             {
4307                 windowFrame.origin.x = NSMaxX( mainTermBaseRect ) + 1.0;
4308                 windowFrame.origin.y =
4309                     NSMinY( mainTermBaseRect ) - NSHeight( windowFrame ) - 1.0;
4310             }
4311             else if( termIdx == 4 )
4312             {
4313                 windowFrame.origin.x = NSMaxX( mainTermBaseRect ) + 1.0;
4314                 windowFrame.origin.y = NSMinY( mainTermBaseRect );
4315             }
4316             else if( termIdx == 5 )
4317             {
4318                 windowFrame.origin.x =
4319                     NSMinX( mainTermBaseRect ) + NSWidth( windowFrame ) + 1.0;
4320                 windowFrame.origin.y =
4321                     NSMinY( mainTermBaseRect ) - NSHeight( windowFrame ) - 1.0;
4322             }
4323
4324             [window setFrame: windowFrame display: NO];
4325         }
4326
4327         /* Override the default frame above if the user has adjusted windows in
4328          * the past */
4329         if (autosaveName) [window setFrameAutosaveName:autosaveName];
4330
4331         /*
4332          * Tell it about its term. Do this after we've sized it so that the
4333          * sizing doesn't trigger redrawing and such.
4334          */
4335         [context setTerm:t];
4336
4337         /*
4338          * Only order front if it's the first term. Other terms will be ordered
4339          * front from AngbandUpdateWindowVisibility(). This is to work around a
4340          * problem where Angband aggressively tells us to initialize terms that
4341          * don't do anything!
4342          */
4343         if (t == angband_term[0])
4344             [context.primaryWindow makeKeyAndOrderFront: nil];
4345
4346         NSEnableScreenUpdates();
4347
4348         /* Set "mapped" flag */
4349         t->mapped_flag = true;
4350     }
4351 }
4352
4353
4354
4355 /**
4356  * Nuke an old Term
4357  */
4358 static void Term_nuke_cocoa(term *t)
4359 {
4360     @autoreleasepool {
4361         AngbandContext *context = (__bridge AngbandContext*) (t->data);
4362         if (context)
4363         {
4364             /* Tell the context to get rid of its windows, etc. */
4365             [context dispose];
4366
4367             /* Balance our CFBridgingRetain from when we created it */
4368             CFRelease(t->data);
4369
4370             /* Done with it */
4371             t->data = NULL;
4372         }
4373     }
4374 }
4375
4376 /**
4377  * Returns the CGImageRef corresponding to an image with the given path.
4378  * Transfers ownership to the caller.
4379  */
4380 static CGImageRef create_angband_image(NSString *path)
4381 {
4382     CGImageRef decodedImage = NULL, result = NULL;
4383     
4384     /* Try using ImageIO to load the image */
4385     if (path)
4386     {
4387         NSURL *url = [[NSURL alloc] initFileURLWithPath:path isDirectory:NO];
4388         if (url)
4389         {
4390             NSDictionary *options = [[NSDictionary alloc] initWithObjectsAndKeys:(id)kCFBooleanTrue, kCGImageSourceShouldCache, nil];
4391             CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)url, (CFDictionaryRef)options);
4392             if (source)
4393             {
4394                 /*
4395                  * We really want the largest image, but in practice there's
4396                  * only going to be one
4397                  */
4398                 decodedImage = CGImageSourceCreateImageAtIndex(source, 0, (CFDictionaryRef)options);
4399                 CFRelease(source);
4400             }
4401         }
4402     }
4403     
4404     /*
4405      * Draw the sucker to defeat ImageIO's weird desire to cache and decode on
4406      * demand. Our images aren't that big!
4407      */
4408     if (decodedImage)
4409     {
4410         size_t width = CGImageGetWidth(decodedImage), height = CGImageGetHeight(decodedImage);
4411         
4412         /* Compute our own bitmap info */
4413         CGBitmapInfo imageBitmapInfo = CGImageGetBitmapInfo(decodedImage);
4414         CGBitmapInfo contextBitmapInfo = kCGBitmapByteOrderDefault;
4415         
4416         switch (imageBitmapInfo & kCGBitmapAlphaInfoMask) {
4417             case kCGImageAlphaNone:
4418             case kCGImageAlphaNoneSkipLast:
4419             case kCGImageAlphaNoneSkipFirst:
4420                 /* No alpha */
4421                 contextBitmapInfo |= kCGImageAlphaNone;
4422                 break;
4423             default:
4424                 /* Some alpha, use premultiplied last which is most efficient. */
4425                 contextBitmapInfo |= kCGImageAlphaPremultipliedLast;
4426                 break;
4427         }
4428
4429         /* Draw the source image flipped, since the view is flipped */
4430         CGContextRef ctx = CGBitmapContextCreate(NULL, width, height, CGImageGetBitsPerComponent(decodedImage), CGImageGetBytesPerRow(decodedImage), CGImageGetColorSpace(decodedImage), contextBitmapInfo);
4431         if (ctx) {
4432             CGContextSetBlendMode(ctx, kCGBlendModeCopy);
4433             CGContextTranslateCTM(ctx, 0.0, height);
4434             CGContextScaleCTM(ctx, 1.0, -1.0);
4435             CGContextDrawImage(
4436                 ctx, CGRectMake(0, 0, width, height), decodedImage);
4437             result = CGBitmapContextCreateImage(ctx);
4438             CFRelease(ctx);
4439         }
4440
4441         CGImageRelease(decodedImage);
4442     }
4443     return result;
4444 }
4445
4446 /**
4447  * React to changes
4448  */
4449 static errr Term_xtra_cocoa_react(void)
4450 {
4451     /* Don't actually switch graphics until the game is running */
4452     if (!initialized || !game_in_progress) return (-1);
4453
4454     @autoreleasepool {
4455         /* Handle graphics */
4456         int expected_graf_mode = (current_graphics_mode) ?
4457             current_graphics_mode->grafID : GRAPHICS_NONE;
4458         if (graf_mode_req != expected_graf_mode)
4459         {
4460             graphics_mode *new_mode;
4461             if (graf_mode_req != GRAPHICS_NONE) {
4462                 new_mode = get_graphics_mode(graf_mode_req);
4463             } else {
4464                 new_mode = NULL;
4465             }
4466
4467             /* Get rid of the old image. CGImageRelease is NULL-safe. */
4468             CGImageRelease(pict_image);
4469             pict_image = NULL;
4470
4471             /* Try creating the image if we want one */
4472             if (new_mode != NULL)
4473             {
4474                 NSString *img_path =
4475                     [NSString stringWithFormat:@"%s/%s", new_mode->path, new_mode->file];
4476                 pict_image = create_angband_image(img_path);
4477
4478                 /* If we failed to create the image, revert to ASCII. */
4479                 if (! pict_image) {
4480                     new_mode = NULL;
4481                     if (use_bigtile) {
4482                         arg_bigtile = FALSE;
4483                     }
4484                     [[NSUserDefaults angbandDefaults]
4485                         setInteger:GRAPHICS_NONE
4486                         forKey:AngbandGraphicsDefaultsKey];
4487
4488                     NSString *msg = NSLocalizedStringWithDefaultValue(
4489                         @"Error.TileSetLoadFailed",
4490                         AngbandMessageCatalog,
4491                         [NSBundle mainBundle],
4492                         @"Failed to Load Tile Set",
4493                         @"Alert text for failed tile set load");
4494                     NSString *info = NSLocalizedStringWithDefaultValue(
4495                         @"Error.TileSetRevertToASCII",
4496                         AngbandMessageCatalog,
4497                         [NSBundle mainBundle],
4498                         @"Could not load the tile set.  Switched back to ASCII.",
4499                         @"Alert informative message for failed tile set load");
4500                     NSAlert *alert = [[NSAlert alloc] init];
4501                     alert.messageText = msg;
4502                     alert.informativeText = info;
4503                     [alert runModal];
4504                 }
4505             }
4506
4507             if (graphics_are_enabled()) {
4508                 /*
4509                  * The contents stored in the AngbandContext may have
4510                  * references to the old tile set.  Out of an abundance
4511                  * of caution, clear those references in case there's an
4512                  * attempt to redraw the contents before the core has the
4513                  * chance to update it via the text_hook, pict_hook, and
4514                  * wipe_hook.
4515                  */
4516                 for (int iterm = 0; iterm < ANGBAND_TERM_MAX; ++iterm) {
4517                     AngbandContext* aContext =
4518                         (__bridge AngbandContext*) (angband_term[iterm]->data);
4519
4520                     [aContext.contents wipeTiles];
4521                 }
4522             }
4523
4524             /* Record what we did */
4525             use_graphics = new_mode ? new_mode->grafID : 0;
4526             ANGBAND_GRAF = (new_mode ? new_mode->graf : "ascii");
4527             current_graphics_mode = new_mode;
4528
4529             /* Enable or disable higher picts.  */
4530             for (int iterm = 0; iterm < ANGBAND_TERM_MAX; ++iterm) {
4531                 if (angband_term[iterm]) {
4532                     angband_term[iterm]->higher_pict = !! use_graphics;
4533                 }
4534             }
4535
4536             if (pict_image && current_graphics_mode)
4537             {
4538                 /*
4539                  * Compute the row and column count via the image height and
4540                  * width.
4541                  */
4542                 pict_rows = (int)(CGImageGetHeight(pict_image) /
4543                                   current_graphics_mode->cell_height);
4544                 pict_cols = (int)(CGImageGetWidth(pict_image) /
4545                                   current_graphics_mode->cell_width);
4546             }
4547             else
4548             {
4549                 pict_rows = 0;
4550                 pict_cols = 0;
4551             }
4552
4553             /* Reset visuals */
4554             if (arg_bigtile == use_bigtile && character_generated)
4555             {
4556                 reset_visuals();
4557             }
4558         }
4559
4560         if (arg_bigtile != use_bigtile) {
4561             if (character_generated)
4562             {
4563                 /* Reset visuals */
4564                 reset_visuals();
4565             }
4566
4567             Term_activate(angband_term[0]);
4568             Term_resize(angband_term[0]->wid, angband_term[0]->hgt);
4569         }
4570     }
4571
4572     /* Success */
4573     return (0);
4574 }
4575
4576
4577 /**
4578  * Do a "special thing"
4579  */
4580 static errr Term_xtra_cocoa(int n, int v)
4581 {
4582     errr result = 0;
4583     @autoreleasepool {
4584         AngbandContext* angbandContext =
4585             (__bridge AngbandContext*) (Term->data);
4586
4587         /* Analyze */
4588         switch (n) {
4589             /* Make a noise */
4590         case TERM_XTRA_NOISE:
4591             NSBeep();
4592             break;
4593
4594             /*  Make a sound */
4595         case TERM_XTRA_SOUND:
4596             play_sound(v);
4597             break;
4598
4599             /* Process random events */
4600         case TERM_XTRA_BORED:
4601             /*
4602              * Show or hide cocoa windows based on the subwindow flags set by
4603              * the user.
4604              */
4605             AngbandUpdateWindowVisibility();
4606             /* Process an event */
4607             (void)check_events(CHECK_EVENTS_NO_WAIT);
4608             break;
4609
4610             /* Process pending events */
4611         case TERM_XTRA_EVENT:
4612             /* Process an event */
4613             (void)check_events(v);
4614             break;
4615
4616             /* Flush all pending events (if any) */
4617         case TERM_XTRA_FLUSH:
4618             /* Hack -- flush all events */
4619             while (check_events(CHECK_EVENTS_DRAIN)) /* loop */;
4620
4621             break;
4622
4623             /* Hack -- Change the "soft level" */
4624         case TERM_XTRA_LEVEL:
4625             /*
4626              * Here we could activate (if requested), but I don't think
4627              * Angband should be telling us our window order (the user
4628              * should decide that), so do nothing.
4629              */
4630             break;
4631
4632             /* Clear the screen */
4633         case TERM_XTRA_CLEAR:
4634             [angbandContext.contents wipe];
4635             [angbandContext setNeedsDisplay:YES];
4636             break;
4637
4638             /* React to changes */
4639         case TERM_XTRA_REACT:
4640             result = Term_xtra_cocoa_react();
4641             break;
4642
4643             /* Delay (milliseconds) */
4644         case TERM_XTRA_DELAY:
4645             /* If needed */
4646             if (v > 0) {
4647                 double seconds = v / 1000.;
4648                 NSDate* date = [NSDate dateWithTimeIntervalSinceNow:seconds];
4649                 do {
4650                     NSEvent* event;
4651                     do {
4652                         event = [NSApp nextEventMatchingMask:-1
4653                                        untilDate:date
4654                                        inMode:NSDefaultRunLoopMode
4655                                        dequeue:YES];
4656                         if (event) send_event(event);
4657                     } while (event);
4658                 } while ([date timeIntervalSinceNow] >= 0);
4659             }
4660             break;
4661
4662             /* Draw the pending changes. */
4663         case TERM_XTRA_FRESH:
4664             {
4665                 /*
4666                  * Check the cursor visibility since the core will tell us
4667                  * explicitly to draw it, but tells us implicitly to forget it
4668                  * by simply telling us to redraw a location.
4669                  */
4670                 int isVisible = 0;
4671
4672                 Term_get_cursor(&isVisible);
4673                 if (! isVisible) {
4674                     [angbandContext.contents removeCursor];
4675                 }
4676                 [angbandContext computeInvalidRects];
4677                 [angbandContext.changes clear];
4678             }
4679             break;
4680
4681         default:
4682             /* Oops */
4683             result = 1;
4684             break;
4685         }
4686     }
4687
4688     return result;
4689 }
4690
4691 static errr Term_curs_cocoa(TERM_LEN x, TERM_LEN y)
4692 {
4693     AngbandContext *angbandContext = (__bridge AngbandContext*) (Term->data);
4694
4695     [angbandContext.contents setCursorAtColumn:x row:y width:1 height:1];
4696     /*
4697      * Unfortunately, this (and the same logic in Term_bigcurs_cocoa) will
4698      * also trigger what's under the cursor to be redrawn as well, even if
4699      * it has not changed.  In the current drawing implementation, that
4700      * inefficiency seems unavoidable.
4701      */
4702     [angbandContext.changes markChangedAtColumn:x row:y];
4703
4704     /* Success */
4705     return 0;
4706 }
4707
4708 /**
4709  * Draw a cursor that's two tiles wide.  For Japanese, that's used when
4710  * the cursor points at a kanji character, irregardless of whether operating
4711  * in big tile mode.
4712  */
4713 static errr Term_bigcurs_cocoa(TERM_LEN x, TERM_LEN y)
4714 {
4715     AngbandContext *angbandContext = (__bridge AngbandContext*) (Term->data);
4716
4717     [angbandContext.contents setCursorAtColumn:x row:y width:2 height:1];
4718     [angbandContext.changes markChangedBlockAtColumn:x row:y width:2 height:1];
4719
4720     /* Success */
4721     return 0;
4722 }
4723
4724 /**
4725  * Low level graphics (Assumes valid input)
4726  *
4727  * Erase "n" characters starting at (x,y)
4728  */
4729 static errr Term_wipe_cocoa(TERM_LEN x, TERM_LEN y, int n)
4730 {
4731     AngbandContext *angbandContext = (__bridge AngbandContext*) (Term->data);
4732
4733     [angbandContext.contents wipeBlockAtColumn:x row:y width:n height:1];
4734     [angbandContext.changes markChangedRangeAtColumn:x row:y width:n];
4735
4736     /* Success */
4737     return 0;
4738 }
4739
4740 static errr Term_pict_cocoa(TERM_LEN x, TERM_LEN y, int n,
4741                             TERM_COLOR *ap, concptr cp,
4742                             const TERM_COLOR *tap, concptr tcp)
4743 {
4744     /* Paranoia: Bail if graphics aren't enabled */
4745     if (! graphics_are_enabled()) return -1;
4746
4747     AngbandContext* angbandContext = (__bridge AngbandContext*) (Term->data);
4748     int step = (use_bigtile) ? 2 : 1;
4749
4750     int alphablend;
4751     if (use_graphics) {
4752         CGImageAlphaInfo ainfo = CGImageGetAlphaInfo(pict_image);
4753
4754         alphablend = (ainfo & (kCGImageAlphaPremultipliedFirst |
4755                                kCGImageAlphaPremultipliedLast)) ? 1 : 0;
4756     } else {
4757         alphablend = 0;
4758     }
4759
4760     for (int i = x; i < x + n * step; i += step) {
4761         TERM_COLOR a = *ap;
4762         char c = *cp;
4763         TERM_COLOR ta = *tap;
4764         char tc = *tcp;
4765
4766         ap += step;
4767         cp += step;
4768         tap += step;
4769         tcp += step;
4770         if (use_graphics && (a & 0x80) && (c & 0x80)) {
4771             char fgdRow = ((byte)a & 0x7F) % pict_rows;
4772             char fgdCol = ((byte)c & 0x7F) % pict_cols;
4773             char bckRow, bckCol;
4774
4775             if (alphablend) {
4776                 bckRow = ((byte)ta & 0x7F) % pict_rows;
4777                 bckCol = ((byte)tc & 0x7F) % pict_cols;
4778             } else {
4779                 /*
4780                  * Not blending so make the background the same as the
4781                  * the foreground.
4782                  */
4783                 bckRow = fgdRow;
4784                 bckCol = fgdCol;
4785             }
4786             [angbandContext.contents setTileAtColumn:i row:y
4787                            foregroundColumn:fgdCol
4788                            foregroundRow:fgdRow
4789                            backgroundColumn:bckCol
4790                            backgroundRow:bckRow
4791                            tileWidth:step
4792                            tileHeight:1];
4793             [angbandContext.changes markChangedBlockAtColumn:i row:y
4794                            width:step height:1];
4795         }
4796     }
4797
4798     /* Success */
4799     return (0);
4800 }
4801
4802 /**
4803  * Low level graphics.  Assumes valid input.
4804  *
4805  * Draw several ("n") chars, with an attr, at a given location.
4806  */
4807 static errr Term_text_cocoa(
4808     TERM_LEN x, TERM_LEN y, int n, TERM_COLOR a, concptr cp)
4809 {
4810     AngbandContext* angbandContext = (__bridge AngbandContext*) (Term->data);
4811
4812     [angbandContext.contents setUniformAttributeTextRunAtColumn:x
4813                    row:y n:n glyphs:cp attribute:a];
4814     [angbandContext.changes markChangedRangeAtColumn:x row:y width:n];
4815
4816     /* Success */
4817     return 0;
4818 }
4819
4820 #if 0
4821 /* From the Linux mbstowcs(3) man page:
4822  *   If dest is NULL, n is ignored, and the conversion  proceeds  as  above,
4823  *   except  that  the converted wide characters are not written out to mem‐
4824  *   ory, and that no length limit exists.
4825  */
4826 static size_t Term_mbcs_cocoa(wchar_t *dest, const char *src, int n)
4827 {
4828     int i;
4829     int count = 0;
4830
4831     /* Unicode code point to UTF-8
4832      *  0x0000-0x007f:   0xxxxxxx
4833      *  0x0080-0x07ff:   110xxxxx 10xxxxxx
4834      *  0x0800-0xffff:   1110xxxx 10xxxxxx 10xxxxxx
4835      * 0x10000-0x1fffff: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
4836      * Note that UTF-16 limits Unicode to 0x10ffff. This code is not
4837      * endian-agnostic.
4838      */
4839     for (i = 0; i < n || dest == NULL; i++) {
4840         if ((src[i] & 0x80) == 0) {
4841             if (dest != NULL) dest[count] = src[i];
4842             if (src[i] == 0) break;
4843         } else if ((src[i] & 0xe0) == 0xc0) {
4844             if (dest != NULL) dest[count] =
4845                             (((unsigned char)src[i] & 0x1f) << 6)|
4846                             ((unsigned char)src[i+1] & 0x3f);
4847             i++;
4848         } else if ((src[i] & 0xf0) == 0xe0) {
4849             if (dest != NULL) dest[count] =
4850                             (((unsigned char)src[i] & 0x0f) << 12) |
4851                             (((unsigned char)src[i+1] & 0x3f) << 6) |
4852                             ((unsigned char)src[i+2] & 0x3f);
4853             i += 2;
4854         } else if ((src[i] & 0xf8) == 0xf0) {
4855             if (dest != NULL) dest[count] =
4856                             (((unsigned char)src[i] & 0x0f) << 18) |
4857                             (((unsigned char)src[i+1] & 0x3f) << 12) |
4858                             (((unsigned char)src[i+2] & 0x3f) << 6) |
4859                             ((unsigned char)src[i+3] & 0x3f);
4860             i += 3;
4861         } else {
4862             /* Found an invalid multibyte sequence */
4863             return (size_t)-1;
4864         }
4865         count++;
4866     }
4867     return count;
4868 }
4869 #endif
4870
4871 /**
4872  * Handle redrawing for a change to the tile set, tile scaling, or main window
4873  * font.  Returns YES if the redrawing was initiated.  Otherwise returns NO.
4874  */
4875 static BOOL redraw_for_tiles_or_term0_font(void)
4876 {
4877     /*
4878      * In Angband 4.2, do_cmd_redraw() will always clear, but only provides
4879      * something to replace the erased content if a character has been
4880      * generated.  In Hengband, do_cmd_redraw() isn't safe to call unless a
4881      * character has been generated.  Therefore, only call it if a character
4882      * has been generated.
4883      */
4884     if (character_generated) {
4885         do_cmd_redraw();
4886         wakeup_event_loop();
4887         return YES;
4888     }
4889     return NO;
4890 }
4891
4892 /**
4893  * Post a nonsense event so that our event loop wakes up
4894  */
4895 static void wakeup_event_loop(void)
4896 {
4897     /* Big hack - send a nonsense event to make us update */
4898     NSEvent *event = [NSEvent otherEventWithType:NSApplicationDefined location:NSZeroPoint modifierFlags:0 timestamp:0 windowNumber:0 context:NULL subtype:AngbandEventWakeup data1:0 data2:0];
4899     [NSApp postEvent:event atStart:NO];
4900 }
4901
4902
4903 /**
4904  * Handle the "open_when_ready" flag
4905  */
4906 static void handle_open_when_ready(void)
4907 {
4908     /* Check the flag XXX XXX XXX make a function for this */
4909     if (open_when_ready && initialized && !game_in_progress)
4910     {
4911         /* Forget */
4912         open_when_ready = FALSE;
4913         
4914         /* Game is in progress */
4915         game_in_progress = TRUE;
4916         
4917         /* Wait for a keypress */
4918         pause_line(Term->hgt - 1);
4919     }
4920 }
4921
4922
4923 /**
4924  * Handle quit_when_ready, by Peter Ammon,
4925  * slightly modified to check inkey_flag.
4926  */
4927 static void quit_calmly(void)
4928 {
4929     /* Quit immediately if game's not started */
4930     if (!game_in_progress || !character_generated) quit(NULL);
4931
4932     /* Save the game and Quit (if it's safe) */
4933     if (inkey_flag)
4934     {
4935         /* Hack -- Forget messages and term */
4936         msg_flag = FALSE;
4937         Term->mapped_flag = FALSE;
4938
4939         /* Save the game */
4940         do_cmd_save_game(FALSE);
4941         record_current_savefile();
4942
4943         /* Quit */
4944         quit(NULL);
4945     }
4946
4947     /* Wait until inkey_flag is set */
4948 }
4949
4950
4951
4952 /**
4953  * Returns YES if we contain an AngbandView (and hence should direct our events
4954  * to Angband)
4955  */
4956 static BOOL contains_angband_view(NSView *view)
4957 {
4958     if ([view isKindOfClass:[AngbandView class]]) return YES;
4959     for (NSView *subview in [view subviews]) {
4960         if (contains_angband_view(subview)) return YES;
4961     }
4962     return NO;
4963 }
4964
4965
4966 /**
4967  * Queue mouse presses if they occur in the map section of the main window.
4968  */
4969 static void AngbandHandleEventMouseDown( NSEvent *event )
4970 {
4971 #if 0
4972         AngbandContext *angbandContext = [[[event window] contentView] angbandContext];
4973         AngbandContext *mainAngbandContext =
4974             (__bridge AngbandContext*) (angband_term[0]->data);
4975
4976         if (mainAngbandContext.primaryWindow &&
4977             [[event window] windowNumber] ==
4978             [mainAngbandContext.primaryWindow windowNumber])
4979         {
4980                 int cols, rows, x, y;
4981                 Term_get_size(&cols, &rows);
4982                 NSSize tileSize = angbandContext.tileSize;
4983                 NSSize border = angbandContext.borderSize;
4984                 NSPoint windowPoint = [event locationInWindow];
4985
4986                 /*
4987                  * Adjust for border; add border height because window origin
4988                  * is at bottom
4989                  */
4990                 windowPoint = NSMakePoint( windowPoint.x - border.width, windowPoint.y + border.height );
4991
4992                 NSPoint p = [[[event window] contentView] convertPoint: windowPoint fromView: nil];
4993                 x = floor( p.x / tileSize.width );
4994                 y = floor( p.y / tileSize.height );
4995
4996                 /*
4997                  * Being safe about this, since xcode doesn't seem to like the
4998                  * bool_hack stuff
4999                  */
5000                 BOOL displayingMapInterface = ((int)inkey_flag != 0);
5001
5002                 /* Sidebar plus border == thirteen characters; top row is reserved. */
5003                 /* Coordinates run from (0,0) to (cols-1, rows-1). */
5004                 BOOL mouseInMapSection = (x > 13 && x <= cols - 1 && y > 0  && y <= rows - 2);
5005
5006                 /*
5007                  * If we are displaying a menu, allow clicks anywhere within
5008                  * the terminal bounds; if we are displaying the main game
5009                  * interface, only allow clicks in the map section
5010                  */
5011                 if ((!displayingMapInterface && x >= 0 && x < cols &&
5012                      y >= 0 && y < rows) ||
5013                      (displayingMapInterface && mouseInMapSection))
5014                 {
5015                         /*
5016                          * [event buttonNumber] will return 0 for left click,
5017                          * 1 for right click, but this is safer
5018                          */
5019                         int button = ([event type] == NSLeftMouseDown) ? 1 : 2;
5020
5021 #ifdef KC_MOD_ALT
5022                         NSUInteger eventModifiers = [event modifierFlags];
5023                         byte angbandModifiers = 0;
5024                         angbandModifiers |= (eventModifiers & NSShiftKeyMask) ? KC_MOD_SHIFT : 0;
5025                         angbandModifiers |= (eventModifiers & NSControlKeyMask) ? KC_MOD_CONTROL : 0;
5026                         angbandModifiers |= (eventModifiers & NSAlternateKeyMask) ? KC_MOD_ALT : 0;
5027                         button |= (angbandModifiers & 0x0F) << 4; /* encode modifiers in the button number (see Term_mousepress()) */
5028 #endif
5029
5030                         Term_mousepress(x, y, button);
5031                 }
5032         }
5033 #endif
5034
5035         /* Pass click through to permit focus change, resize, etc. */
5036         [NSApp sendEvent:event];
5037 }
5038
5039
5040
5041 /**
5042  * Encodes an NSEvent Angband-style, or forwards it along.  Returns YES if the
5043  * event was sent to Angband, NO if Cocoa (or nothing) handled it */
5044 static BOOL send_event(NSEvent *event)
5045 {
5046
5047     /* If the receiving window is not an Angband window, then do nothing */
5048     if (! contains_angband_view([[event window] contentView]))
5049     {
5050         [NSApp sendEvent:event];
5051         return NO;
5052     }
5053
5054     /* Analyze the event */
5055     switch ([event type])
5056     {
5057         case NSKeyDown:
5058         {
5059             /* Try performing a key equivalent */
5060             if ([[NSApp mainMenu] performKeyEquivalent:event]) break;
5061             
5062             unsigned modifiers = [event modifierFlags];
5063             
5064             /* Send all NSCommandKeyMasks through */
5065             if (modifiers & NSCommandKeyMask)
5066             {
5067                 [NSApp sendEvent:event];
5068                 break;
5069             }
5070             
5071             if (! [[event characters] length]) break;
5072             
5073             
5074             /* Extract some modifiers */
5075             int mc = !! (modifiers & NSControlKeyMask);
5076             int ms = !! (modifiers & NSShiftKeyMask);
5077             int mo = !! (modifiers & NSAlternateKeyMask);
5078             int kp = !! (modifiers & NSNumericPadKeyMask);
5079             
5080             
5081             /* Get the Angband char corresponding to this unichar */
5082             unichar c = [[event characters] characterAtIndex:0];
5083             char ch;
5084             /*
5085              * Have anything from the numeric keypad generate a macro
5086              * trigger so that shift or control modifiers can be passed.
5087              */
5088             if (c <= 0x7F && !kp)
5089             {
5090                 ch = (char) c;
5091             }
5092             else {
5093                 /*
5094                  * The rest of Hengband uses Angband 2.7's or so key handling:
5095                  * so for the rest do something like the encoding that
5096                  * main-win.c does:  send a macro trigger with the Unicode
5097                  * value encoded into printable ASCII characters.
5098                  */
5099                 ch = '\0';
5100             }
5101             
5102             /* override special keys */
5103             switch([event keyCode]) {
5104                 case kVK_Return: ch = '\r'; break;
5105                 case kVK_Escape: ch = 27; break;
5106                 case kVK_Tab: ch = '\t'; break;
5107                 case kVK_Delete: ch = '\b'; break;
5108                 case kVK_ANSI_KeypadEnter: ch = '\r'; kp = TRUE; break;
5109             }
5110
5111             /* Hide the mouse pointer */
5112             [NSCursor setHiddenUntilMouseMoves:YES];
5113             
5114             /* Enqueue it */
5115             if (ch != '\0')
5116             {
5117                 Term_keypress(ch);
5118             }
5119             else
5120             {
5121                 /*
5122                  * Could use the hexsym global but some characters overlap with
5123                  * those used to indicate modifiers.
5124                  */
5125                 const char encoded[16] = {
5126                     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b',
5127                     'c', 'd', 'e', 'f'
5128                 };
5129
5130                 /* Begin the macro trigger. */
5131                 Term_keypress(31);
5132
5133                 /* Send the modifiers. */
5134                 if (mc) Term_keypress('C');
5135                 if (ms) Term_keypress('S');
5136                 if (mo) Term_keypress('O');
5137                 if (kp) Term_keypress('K');
5138
5139                 do {
5140                     Term_keypress(encoded[c & 0xF]);
5141                     c >>= 4;
5142                 } while (c > 0);
5143
5144                 /* End the macro trigger. */
5145                 Term_keypress(13);
5146             }
5147             
5148             break;
5149         }
5150             
5151         case NSLeftMouseDown:
5152                 case NSRightMouseDown:
5153                         AngbandHandleEventMouseDown(event);
5154             break;
5155
5156         case NSApplicationDefined:
5157         {
5158             if ([event subtype] == AngbandEventWakeup)
5159             {
5160                 return YES;
5161             }
5162             break;
5163         }
5164             
5165         default:
5166             [NSApp sendEvent:event];
5167             return YES;
5168     }
5169     return YES;
5170 }
5171
5172 /**
5173  * Check for Events, return TRUE if we process any
5174  */
5175 static BOOL check_events(int wait)
5176 {
5177     BOOL result = YES;
5178
5179     @autoreleasepool {
5180         /* Handles the quit_when_ready flag */
5181         if (quit_when_ready) quit_calmly();
5182
5183         NSDate* endDate;
5184         if (wait == CHECK_EVENTS_WAIT) endDate = [NSDate distantFuture];
5185         else endDate = [NSDate distantPast];
5186
5187         NSEvent* event;
5188         for (;;) {
5189             if (quit_when_ready)
5190             {
5191                 /* send escape events until we quit */
5192                 Term_keypress(0x1B);
5193                 result = NO;
5194                 break;
5195             }
5196             else {
5197                 event = [NSApp nextEventMatchingMask:-1 untilDate:endDate
5198                                inMode:NSDefaultRunLoopMode dequeue:YES];
5199                 if (! event) {
5200                     result = NO;
5201                     break;
5202                 }
5203                 if (send_event(event)) break;
5204             }
5205         }
5206     }
5207
5208     return result;
5209 }
5210
5211 /**
5212  * Hook to tell the user something important
5213  */
5214 static void hook_plog(const char * str)
5215 {
5216     if (str)
5217     {
5218         NSString *msg = NSLocalizedStringWithDefaultValue(
5219             @"Warning", AngbandMessageCatalog, [NSBundle mainBundle],
5220             @"Warning", @"Alert text for generic warning");
5221         NSString *info = [NSString stringWithCString:str
5222 #ifdef JP
5223                                    encoding:NSJapaneseEUCStringEncoding
5224 #else
5225                                    encoding:NSMacOSRomanStringEncoding
5226 #endif
5227         ];
5228         NSAlert *alert = [[NSAlert alloc] init];
5229
5230         alert.messageText = msg;
5231         alert.informativeText = info;
5232         [alert runModal];
5233     }
5234 }
5235
5236
5237 /**
5238  * Hook to tell the user something, and then quit
5239  */
5240 static void hook_quit(const char * str)
5241 {
5242     for (int i = ANGBAND_TERM_MAX - 1; i >= 0; --i) {
5243         if (angband_term[i]) {
5244             term_nuke(angband_term[i]);
5245         }
5246     }
5247     [AngbandSoundCatalog clearSharedSounds];
5248     [AngbandContext setDefaultFont:nil];
5249     plog(str);
5250     exit(0);
5251 }
5252
5253 /**
5254  * Return the path for Angband's lib directory and bail if it isn't found. The
5255  * lib directory should be in the bundle's resources directory, since it's
5256  * copied when built.
5257  */
5258 static NSString* get_lib_directory(void)
5259 {
5260     NSString *bundleLibPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: AngbandDirectoryNameLib];
5261     BOOL isDirectory = NO;
5262     BOOL libExists = [[NSFileManager defaultManager] fileExistsAtPath: bundleLibPath isDirectory: &isDirectory];
5263
5264     if( !libExists || !isDirectory )
5265     {
5266         NSLog( @"%@: can't find %@/ in bundle: isDirectory: %d libExists: %d", @VERSION_NAME, AngbandDirectoryNameLib, isDirectory, libExists );
5267
5268         NSString *msg = NSLocalizedStringWithDefaultValue(
5269             @"Error.MissingResources",
5270             AngbandMessageCatalog,
5271             [NSBundle mainBundle],
5272             @"Missing Resources",
5273             @"Alert text for missing resources");
5274         NSString *info = NSLocalizedStringWithDefaultValue(
5275             @"Error.MissingAngbandLib",
5276             AngbandMessageCatalog,
5277             [NSBundle mainBundle],
5278             @"Hengband was unable to find required resources and must quit. Please report a bug on the Angband forums.",
5279             @"Alert informative message for missing Angband lib/ folder");
5280         NSString *quit_label = NSLocalizedStringWithDefaultValue(
5281             @"Label.Quit", AngbandMessageCatalog, [NSBundle mainBundle],
5282             @"Quit", @"Quit");
5283         NSAlert *alert = [[NSAlert alloc] init];
5284         /*
5285          * Note that NSCriticalAlertStyle was deprecated in 10.10.  The
5286          * replacement is NSAlertStyleCritical.
5287          */
5288         alert.alertStyle = NSCriticalAlertStyle;
5289         alert.messageText = msg;
5290         alert.informativeText = info;
5291         [alert addButtonWithTitle:quit_label];
5292         [alert runModal];
5293         exit(0);
5294     }
5295
5296     return bundleLibPath;
5297 }
5298
5299 /**
5300  * Return the path for the directory where Angband should look for its standard
5301  * user file tree.
5302  */
5303 static NSString* get_doc_directory(void)
5304 {
5305         NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
5306
5307 #if defined(SAFE_DIRECTORY)
5308         NSString *versionedDirectory = [NSString stringWithFormat: @"%@-%s", AngbandDirectoryNameBase, VERSION_STRING];
5309         return [documents stringByAppendingPathComponent: versionedDirectory];
5310 #else
5311         return [documents stringByAppendingPathComponent: AngbandDirectoryNameBase];
5312 #endif
5313 }
5314
5315 /**
5316  * Adjust directory paths as needed to correct for any differences needed by
5317  * Angband.  init_file_paths() currently requires that all paths provided have
5318  * a trailing slash and all other platforms honor this.
5319  *
5320  * \param originalPath The directory path to adjust.
5321  * \return A path suitable for Angband or nil if an error occurred.
5322  */
5323 static NSString* AngbandCorrectedDirectoryPath(NSString *originalPath)
5324 {
5325         if ([originalPath length] == 0) {
5326                 return nil;
5327         }
5328
5329         if (![originalPath hasSuffix: @"/"]) {
5330                 return [originalPath stringByAppendingString: @"/"];
5331         }
5332
5333         return originalPath;
5334 }
5335
5336 /**
5337  * Give Angband the base paths that should be used for the various directories
5338  * it needs. It will create any needed directories.
5339  */
5340 static void prepare_paths_and_directories(void)
5341 {
5342         char libpath[PATH_MAX + 1] = "\0";
5343         NSString *libDirectoryPath =
5344             AngbandCorrectedDirectoryPath(get_lib_directory());
5345         [libDirectoryPath getFileSystemRepresentation: libpath maxLength: sizeof(libpath)];
5346
5347         char basepath[PATH_MAX + 1] = "\0";
5348         NSString *angbandDocumentsPath =
5349             AngbandCorrectedDirectoryPath(get_doc_directory());
5350         [angbandDocumentsPath getFileSystemRepresentation: basepath maxLength: sizeof(basepath)];
5351
5352         init_file_paths(libpath, basepath);
5353         create_needed_dirs();
5354 }
5355
5356 /**
5357  * Create and initialize Angband terminal number "i".
5358  */
5359 static term *term_data_link(int i)
5360 {
5361     NSArray *terminalDefaults = [[NSUserDefaults standardUserDefaults]
5362                                     valueForKey: AngbandTerminalsDefaultsKey];
5363     NSInteger rows = 24;
5364     NSInteger columns = 80;
5365
5366     if (i < (int)[terminalDefaults count]) {
5367         NSDictionary *term = [terminalDefaults objectAtIndex:i];
5368         rows = [[term valueForKey: AngbandTerminalRowsDefaultsKey]
5369                    integerValue];
5370         columns = [[term valueForKey: AngbandTerminalColumnsDefaultsKey]
5371                       integerValue];
5372     }
5373
5374     /* Allocate */
5375     term *newterm = ZNEW(term);
5376
5377     /* Initialize the term */
5378     term_init(newterm, columns, rows, 256 /* keypresses, for some reason? */);
5379
5380     /* Use a "software" cursor */
5381     newterm->soft_cursor = TRUE;
5382
5383     /* Disable the per-row flush notifications since they are not used. */
5384     newterm->never_frosh = TRUE;
5385
5386     /*
5387      * Differentiate between BS/^h, Tab/^i, ... so ^h and ^j work under the
5388      * roguelike command set.
5389      */
5390     /* newterm->complex_input = TRUE; */
5391
5392     /* Erase with "white space" */
5393     newterm->attr_blank = TERM_WHITE;
5394     newterm->char_blank = ' ';
5395
5396     /* Prepare the init/nuke hooks */
5397     newterm->init_hook = Term_init_cocoa;
5398     newterm->nuke_hook = Term_nuke_cocoa;
5399
5400     /* Prepare the function hooks */
5401     newterm->xtra_hook = Term_xtra_cocoa;
5402     newterm->wipe_hook = Term_wipe_cocoa;
5403     newterm->curs_hook = Term_curs_cocoa;
5404     newterm->bigcurs_hook = Term_bigcurs_cocoa;
5405     newterm->text_hook = Term_text_cocoa;
5406     newterm->pict_hook = Term_pict_cocoa;
5407     /* newterm->mbcs_hook = Term_mbcs_cocoa; */
5408
5409     /* Global pointer */
5410     angband_term[i] = newterm;
5411
5412     return newterm;
5413 }
5414
5415 /**
5416  * Load preferences from preferences file for current host+current user+
5417  * current application.
5418  */
5419 static void load_prefs(void)
5420 {
5421     NSUserDefaults *defs = [NSUserDefaults angbandDefaults];
5422
5423     /* Make some default defaults */
5424     NSMutableArray *defaultTerms = [[NSMutableArray alloc] init];
5425
5426     /*
5427      * The following default rows/cols were determined experimentally by first
5428      * finding the ideal window/font size combinations. But because of awful
5429      * temporal coupling in Term_init_cocoa(), it's impossible to set up the
5430      * defaults there, so we do it this way.
5431      */
5432     for (NSUInteger i = 0; i < ANGBAND_TERM_MAX; i++) {
5433         int columns, rows;
5434         BOOL visible = YES;
5435
5436         switch (i) {
5437         case 0:
5438             columns = 129;
5439             rows = 32;
5440             break;
5441         case 1:
5442             columns = 84;
5443             rows = 20;
5444             break;
5445         case 2:
5446             columns = 42;
5447             rows = 24;
5448             break;
5449         case 3:
5450             columns = 42;
5451             rows = 20;
5452             break;
5453         case 4:
5454             columns = 42;
5455             rows = 16;
5456             break;
5457         case 5:
5458             columns = 84;
5459             rows = 20;
5460             break;
5461         default:
5462             columns = 80;
5463             rows = 24;
5464             visible = NO;
5465             break;
5466         }
5467
5468         NSDictionary *standardTerm =
5469             [NSDictionary dictionaryWithObjectsAndKeys:
5470                           [NSNumber numberWithInt: rows], AngbandTerminalRowsDefaultsKey,
5471                           [NSNumber numberWithInt: columns], AngbandTerminalColumnsDefaultsKey,
5472                           [NSNumber numberWithBool: visible], AngbandTerminalVisibleDefaultsKey,
5473                           nil];
5474         [defaultTerms addObject: standardTerm];
5475     }
5476
5477     NSDictionary *defaults = [[NSDictionary alloc] initWithObjectsAndKeys:
5478 #ifdef JP
5479                               @"Osaka", @"FontName",
5480 #else
5481                               @"Menlo", @"FontName",
5482 #endif
5483                               [NSNumber numberWithFloat:13.f], @"FontSize",
5484                               [NSNumber numberWithInt:60], AngbandFrameRateDefaultsKey,
5485                               [NSNumber numberWithBool:YES], AngbandSoundDefaultsKey,
5486                               [NSNumber numberWithInt:GRAPHICS_NONE], AngbandGraphicsDefaultsKey,
5487                               [NSNumber numberWithBool:YES], AngbandBigTileDefaultsKey,
5488                               defaultTerms, AngbandTerminalsDefaultsKey,
5489                               nil];
5490     [defs registerDefaults:defaults];
5491
5492     /* Preferred graphics mode */
5493     graf_mode_req = [defs integerForKey:AngbandGraphicsDefaultsKey];
5494     if (graphics_will_be_enabled() &&
5495         [defs boolForKey:AngbandBigTileDefaultsKey] == YES) {
5496         use_bigtile = TRUE;
5497         arg_bigtile = TRUE;
5498     } else {
5499         use_bigtile = FALSE;
5500         arg_bigtile = FALSE;
5501     }
5502
5503     /* Use sounds; set the Angband global */
5504     if ([defs boolForKey:AngbandSoundDefaultsKey] == YES) {
5505         use_sound = TRUE;
5506         [AngbandSoundCatalog sharedSounds].enabled = YES;
5507     } else {
5508         use_sound = FALSE;
5509         [AngbandSoundCatalog sharedSounds].enabled = NO;
5510     }
5511
5512     /* fps */
5513     frames_per_second = [defs integerForKey:AngbandFrameRateDefaultsKey];
5514
5515     /* Font */
5516     [AngbandContext
5517         setDefaultFont:[NSFont fontWithName:[defs valueForKey:@"FontName-0"]
5518                                size:[defs floatForKey:@"FontSize-0"]]];
5519     if (! [AngbandContext defaultFont])
5520         [AngbandContext
5521             setDefaultFont:[NSFont fontWithName:@"Menlo" size:13.]];
5522 }
5523
5524 /**
5525  * Play sound effects asynchronously.  Select a sound from any available
5526  * for the required event, and bridge to Cocoa to play it.
5527  */
5528 static void play_sound(int event)
5529 {
5530     [[AngbandSoundCatalog sharedSounds] playSound:event];
5531 }
5532
5533 /**
5534  * Allocate the primary Angband terminal and activate it.  Allocate the other
5535  * Angband terminals.
5536  */
5537 static void init_windows(void)
5538 {
5539     /* Create the primary window */
5540     term *primary = term_data_link(0);
5541
5542     /* Prepare to create any additional windows */
5543     for (int i = 1; i < ANGBAND_TERM_MAX; i++) {
5544         term_data_link(i);
5545     }
5546
5547     /* Activate the primary term */
5548     Term_activate(primary);
5549 }
5550
5551 /**
5552  * ------------------------------------------------------------------------
5553  * Main program
5554  * ------------------------------------------------------------------------ */
5555
5556 @implementation AngbandAppDelegate
5557
5558 @synthesize graphicsMenu=_graphicsMenu;
5559 @synthesize commandMenu=_commandMenu;
5560 @synthesize commandMenuTagMap=_commandMenuTagMap;
5561
5562 - (IBAction)newGame:sender
5563 {
5564     /* Game is in progress */
5565     game_in_progress = TRUE;
5566     new_game = TRUE;
5567 }
5568
5569 - (IBAction)editFont:sender
5570 {
5571     NSFontPanel *panel = [NSFontPanel sharedFontPanel];
5572     NSFont *termFont = [AngbandContext defaultFont];
5573
5574     int i;
5575     for (i=0; i < ANGBAND_TERM_MAX; i++) {
5576         AngbandContext *context =
5577             (__bridge AngbandContext*) (angband_term[i]->data);
5578         if ([context isKeyWindow]) {
5579             termFont = [context angbandViewFont];
5580             break;
5581         }
5582     }
5583
5584     [panel setPanelFont:termFont isMultiple:NO];
5585     [panel orderFront:self];
5586 }
5587
5588 /**
5589  * Implement NSObject's changeFont() method to receive a notification about the
5590  * changed font.  Note that, as of 10.14, changeFont() is deprecated in
5591  * NSObject - it will be removed at some point and the application delegate
5592  * will have to be declared as implementing the NSFontChanging protocol.
5593  */
5594 - (void)changeFont:(id)sender
5595 {
5596     int mainTerm;
5597     for (mainTerm=0; mainTerm < ANGBAND_TERM_MAX; mainTerm++) {
5598         AngbandContext *context =
5599             (__bridge AngbandContext*) (angband_term[mainTerm]->data);
5600         if ([context isKeyWindow]) {
5601             break;
5602         }
5603     }
5604
5605     /* Bug #1709: Only change font for angband windows */
5606     if (mainTerm == ANGBAND_TERM_MAX) return;
5607
5608     NSFont *oldFont = [AngbandContext defaultFont];
5609     NSFont *newFont = [sender convertFont:oldFont];
5610     if (! newFont) return; /*paranoia */
5611
5612     /* Store as the default font if we changed the first term */
5613     if (mainTerm == 0) {
5614         [AngbandContext setDefaultFont:newFont];
5615     }
5616
5617     /* Record it in the preferences */
5618     NSUserDefaults *defs = [NSUserDefaults angbandDefaults];
5619     [defs setValue:[newFont fontName] 
5620         forKey:[NSString stringWithFormat:@"FontName-%d", mainTerm]];
5621     [defs setFloat:[newFont pointSize]
5622         forKey:[NSString stringWithFormat:@"FontSize-%d", mainTerm]];
5623
5624     NSDisableScreenUpdates();
5625
5626     /* Update window */
5627     AngbandContext *angbandContext =
5628         (__bridge AngbandContext*) (angband_term[mainTerm]->data);
5629     [(id)angbandContext setSelectionFont:newFont adjustTerminal: YES];
5630
5631     NSEnableScreenUpdates();
5632
5633     if (mainTerm != 0 || ! redraw_for_tiles_or_term0_font()) {
5634         [(id)angbandContext requestRedraw];
5635     }
5636 }
5637
5638 - (IBAction)openGame:sender
5639 {
5640     @autoreleasepool {
5641         BOOL selectedSomething = NO;
5642         int panelResult;
5643
5644         /* Get where we think the save files are */
5645         NSURL *startingDirectoryURL =
5646             [NSURL fileURLWithPath:[NSString stringWithCString:ANGBAND_DIR_SAVE encoding:NSASCIIStringEncoding]
5647                    isDirectory:YES];
5648
5649         /* Set up an open panel */
5650         NSOpenPanel* panel = [NSOpenPanel openPanel];
5651         [panel setCanChooseFiles:YES];
5652         [panel setCanChooseDirectories:NO];
5653         [panel setResolvesAliases:YES];
5654         [panel setAllowsMultipleSelection:NO];
5655         [panel setTreatsFilePackagesAsDirectories:YES];
5656         [panel setDirectoryURL:startingDirectoryURL];
5657
5658         /* Run it */
5659         panelResult = [panel runModal];
5660         if (panelResult == NSOKButton)
5661         {
5662             NSArray* fileURLs = [panel URLs];
5663             if ([fileURLs count] > 0 && [[fileURLs objectAtIndex:0] isFileURL])
5664             {
5665                 NSURL* savefileURL = (NSURL *)[fileURLs objectAtIndex:0];
5666                 /*
5667                  * The path property doesn't do the right thing except for
5668                  * URLs with the file scheme. We had
5669                  * getFileSystemRepresentation here before, but that wasn't
5670                  * introduced until OS X 10.9.
5671                  */
5672                 selectedSomething = [[savefileURL path]
5673                                         getCString:savefile
5674                                         maxLength:sizeof savefile
5675                                         encoding:NSMacOSRomanStringEncoding];
5676             }
5677         }
5678
5679         if (selectedSomething)
5680         {
5681             /* Remember this so we can select it by default next time */
5682             record_current_savefile();
5683
5684             /* Game is in progress */
5685             game_in_progress = TRUE;
5686         }
5687     }
5688 }
5689
5690 - (IBAction)saveGame:sender
5691 {
5692     /* Hack -- Forget messages */
5693     msg_flag = FALSE;
5694     
5695     /* Save the game */
5696     do_cmd_save_game(FALSE);
5697     
5698     /*
5699      * Record the current save file so we can select it by default next time.
5700      * It's a little sketchy that this only happens when we save through the
5701      * menu; ideally game-triggered saves would trigger it too.
5702      */
5703     record_current_savefile();
5704 }
5705
5706 /**
5707  * Entry point for initializing Angband
5708  */
5709 - (void)beginGame
5710 {
5711     @autoreleasepool {
5712         /* Hooks in some "z-util.c" hooks */
5713         plog_aux = hook_plog;
5714         quit_aux = hook_quit;
5715
5716         /* Initialize file paths */
5717         prepare_paths_and_directories();
5718
5719         /* Note the "system" */
5720         ANGBAND_SYS = "coc";
5721
5722         /* Load possible graphics modes */
5723         init_graphics_modes();
5724
5725         /* Load preferences */
5726         load_prefs();
5727
5728         /* Prepare the windows */
5729         init_windows();
5730
5731         /* Set up game event handlers */
5732         /* init_display(); */
5733
5734         /* Register the sound hook */
5735         /* sound_hook = play_sound; */
5736
5737         /* Initialize some save file stuff */
5738         player_euid = geteuid();
5739         player_egid = getegid();
5740
5741         /* Initialise game */
5742         init_angband();
5743
5744         /* We are now initialized */
5745         initialized = TRUE;
5746
5747         /* Handle "open_when_ready" */
5748         handle_open_when_ready();
5749
5750         /* Handle pending events (most notably update) and flush input */
5751         Term_flush();
5752
5753         /*
5754          * Prompt the user; assume the splash screen is 80 x 23 and position
5755          * relative to that rather than center based on the full size of the
5756          * window.
5757          */
5758         int message_row = 23;
5759         Term_erase(0, message_row, 255);
5760         put_str(
5761 #ifdef JP
5762             "['ファイル' メニューから '新規' または '開く' を選択します]",
5763             message_row, (80 - 59) / 2
5764 #else
5765             "[Choose 'New' or 'Open' from the 'File' menu]",
5766             message_row, (80 - 45) / 2
5767 #endif
5768         );
5769         Term_fresh();
5770     }
5771
5772     while (!game_in_progress) {
5773         @autoreleasepool {
5774             NSEvent *event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:[NSDate distantFuture] inMode:NSDefaultRunLoopMode dequeue:YES];
5775             if (event) [NSApp sendEvent:event];
5776         }
5777     }
5778
5779     /*
5780      * Play a game -- "new_game" is set by "new", "open" or the open document
5781      * even handler as appropriate
5782      */
5783     Term_fresh();
5784     play_game(new_game);
5785
5786     quit(NULL);
5787 }
5788
5789 /**
5790  * Implement NSObject's validateMenuItem() method to override enabling or
5791  * disabling a menu item.  Note that, as of 10.14, validateMenuItem() is
5792  * deprecated in NSObject - it will be removed at some point and the
5793  * application delegate will have to be declared as implementing the
5794  * NSMenuItemValidation protocol.
5795  */
5796 - (BOOL)validateMenuItem:(NSMenuItem *)menuItem
5797 {
5798     SEL sel = [menuItem action];
5799     NSInteger tag = [menuItem tag];
5800
5801     if( tag >= AngbandWindowMenuItemTagBase && tag < AngbandWindowMenuItemTagBase + ANGBAND_TERM_MAX )
5802     {
5803         if( tag == AngbandWindowMenuItemTagBase )
5804         {
5805             /* The main window should always be available and visible */
5806             return YES;
5807         }
5808         else
5809         {
5810             /*
5811              * Another window is only usable after Term_init_cocoa() has
5812              * been called for it.  For Angband, if window_flag[i] is nonzero
5813              * then that has happened for window i.  For Hengband, that is
5814              * not the case so also test angband_term[i]->data.
5815              */
5816             NSInteger subwindowNumber = tag - AngbandWindowMenuItemTagBase;
5817             return (angband_term[subwindowNumber]->data != 0
5818                     && window_flag[subwindowNumber] > 0);
5819         }
5820
5821         return NO;
5822     }
5823
5824     if (sel == @selector(newGame:))
5825     {
5826         return ! game_in_progress;
5827     }
5828     else if (sel == @selector(editFont:))
5829     {
5830         return YES;
5831     }
5832     else if (sel == @selector(openGame:))
5833     {
5834         return ! game_in_progress;
5835     }
5836     else if (sel == @selector(setRefreshRate:) &&
5837              [[menuItem parentItem] tag] == 150)
5838     {
5839         NSInteger fps = [[NSUserDefaults standardUserDefaults] integerForKey:AngbandFrameRateDefaultsKey];
5840         [menuItem setState: ([menuItem tag] == fps)];
5841         return YES;
5842     }
5843     else if( sel == @selector(setGraphicsMode:) )
5844     {
5845         NSInteger requestedGraphicsMode = [[NSUserDefaults standardUserDefaults] integerForKey:AngbandGraphicsDefaultsKey];
5846         [menuItem setState: (tag == requestedGraphicsMode)];
5847         return YES;
5848     }
5849     else if( sel == @selector(toggleSound:) )
5850     {
5851         BOOL is_on = [[NSUserDefaults standardUserDefaults]
5852                          boolForKey:AngbandSoundDefaultsKey];
5853
5854         [menuItem setState: ((is_on) ? NSOnState : NSOffState)];
5855         return YES;
5856     }
5857     else if (sel == @selector(toggleWideTiles:)) {
5858         BOOL is_on = [[NSUserDefaults standardUserDefaults]
5859                          boolForKey:AngbandBigTileDefaultsKey];
5860
5861         [menuItem setState: ((is_on) ? NSOnState : NSOffState)];
5862         return YES;
5863     }
5864     else if( sel == @selector(sendAngbandCommand:) ||
5865              sel == @selector(saveGame:) )
5866     {
5867         /*
5868          * we only want to be able to send commands during an active game
5869          * after the birth screens
5870          */
5871         return !!game_in_progress && character_generated;
5872     }
5873     else return YES;
5874 }
5875
5876
5877 - (IBAction)setRefreshRate:(NSMenuItem *)menuItem
5878 {
5879     frames_per_second = [menuItem tag];
5880     [[NSUserDefaults angbandDefaults] setInteger:frames_per_second forKey:AngbandFrameRateDefaultsKey];
5881 }
5882
5883 - (void)setGraphicsMode:(NSMenuItem *)sender
5884 {
5885     /* We stashed the graphics mode ID in the menu item's tag */
5886     graf_mode_req = [sender tag];
5887
5888     /* Stash it in UserDefaults */
5889     [[NSUserDefaults angbandDefaults] setInteger:graf_mode_req forKey:AngbandGraphicsDefaultsKey];
5890
5891     if (! graphics_will_be_enabled()) {
5892         if (use_bigtile) {
5893             arg_bigtile = FALSE;
5894         }
5895     } else if ([[NSUserDefaults angbandDefaults] boolForKey:AngbandBigTileDefaultsKey] == YES &&
5896                ! use_bigtile) {
5897         arg_bigtile = TRUE;
5898     }
5899
5900     if (arg_bigtile != use_bigtile) {
5901         Term_activate(angband_term[0]);
5902         Term_resize(angband_term[0]->wid, angband_term[0]->hgt);
5903     }
5904     redraw_for_tiles_or_term0_font();
5905 }
5906
5907 - (void)selectWindow: (id)sender
5908 {
5909     NSInteger subwindowNumber =
5910         [(NSMenuItem *)sender tag] - AngbandWindowMenuItemTagBase;
5911     AngbandContext *context =
5912         (__bridge AngbandContext*) (angband_term[subwindowNumber]->data);
5913     [context.primaryWindow makeKeyAndOrderFront: self];
5914     [context saveWindowVisibleToDefaults: YES];
5915 }
5916
5917 - (IBAction) toggleSound: (NSMenuItem *) sender
5918 {
5919     BOOL is_on = (sender.state == NSOnState);
5920
5921     /* Toggle the state and update the Angband global and preferences. */
5922     if (is_on) {
5923         sender.state = NSOffState;
5924         use_sound = FALSE;
5925         [AngbandSoundCatalog sharedSounds].enabled = NO;
5926     } else {
5927         sender.state = NSOnState;
5928         use_sound = TRUE;
5929         [AngbandSoundCatalog sharedSounds].enabled = YES;
5930     }
5931     [[NSUserDefaults angbandDefaults] setBool:(! is_on)
5932                                       forKey:AngbandSoundDefaultsKey];
5933 }
5934
5935 - (IBAction)toggleWideTiles:(NSMenuItem *) sender
5936 {
5937     BOOL is_on = (sender.state == NSOnState);
5938
5939     /* Toggle the state and update the Angband globals and preferences. */
5940     sender.state = (is_on) ? NSOffState : NSOnState;
5941     [[NSUserDefaults angbandDefaults] setBool:(! is_on)
5942                                       forKey:AngbandBigTileDefaultsKey];
5943     if (graphics_are_enabled()) {
5944         arg_bigtile = (is_on) ? FALSE : TRUE;
5945         if (arg_bigtile != use_bigtile) {
5946             Term_activate(angband_term[0]);
5947             Term_resize(angband_term[0]->wid, angband_term[0]->hgt);
5948             redraw_for_tiles_or_term0_font();
5949         }
5950     }
5951 }
5952
5953 - (void)prepareWindowsMenu
5954 {
5955     @autoreleasepool {
5956         /*
5957          * Get the window menu with default items and add a separator and
5958          * item for the main window.
5959          */
5960         NSMenu *windowsMenu = [[NSApplication sharedApplication] windowsMenu];
5961         [windowsMenu addItem: [NSMenuItem separatorItem]];
5962
5963         NSString *title1 = [NSString stringWithCString:angband_term_name[0]
5964 #ifdef JP
5965                                      encoding:NSJapaneseEUCStringEncoding
5966 #else
5967                                      encoding:NSMacOSRomanStringEncoding
5968 #endif
5969         ];
5970         NSMenuItem *angbandItem = [[NSMenuItem alloc] initWithTitle:title1 action: @selector(selectWindow:) keyEquivalent: @"0"];
5971         [angbandItem setTarget: self];
5972         [angbandItem setTag: AngbandWindowMenuItemTagBase];
5973         [windowsMenu addItem: angbandItem];
5974
5975         /* Add items for the additional term windows */
5976         for( NSInteger i = 1; i < ANGBAND_TERM_MAX; i++ )
5977         {
5978             NSString *title = [NSString stringWithCString:angband_term_name[i]
5979 #ifdef JP
5980                                         encoding:NSJapaneseEUCStringEncoding
5981 #else
5982                                         encoding:NSMacOSRomanStringEncoding
5983 #endif
5984             ];
5985             NSString *keyEquivalent =
5986                 [NSString stringWithFormat: @"%ld", (long)i];
5987             NSMenuItem *windowItem =
5988                 [[NSMenuItem alloc] initWithTitle: title
5989                                     action: @selector(selectWindow:)
5990                                     keyEquivalent: keyEquivalent];
5991             [windowItem setTarget: self];
5992             [windowItem setTag: AngbandWindowMenuItemTagBase + i];
5993             [windowsMenu addItem: windowItem];
5994         }
5995     }
5996 }
5997
5998 /**
5999  *  Send a command to Angband via a menu item. This places the appropriate key
6000  * down events into the queue so that it seems like the user pressed them
6001  * (instead of trying to use the term directly).
6002  */
6003 - (void)sendAngbandCommand: (id)sender
6004 {
6005     NSMenuItem *menuItem = (NSMenuItem *)sender;
6006     NSString *command = [self.commandMenuTagMap objectForKey: [NSNumber numberWithInteger: [menuItem tag]]];
6007     AngbandContext* context =
6008         (__bridge AngbandContext*) (angband_term[0]->data);
6009     NSInteger windowNumber = [context.primaryWindow windowNumber];
6010
6011     /* Send a \ to bypass keymaps */
6012     NSEvent *escape = [NSEvent keyEventWithType: NSKeyDown
6013                                        location: NSZeroPoint
6014                                   modifierFlags: 0
6015                                       timestamp: 0.0
6016                                    windowNumber: windowNumber
6017                                         context: nil
6018                                      characters: @"\\"
6019                     charactersIgnoringModifiers: @"\\"
6020                                       isARepeat: NO
6021                                         keyCode: 0];
6022     [[NSApplication sharedApplication] postEvent: escape atStart: NO];
6023
6024     /* Send the actual command (from the original command set) */
6025     NSEvent *keyDown = [NSEvent keyEventWithType: NSKeyDown
6026                                         location: NSZeroPoint
6027                                    modifierFlags: 0
6028                                        timestamp: 0.0
6029                                     windowNumber: windowNumber
6030                                          context: nil
6031                                       characters: command
6032                      charactersIgnoringModifiers: command
6033                                        isARepeat: NO
6034                                          keyCode: 0];
6035     [[NSApplication sharedApplication] postEvent: keyDown atStart: NO];
6036 }
6037
6038 /**
6039  *  Set up the command menu dynamically, based on CommandMenu.plist.
6040  */
6041 - (void)prepareCommandMenu
6042 {
6043     @autoreleasepool {
6044         NSString *commandMenuPath =
6045             [[NSBundle mainBundle] pathForResource: @"CommandMenu"
6046                                    ofType: @"plist"];
6047         NSArray *commandMenuItems =
6048             [[NSArray alloc] initWithContentsOfFile: commandMenuPath];
6049         NSMutableDictionary *angbandCommands =
6050             [[NSMutableDictionary alloc] init];
6051         NSString *tblname = @"CommandMenu";
6052         NSInteger tagOffset = 0;
6053
6054         for( NSDictionary *item in commandMenuItems )
6055         {
6056             BOOL useShiftModifier =
6057                 [[item valueForKey: @"ShiftModifier"] boolValue];
6058             BOOL useOptionModifier =
6059                 [[item valueForKey: @"OptionModifier"] boolValue];
6060             NSUInteger keyModifiers = NSCommandKeyMask;
6061             keyModifiers |= (useShiftModifier) ? NSShiftKeyMask : 0;
6062             keyModifiers |= (useOptionModifier) ? NSAlternateKeyMask : 0;
6063
6064             NSString *lookup = [item valueForKey: @"Title"];
6065             NSString *title = NSLocalizedStringWithDefaultValue(
6066                 lookup, tblname, [NSBundle mainBundle], lookup, @"");
6067             NSString *key = [item valueForKey: @"KeyEquivalent"];
6068             NSMenuItem *menuItem =
6069                 [[NSMenuItem alloc] initWithTitle: title
6070                                     action: @selector(sendAngbandCommand:)
6071                                     keyEquivalent: key];
6072             [menuItem setTarget: self];
6073             [menuItem setKeyEquivalentModifierMask: keyModifiers];
6074             [menuItem setTag: AngbandCommandMenuItemTagBase + tagOffset];
6075             [self.commandMenu addItem: menuItem];
6076
6077             NSString *angbandCommand = [item valueForKey: @"AngbandCommand"];
6078             [angbandCommands setObject: angbandCommand
6079                              forKey: [NSNumber numberWithInteger: [menuItem tag]]];
6080             tagOffset++;
6081         }
6082
6083         self.commandMenuTagMap = [[NSDictionary alloc]
6084                                      initWithDictionary: angbandCommands];
6085     }
6086 }
6087
6088 - (void)awakeFromNib
6089 {
6090     [super awakeFromNib];
6091
6092     [self prepareWindowsMenu];
6093     [self prepareCommandMenu];
6094 }
6095
6096 - (void)applicationDidFinishLaunching:sender
6097 {
6098     [self beginGame];
6099     
6100     /*
6101      * Once beginGame finished, the game is over - that's how Angband works,
6102      * and we should quit
6103      */
6104     game_is_finished = TRUE;
6105     [NSApp terminate:self];
6106 }
6107
6108 - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
6109 {
6110     if (p_ptr->playing == FALSE || game_is_finished == TRUE)
6111     {
6112         quit_when_ready = true;
6113         return NSTerminateNow;
6114     }
6115     else if (! inkey_flag)
6116     {
6117         /* For compatibility with other ports, do not quit in this case */
6118         return NSTerminateCancel;
6119     }
6120     else
6121     {
6122         /* Stop playing */
6123         /* player->upkeep->playing = FALSE; */
6124
6125         /*
6126          * Post an escape event so that we can return from our get-key-event
6127          * function
6128          */
6129         wakeup_event_loop();
6130         quit_when_ready = true;
6131         /*
6132          * Must return Cancel, not Later, because we need to get out of the
6133          * run loop and back to Angband's loop
6134          */
6135         return NSTerminateCancel;
6136     }
6137 }
6138
6139 /**
6140  * Dynamically build the Graphics menu
6141  */
6142 - (void)menuNeedsUpdate:(NSMenu *)menu {
6143     
6144     /* Only the graphics menu is dynamic */
6145     if (! [menu isEqual:self.graphicsMenu])
6146         return;
6147     
6148     /*
6149      * If it's non-empty, then we've already built it. Currently graphics modes
6150      * won't change once created; if they ever can we can remove this check.
6151      * Note that the check mark does change, but that's handled in
6152      * validateMenuItem: instead of menuNeedsUpdate:
6153      */
6154     if ([menu numberOfItems] > 0)
6155         return;
6156     
6157     /* This is the action for all these menu items */
6158     SEL action = @selector(setGraphicsMode:);
6159     
6160     /* Add an initial Classic ASCII menu item */
6161     NSString *tblname = @"GraphicsMenu";
6162     NSString *key = @"Classic ASCII";
6163     NSString *title = NSLocalizedStringWithDefaultValue(
6164         key, tblname, [NSBundle mainBundle], key, @"");
6165     NSMenuItem *classicItem = [menu addItemWithTitle:title action:action keyEquivalent:@""];
6166     [classicItem setTag:GRAPHICS_NONE];
6167     
6168     /* Walk through the list of graphics modes */
6169     if (graphics_modes) {
6170         NSInteger i;
6171
6172         for (i=0; graphics_modes[i].pNext; i++)
6173         {
6174             const graphics_mode *graf = &graphics_modes[i];
6175
6176             if (graf->grafID == GRAPHICS_NONE) {
6177                 continue;
6178             }
6179             /* Make the title. NSMenuItem throws on a nil title, so ensure it's
6180                    * not nil. */
6181             key = [[NSString alloc] initWithUTF8String:graf->menuname];
6182             title = NSLocalizedStringWithDefaultValue(
6183                 key, tblname, [NSBundle mainBundle], key, @"");
6184
6185             /* Make the item */
6186             NSMenuItem *item = [menu addItemWithTitle:title action:action keyEquivalent:@""];
6187             [item setTag:graf->grafID];
6188         }
6189     }
6190 }
6191
6192 /**
6193  * Delegate method that gets called if we're asked to open a file.
6194  */
6195 - (void)application:(NSApplication *)sender openFiles:(NSArray *)filenames
6196 {
6197     /* Can't open a file once we've started */
6198     if (game_in_progress) {
6199         [[NSApplication sharedApplication]
6200             replyToOpenOrPrint:NSApplicationDelegateReplyFailure];
6201         return;
6202     }
6203
6204     /* We can only open one file. Use the last one. */
6205     NSString *file = [filenames lastObject];
6206     if (! file) {
6207         [[NSApplication sharedApplication]
6208             replyToOpenOrPrint:NSApplicationDelegateReplyFailure];
6209         return;
6210     }
6211
6212     /* Put it in savefile */
6213     if (! [file getFileSystemRepresentation:savefile maxLength:sizeof savefile]) {
6214         [[NSApplication sharedApplication]
6215             replyToOpenOrPrint:NSApplicationDelegateReplyFailure];
6216         return;
6217     }
6218
6219     game_in_progress = TRUE;
6220
6221     /*
6222      * Wake us up in case this arrives while we're sitting at the Welcome
6223      * screen!
6224      */
6225     wakeup_event_loop();
6226
6227     [[NSApplication sharedApplication]
6228         replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
6229 }
6230
6231 @end
6232
6233 int main(int argc, char* argv[])
6234 {
6235     NSApplicationMain(argc, (void*)argv);
6236     return (0);
6237 }
6238
6239 #endif /* MACINTOSH || MACH_O_COCOA */