OSDN Git Service

d2dd9ecd2f68914eb6ae3da355770078b33cc3a6
[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 /* An AngbandContext represents a logical Term (i.e. what Angband thinks is
1808  * a window). */
1809 @interface AngbandContext : NSObject <NSWindowDelegate>
1810 {
1811 @public
1812
1813     /* The Angband term */
1814     term *terminal;
1815
1816 @private
1817     /* Is the last time we drew, so we can throttle drawing. */
1818     CFAbsoluteTime lastRefreshTime;
1819
1820     /* Flags whether or not a fullscreen transition is in progress. */
1821     BOOL inFullscreenTransition;
1822
1823     /* Our view */
1824     AngbandView *angbandView;
1825 }
1826
1827 /* Column and row counts, by default 80 x 24 */
1828 @property (readonly) int cols;
1829 @property (readonly) int rows;
1830
1831 /* The size of the border between the window edge and the contents */
1832 @property (readonly) NSSize borderSize;
1833
1834 /* The font of this context */
1835 @property NSFont *angbandViewFont;
1836
1837 /* The size of one tile */
1838 @property (readonly) NSSize tileSize;
1839
1840 /* Font's ascender and descender */
1841 @property (readonly) CGFloat fontAscender;
1842 @property (readonly) CGFloat fontDescender;
1843
1844 /*
1845  * These are the number of columns before or after, respectively, a text
1846  * change that may need to be redrawn.
1847  */
1848 @property (readonly) int nColPre;
1849 @property (readonly) int nColPost;
1850
1851 /* If this context owns a window, here it is. */
1852 @property NSWindow *primaryWindow;
1853
1854 /* Holds our version of the contents of the terminal. */
1855 @property TerminalContents *contents;
1856
1857 /*
1858  * Marks which locations have been changed by the text_hook, pict_hook,
1859  * wipe_hook, curs_hook, and bigcurs_hhok callbacks on the terminal since
1860  * the last call to xtra_hook with TERM_XTRA_FRESH.
1861  */
1862 @property TerminalChanges *changes;
1863
1864 @property (nonatomic, assign) BOOL hasSubwindowFlags;
1865 @property (nonatomic, assign) BOOL windowVisibilityChecked;
1866
1867 - (void)resizeWithColumns:(int)nCol rows:(int)nRow;
1868
1869 /**
1870  * Based on what has been marked as changed, inform AppKit of the bounding
1871  * rectangles for the changed areas.
1872  */
1873 - (void)computeInvalidRects;
1874
1875 - (void)drawRect:(NSRect)rect inView:(NSView *)view;
1876
1877 /* Called at initialization to set the term */
1878 - (void)setTerm:(term *)t;
1879
1880 /* Called when the context is going down. */
1881 - (void)dispose;
1882
1883 /*
1884  * Return the rect in view coordinates for the block of cells whose upper
1885  * left corner is (x,y).
1886  */
1887 - (NSRect)viewRectForCellBlockAtX:(int)x y:(int)y width:(int)w height:(int)h;
1888
1889 /* Draw the given wide character into the given tile rect. */
1890 - (void)drawWChar:(wchar_t)wchar inRect:(NSRect)tile screenFont:(NSFont*)font
1891           context:(CGContextRef)ctx;
1892
1893 /* Returns the primary window for this angband context, creating it if
1894  * necessary */
1895 - (NSWindow *)makePrimaryWindow;
1896
1897 /* Handle becoming the main window */
1898 - (void)windowDidBecomeMain:(NSNotification *)notification;
1899
1900 /* Return whether the context's primary window is ordered in or not */
1901 - (BOOL)isOrderedIn;
1902
1903 /*
1904  * Return whether the context's primary window is the main window.
1905  * Since the terminals other than terminal 0 are configured as panels in
1906  * Hengband, this will only be true for terminal 0.
1907  */
1908 - (BOOL)isMainWindow;
1909
1910 /*
1911  * Return whether the context's primary window is the destination for key
1912  * input.
1913  */
1914 - (BOOL)isKeyWindow;
1915
1916 /* Invalidate the whole image */
1917 - (void)setNeedsDisplay:(BOOL)val;
1918
1919 /* Invalidate part of the image, with the rect expressed in view coordinates */
1920 - (void)setNeedsDisplayInRect:(NSRect)rect;
1921
1922 /* Display (flush) our Angband views */
1923 - (void)displayIfNeeded;
1924
1925 /* Resize context to size of contentRect, and optionally save size to
1926  * defaults */
1927 - (void)resizeTerminalWithContentRect: (NSRect)contentRect saveToDefaults: (BOOL)saveToDefaults;
1928
1929 /*
1930  * Change the minimum size and size increments for the window associated with
1931  * the context.  termIdx is the index for the terminal:  pass it so this
1932  * function can be used when self->terminal has not yet been set.
1933  */
1934 - (void)constrainWindowSize:(int)termIdx;
1935
1936 - (void)saveWindowVisibleToDefaults: (BOOL)windowVisible;
1937 - (BOOL)windowVisibleUsingDefaults;
1938
1939 /* Class methods */
1940 /**
1941  * Gets the default font for all contexts.  Currently not declaring this as
1942  * a class property for compatibility with versions of Xcode prior to 8.
1943  */
1944 + (NSFont*)defaultFont;
1945 /**
1946  * Sets the default font for all contexts.
1947  */
1948 + (void)setDefaultFont:(NSFont*)font;
1949
1950 /* Internal methods */
1951 /* Set the title for the primary window. */
1952 - (void)setDefaultTitle:(int)termIdx;
1953
1954 @end
1955
1956 /**
1957  * Generate a mask for the subwindow flags. The mask is just a safety check to
1958  * make sure that our windows show and hide as expected.  This function allows
1959  * for future changes to the set of flags without needed to update it here
1960  * (unless the underlying types change).
1961  */
1962 u32b AngbandMaskForValidSubwindowFlags(void)
1963 {
1964     int windowFlagBits = sizeof(*(window_flag)) * CHAR_BIT;
1965     int maxBits = MIN( 16, windowFlagBits );
1966     u32b mask = 0;
1967
1968     for( int i = 0; i < maxBits; i++ )
1969     {
1970         if( window_flag_desc[i] != NULL )
1971         {
1972             mask |= (1 << i);
1973         }
1974     }
1975
1976     return mask;
1977 }
1978
1979 /**
1980  * Check for changes in the subwindow flags and update window visibility.
1981  * This seems to be called for every user event, so we don't
1982  * want to do any unnecessary hiding or showing of windows.
1983  */
1984 static void AngbandUpdateWindowVisibility(void)
1985 {
1986     /* Because this function is called frequently, we'll make the mask static.
1987          * It doesn't change between calls, as the flags themselves are hardcoded */
1988     static u32b validWindowFlagsMask = 0;
1989
1990     if( validWindowFlagsMask == 0 )
1991     {
1992         validWindowFlagsMask = AngbandMaskForValidSubwindowFlags();
1993     }
1994
1995     /* Loop through all of the subwindows and see if there is a change in the
1996          * flags. If so, show or hide the corresponding window. We don't care about
1997          * the flags themselves; we just want to know if any are set. */
1998     for( int i = 1; i < ANGBAND_TERM_MAX; i++ )
1999     {
2000         AngbandContext *angbandContext =
2001             (__bridge AngbandContext*) (angband_term[i]->data);
2002
2003         if( angbandContext == nil )
2004         {
2005             continue;
2006         }
2007
2008         /* This horrible mess of flags is so that we can try to maintain some
2009                  * user visibility preference. This should allow the user a window and
2010                  * have it stay closed between application launches. However, this
2011                  * means that when a subwindow is turned on, it will no longer appear
2012                  * automatically. Angband has no concept of user control over window
2013                  * visibility, other than the subwindow flags. */
2014         if( !angbandContext.windowVisibilityChecked )
2015         {
2016             if( [angbandContext windowVisibleUsingDefaults] )
2017             {
2018                 [angbandContext.primaryWindow orderFront: nil];
2019                 angbandContext.windowVisibilityChecked = YES;
2020             }
2021             else
2022             {
2023                 [angbandContext.primaryWindow close];
2024                 angbandContext.windowVisibilityChecked = NO;
2025             }
2026         }
2027         else
2028         {
2029             BOOL termHasSubwindowFlags = ((window_flag[i] & validWindowFlagsMask) > 0);
2030
2031             if( angbandContext.hasSubwindowFlags && !termHasSubwindowFlags )
2032             {
2033                 [angbandContext.primaryWindow close];
2034                 angbandContext.hasSubwindowFlags = NO;
2035                 [angbandContext saveWindowVisibleToDefaults: NO];
2036             }
2037             else if( !angbandContext.hasSubwindowFlags && termHasSubwindowFlags )
2038             {
2039                 [angbandContext.primaryWindow orderFront: nil];
2040                 angbandContext.hasSubwindowFlags = YES;
2041                 [angbandContext saveWindowVisibleToDefaults: YES];
2042             }
2043         }
2044     }
2045
2046     /* Make the main window key so that user events go to the right spot */
2047     AngbandContext *mainWindow =
2048         (__bridge AngbandContext*) (angband_term[0]->data);
2049     [mainWindow.primaryWindow makeKeyAndOrderFront: nil];
2050 }
2051
2052 /**
2053  * ------------------------------------------------------------------------
2054  * Graphics support
2055  * ------------------------------------------------------------------------ */
2056
2057 /**
2058  * The tile image
2059  */
2060 static CGImageRef pict_image;
2061
2062 /**
2063  * Numbers of rows and columns in a tileset,
2064  * calculated by the PICT/PNG loading code
2065  */
2066 static int pict_cols = 0;
2067 static int pict_rows = 0;
2068
2069 /**
2070  * Requested graphics mode (as a grafID).
2071  * The current mode is stored in current_graphics_mode.
2072  */
2073 static int graf_mode_req = 0;
2074
2075 /**
2076  * Helper function to check the various ways that graphics can be enabled,
2077  * guarding against NULL
2078  */
2079 static BOOL graphics_are_enabled(void)
2080 {
2081     return current_graphics_mode
2082         && current_graphics_mode->grafID != GRAPHICS_NONE;
2083 }
2084
2085 /**
2086  * Like graphics_are_enabled(), but test the requested graphics mode.
2087  */
2088 static BOOL graphics_will_be_enabled(void)
2089 {
2090     if (graf_mode_req == GRAPHICS_NONE) {
2091         return NO;
2092     }
2093
2094     graphics_mode *new_mode = get_graphics_mode(graf_mode_req);
2095     return new_mode && new_mode->grafID != GRAPHICS_NONE;
2096 }
2097
2098 /**
2099  * Hack -- game in progress
2100  */
2101 static Boolean game_in_progress = FALSE;
2102
2103
2104 #pragma mark Prototypes
2105 static BOOL redraw_for_tiles_or_term0_font(void);
2106 static void wakeup_event_loop(void);
2107 static void hook_plog(const char *str);
2108 static void hook_quit(const char * str);
2109 static NSString* get_lib_directory(void);
2110 static NSString* get_doc_directory(void);
2111 static NSString* AngbandCorrectedDirectoryPath(NSString *originalPath);
2112 static void prepare_paths_and_directories(void);
2113 static void load_prefs(void);
2114 static void init_windows(void);
2115 static void handle_open_when_ready(void);
2116 static void play_sound(int event);
2117 static BOOL check_events(int wait);
2118 static BOOL send_event(NSEvent *event);
2119 static void set_color_for_index(int idx);
2120 static void record_current_savefile(void);
2121
2122 /**
2123  * Available values for 'wait'
2124  */
2125 #define CHECK_EVENTS_DRAIN -1
2126 #define CHECK_EVENTS_NO_WAIT    0
2127 #define CHECK_EVENTS_WAIT 1
2128
2129
2130 /**
2131  * Note when "open"/"new" become valid
2132  */
2133 static bool initialized = FALSE;
2134
2135 /* Methods for getting the appropriate NSUserDefaults */
2136 @interface NSUserDefaults (AngbandDefaults)
2137 + (NSUserDefaults *)angbandDefaults;
2138 @end
2139
2140 @implementation NSUserDefaults (AngbandDefaults)
2141 + (NSUserDefaults *)angbandDefaults
2142 {
2143     return [NSUserDefaults standardUserDefaults];
2144 }
2145 @end
2146
2147 /* Methods for pulling images out of the Angband bundle (which may be separate
2148  * from the current bundle in the case of a screensaver */
2149 @interface NSImage (AngbandImages)
2150 + (NSImage *)angbandImage:(NSString *)name;
2151 @end
2152
2153 /* The NSView subclass that draws our Angband image */
2154 @interface AngbandView : NSView {
2155 @private
2156     NSBitmapImageRep *cacheForResize;
2157     NSRect cacheBounds;
2158 }
2159
2160 @property (nonatomic, weak) AngbandContext *angbandContext;
2161
2162 @end
2163
2164 @implementation NSImage (AngbandImages)
2165
2166 /* Returns an image in the resource directoy of the bundle containing the
2167  * Angband view class. */
2168 + (NSImage *)angbandImage:(NSString *)name
2169 {
2170     NSBundle *bundle = [NSBundle bundleForClass:[AngbandView class]];
2171     NSString *path = [bundle pathForImageResource:name];
2172     return (path) ? [[NSImage alloc] initByReferencingFile:path] : nil;
2173 }
2174
2175 @end
2176
2177
2178 @implementation AngbandContext
2179
2180 - (NSSize)baseSize
2181 {
2182     /*
2183      * We round the base size down. If we round it up, I believe we may end up
2184      * with pixels that nobody "owns" that may accumulate garbage. In general
2185      * rounding down is harmless, because any lost pixels may be sopped up by
2186      * the border.
2187      */
2188     return NSMakeSize(
2189         floor(self.cols * self.tileSize.width + 2 * self.borderSize.width),
2190         floor(self.rows * self.tileSize.height + 2 * self.borderSize.height));
2191 }
2192
2193 /* qsort-compatible compare function for CGSizes */
2194 static int compare_advances(const void *ap, const void *bp)
2195 {
2196     const CGSize *a = ap, *b = bp;
2197     return (a->width > b->width) - (a->width < b->width);
2198 }
2199
2200 /**
2201  * Precompute certain metrics (tileSize, fontAscender, fontDescender, nColPre,
2202  * and nColPost) for the current font.
2203  */
2204 - (void)updateGlyphInfo
2205 {
2206     NSFont *screenFont = [self.angbandViewFont screenFont];
2207
2208     /* Generate a string containing each MacRoman character */
2209     /*
2210      * Here and below, dynamically allocate working arrays rather than put them
2211      * on the stack in case limited stack space is an issue.
2212      */
2213     unsigned char *latinString = malloc(GLYPH_COUNT);
2214     if (latinString == 0) {
2215         NSException *exc = [NSException exceptionWithName:@"OutOfMemory"
2216                                         reason:@"latinString in updateGlyphInfo"
2217                                         userInfo:nil];
2218         @throw exc;
2219     }
2220     size_t i;
2221     for (i=0; i < GLYPH_COUNT; i++) latinString[i] = (unsigned char)i;
2222
2223     /* Turn that into unichar. Angband uses ISO Latin 1. */
2224     NSString *allCharsString = [[NSString alloc] initWithBytes:latinString
2225         length:GLYPH_COUNT encoding:NSISOLatin1StringEncoding];
2226     unichar *unicharString = malloc(GLYPH_COUNT * sizeof(unichar));
2227     if (unicharString == 0) {
2228         free(latinString);
2229         NSException *exc = [NSException exceptionWithName:@"OutOfMemory"
2230                                         reason:@"unicharString in updateGlyphInfo"
2231                                         userInfo:nil];
2232         @throw exc;
2233     }
2234     unicharString[0] = 0;
2235     [allCharsString getCharacters:unicharString range:NSMakeRange(0, MIN(GLYPH_COUNT, [allCharsString length]))];
2236     allCharsString = nil;
2237     free(latinString);
2238
2239     /* Get glyphs */
2240     CGGlyph *glyphArray = calloc(GLYPH_COUNT, sizeof(CGGlyph));
2241     if (glyphArray == 0) {
2242         free(unicharString);
2243         NSException *exc = [NSException exceptionWithName:@"OutOfMemory"
2244                                         reason:@"glyphArray in updateGlyphInfo"
2245                                         userInfo:nil];
2246         @throw exc;
2247     }
2248     CTFontGetGlyphsForCharacters((CTFontRef)screenFont, unicharString,
2249                                  glyphArray, GLYPH_COUNT);
2250     free(unicharString);
2251
2252     /* Get advances. Record the max advance. */
2253     CGSize *advances = malloc(GLYPH_COUNT * sizeof(CGSize));
2254     if (advances == 0) {
2255         free(glyphArray);
2256         NSException *exc = [NSException exceptionWithName:@"OutOfMemory"
2257                                         reason:@"advances in updateGlyphInfo"
2258                                         userInfo:nil];
2259         @throw exc;
2260     }
2261     CTFontGetAdvancesForGlyphs(
2262         (CTFontRef)screenFont, kCTFontHorizontalOrientation, glyphArray,
2263         advances, GLYPH_COUNT);
2264     CGFloat *glyphWidths = malloc(GLYPH_COUNT * sizeof(CGFloat));
2265     if (glyphWidths == 0) {
2266         free(glyphArray);
2267         free(advances);
2268         NSException *exc = [NSException exceptionWithName:@"OutOfMemory"
2269                                         reason:@"glyphWidths in updateGlyphInfo"
2270                                         userInfo:nil];
2271         @throw exc;
2272     }
2273     for (i=0; i < GLYPH_COUNT; i++) {
2274         glyphWidths[i] = advances[i].width;
2275     }
2276
2277     /*
2278      * For good non-mono-font support, use the median advance. Start by sorting
2279      * all advances.
2280      */
2281     qsort(advances, GLYPH_COUNT, sizeof *advances, compare_advances);
2282
2283     /* Skip over any initially empty run */
2284     size_t startIdx;
2285     for (startIdx = 0; startIdx < GLYPH_COUNT; startIdx++)
2286     {
2287         if (advances[startIdx].width > 0) break;
2288     }
2289
2290     /* Pick the center to find the median */
2291     CGFloat medianAdvance = 0;
2292     /* In case we have all zero advances for some reason */
2293     if (startIdx < GLYPH_COUNT)
2294     {
2295         medianAdvance = advances[(startIdx + GLYPH_COUNT)/2].width;
2296     }
2297
2298     free(advances);
2299
2300     /*
2301      * Record the ascender and descender.  Some fonts, for instance DIN
2302      * Condensed and Rockwell in 10.14, the ascent on '@' exceeds that
2303      * reported by [screenFont ascender].  Get the overall bounding box
2304      * for the glyphs and use that instead of the ascender and descender
2305      * values if the bounding box result extends farther from the baseline.
2306      */
2307     CGRect bounds = CTFontGetBoundingRectsForGlyphs(
2308         (CTFontRef) screenFont, kCTFontHorizontalOrientation, glyphArray,
2309         NULL, GLYPH_COUNT);
2310     self->_fontAscender = [screenFont ascender];
2311     if (self->_fontAscender < bounds.origin.y + bounds.size.height) {
2312         self->_fontAscender = bounds.origin.y + bounds.size.height;
2313     }
2314     self->_fontDescender = [screenFont descender];
2315     if (self->_fontDescender > bounds.origin.y) {
2316         self->_fontDescender = bounds.origin.y;
2317     }
2318
2319     /*
2320      * Record the tile size.  Round both values up to have tile boundaries
2321      * match pixel boundaries.
2322      */
2323     self->_tileSize.width = ceil(medianAdvance);
2324     self->_tileSize.height = ceil(self.fontAscender - self.fontDescender);
2325
2326     /*
2327      * Determine whether neighboring columns need to be redrawn when a
2328      * character changes.
2329      */
2330     CGRect *boxes = malloc(GLYPH_COUNT * sizeof(CGRect));
2331     if (boxes == 0) {
2332         free(glyphWidths);
2333         free(glyphArray);
2334         NSException *exc = [NSException exceptionWithName:@"OutOfMemory"
2335                                         reason:@"boxes in updateGlyphInfo"
2336                                         userInfo:nil];
2337         @throw exc;
2338     }
2339     CGFloat beyond_right = 0.;
2340     CGFloat beyond_left = 0.;
2341     CTFontGetBoundingRectsForGlyphs(
2342         (CTFontRef)screenFont,
2343         kCTFontHorizontalOrientation,
2344         glyphArray,
2345         boxes,
2346         GLYPH_COUNT);
2347     for (i = 0; i < GLYPH_COUNT; i++) {
2348         /* Account for the compression and offset used by drawWChar(). */
2349         CGFloat compression, offset;
2350         CGFloat v;
2351
2352         if (glyphWidths[i] <= self.tileSize.width) {
2353             compression = 1.;
2354             offset = 0.5 * (self.tileSize.width - glyphWidths[i]);
2355         } else {
2356             compression = self.tileSize.width / glyphWidths[i];
2357             offset = 0.;
2358         }
2359         v = (offset + boxes[i].origin.x) * compression;
2360         if (beyond_left > v) {
2361             beyond_left = v;
2362         }
2363         v = (offset + boxes[i].origin.x + boxes[i].size.width) * compression;
2364         if (beyond_right < v) {
2365             beyond_right = v;
2366         }
2367     }
2368     free(boxes);
2369     self->_nColPre = ceil(-beyond_left / self.tileSize.width);
2370     if (beyond_right > self.tileSize.width) {
2371         self->_nColPost =
2372             ceil((beyond_right - self.tileSize.width) / self.tileSize.width);
2373     } else {
2374         self->_nColPost = 0;
2375     }
2376
2377     free(glyphWidths);
2378     free(glyphArray);
2379 }
2380
2381
2382 - (void)requestRedraw
2383 {
2384     if (! self->terminal) return;
2385     
2386     term *old = Term;
2387     
2388     /* Activate the term */
2389     Term_activate(self->terminal);
2390     
2391     /* Redraw the contents */
2392     Term_redraw();
2393     
2394     /* Flush the output */
2395     Term_fresh();
2396     
2397     /* Restore the old term */
2398     Term_activate(old);
2399 }
2400
2401 - (void)setTerm:(term *)t
2402 {
2403     self->terminal = t;
2404 }
2405
2406 /**
2407  * If we're trying to limit ourselves to a certain number of frames per second,
2408  * then compute how long it's been since we last drew, and then wait until the
2409  * next frame has passed. */
2410 - (void)throttle
2411 {
2412     if (frames_per_second > 0)
2413     {
2414         CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
2415         CFTimeInterval timeSinceLastRefresh = now - self->lastRefreshTime;
2416         CFTimeInterval timeUntilNextRefresh = (1. / (double)frames_per_second) - timeSinceLastRefresh;
2417         
2418         if (timeUntilNextRefresh > 0)
2419         {
2420             usleep((unsigned long)(timeUntilNextRefresh * 1000000.));
2421         }
2422     }
2423     self->lastRefreshTime = CFAbsoluteTimeGetCurrent();
2424 }
2425
2426 - (void)drawWChar:(wchar_t)wchar inRect:(NSRect)tile screenFont:(NSFont*)font
2427           context:(CGContextRef)ctx
2428 {
2429     CGFloat tileOffsetY = self.fontAscender;
2430     CGFloat tileOffsetX = 0.0;
2431     UniChar unicharString[2] = {(UniChar)wchar, 0};
2432
2433     /* Get glyph and advance */
2434     CGGlyph thisGlyphArray[1] = { 0 };
2435     CGSize advances[1] = { { 0, 0 } };
2436     CTFontGetGlyphsForCharacters(
2437         (CTFontRef)font, unicharString, thisGlyphArray, 1);
2438     CGGlyph glyph = thisGlyphArray[0];
2439     CTFontGetAdvancesForGlyphs(
2440         (CTFontRef)font, kCTFontHorizontalOrientation, thisGlyphArray,
2441         advances, 1);
2442     CGSize advance = advances[0];
2443
2444     /* If our font is not monospaced, our tile width is deliberately not big
2445          * enough for every character. In that event, if our glyph is too wide, we
2446          * need to compress it horizontally. Compute the compression ratio.
2447          * 1.0 means no compression. */
2448     double compressionRatio;
2449     if (advance.width <= NSWidth(tile))
2450     {
2451         /* Our glyph fits, so we can just draw it, possibly with an offset */
2452         compressionRatio = 1.0;
2453         tileOffsetX = (NSWidth(tile) - advance.width)/2;
2454     }
2455     else
2456     {
2457         /* Our glyph doesn't fit, so we'll have to compress it */
2458         compressionRatio = NSWidth(tile) / advance.width;
2459         tileOffsetX = 0;
2460     }
2461
2462     /* Now draw it */
2463     CGAffineTransform textMatrix = CGContextGetTextMatrix(ctx);
2464     CGFloat savedA = textMatrix.a;
2465
2466     /* Set the position */
2467     textMatrix.tx = tile.origin.x + tileOffsetX;
2468     textMatrix.ty = tile.origin.y + tileOffsetY;
2469
2470     /* Maybe squish it horizontally. */
2471     if (compressionRatio != 1.)
2472     {
2473         textMatrix.a *= compressionRatio;
2474     }
2475
2476     CGContextSetTextMatrix(ctx, textMatrix);
2477     CGContextShowGlyphsAtPositions(ctx, &glyph, &CGPointZero, 1);
2478
2479     /* Restore the text matrix if we messed with the compression ratio */
2480     if (compressionRatio != 1.)
2481     {
2482         textMatrix.a = savedA;
2483     }
2484
2485     CGContextSetTextMatrix(ctx, textMatrix);
2486 }
2487
2488 - (NSRect)viewRectForCellBlockAtX:(int)x y:(int)y width:(int)w height:(int)h
2489 {
2490     return NSMakeRect(
2491         x * self.tileSize.width + self.borderSize.width,
2492         y * self.tileSize.height + self.borderSize.height,
2493         w * self.tileSize.width, h * self.tileSize.height);
2494 }
2495
2496 - (void)setSelectionFont:(NSFont*)font adjustTerminal: (BOOL)adjustTerminal
2497 {
2498     /* Record the new font */
2499     self.angbandViewFont = font;
2500
2501     /* Update our glyph info */
2502     [self updateGlyphInfo];
2503
2504     if( adjustTerminal )
2505     {
2506         /* Adjust terminal to fit window with new font; save the new columns
2507                  * and rows since they could be changed */
2508         NSRect contentRect =
2509             [self.primaryWindow
2510                  contentRectForFrameRect: [self.primaryWindow frame]];
2511
2512         [self constrainWindowSize:[self terminalIndex]];
2513         NSSize size = self.primaryWindow.contentMinSize;
2514         BOOL windowNeedsResizing = NO;
2515         if (contentRect.size.width < size.width) {
2516             contentRect.size.width = size.width;
2517             windowNeedsResizing = YES;
2518         }
2519         if (contentRect.size.height < size.height) {
2520             contentRect.size.height = size.height;
2521             windowNeedsResizing = YES;
2522         }
2523         if (windowNeedsResizing) {
2524             size.width = contentRect.size.width;
2525             size.height = contentRect.size.height;
2526             [self.primaryWindow setContentSize:size];
2527         }
2528         [self resizeTerminalWithContentRect: contentRect saveToDefaults: YES];
2529     }
2530 }
2531
2532 - (id)init
2533 {
2534     if ((self = [super init]))
2535     {
2536         /* Default rows and cols */
2537         self->_cols = 80;
2538         self->_rows = 24;
2539
2540         /* Default border size */
2541         self->_borderSize = NSMakeSize(2, 2);
2542
2543         self->_nColPre = 0;
2544         self->_nColPost = 0;
2545
2546         self->_contents =
2547             [[TerminalContents alloc] initWithColumns:self->_cols
2548                                       rows:self->_rows];
2549         self->_changes =
2550             [[TerminalChanges alloc] initWithColumns:self->_cols
2551                                      rows:self->_rows];
2552         self->lastRefreshTime = CFAbsoluteTimeGetCurrent();
2553         self->inFullscreenTransition = NO;
2554
2555         self->_windowVisibilityChecked = NO;
2556     }
2557     return self;
2558 }
2559
2560 /**
2561  * Destroy all the receiver's stuff. This is intended to be callable more than
2562  * once.
2563  */
2564 - (void)dispose
2565 {
2566     self->terminal = NULL;
2567
2568     /* Disassociate ourselves from our view. */
2569     [self->angbandView setAngbandContext:nil];
2570     self->angbandView = nil;
2571
2572     /* Font */
2573     self.angbandViewFont = nil;
2574
2575     /* Window */
2576     [self.primaryWindow setDelegate:nil];
2577     [self.primaryWindow close];
2578     self.primaryWindow = nil;
2579
2580     /* Contents and pending changes */
2581     self.contents = nil;
2582     self.changes = nil;
2583 }
2584
2585 /* Usual Cocoa fare */
2586 - (void)dealloc
2587 {
2588     [self dispose];
2589 }
2590
2591 - (void)resizeWithColumns:(int)nCol rows:(int)nRow
2592 {
2593     [self.contents resizeWithColumns:nCol rows:nRow];
2594     [self.changes resizeWithColumns:nCol rows:nRow];
2595     self->_cols = nCol;
2596     self->_rows = nRow;
2597 }
2598
2599 /**
2600  * For defaultFont and setDefaultFont.
2601  */
2602 static __strong NSFont* gDefaultFont = nil;
2603
2604 + (NSFont*)defaultFont
2605 {
2606     return gDefaultFont;
2607 }
2608
2609 + (void)setDefaultFont:(NSFont*)font
2610 {
2611     gDefaultFont = font;
2612 }
2613
2614 - (void)setDefaultTitle:(int)termIdx
2615 {
2616     NSMutableString *title =
2617         [NSMutableString stringWithCString:angband_term_name[termIdx]
2618 #ifdef JP
2619                          encoding:NSJapaneseEUCStringEncoding
2620 #else
2621                          encoding:NSMacOSRomanStringEncoding
2622 #endif
2623         ];
2624     [title appendFormat:@" %dx%d", self.cols, self.rows];
2625     [[self makePrimaryWindow] setTitle:title];
2626 }
2627
2628 - (NSWindow *)makePrimaryWindow
2629 {
2630     if (! self.primaryWindow)
2631     {
2632         /* This has to be done after the font is set, which it already is in
2633                  * term_init_cocoa() */
2634         NSSize sz = self.baseSize;
2635         NSRect contentRect = NSMakeRect( 0.0, 0.0, sz.width, sz.height );
2636
2637         NSUInteger styleMask = NSTitledWindowMask | NSResizableWindowMask | NSMiniaturizableWindowMask;
2638
2639         /*
2640          * Make every window other than the main window closable, also create
2641          * them as utility panels to get the thinner title bar and other
2642          * attributes that already match up with how those windows are used.
2643          */
2644         if ((__bridge AngbandContext*) (angband_term[0]->data) != self)
2645         {
2646             NSPanel *panel =
2647                 [[NSPanel alloc] initWithContentRect:contentRect
2648                                  styleMask:(styleMask | NSClosableWindowMask |
2649                                             NSUtilityWindowMask)
2650                                  backing:NSBackingStoreBuffered defer:YES];
2651
2652             panel.floatingPanel = NO;
2653             self.primaryWindow = panel;
2654         } else {
2655             self.primaryWindow =
2656                 [[NSWindow alloc] initWithContentRect:contentRect
2657                                   styleMask:styleMask
2658                                   backing:NSBackingStoreBuffered defer:YES];
2659         }
2660
2661         /* Not to be released when closed */
2662         [self.primaryWindow setReleasedWhenClosed:NO];
2663         [self.primaryWindow setExcludedFromWindowsMenu: YES]; /* we're using custom window menu handling */
2664
2665         /* Make the view */
2666         self->angbandView = [[AngbandView alloc] initWithFrame:contentRect];
2667         [angbandView setAngbandContext:self];
2668         [angbandView setNeedsDisplay:YES];
2669         [self.primaryWindow setContentView:angbandView];
2670
2671         /* We are its delegate */
2672         [self.primaryWindow setDelegate:self];
2673     }
2674     return self.primaryWindow;
2675 }
2676
2677
2678 - (void)computeInvalidRects
2679 {
2680     for (int irow = self.changes.firstChangedRow;
2681          irow <= self.changes.lastChangedRow;
2682          ++irow) {
2683         int icol = [self.changes scanForChangedInRow:irow
2684                         col0:0 col1:self.cols];
2685
2686         while (icol < self.cols) {
2687             /* Find the end of the changed region. */
2688             int jcol =
2689                 [self.changes scanForUnchangedInRow:irow col0:(icol + 1)
2690                      col1:self.cols];
2691
2692             /*
2693              * If the last column is a character, extend the region drawn
2694              * because characters can exceed the horizontal bounds of the cell
2695              * and those parts will need to be cleared.  Don't extend into a
2696              * tile because the clipping is set while drawing to never
2697              * extend text into a tile.  For a big character that's been
2698              * partially overwritten, allow what comes after the point
2699              * where the overwrite occurred to influence the stuff before
2700              * but not vice versa.  If extending the region reaches another
2701              * changed block, find the end of that block and repeat the
2702              * process.
2703              */
2704             /*
2705              * A value of zero means checking for a character immediately
2706              * prior to the column, isrch.  A value of one means checking for
2707              * something past the end that could either influence the changed
2708              * region (within nColPre of it and no intervening tile) or be
2709              * influenced by it (within nColPost of it and no intervening
2710              * tile or partially overwritten big character).  A value of two
2711              * means checking for something past the end which is both changed
2712              * and could affect the part of the unchanged region that has to
2713              * be redrawn because it is affected by the prior changed region
2714              * Values of three and four are like one and two, respectively,
2715              * but indicate that a partially overwritten big character was
2716              * found.
2717              */
2718             int stage = 0;
2719             int isrch = jcol;
2720             int irng0 = jcol;
2721             int irng1 = jcol;
2722             while (1) {
2723                 if (stage == 0) {
2724                     const struct TerminalCell *pcell =
2725                         [self.contents getCellAtColumn:(isrch - 1) row:irow];
2726                     if ((pcell->form &
2727                          (TERM_CELL_TILE | TERM_CELL_TILE_PADDING)) != 0) {
2728                         break;
2729                     } else {
2730                         irng0 = isrch + self.nColPre;
2731                         if (irng0 > self.cols) {
2732                             irng0 = self.cols;
2733                         }
2734                         irng1 = isrch + self.nColPost;
2735                         if (irng1 > self.cols) {
2736                             irng1 = self.cols;
2737                         }
2738                         if (isrch < irng0 || isrch < irng1) {
2739                             stage = isPartiallyOverwrittenBigChar(pcell) ?
2740                                 3 : 1;
2741                         } else {
2742                             break;
2743                         }
2744                     }
2745                 }
2746
2747                 if (stage == 1) {
2748                     const struct TerminalCell *pcell =
2749                         [self.contents getCellAtColumn:isrch row:irow];
2750
2751                     if ((pcell->form &
2752                          (TERM_CELL_TILE | TERM_CELL_TILE_PADDING)) != 0) {
2753                         /*
2754                          * Check if still in the region that could be
2755                          * influenced by the changed region.  If so,
2756                          * everything up to the tile will be redrawn anyways
2757                          * so combine the regions if the tile has changed
2758                          * as well.  Otherwise, terminate the search since
2759                          * the tile doesn't allow influence to propagate
2760                          * through it and don't want to affect what's in the
2761                          * tile.
2762                          */
2763                         if (isrch < irng1) {
2764                             if ([self.changes isChangedAtColumn:isrch
2765                                      row:irow]) {
2766                                 jcol = [self.changes scanForUnchangedInRow:irow
2767                                             col0:(isrch + 1) col1:self.cols];
2768                                 if (jcol < self.cols) {
2769                                     stage = 0;
2770                                     isrch = jcol;
2771                                     continue;
2772                                 }
2773                             }
2774                         }
2775                         break;
2776                     } else {
2777                         /*
2778                          * With a changed character, combine the regions (if
2779                          * still in the region affected by the changed region
2780                          * am going to redraw everything up to this new region
2781                          * anyway; if only in the region that can affect the
2782                          * changed region, this changed text could influence
2783                          * the current changed region).
2784                          */
2785                         if ([self.changes isChangedAtColumn:isrch 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                             break;
2794                         }
2795
2796                         if (isrch < irng1) {
2797                             /*
2798                              * Can be affected by the changed region so
2799                              * has to be redrawn.
2800                              */
2801                             ++jcol;
2802                         }
2803                         ++isrch;
2804                         if (isrch >= irng1) {
2805                             irng0 = jcol + self.nColPre;
2806                             if (irng0 > self.cols) {
2807                                 irng0 = self.cols;
2808                             }
2809                             if (isrch >= irng0) {
2810                                 break;
2811                             }
2812                             stage = isPartiallyOverwrittenBigChar(pcell) ?
2813                                 4 : 2;
2814                         } else if (isPartiallyOverwrittenBigChar(pcell)) {
2815                             stage = 3;
2816                         }
2817                     }
2818                 }
2819
2820                 if (stage == 2) {
2821                     /*
2822                      * Looking for a later changed region that could influence
2823                      * the region that has to be redrawn.  The region that has
2824                      * to be redrawn ends just before jcol.
2825                      */
2826                     const struct TerminalCell *pcell =
2827                         [self.contents getCellAtColumn:isrch row:irow];
2828
2829                     if ((pcell->form &
2830                          (TERM_CELL_TILE | TERM_CELL_TILE_PADDING)) != 0) {
2831                         /* Can not spread influence through a tile. */
2832                         break;
2833                     }
2834                     if ([self.changes isChangedAtColumn:isrch row:irow]) {
2835                         /*
2836                          * Found one.  Combine with the one ending just before
2837                          * jcol.
2838                          */
2839                         jcol = [self.changes scanForUnchangedInRow:irow
2840                                     col0:(isrch + 1) col1:self.cols];
2841                         if (jcol < self.cols) {
2842                             stage = 0;
2843                             isrch = jcol;
2844                             continue;
2845                         }
2846                         break;
2847                     }
2848
2849                     ++isrch;
2850                     if (isrch >= irng0) {
2851                         break;
2852                     }
2853                     if (isPartiallyOverwrittenBigChar(pcell)) {
2854                         stage = 4;
2855                     }
2856                 }
2857
2858                 if (stage == 3) {
2859                     const struct TerminalCell *pcell =
2860                         [self.contents getCellAtColumn:isrch row:irow];
2861
2862                     /*
2863                      * Have encountered a partially overwritten big character
2864                      * but still may be in the region that could be influenced
2865                      * by the changed region.  That influence can not extend
2866                      * past the past the padding for the partially overwritten
2867                      * character.
2868                      */
2869                     if ((pcell->form & (TERM_CELL_CHAR | TERM_CELL_TILE |
2870                                         TERM_CELL_TILE_PADDING)) != 0) {
2871                         if (isrch < irng1) {
2872                             /*
2873                              * Still can be affected by the changed region
2874                              * so everything up to isrch will be redrawn
2875                              * anyways.  If this location has changed,
2876                              * merge the changed regions.
2877                              */
2878                             if ([self.changes isChangedAtColumn:isrch
2879                                      row:irow]) {
2880                                 jcol = [self.changes scanForUnchangedInRow:irow
2881                                             col0:(isrch + 1) col1:self.cols];
2882                                 if (jcol < self.cols) {
2883                                     stage = 0;
2884                                     isrch = jcol;
2885                                     continue;
2886                                 }
2887                                 break;
2888                             }
2889                         }
2890                         if ((pcell->form &
2891                              (TERM_CELL_TILE | TERM_CELL_TILE_PADDING)) != 0) {
2892                             /*
2893                              * It's a tile.  That blocks influence in either
2894                              * direction.
2895                              */
2896                             break;
2897                         }
2898
2899                         /*
2900                          * The partially overwritten big character was
2901                          * overwritten by a character.  Check to see if it
2902                          * can either influence the unchanged region that
2903                          * has to redrawn or the changed region prior to
2904                          * that.
2905                          */
2906                         if (isrch >= irng0) {
2907                             break;
2908                         }
2909                         stage = 4;
2910                     } else {
2911                         if (isrch < irng1) {
2912                             /*
2913                              * Can be affected by the changed region so has to
2914                              * be redrawn.
2915                              */
2916                             ++jcol;
2917                         }
2918                         ++isrch;
2919                         if (isrch >= irng1) {
2920                             irng0 = jcol + self.nColPre;
2921                             if (irng0 > self.cols) {
2922                                 irng0 = self.cols;
2923                             }
2924                             if (isrch >= irng0) {
2925                                 break;
2926                             }
2927                             stage = 4;
2928                         }
2929                     }
2930                 }
2931
2932                 if (stage == 4) {
2933                     /*
2934                      * Have already encountered a partially overwritten big
2935                      * character.  Looking for a later changed region that
2936                      * could influence the region that has to be redrawn
2937                      * The region that has to be redrawn ends just before jcol.
2938                      */
2939                     const struct TerminalCell *pcell =
2940                         [self.contents getCellAtColumn:isrch row:irow];
2941
2942                     if ((pcell->form &
2943                          (TERM_CELL_TILE | TERM_CELL_TILE_PADDING)) != 0) {
2944                         /* Can not spread influence through a tile. */
2945                         break;
2946                     }
2947                     if (pcell->form == TERM_CELL_CHAR) {
2948                         if ([self.changes isChangedAtColumn:isrch row:irow]) {
2949                             /*
2950                              * Found a changed region.  Combine with the one
2951                              * ending just before jcol.
2952                              */
2953                             jcol = [self.changes scanForUnchangedInRow:irow
2954                                         col0:(isrch + 1) col1:self.cols];
2955                             if (jcol < self.cols) {
2956                                 stage = 0;
2957                                 isrch = jcol;
2958                                 continue;
2959                             }
2960                             break;
2961                         }
2962                     }
2963                     ++isrch;
2964                     if (isrch >= irng0) {
2965                         break;
2966                     }
2967                 }
2968             }
2969
2970             /*
2971              * Check to see if there's characters before the changed region
2972              * that would have to be redrawn because it's influenced by the
2973              * changed region.  Do not have to check for merging with a prior
2974              * region because of the screening already done.
2975              */
2976             if (self.nColPre > 0 &&
2977                 ([self.contents getCellAtColumn:icol row:irow]->form &
2978                  (TERM_CELL_CHAR | TERM_CELL_CHAR_PADDING)) != 0) {
2979                 int irng = icol - self.nColPre;
2980
2981                 if (irng < 0) {
2982                     irng = 0;
2983                 }
2984                 while (icol > irng &&
2985                        ([self.contents getCellAtColumn:(icol - 1)
2986                              row:irow]->form &
2987                         (TERM_CELL_CHAR | TERM_CELL_CHAR_PADDING)) != 0) {
2988                     --icol;
2989                 }
2990             }
2991
2992             NSRect r = [self viewRectForCellBlockAtX:icol y:irow
2993                              width:(jcol - icol) height:1];
2994             [self setNeedsDisplayInRect:r];
2995
2996             icol = [self.changes scanForChangedInRow:irow col0:jcol
2997                         col1:self.cols];
2998         }
2999     }
3000 }
3001
3002
3003 #pragma mark View/Window Passthrough
3004
3005 /*
3006  * This is a qsort-compatible compare function for NSRect, to get them in
3007  * ascending order by y origin.
3008  */
3009 static int compare_nsrect_yorigin_greater(const void *ap, const void *bp)
3010 {
3011     const NSRect *arp = ap;
3012     const NSRect *brp = bp;
3013     return (arp->origin.y > brp->origin.y) - (arp->origin.y < brp->origin.y);
3014 }
3015
3016 /**
3017  * This is a helper function for drawRect.
3018  */
3019 - (void)renderTileRunInRow:(int)irow col0:(int)icol0 col1:(int)icol1
3020                      nsctx:(NSGraphicsContext*)nsctx ctx:(CGContextRef)ctx
3021                  grafWidth:(int)graf_width grafHeight:(int)graf_height
3022                overdrawRow:(int)overdraw_row overdrawMax:(int)overdraw_max
3023 {
3024     /* Save the compositing mode since it is modified below. */
3025     NSCompositingOperation op = nsctx.compositingOperation;
3026
3027     while (icol0 < icol1) {
3028         const struct TerminalCell *pcell =
3029             [self.contents getCellAtColumn:icol0 row:irow];
3030         NSRect destinationRect =
3031             [self viewRectForCellBlockAtX:icol0 y:irow
3032                   width:pcell->hscl height:pcell->vscl];
3033         NSRect fgdRect = NSMakeRect(
3034             graf_width * (pcell->v.ti.fgdCol +
3035                           pcell->hoff_n / (1.0 * pcell->hoff_d)),
3036             graf_height * (pcell->v.ti.fgdRow +
3037                            pcell->voff_n / (1.0 * pcell->voff_d)),
3038             graf_width * pcell->hscl / (1.0 * pcell->hoff_d),
3039             graf_height * pcell->vscl / (1.0 * pcell->voff_d));
3040         NSRect bckRect = NSMakeRect(
3041             graf_width * (pcell->v.ti.bckCol +
3042                           pcell->hoff_n / (1.0 * pcell->hoff_d)),
3043             graf_height * (pcell->v.ti.bckRow +
3044                            pcell->voff_n / (1.0 * pcell->voff_d)),
3045             graf_width * pcell->hscl / (1.0 * pcell->hoff_d),
3046             graf_height * pcell->vscl / (1.0 * pcell->voff_d));
3047         int dbl_height_bck = overdraw_row && (irow > 2) &&
3048             (pcell->v.ti.bckRow >= overdraw_row &&
3049              pcell->v.ti.bckRow <= overdraw_max);
3050         int dbl_height_fgd = overdraw_row && (irow > 2) &&
3051             (pcell->v.ti.fgdRow >= overdraw_row) &&
3052             (pcell->v.ti.fgdRow <= overdraw_max);
3053         int aligned_row = 0, aligned_col = 0;
3054         int is_first_piece = 0, simple_upper = 0;
3055
3056         /* Initialize stuff for handling a double-height tile. */
3057         if (dbl_height_bck || dbl_height_fgd) {
3058             if (self->terminal == angband_term[0]) {
3059                 aligned_col = ((icol0 - COL_MAP) / pcell->hoff_d) *
3060                     pcell->hoff_d + COL_MAP;
3061             } else {
3062                 aligned_col = (icol0 / pcell->hoff_d) * pcell->hoff_d;
3063             }
3064             aligned_row = ((irow - ROW_MAP) / pcell->voff_d) *
3065                 pcell->voff_d + ROW_MAP;
3066
3067             /*
3068              * If the lower half has been broken into multiple pieces, only
3069              * do the work of rendering whatever is necessary for the upper
3070              * half when drawing the first piece (the one closest to the
3071              * upper left corner).
3072              */
3073             struct TerminalCellLocation curs = { 0, 0 };
3074
3075             [self.contents scanForTypeMaskInBlockAtColumn:aligned_col
3076                  row:aligned_row width:pcell->hoff_d height:pcell->voff_d
3077                  mask:TERM_CELL_TILE cursor:&curs];
3078             if (curs.col + aligned_col == icol0 &&
3079                 curs.row + aligned_row == irow) {
3080                 is_first_piece = 1;
3081
3082                 /*
3083                  * Hack:  lookup the previous row to determine how much of the
3084                  * tile there is shown to apply it the upper half of the
3085                  * double-height tile.  That will do the right thing if there
3086                  * is a menu displayed in that row but isn't right if there's
3087                  * an object/creature/feature there that doesn't have a
3088                  * mapping to the tile set and is rendered with a character.
3089                  */
3090                 curs.col = 0;
3091                 curs.row = 0;
3092                 [self.contents scanForTypeMaskInBlockAtColumn:aligned_col
3093                      row:(aligned_row - pcell->voff_d) width:pcell->hoff_d
3094                      height:pcell->voff_d mask:TERM_CELL_TILE cursor:&curs];
3095                 if (curs.col == 0 && curs.row == 0) {
3096                     const struct TerminalCell *pcell2 =
3097                         [self.contents
3098                              getCellAtColumn:(aligned_col + curs.col)
3099                              row:(aligned_row + curs.row - pcell->voff_d)];
3100
3101                     if (pcell2->hscl == pcell2->hoff_d &&
3102                         pcell2->vscl == pcell2->voff_d) {
3103                         /*
3104                          * The tile in the previous row hasn't been clipped
3105                          * or partially overwritten.  Use a streamlined
3106                          * rendering procedure.
3107                          */
3108                         simple_upper = 1;
3109                     }
3110                 }
3111             }
3112         }
3113
3114         /*
3115          * Draw the background.  For a double-height tile, this is only the
3116          * the lower half.
3117          */
3118         draw_image_tile(
3119             nsctx, ctx, pict_image, bckRect, destinationRect, NSCompositeCopy);
3120         if (dbl_height_bck && is_first_piece) {
3121             /* Combine upper half with previously drawn row. */
3122             if (simple_upper) {
3123                 const struct TerminalCell *pcell2 =
3124                     [self.contents getCellAtColumn:aligned_col
3125                          row:(aligned_row - pcell->voff_d)];
3126                 NSRect drect2 =
3127                     [self viewRectForCellBlockAtX:aligned_col
3128                           y:(aligned_row - pcell->voff_d)
3129                           width:pcell2->hscl height:pcell2->vscl];
3130                 NSRect brect2 = NSMakeRect(
3131                     graf_width * pcell->v.ti.bckCol,
3132                     graf_height * (pcell->v.ti.bckRow - 1),
3133                     graf_width, graf_height);
3134
3135                 draw_image_tile(nsctx, ctx, pict_image, brect2, drect2,
3136                                 NSCompositeSourceOver);
3137             } else {
3138                 struct TerminalCellLocation curs = { 0, 0 };
3139
3140                 [self.contents scanForTypeMaskInBlockAtColumn:aligned_col
3141                      row:(aligned_row - pcell->voff_d) width:pcell->hoff_d
3142                      height:pcell->voff_d mask:TERM_CELL_TILE
3143                      cursor:&curs];
3144                 while (curs.col < pcell->hoff_d &&
3145                        curs.row < pcell->voff_d) {
3146                     const struct TerminalCell *pcell2 =
3147                         [self.contents getCellAtColumn:(aligned_col + curs.col)
3148                              row:(aligned_row + curs.row - pcell->voff_d)];
3149                     NSRect drect2 =
3150                         [self viewRectForCellBlockAtX:(aligned_col + curs.col)
3151                               y:(aligned_row + curs.row - pcell->voff_d)
3152                               width:pcell2->hscl height:pcell2->vscl];
3153                     /*
3154                      * Column and row in the tile set are from the
3155                      * double-height tile at *pcell, but the offsets within
3156                      * that and size are from what's visible for *pcell2.
3157                      */
3158                     NSRect brect2 = NSMakeRect(
3159                         graf_width * (pcell->v.ti.bckCol +
3160                                       pcell2->hoff_n / (1.0 * pcell2->hoff_d)),
3161                         graf_height * (pcell->v.ti.bckRow - 1 +
3162                                        pcell2->voff_n /
3163                                        (1.0 * pcell2->voff_d)),
3164                         graf_width * pcell2->hscl / (1.0 * pcell2->hoff_d),
3165                         graf_height * pcell2->vscl / (1.0 * pcell2->voff_d));
3166
3167                     draw_image_tile(nsctx, ctx, pict_image, brect2, drect2,
3168                                     NSCompositeSourceOver);
3169                     curs.col += pcell2->hscl;
3170                     [self.contents
3171                          scanForTypeMaskInBlockAtColumn:aligned_col
3172                          row:(aligned_row - pcell->voff_d)
3173                          width:pcell->hoff_d height:pcell->voff_d
3174                          mask:TERM_CELL_TILE cursor:&curs];
3175                 }
3176             }
3177         }
3178
3179         /* Skip drawing the foreground if it is the same as the background. */
3180         if (fgdRect.origin.x != bckRect.origin.x ||
3181             fgdRect.origin.y != bckRect.origin.y) {
3182             if (is_first_piece && dbl_height_fgd) {
3183                 if (simple_upper) {
3184                     if (pcell->hoff_n == 0 && pcell->voff_n == 0 &&
3185                         pcell->hscl == pcell->hoff_d) {
3186                         /*
3187                          * Render upper and lower parts as one since they
3188                          * are contiguous.
3189                          */
3190                         fgdRect.origin.y -= graf_height;
3191                         fgdRect.size.height += graf_height;
3192                         destinationRect.origin.y -=
3193                             destinationRect.size.height;
3194                         destinationRect.size.height +=
3195                             destinationRect.size.height;
3196                     } else {
3197                         /* Not contiguous.  Render the upper half. */
3198                         NSRect drect2 =
3199                             [self viewRectForCellBlockAtX:aligned_col
3200                                   y:(aligned_row - pcell->voff_d)
3201                                   width:pcell->hoff_d height:pcell->voff_d];
3202                         NSRect frect2 = NSMakeRect(
3203                             graf_width * pcell->v.ti.fgdCol,
3204                             graf_height * (pcell->v.ti.fgdRow - 1),
3205                             graf_width, graf_height);
3206
3207                         draw_image_tile(
3208                             nsctx, ctx, pict_image, frect2, drect2,
3209                             NSCompositeSourceOver);
3210                     }
3211                 } else {
3212                     /* Render the upper half pieces. */
3213                     struct TerminalCellLocation curs = { 0, 0 };
3214
3215                     while (1) {
3216                         [self.contents
3217                              scanForTypeMaskInBlockAtColumn:aligned_col
3218                              row:(aligned_row - pcell->voff_d)
3219                              width:pcell->hoff_d height:pcell->voff_d
3220                              mask:TERM_CELL_TILE cursor:&curs];
3221
3222                         if (curs.col >= pcell->hoff_d ||
3223                             curs.row >= pcell->voff_d) {
3224                             break;
3225                         }
3226
3227                         const struct TerminalCell *pcell2 =
3228                             [self.contents
3229                                  getCellAtColumn:(aligned_col + curs.col)
3230                                  row:(aligned_row + curs.row - pcell->voff_d)];
3231                         NSRect drect2 =
3232                             [self viewRectForCellBlockAtX:(aligned_col + curs.col)
3233                                   y:(aligned_row + curs.row - pcell->voff_d)
3234                                   width:pcell2->hscl height:pcell2->vscl];
3235                         NSRect frect2 = NSMakeRect(
3236                             graf_width * (pcell->v.ti.fgdCol +
3237                                           pcell2->hoff_n /
3238                                           (1.0 * pcell2->hoff_d)),
3239                             graf_height * (pcell->v.ti.fgdRow - 1 +
3240                                            pcell2->voff_n /
3241                                            (1.0 * pcell2->voff_d)),
3242                             graf_width * pcell2->hscl / (1.0 * pcell2->hoff_d),
3243                             graf_height * pcell2->vscl /
3244                                 (1.0 * pcell2->voff_d));
3245
3246                         draw_image_tile(nsctx, ctx, pict_image, frect2, drect2,
3247                                         NSCompositeSourceOver);
3248                         curs.col += pcell2->hscl;
3249                     }
3250                 }
3251             }
3252             /*
3253              * Render the foreground (if a double height tile and the bottom
3254              * part is contiguous with the upper part this also render the
3255              * upper part.
3256              */
3257             draw_image_tile(
3258                 nsctx, ctx, pict_image, fgdRect, destinationRect,
3259                 NSCompositeSourceOver);
3260         }
3261         icol0 = [self.contents scanForTypeMaskInRow:irow mask:TERM_CELL_TILE
3262                      col0:(icol0+pcell->hscl) col1:icol1];
3263     }
3264
3265     /* Restore the compositing mode. */
3266     nsctx.compositingOperation = op;
3267 }
3268
3269 /**
3270  * This is what our views call to get us to draw to the window
3271  */
3272 - (void)drawRect:(NSRect)rect inView:(NSView *)view
3273 {
3274     /* Take this opportunity to throttle so we don't flush faster than desired.
3275          */
3276     [self throttle];
3277
3278     CGFloat bottomY =
3279         self.borderSize.height + self.tileSize.height * self.rows;
3280     CGFloat rightX =
3281         self.borderSize.width + self.tileSize.width * self.cols;
3282
3283     const NSRect *invalidRects;
3284     NSInteger invalidCount;
3285     [view getRectsBeingDrawn:&invalidRects count:&invalidCount];
3286
3287     /*
3288      * If the non-border areas need rendering, set some things up so they can
3289      * be reused for each invalid rectangle.
3290      */
3291     NSGraphicsContext *nsctx = nil;
3292     CGContextRef ctx = 0;
3293     NSFont* screenFont = nil;
3294     int graf_width = 0, graf_height = 0;
3295     int overdraw_row = 0, overdraw_max = 0;
3296     wchar_t blank = 0;
3297     if (rect.origin.x < rightX &&
3298         rect.origin.x + rect.size.width > self.borderSize.width &&
3299         rect.origin.y < bottomY &&
3300         rect.origin.y + rect.size.height > self.borderSize.height) {
3301         nsctx = [NSGraphicsContext currentContext];
3302         ctx = [nsctx graphicsPort];
3303         screenFont = [self.angbandViewFont screenFont];
3304         [screenFont set];
3305         blank = [TerminalContents getBlankChar];
3306         if (use_graphics) {
3307             graf_width = current_graphics_mode->cell_width;
3308             graf_height = current_graphics_mode->cell_height;
3309             overdraw_row = current_graphics_mode->overdrawRow;
3310             overdraw_max = current_graphics_mode->overdrawMax;
3311         }
3312     }
3313
3314     /*
3315      * With double height tiles, need to have rendered prior rows (i.e.
3316      * smaller y) before the current one.  Since the invalid rectanges are
3317      * processed in order, ensure that by sorting the invalid rectangles in
3318      * increasing order of y origin (AppKit guarantees the invalid rectanges
3319      * are non-overlapping).
3320      */
3321     NSRect* sortedRects = 0;
3322     const NSRect* workingRects;
3323     if (overdraw_row && invalidCount > 1) {
3324         sortedRects = malloc(invalidCount * sizeof(NSRect));
3325         if (sortedRects == 0) {
3326             NSException *exc = [NSException exceptionWithName:@"OutOfMemory"
3327                                             reason:@"sorted rects in drawRect"
3328                                             userInfo:nil];
3329             @throw exc;
3330         }
3331         (void) memcpy(
3332             sortedRects, invalidRects, invalidCount * sizeof(NSRect));
3333         qsort(sortedRects, invalidCount, sizeof(NSRect),
3334               compare_nsrect_yorigin_greater);
3335         workingRects = sortedRects;
3336     } else {
3337         workingRects = invalidRects;
3338     }
3339
3340     /*
3341      * Use -2 for unknown.  Use -1 for Cocoa's blackColor.  All others are the
3342      * Angband color index.
3343      */
3344     int alast = -2;
3345     int redrawCursor = 0;
3346
3347     for (NSInteger irect = 0; irect < invalidCount; ++irect) {
3348         NSRect modRect, clearRect;
3349         CGFloat edge;
3350         int iRowFirst, iRowLast;
3351         int iColFirst, iColLast;
3352
3353         /* Handle the top border. */
3354         if (workingRects[irect].origin.y < self.borderSize.height) {
3355             edge =
3356                 workingRects[irect].origin.y + workingRects[irect].size.height;
3357             if (edge <= self.borderSize.height) {
3358                 if (alast != -1) {
3359                     [[NSColor blackColor] set];
3360                     alast = -1;
3361                 }
3362                 NSRectFill(workingRects[irect]);
3363                 continue;
3364             }
3365             clearRect = workingRects[irect];
3366             clearRect.size.height =
3367                 self.borderSize.height - workingRects[irect].origin.y;
3368             if (alast != -1) {
3369                 [[NSColor blackColor] set];
3370                 alast = -1;
3371             }
3372             NSRectFill(clearRect);
3373             modRect.origin.x = workingRects[irect].origin.x;
3374             modRect.origin.y = self.borderSize.height;
3375             modRect.size.width = workingRects[irect].size.width;
3376             modRect.size.height = edge - self.borderSize.height;
3377         } else {
3378             modRect = workingRects[irect];
3379         }
3380
3381         /* Handle the left border. */
3382         if (modRect.origin.x < self.borderSize.width) {
3383             edge = modRect.origin.x + modRect.size.width;
3384             if (edge <= self.borderSize.width) {
3385                 if (alast != -1) {
3386                     alast = -1;
3387                     [[NSColor blackColor] set];
3388                 }
3389                 NSRectFill(modRect);
3390                 continue;
3391             }
3392             clearRect = modRect;
3393             clearRect.size.width = self.borderSize.width - clearRect.origin.x;
3394             if (alast != -1) {
3395                 alast = -1;
3396                 [[NSColor blackColor] set];
3397             }
3398             NSRectFill(clearRect);
3399             modRect.origin.x = self.borderSize.width;
3400             modRect.size.width = edge - self.borderSize.width;
3401         }
3402
3403         iRowFirst = floor((modRect.origin.y - self.borderSize.height) /
3404                           self.tileSize.height);
3405         iColFirst = floor((modRect.origin.x - self.borderSize.width) /
3406                           self.tileSize.width);
3407         edge = modRect.origin.y + modRect.size.height;
3408         if (edge <= bottomY) {
3409             iRowLast =
3410                 ceil((edge - self.borderSize.height) / self.tileSize.height);
3411         } else {
3412             iRowLast = self.rows;
3413         }
3414         edge = modRect.origin.x + modRect.size.width;
3415         if (edge <= rightX) {
3416             iColLast =
3417                 ceil((edge - self.borderSize.width) / self.tileSize.width);
3418         } else {
3419             iColLast = self.cols;
3420         }
3421
3422         if (self.contents.cursorColumn != -1 &&
3423             self.contents.cursorRow != -1 &&
3424             self.contents.cursorColumn + self.contents.cursorWidth - 1 >=
3425             iColFirst &&
3426             self.contents.cursorColumn < iColLast &&
3427             self.contents.cursorRow + self.contents.cursorHeight - 1 >=
3428             iRowFirst &&
3429             self.contents.cursorRow < iRowLast) {
3430             redrawCursor = 1;
3431         }
3432
3433         for (int irow = iRowFirst; irow < iRowLast; ++irow) {
3434             int icol =
3435                 [self.contents scanForTypeMaskInRow:irow
3436                      mask:(TERM_CELL_CHAR | TERM_CELL_TILE)
3437                      col0:iColFirst col1:iColLast];
3438
3439             while (1) {
3440                 if (icol >= iColLast) {
3441                     break;
3442                 }
3443
3444                 if ([self.contents getCellAtColumn:icol row:irow]->form ==
3445                     TERM_CELL_TILE) {
3446                     /*
3447                      * It is a tile.  Identify how far the run of tiles goes.
3448                      */
3449                     int jcol = [self.contents scanForPredicateInRow:irow
3450                                     predicate:isTileTop desired:1
3451                                     col0:(icol + 1) col1:iColLast];
3452
3453                     [self renderTileRunInRow:irow col0:icol col1:jcol
3454                           nsctx:nsctx ctx:ctx
3455                           grafWidth:graf_width grafHeight:graf_height
3456                           overdrawRow:overdraw_row overdrawMax:overdraw_max];
3457                     icol = jcol;
3458                 } else {
3459                     /*
3460                      * It is a character.  Identify how far the run of
3461                      * characters goes.
3462                      */
3463                     int jcol = [self.contents scanForPredicateInRow:irow
3464                                     predicate:isCharNoPartial desired:1
3465                                     col0:(icol + 1) col1:iColLast];
3466                     int jcol2;
3467
3468                     if (jcol < iColLast &&
3469                         isPartiallyOverwrittenBigChar(
3470                             [self.contents getCellAtColumn:jcol row:irow])) {
3471                         jcol2 = [self.contents scanForTypeMaskInRow:irow
3472                                      mask:~TERM_CELL_CHAR_PADDING
3473                                      col0:(jcol + 1) col1:iColLast];
3474                     } else {
3475                         jcol2 = jcol;
3476                     }
3477
3478                     /*
3479                      * Set up clipping rectangle for text.  Save the
3480                      * graphics context so the clipping rectangle can be
3481                      * forgotten.  Use CGContextBeginPath to clear the current
3482                      * path so it does not affect clipping.  Do not call
3483                      * CGContextSetTextDrawingMode() to include clipping since
3484                      * that does not appear to necessary on 10.14 and is
3485                      * actually detrimental:  when displaying more than one
3486                      * character, only the first is visible.
3487                      */
3488                     CGContextSaveGState(ctx);
3489                     CGContextBeginPath(ctx);
3490                     NSRect r = [self viewRectForCellBlockAtX:icol y:irow
3491                                      width:(jcol2 - icol) height:1];
3492                     CGContextClipToRect(ctx, r);
3493
3494                     /*
3495                      * See if the region to be rendered needs to be expanded:
3496                      * adjacent text that could influence what's in the clipped
3497                      * region.
3498                      */
3499                     int isrch = icol;
3500                     int irng = icol - self.nColPost;
3501                     if (irng < 1) {
3502                         irng = 1;
3503                     }
3504
3505                     while (1) {
3506                         if (isrch <= irng) {
3507                             break;
3508                         }
3509
3510                         const struct TerminalCell *pcell2 =
3511                             [self.contents getCellAtColumn:(isrch - 1)
3512                                  row:irow];
3513                         if (pcell2->form == TERM_CELL_CHAR) {
3514                             --isrch;
3515                             if (pcell2->v.ch.glyph != blank) {
3516                                 icol = isrch;
3517                             }
3518                         } else if (pcell2->form == TERM_CELL_CHAR_PADDING) {
3519                             /*
3520                              * Only extend the rendering if this is padding
3521                              * for a character that hasn't been partially
3522                              * overwritten.
3523                              */
3524                             if (! isPartiallyOverwrittenBigChar(pcell2)) {
3525                                 if (isrch - pcell2->v.pd.hoff >= 0) {
3526                                     const struct TerminalCell* pcell3 =
3527                                         [self.contents
3528                                              getCellAtColumn:(isrch - pcell2->v.pd.hoff)
3529                                              row:irow];
3530
3531                                     if (pcell3->v.ch.glyph != blank) {
3532                                         icol = isrch - pcell2->v.pd.hoff;
3533                                         isrch = icol - 1;
3534                                     } else {
3535                                         isrch = isrch - pcell2->v.pd.hoff - 1;
3536                                     }
3537                                 } else {
3538                                     /* Should not happen, corrupt offset. */
3539                                     --isrch;
3540                                 }
3541                             } else {
3542                                 break;
3543                             }
3544                         } else {
3545                             /*
3546                              * Tiles or tile padding block anything before
3547                              * them from rendering after them.
3548                              */
3549                             break;
3550                         }
3551                     }
3552
3553                     isrch = jcol2;
3554                     irng = jcol2 + self.nColPre;
3555                     if (irng > self.cols) {
3556                         irng = self.cols;
3557                     }
3558                     while (1) {
3559                         if (isrch >= irng) {
3560                             break;
3561                         }
3562
3563                         const struct TerminalCell *pcell2 =
3564                             [self.contents getCellAtColumn:isrch row:irow];
3565                         if (pcell2->form == TERM_CELL_CHAR) {
3566                             if (pcell2->v.ch.glyph != blank) {
3567                                 jcol2 = isrch;
3568                             }
3569                             ++isrch;
3570                         } else if (pcell2->form == TERM_CELL_CHAR_PADDING) {
3571                             ++isrch;
3572                         } else {
3573                             break;
3574                         }
3575                     }
3576
3577                     /* Render text. */
3578                     /* Clear where rendering will be done. */
3579                     if (alast != -1) {
3580                         [[NSColor blackColor] set];
3581                         alast = -1;
3582                     }
3583                     r = [self viewRectForCellBlockAtX:icol y:irow
3584                               width:(jcol - icol) height:1];
3585                     NSRectFill(r);
3586
3587                     while (icol < jcol) {
3588                         const struct TerminalCell *pcell =
3589                             [self.contents getCellAtColumn:icol row:irow];
3590
3591                         /*
3592                          * For blanks, clearing was all that was necessary.
3593                          * Don't redraw them.
3594                          */
3595                         if (pcell->v.ch.glyph != blank) {
3596                             int a = pcell->v.ch.attr % MAX_COLORS;
3597
3598                             if (alast != a) {
3599                                 alast = a;
3600                                 set_color_for_index(a);
3601                             }
3602                             r = [self viewRectForCellBlockAtX:icol
3603                                       y:irow width:pcell->hscl
3604                                       height:1];
3605                             [self drawWChar:pcell->v.ch.glyph inRect:r
3606                                   screenFont:screenFont context:ctx];
3607                         }
3608                         icol += pcell->hscl;
3609                     }
3610
3611                     /*
3612                      * Forget the clipping rectangle.  As a side effect, lose
3613                      * the color.
3614                      */
3615                     CGContextRestoreGState(ctx);
3616                     alast = -2;
3617                 }
3618                 icol =
3619                     [self.contents scanForTypeMaskInRow:irow
3620                          mask:(TERM_CELL_CHAR | TERM_CELL_TILE)
3621                          col0:icol col1:iColLast];
3622             }
3623         }
3624
3625         /* Handle the right border. */
3626         edge = modRect.origin.x + modRect.size.width;
3627         if (edge > rightX) {
3628             if (modRect.origin.x >= rightX) {
3629                 if (alast != -1) {
3630                     alast = -1;
3631                     [[NSColor blackColor] set];
3632                 }
3633                 NSRectFill(modRect);
3634                 continue;
3635             }
3636             clearRect = modRect;
3637             clearRect.origin.x = rightX;
3638             clearRect.size.width = edge - rightX;
3639             if (alast != -1) {
3640                 alast = -1;
3641                 [[NSColor blackColor] set];
3642             }
3643             NSRectFill(clearRect);
3644             modRect.size.width = edge - modRect.origin.x;
3645         }
3646
3647         /* Handle the bottom border. */
3648         edge = modRect.origin.y + modRect.size.height;
3649         if (edge > bottomY) {
3650             if (modRect.origin.y < bottomY) {
3651                 modRect.origin.y = bottomY;
3652                 modRect.size.height = edge - bottomY;
3653             }
3654             if (alast != -1) {
3655                 alast = -1;
3656                 [[NSColor blackColor] set];
3657             }
3658             NSRectFill(modRect);
3659         }
3660     }
3661
3662     if (redrawCursor) {
3663         NSRect r = [self viewRectForCellBlockAtX:self.contents.cursorColumn
3664                          y:self.contents.cursorRow
3665                          width:self.contents.cursorWidth
3666                          height:self.contents.cursorHeight];
3667         [[NSColor yellowColor] set];
3668         NSFrameRectWithWidth(r, 1);
3669     }
3670
3671     free(sortedRects);
3672 }
3673
3674 - (BOOL)isOrderedIn
3675 {
3676     return [[self->angbandView window] isVisible];
3677 }
3678
3679 - (BOOL)isMainWindow
3680 {
3681     return [[self->angbandView window] isMainWindow];
3682 }
3683
3684 - (BOOL)isKeyWindow
3685 {
3686     return [[self->angbandView window] isKeyWindow];
3687 }
3688
3689 - (void)setNeedsDisplay:(BOOL)val
3690 {
3691     [self->angbandView setNeedsDisplay:val];
3692 }
3693
3694 - (void)setNeedsDisplayInRect:(NSRect)rect
3695 {
3696     [self->angbandView setNeedsDisplayInRect:rect];
3697 }
3698
3699 - (void)displayIfNeeded
3700 {
3701     [self->angbandView displayIfNeeded];
3702 }
3703
3704 - (int)terminalIndex
3705 {
3706         int termIndex = 0;
3707
3708         for( termIndex = 0; termIndex < ANGBAND_TERM_MAX; termIndex++ )
3709         {
3710                 if( angband_term[termIndex] == self->terminal )
3711                 {
3712                         break;
3713                 }
3714         }
3715
3716         return termIndex;
3717 }
3718
3719 - (void)resizeTerminalWithContentRect: (NSRect)contentRect saveToDefaults: (BOOL)saveToDefaults
3720 {
3721     CGFloat newRows = floor(
3722         (contentRect.size.height - (self.borderSize.height * 2.0)) /
3723         self.tileSize.height);
3724     CGFloat newColumns = floor(
3725         (contentRect.size.width - (self.borderSize.width * 2.0)) /
3726         self.tileSize.width);
3727
3728     if (newRows < 1 || newColumns < 1) return;
3729     [self resizeWithColumns:newColumns rows:newRows];
3730
3731     int termIndex = [self terminalIndex];
3732     [self setDefaultTitle:termIndex];
3733
3734     if( saveToDefaults )
3735     {
3736         NSArray *terminals = [[NSUserDefaults standardUserDefaults] valueForKey: AngbandTerminalsDefaultsKey];
3737
3738         if( termIndex < (int)[terminals count] )
3739         {
3740             NSMutableDictionary *mutableTerm = [[NSMutableDictionary alloc] initWithDictionary: [terminals objectAtIndex: termIndex]];
3741             [mutableTerm setValue: [NSNumber numberWithInteger: self.cols]
3742                          forKey: AngbandTerminalColumnsDefaultsKey];
3743             [mutableTerm setValue: [NSNumber numberWithInteger: self.rows]
3744                          forKey: AngbandTerminalRowsDefaultsKey];
3745
3746             NSMutableArray *mutableTerminals = [[NSMutableArray alloc] initWithArray: terminals];
3747             [mutableTerminals replaceObjectAtIndex: termIndex withObject: mutableTerm];
3748
3749             [[NSUserDefaults standardUserDefaults] setValue: mutableTerminals forKey: AngbandTerminalsDefaultsKey];
3750         }
3751     }
3752
3753     term *old = Term;
3754     Term_activate( self->terminal );
3755     Term_resize( self.cols, self.rows );
3756     Term_redraw();
3757     Term_activate( old );
3758 }
3759
3760 - (void)constrainWindowSize:(int)termIdx
3761 {
3762     NSSize minsize;
3763
3764     if (termIdx == 0) {
3765         minsize.width = 80;
3766         minsize.height = 24;
3767     } else {
3768         minsize.width = 1;
3769         minsize.height = 1;
3770     }
3771     minsize.width =
3772         minsize.width * self.tileSize.width + self.borderSize.width * 2.0;
3773     minsize.height =
3774         minsize.height * self.tileSize.height + self.borderSize.height * 2.0;
3775     [[self makePrimaryWindow] setContentMinSize:minsize];
3776     self.primaryWindow.contentResizeIncrements = self.tileSize;
3777 }
3778
3779 - (void)saveWindowVisibleToDefaults: (BOOL)windowVisible
3780 {
3781         int termIndex = [self terminalIndex];
3782         BOOL safeVisibility = (termIndex == 0) ? YES : windowVisible; /* Ensure main term doesn't go away because of these defaults */
3783         NSArray *terminals = [[NSUserDefaults standardUserDefaults] valueForKey: AngbandTerminalsDefaultsKey];
3784
3785         if( termIndex < (int)[terminals count] )
3786         {
3787                 NSMutableDictionary *mutableTerm = [[NSMutableDictionary alloc] initWithDictionary: [terminals objectAtIndex: termIndex]];
3788                 [mutableTerm setValue: [NSNumber numberWithBool: safeVisibility] forKey: AngbandTerminalVisibleDefaultsKey];
3789
3790                 NSMutableArray *mutableTerminals = [[NSMutableArray alloc] initWithArray: terminals];
3791                 [mutableTerminals replaceObjectAtIndex: termIndex withObject: mutableTerm];
3792
3793                 [[NSUserDefaults standardUserDefaults] setValue: mutableTerminals forKey: AngbandTerminalsDefaultsKey];
3794         }
3795 }
3796
3797 - (BOOL)windowVisibleUsingDefaults
3798 {
3799         int termIndex = [self terminalIndex];
3800
3801         if( termIndex == 0 )
3802         {
3803                 return YES;
3804         }
3805
3806         NSArray *terminals = [[NSUserDefaults standardUserDefaults] valueForKey: AngbandTerminalsDefaultsKey];
3807         BOOL visible = NO;
3808
3809         if( termIndex < (int)[terminals count] )
3810         {
3811                 NSDictionary *term = [terminals objectAtIndex: termIndex];
3812                 NSNumber *visibleValue = [term valueForKey: AngbandTerminalVisibleDefaultsKey];
3813
3814                 if( visibleValue != nil )
3815                 {
3816                         visible = [visibleValue boolValue];
3817                 }
3818         }
3819
3820         return visible;
3821 }
3822
3823 #pragma mark -
3824 #pragma mark NSWindowDelegate Methods
3825
3826 /*- (void)windowWillStartLiveResize: (NSNotification *)notification
3827
3828 }*/ 
3829
3830 - (void)windowDidEndLiveResize: (NSNotification *)notification
3831 {
3832     NSWindow *window = [notification object];
3833     NSRect contentRect = [window contentRectForFrameRect: [window frame]];
3834     [self resizeTerminalWithContentRect: contentRect saveToDefaults: !(self->inFullscreenTransition)];
3835 }
3836
3837 /*- (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
3838 {
3839 } */
3840
3841 - (void)windowWillEnterFullScreen: (NSNotification *)notification
3842 {
3843     self->inFullscreenTransition = YES;
3844 }
3845
3846 - (void)windowDidEnterFullScreen: (NSNotification *)notification
3847 {
3848     NSWindow *window = [notification object];
3849     NSRect contentRect = [window contentRectForFrameRect: [window frame]];
3850     self->inFullscreenTransition = NO;
3851     [self resizeTerminalWithContentRect: contentRect saveToDefaults: NO];
3852 }
3853
3854 - (void)windowWillExitFullScreen: (NSNotification *)notification
3855 {
3856     self->inFullscreenTransition = YES;
3857 }
3858
3859 - (void)windowDidExitFullScreen: (NSNotification *)notification
3860 {
3861     NSWindow *window = [notification object];
3862     NSRect contentRect = [window contentRectForFrameRect: [window frame]];
3863     self->inFullscreenTransition = NO;
3864     [self resizeTerminalWithContentRect: contentRect saveToDefaults: NO];
3865 }
3866
3867 - (void)windowDidBecomeMain:(NSNotification *)notification
3868 {
3869     NSWindow *window = [notification object];
3870
3871     if( window != self.primaryWindow )
3872     {
3873         return;
3874     }
3875
3876     int termIndex = [self terminalIndex];
3877     NSMenuItem *item = [[[NSApplication sharedApplication] windowsMenu] itemWithTag: AngbandWindowMenuItemTagBase + termIndex];
3878     [item setState: NSOnState];
3879
3880     if( [[NSFontPanel sharedFontPanel] isVisible] )
3881     {
3882         [[NSFontPanel sharedFontPanel] setPanelFont:self.angbandViewFont
3883                                        isMultiple: NO];
3884     }
3885 }
3886
3887 - (void)windowDidResignMain: (NSNotification *)notification
3888 {
3889     NSWindow *window = [notification object];
3890
3891     if( window != self.primaryWindow )
3892     {
3893         return;
3894     }
3895
3896     int termIndex = [self terminalIndex];
3897     NSMenuItem *item = [[[NSApplication sharedApplication] windowsMenu] itemWithTag: AngbandWindowMenuItemTagBase + termIndex];
3898     [item setState: NSOffState];
3899 }
3900
3901 - (void)windowWillClose: (NSNotification *)notification
3902 {
3903     /*
3904      * If closing only because the application is terminating, don't update
3905      * the visible state for when the application is relaunched.
3906      */
3907     if (! quit_when_ready) {
3908         [self saveWindowVisibleToDefaults: NO];
3909     }
3910 }
3911
3912 @end
3913
3914
3915 @implementation AngbandView
3916
3917 - (BOOL)isOpaque
3918 {
3919     return YES;
3920 }
3921
3922 - (BOOL)isFlipped
3923 {
3924     return YES;
3925 }
3926
3927 - (void)drawRect:(NSRect)rect
3928 {
3929     if ([self inLiveResize]) {
3930         /*
3931          * Always anchor the cached area to the upper left corner of the view.
3932          * Any parts on the right or bottom that can't be drawn from the cached
3933          * area are simply cleared.  Will fill them with appropriate content
3934          * when resizing is done.
3935          */
3936         const NSRect *rects;
3937         NSInteger count;
3938
3939         [self getRectsBeingDrawn:&rects count:&count];
3940         if (count > 0) {
3941             NSRect viewRect = [self visibleRect];
3942
3943             [[NSColor blackColor] set];
3944             while (count-- > 0) {
3945                 CGFloat drawTop = rects[count].origin.y - viewRect.origin.y;
3946                 CGFloat drawBottom = drawTop + rects[count].size.height;
3947                 CGFloat drawLeft = rects[count].origin.x - viewRect.origin.x;
3948                 CGFloat drawRight = drawLeft + rects[count].size.width;
3949                 /*
3950                  * modRect and clrRect, like rects[count], are in the view
3951                  * coordinates with y flipped.  cacheRect is in the bitmap
3952                  * coordinates and y is not flipped.
3953                  */
3954                 NSRect modRect, clrRect, cacheRect;
3955
3956                 /*
3957                  * Clip by bottom edge of cached area.  Clear what's below
3958                  * that.
3959                  */
3960                 if (drawTop >= self->cacheBounds.size.height) {
3961                     NSRectFill(rects[count]);
3962                     continue;
3963                 }
3964                 modRect.origin.x = rects[count].origin.x;
3965                 modRect.origin.y = rects[count].origin.y;
3966                 modRect.size.width = rects[count].size.width;
3967                 cacheRect.origin.y = drawTop;
3968                 if (drawBottom > self->cacheBounds.size.height) {
3969                     CGFloat excess =
3970                         drawBottom - self->cacheBounds.size.height;
3971
3972                     modRect.size.height = rects[count].size.height - excess;
3973                     cacheRect.origin.y = 0;
3974                     clrRect.origin.x = modRect.origin.x;
3975                     clrRect.origin.y = modRect.origin.y + modRect.size.height;
3976                     clrRect.size.width = modRect.size.width;
3977                     clrRect.size.height = excess;
3978                     NSRectFill(clrRect);
3979                 } else {
3980                     modRect.size.height = rects[count].size.height;
3981                     cacheRect.origin.y = self->cacheBounds.size.height -
3982                         rects[count].size.height;
3983                 }
3984                 cacheRect.size.height = modRect.size.height;
3985
3986                 /*
3987                  * Clip by right edge of cached area.  Clear what's to the
3988                  * right of that and copy the remainder from the cache.
3989                  */
3990                 if (drawLeft >= self->cacheBounds.size.width) {
3991                     NSRectFill(modRect);
3992                     continue;
3993                 }
3994                 cacheRect.origin.x = drawLeft;
3995                 if (drawRight > self->cacheBounds.size.width) {
3996                     CGFloat excess = drawRight - self->cacheBounds.size.width;
3997
3998                     modRect.size.width -= excess;
3999                     cacheRect.size.width =
4000                         self->cacheBounds.size.width - drawLeft;
4001                     clrRect.origin.x = modRect.origin.x + modRect.size.width;
4002                     clrRect.origin.y = modRect.origin.y;
4003                     clrRect.size.width = excess;
4004                     clrRect.size.height = modRect.size.height;
4005                     NSRectFill(clrRect);
4006                 } else {
4007                     cacheRect.size.width = drawRight - drawLeft;
4008                 }
4009                 [self->cacheForResize drawInRect:modRect fromRect:cacheRect
4010                      operation:NSCompositeCopy fraction:1.0
4011                      respectFlipped:YES hints:nil];
4012             }
4013         }
4014     } else if (! self.angbandContext) {
4015         /* Draw bright orange, 'cause this ain't right */
4016         [[NSColor orangeColor] set];
4017         NSRectFill([self bounds]);
4018     } else {
4019         /* Tell the Angband context to draw into us */
4020         [self.angbandContext drawRect:rect inView:self];
4021     }
4022 }
4023
4024 /**
4025  * Override NSView's method to set up a cache that's used in drawRect to
4026  * handle drawing during a resize.
4027  */
4028 - (void)viewWillStartLiveResize
4029 {
4030     [super viewWillStartLiveResize];
4031     self->cacheBounds = [self visibleRect];
4032     self->cacheForResize =
4033         [self bitmapImageRepForCachingDisplayInRect:self->cacheBounds];
4034     if (self->cacheForResize != nil) {
4035         [self cacheDisplayInRect:self->cacheBounds
4036               toBitmapImageRep:self->cacheForResize];
4037     } else {
4038         self->cacheBounds.size.width = 0.;
4039         self->cacheBounds.size.height = 0.;
4040     }
4041 }
4042
4043 /**
4044  * Override NSView's method to release the cache set up in
4045  * viewWillStartLiveResize.
4046  */
4047 - (void)viewDidEndLiveResize
4048 {
4049     [super viewDidEndLiveResize];
4050     self->cacheForResize = nil;
4051     [self setNeedsDisplay:YES];
4052 }
4053
4054 @end
4055
4056 /**
4057  * Delay handling of double-clicked savefiles
4058  */
4059 Boolean open_when_ready = FALSE;
4060
4061
4062
4063 /**
4064  * ------------------------------------------------------------------------
4065  * Some generic functions
4066  * ------------------------------------------------------------------------ */
4067
4068 /**
4069  * Sets an Angband color at a given index
4070  */
4071 static void set_color_for_index(int idx)
4072 {
4073     u16b rv, gv, bv;
4074     
4075     /* Extract the R,G,B data */
4076     rv = angband_color_table[idx][1];
4077     gv = angband_color_table[idx][2];
4078     bv = angband_color_table[idx][3];
4079     
4080     CGContextSetRGBFillColor([[NSGraphicsContext currentContext] graphicsPort], rv/255., gv/255., bv/255., 1.);
4081 }
4082
4083 /**
4084  * Remember the current character in UserDefaults so we can select it by
4085  * default next time.
4086  */
4087 static void record_current_savefile(void)
4088 {
4089     NSString *savefileString = [[NSString stringWithCString:savefile encoding:NSMacOSRomanStringEncoding] lastPathComponent];
4090     if (savefileString)
4091     {
4092         NSUserDefaults *angbandDefs = [NSUserDefaults angbandDefaults];
4093         [angbandDefs setObject:savefileString forKey:@"SaveFile"];
4094     }
4095 }
4096
4097
4098 #ifdef JP
4099 /**
4100  * Convert a two-byte EUC-JP encoded character (both *cp and (*cp + 1) are in
4101  * the range, 0xA1-0xFE, or *cp is 0x8E) to a utf16 value in the native byte
4102  * ordering.
4103  */
4104 static wchar_t convert_two_byte_eucjp_to_utf16_native(const char *cp)
4105 {
4106     NSString* str = [[NSString alloc] initWithBytes:cp length:2
4107                                       encoding:NSJapaneseEUCStringEncoding];
4108     wchar_t result = [str characterAtIndex:0];
4109     str = nil;
4110     return result;
4111 }
4112 #endif /* JP */
4113
4114
4115 /**
4116  * ------------------------------------------------------------------------
4117  * Support for the "z-term.c" package
4118  * ------------------------------------------------------------------------ */
4119
4120
4121 /**
4122  * Initialize a new Term
4123  */
4124 static void Term_init_cocoa(term *t)
4125 {
4126     @autoreleasepool {
4127         AngbandContext *context = [[AngbandContext alloc] init];
4128
4129         /* Give the term ownership of the context */
4130         t->data = (void *)CFBridgingRetain(context);
4131
4132         /* Handle graphics */
4133         t->higher_pict = !! use_graphics;
4134         t->always_pict = FALSE;
4135
4136         NSDisableScreenUpdates();
4137
4138         /*
4139          * Figure out the frame autosave name based on the index of this term
4140          */
4141         NSString *autosaveName = nil;
4142         int termIdx;
4143         for (termIdx = 0; termIdx < ANGBAND_TERM_MAX; termIdx++)
4144         {
4145             if (angband_term[termIdx] == t)
4146             {
4147                 autosaveName =
4148                     [NSString stringWithFormat:@"AngbandTerm-%d", termIdx];
4149                 break;
4150             }
4151         }
4152
4153         /* Set its font. */
4154         NSString *fontName =
4155             [[NSUserDefaults angbandDefaults]
4156                 stringForKey:[NSString stringWithFormat:@"FontName-%d", termIdx]];
4157         if (! fontName) fontName = [[AngbandContext defaultFont] fontName];
4158
4159         /*
4160          * Use a smaller default font for the other windows, but only if the
4161          * font hasn't been explicitly set.
4162          */
4163         float fontSize =
4164             (termIdx > 0) ? 10.0 : [[AngbandContext defaultFont] pointSize];
4165         NSNumber *fontSizeNumber =
4166             [[NSUserDefaults angbandDefaults]
4167                 valueForKey: [NSString stringWithFormat: @"FontSize-%d", termIdx]];
4168
4169         if( fontSizeNumber != nil )
4170         {
4171             fontSize = [fontSizeNumber floatValue];
4172         }
4173
4174         [context setSelectionFont:[NSFont fontWithName:fontName size:fontSize]
4175                  adjustTerminal: NO];
4176
4177         NSArray *terminalDefaults =
4178             [[NSUserDefaults standardUserDefaults]
4179                 valueForKey: AngbandTerminalsDefaultsKey];
4180         NSInteger rows = 24;
4181         NSInteger columns = 80;
4182
4183         if( termIdx < (int)[terminalDefaults count] )
4184         {
4185             NSDictionary *term = [terminalDefaults objectAtIndex: termIdx];
4186             NSInteger defaultRows =
4187                 [[term valueForKey: AngbandTerminalRowsDefaultsKey]
4188                     integerValue];
4189             NSInteger defaultColumns =
4190                 [[term valueForKey: AngbandTerminalColumnsDefaultsKey]
4191                     integerValue];
4192
4193             if (defaultRows > 0) rows = defaultRows;
4194             if (defaultColumns > 0) columns = defaultColumns;
4195         }
4196
4197         [context resizeWithColumns:columns rows:rows];
4198
4199         /* Get the window */
4200         NSWindow *window = [context makePrimaryWindow];
4201
4202         /* Set its title and, for auxiliary terms, tentative size */
4203         [context setDefaultTitle:termIdx];
4204         [context constrainWindowSize:termIdx];
4205
4206         /*
4207          * If this is the first term, and we support full screen (Mac OS X Lion
4208          * or later), then allow it to go full screen (sweet). Allow other
4209          * terms to be FullScreenAuxilliary, so they can at least show up.
4210          * Unfortunately in Lion they don't get brought to the full screen
4211          * space; but they would only make sense on multiple displays anyways
4212          * so it's not a big loss.
4213          */
4214         if ([window respondsToSelector:@selector(toggleFullScreen:)])
4215         {
4216             NSWindowCollectionBehavior behavior = [window collectionBehavior];
4217             behavior |=
4218                 (termIdx == 0 ?
4219                  NSWindowCollectionBehaviorFullScreenPrimary :
4220                  NSWindowCollectionBehaviorFullScreenAuxiliary);
4221             [window setCollectionBehavior:behavior];
4222         }
4223
4224         /* No Resume support yet, though it would not be hard to add */
4225         if ([window respondsToSelector:@selector(setRestorable:)])
4226         {
4227             [window setRestorable:NO];
4228         }
4229
4230         /* default window placement */ {
4231             static NSRect overallBoundingRect;
4232
4233             if( termIdx == 0 )
4234             {
4235                 /*
4236                  * This is a bit of a trick to allow us to display multiple
4237                  * windows in the "standard default" window position in OS X:
4238                  * the upper center of the screen.  The term sizes set in
4239                  * load_prefs() are based on a 5-wide by 3-high grid, with the
4240                  * main term being 4/5 wide by 2/3 high (hence the scaling to
4241                  * find what the containing rect would be).
4242                  */
4243                 NSRect originalMainTermFrame = [window frame];
4244                 NSRect scaledFrame = originalMainTermFrame;
4245                 scaledFrame.size.width *= 5.0 / 4.0;
4246                 scaledFrame.size.height *= 3.0 / 2.0;
4247                 scaledFrame.size.width += 1.0; /* spacing between window columns */
4248                 scaledFrame.size.height += 1.0; /* spacing between window rows */
4249                 [window setFrame: scaledFrame  display: NO];
4250                 [window center];
4251                 overallBoundingRect = [window frame];
4252                 [window setFrame: originalMainTermFrame display: NO];
4253             }
4254
4255             static NSRect mainTermBaseRect;
4256             NSRect windowFrame = [window frame];
4257
4258             if( termIdx == 0 )
4259             {
4260                 /*
4261                  * The height and width adjustments were determined
4262                  * experimentally, so that the rest of the windows line up
4263                  * nicely without overlapping.
4264                  */
4265                 windowFrame.size.width += 7.0;
4266                 windowFrame.size.height += 9.0;
4267                 windowFrame.origin.x = NSMinX( overallBoundingRect );
4268                 windowFrame.origin.y =
4269                     NSMaxY( overallBoundingRect ) - NSHeight( windowFrame );
4270                 mainTermBaseRect = windowFrame;
4271             }
4272             else if( termIdx == 1 )
4273             {
4274                 windowFrame.origin.x = NSMinX( mainTermBaseRect );
4275                 windowFrame.origin.y =
4276                     NSMinY( mainTermBaseRect ) - NSHeight( windowFrame ) - 1.0;
4277             }
4278             else if( termIdx == 2 )
4279             {
4280                 windowFrame.origin.x = NSMaxX( mainTermBaseRect ) + 1.0;
4281                 windowFrame.origin.y =
4282                     NSMaxY( mainTermBaseRect ) - NSHeight( windowFrame );
4283             }
4284             else if( termIdx == 3 )
4285             {
4286                 windowFrame.origin.x = NSMaxX( mainTermBaseRect ) + 1.0;
4287                 windowFrame.origin.y =
4288                     NSMinY( mainTermBaseRect ) - NSHeight( windowFrame ) - 1.0;
4289             }
4290             else if( termIdx == 4 )
4291             {
4292                 windowFrame.origin.x = NSMaxX( mainTermBaseRect ) + 1.0;
4293                 windowFrame.origin.y = NSMinY( mainTermBaseRect );
4294             }
4295             else if( termIdx == 5 )
4296             {
4297                 windowFrame.origin.x =
4298                     NSMinX( mainTermBaseRect ) + NSWidth( windowFrame ) + 1.0;
4299                 windowFrame.origin.y =
4300                     NSMinY( mainTermBaseRect ) - NSHeight( windowFrame ) - 1.0;
4301             }
4302
4303             [window setFrame: windowFrame display: NO];
4304         }
4305
4306         /* Override the default frame above if the user has adjusted windows in
4307          * the past */
4308         if (autosaveName) [window setFrameAutosaveName:autosaveName];
4309
4310         /*
4311          * Tell it about its term. Do this after we've sized it so that the
4312          * sizing doesn't trigger redrawing and such.
4313          */
4314         [context setTerm:t];
4315
4316         /*
4317          * Only order front if it's the first term. Other terms will be ordered
4318          * front from AngbandUpdateWindowVisibility(). This is to work around a
4319          * problem where Angband aggressively tells us to initialize terms that
4320          * don't do anything!
4321          */
4322         if (t == angband_term[0])
4323             [context.primaryWindow makeKeyAndOrderFront: nil];
4324
4325         NSEnableScreenUpdates();
4326
4327         /* Set "mapped" flag */
4328         t->mapped_flag = true;
4329     }
4330 }
4331
4332
4333
4334 /**
4335  * Nuke an old Term
4336  */
4337 static void Term_nuke_cocoa(term *t)
4338 {
4339     @autoreleasepool {
4340         AngbandContext *context = (__bridge AngbandContext*) (t->data);
4341         if (context)
4342         {
4343             /* Tell the context to get rid of its windows, etc. */
4344             [context dispose];
4345
4346             /* Balance our CFBridgingRetain from when we created it */
4347             CFRelease(t->data);
4348
4349             /* Done with it */
4350             t->data = NULL;
4351         }
4352     }
4353 }
4354
4355 /**
4356  * Returns the CGImageRef corresponding to an image with the given path.
4357  * Transfers ownership to the caller.
4358  */
4359 static CGImageRef create_angband_image(NSString *path)
4360 {
4361     CGImageRef decodedImage = NULL, result = NULL;
4362     
4363     /* Try using ImageIO to load the image */
4364     if (path)
4365     {
4366         NSURL *url = [[NSURL alloc] initFileURLWithPath:path isDirectory:NO];
4367         if (url)
4368         {
4369             NSDictionary *options = [[NSDictionary alloc] initWithObjectsAndKeys:(id)kCFBooleanTrue, kCGImageSourceShouldCache, nil];
4370             CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)url, (CFDictionaryRef)options);
4371             if (source)
4372             {
4373                 /*
4374                  * We really want the largest image, but in practice there's
4375                  * only going to be one
4376                  */
4377                 decodedImage = CGImageSourceCreateImageAtIndex(source, 0, (CFDictionaryRef)options);
4378                 CFRelease(source);
4379             }
4380         }
4381     }
4382     
4383     /*
4384      * Draw the sucker to defeat ImageIO's weird desire to cache and decode on
4385      * demand. Our images aren't that big!
4386      */
4387     if (decodedImage)
4388     {
4389         size_t width = CGImageGetWidth(decodedImage), height = CGImageGetHeight(decodedImage);
4390         
4391         /* Compute our own bitmap info */
4392         CGBitmapInfo imageBitmapInfo = CGImageGetBitmapInfo(decodedImage);
4393         CGBitmapInfo contextBitmapInfo = kCGBitmapByteOrderDefault;
4394         
4395         switch (imageBitmapInfo & kCGBitmapAlphaInfoMask) {
4396             case kCGImageAlphaNone:
4397             case kCGImageAlphaNoneSkipLast:
4398             case kCGImageAlphaNoneSkipFirst:
4399                 /* No alpha */
4400                 contextBitmapInfo |= kCGImageAlphaNone;
4401                 break;
4402             default:
4403                 /* Some alpha, use premultiplied last which is most efficient. */
4404                 contextBitmapInfo |= kCGImageAlphaPremultipliedLast;
4405                 break;
4406         }
4407
4408         /* Draw the source image flipped, since the view is flipped */
4409         CGContextRef ctx = CGBitmapContextCreate(NULL, width, height, CGImageGetBitsPerComponent(decodedImage), CGImageGetBytesPerRow(decodedImage), CGImageGetColorSpace(decodedImage), contextBitmapInfo);
4410         if (ctx) {
4411             CGContextSetBlendMode(ctx, kCGBlendModeCopy);
4412             CGContextTranslateCTM(ctx, 0.0, height);
4413             CGContextScaleCTM(ctx, 1.0, -1.0);
4414             CGContextDrawImage(
4415                 ctx, CGRectMake(0, 0, width, height), decodedImage);
4416             result = CGBitmapContextCreateImage(ctx);
4417             CFRelease(ctx);
4418         }
4419
4420         CGImageRelease(decodedImage);
4421     }
4422     return result;
4423 }
4424
4425 /**
4426  * React to changes
4427  */
4428 static errr Term_xtra_cocoa_react(void)
4429 {
4430     /* Don't actually switch graphics until the game is running */
4431     if (!initialized || !game_in_progress) return (-1);
4432
4433     @autoreleasepool {
4434         /* Handle graphics */
4435         int expected_graf_mode = (current_graphics_mode) ?
4436             current_graphics_mode->grafID : GRAPHICS_NONE;
4437         if (graf_mode_req != expected_graf_mode)
4438         {
4439             graphics_mode *new_mode;
4440             if (graf_mode_req != GRAPHICS_NONE) {
4441                 new_mode = get_graphics_mode(graf_mode_req);
4442             } else {
4443                 new_mode = NULL;
4444             }
4445
4446             /* Get rid of the old image. CGImageRelease is NULL-safe. */
4447             CGImageRelease(pict_image);
4448             pict_image = NULL;
4449
4450             /* Try creating the image if we want one */
4451             if (new_mode != NULL)
4452             {
4453                 NSString *img_path =
4454                     [NSString stringWithFormat:@"%s/%s", new_mode->path, new_mode->file];
4455                 pict_image = create_angband_image(img_path);
4456
4457                 /* If we failed to create the image, revert to ASCII. */
4458                 if (! pict_image) {
4459                     new_mode = NULL;
4460                     if (use_bigtile) {
4461                         arg_bigtile = FALSE;
4462                     }
4463                     [[NSUserDefaults angbandDefaults]
4464                         setInteger:GRAPHICS_NONE
4465                         forKey:AngbandGraphicsDefaultsKey];
4466
4467                     NSString *msg = NSLocalizedStringWithDefaultValue(
4468                         @"Error.TileSetLoadFailed",
4469                         AngbandMessageCatalog,
4470                         [NSBundle mainBundle],
4471                         @"Failed to Load Tile Set",
4472                         @"Alert text for failed tile set load");
4473                     NSString *info = NSLocalizedStringWithDefaultValue(
4474                         @"Error.TileSetRevertToASCII",
4475                         AngbandMessageCatalog,
4476                         [NSBundle mainBundle],
4477                         @"Could not load the tile set.  Switched back to ASCII.",
4478                         @"Alert informative message for failed tile set load");
4479                     NSAlert *alert = [[NSAlert alloc] init];
4480                     alert.messageText = msg;
4481                     alert.informativeText = info;
4482                     [alert runModal];
4483                 }
4484             }
4485
4486             if (graphics_are_enabled()) {
4487                 /*
4488                  * The contents stored in the AngbandContext may have
4489                  * references to the old tile set.  Out of an abundance
4490                  * of caution, clear those references in case there's an
4491                  * attempt to redraw the contents before the core has the
4492                  * chance to update it via the text_hook, pict_hook, and
4493                  * wipe_hook.
4494                  */
4495                 for (int iterm = 0; iterm < ANGBAND_TERM_MAX; ++iterm) {
4496                     AngbandContext* aContext =
4497                         (__bridge AngbandContext*) (angband_term[iterm]->data);
4498
4499                     [aContext.contents wipeTiles];
4500                 }
4501             }
4502
4503             /* Record what we did */
4504             use_graphics = new_mode ? new_mode->grafID : 0;
4505             ANGBAND_GRAF = (new_mode ? new_mode->graf : "ascii");
4506             current_graphics_mode = new_mode;
4507
4508             /* Enable or disable higher picts.  */
4509             for (int iterm = 0; iterm < ANGBAND_TERM_MAX; ++iterm) {
4510                 if (angband_term[iterm]) {
4511                     angband_term[iterm]->higher_pict = !! use_graphics;
4512                 }
4513             }
4514
4515             if (pict_image && current_graphics_mode)
4516             {
4517                 /*
4518                  * Compute the row and column count via the image height and
4519                  * width.
4520                  */
4521                 pict_rows = (int)(CGImageGetHeight(pict_image) /
4522                                   current_graphics_mode->cell_height);
4523                 pict_cols = (int)(CGImageGetWidth(pict_image) /
4524                                   current_graphics_mode->cell_width);
4525             }
4526             else
4527             {
4528                 pict_rows = 0;
4529                 pict_cols = 0;
4530             }
4531
4532             /* Reset visuals */
4533             if (arg_bigtile == use_bigtile && character_generated)
4534             {
4535                 reset_visuals();
4536             }
4537         }
4538
4539         if (arg_bigtile != use_bigtile) {
4540             if (character_generated)
4541             {
4542                 /* Reset visuals */
4543                 reset_visuals();
4544             }
4545
4546             Term_activate(angband_term[0]);
4547             Term_resize(angband_term[0]->wid, angband_term[0]->hgt);
4548         }
4549     }
4550
4551     /* Success */
4552     return (0);
4553 }
4554
4555
4556 /**
4557  * Do a "special thing"
4558  */
4559 static errr Term_xtra_cocoa(int n, int v)
4560 {
4561     errr result = 0;
4562     @autoreleasepool {
4563         AngbandContext* angbandContext =
4564             (__bridge AngbandContext*) (Term->data);
4565
4566         /* Analyze */
4567         switch (n) {
4568             /* Make a noise */
4569         case TERM_XTRA_NOISE:
4570             NSBeep();
4571             break;
4572
4573             /*  Make a sound */
4574         case TERM_XTRA_SOUND:
4575             play_sound(v);
4576             break;
4577
4578             /* Process random events */
4579         case TERM_XTRA_BORED:
4580             /*
4581              * Show or hide cocoa windows based on the subwindow flags set by
4582              * the user.
4583              */
4584             AngbandUpdateWindowVisibility();
4585             /* Process an event */
4586             (void)check_events(CHECK_EVENTS_NO_WAIT);
4587             break;
4588
4589             /* Process pending events */
4590         case TERM_XTRA_EVENT:
4591             /* Process an event */
4592             (void)check_events(v);
4593             break;
4594
4595             /* Flush all pending events (if any) */
4596         case TERM_XTRA_FLUSH:
4597             /* Hack -- flush all events */
4598             while (check_events(CHECK_EVENTS_DRAIN)) /* loop */;
4599
4600             break;
4601
4602             /* Hack -- Change the "soft level" */
4603         case TERM_XTRA_LEVEL:
4604             /*
4605              * Here we could activate (if requested), but I don't think
4606              * Angband should be telling us our window order (the user
4607              * should decide that), so do nothing.
4608              */
4609             break;
4610
4611             /* Clear the screen */
4612         case TERM_XTRA_CLEAR:
4613             [angbandContext.contents wipe];
4614             [angbandContext setNeedsDisplay:YES];
4615             break;
4616
4617             /* React to changes */
4618         case TERM_XTRA_REACT:
4619             result = Term_xtra_cocoa_react();
4620             break;
4621
4622             /* Delay (milliseconds) */
4623         case TERM_XTRA_DELAY:
4624             /* If needed */
4625             if (v > 0) {
4626                 double seconds = v / 1000.;
4627                 NSDate* date = [NSDate dateWithTimeIntervalSinceNow:seconds];
4628                 do {
4629                     NSEvent* event;
4630                     do {
4631                         event = [NSApp nextEventMatchingMask:-1
4632                                        untilDate:date
4633                                        inMode:NSDefaultRunLoopMode
4634                                        dequeue:YES];
4635                         if (event) send_event(event);
4636                     } while (event);
4637                 } while ([date timeIntervalSinceNow] >= 0);
4638             }
4639             break;
4640
4641             /* Draw the pending changes. */
4642         case TERM_XTRA_FRESH:
4643             {
4644                 /*
4645                  * Check the cursor visibility since the core will tell us
4646                  * explicitly to draw it, but tells us implicitly to forget it
4647                  * by simply telling us to redraw a location.
4648                  */
4649                 int isVisible = 0;
4650
4651                 Term_get_cursor(&isVisible);
4652                 if (! isVisible) {
4653                     [angbandContext.contents removeCursor];
4654                 }
4655                 [angbandContext computeInvalidRects];
4656                 [angbandContext.changes clear];
4657             }
4658             break;
4659
4660         default:
4661             /* Oops */
4662             result = 1;
4663             break;
4664         }
4665     }
4666
4667     return result;
4668 }
4669
4670 static errr Term_curs_cocoa(TERM_LEN x, TERM_LEN y)
4671 {
4672     AngbandContext *angbandContext = (__bridge AngbandContext*) (Term->data);
4673
4674     [angbandContext.contents setCursorAtColumn:x row:y width:1 height:1];
4675     /*
4676      * Unfortunately, this (and the same logic in Term_bigcurs_cocoa) will
4677      * also trigger what's under the cursor to be redrawn as well, even if
4678      * it has not changed.  In the current drawing implementation, that
4679      * inefficiency seems unavoidable.
4680      */
4681     [angbandContext.changes markChangedAtColumn:x row:y];
4682
4683     /* Success */
4684     return 0;
4685 }
4686
4687 /**
4688  * Draw a cursor that's two tiles wide.  For Japanese, that's used when
4689  * the cursor points at a kanji character, irregardless of whether operating
4690  * in big tile mode.
4691  */
4692 static errr Term_bigcurs_cocoa(TERM_LEN x, TERM_LEN y)
4693 {
4694     AngbandContext *angbandContext = (__bridge AngbandContext*) (Term->data);
4695
4696     [angbandContext.contents setCursorAtColumn:x row:y width:2 height:1];
4697     [angbandContext.changes markChangedBlockAtColumn:x row:y width:2 height:1];
4698
4699     /* Success */
4700     return 0;
4701 }
4702
4703 /**
4704  * Low level graphics (Assumes valid input)
4705  *
4706  * Erase "n" characters starting at (x,y)
4707  */
4708 static errr Term_wipe_cocoa(TERM_LEN x, TERM_LEN y, int n)
4709 {
4710     AngbandContext *angbandContext = (__bridge AngbandContext*) (Term->data);
4711
4712     [angbandContext.contents wipeBlockAtColumn:x row:y width:n height:1];
4713     [angbandContext.changes markChangedRangeAtColumn:x row:y width:n];
4714
4715     /* Success */
4716     return 0;
4717 }
4718
4719 static errr Term_pict_cocoa(TERM_LEN x, TERM_LEN y, int n,
4720                             TERM_COLOR *ap, concptr cp,
4721                             const TERM_COLOR *tap, concptr tcp)
4722 {
4723     /* Paranoia: Bail if graphics aren't enabled */
4724     if (! graphics_are_enabled()) return -1;
4725
4726     AngbandContext* angbandContext = (__bridge AngbandContext*) (Term->data);
4727     int step = (use_bigtile) ? 2 : 1;
4728
4729     int alphablend;
4730     if (use_graphics) {
4731         CGImageAlphaInfo ainfo = CGImageGetAlphaInfo(pict_image);
4732
4733         alphablend = (ainfo & (kCGImageAlphaPremultipliedFirst |
4734                                kCGImageAlphaPremultipliedLast)) ? 1 : 0;
4735     } else {
4736         alphablend = 0;
4737     }
4738
4739     for (int i = x; i < x + n * step; i += step) {
4740         TERM_COLOR a = *ap;
4741         char c = *cp;
4742         TERM_COLOR ta = *tap;
4743         char tc = *tcp;
4744
4745         ap += step;
4746         cp += step;
4747         tap += step;
4748         tcp += step;
4749         if (use_graphics && (a & 0x80) && (c & 0x80)) {
4750             char fgdRow = ((byte)a & 0x7F) % pict_rows;
4751             char fgdCol = ((byte)c & 0x7F) % pict_cols;
4752             char bckRow, bckCol;
4753
4754             if (alphablend) {
4755                 bckRow = ((byte)ta & 0x7F) % pict_rows;
4756                 bckCol = ((byte)tc & 0x7F) % pict_cols;
4757             } else {
4758                 /*
4759                  * Not blending so make the background the same as the
4760                  * the foreground.
4761                  */
4762                 bckRow = fgdRow;
4763                 bckCol = fgdCol;
4764             }
4765             [angbandContext.contents setTileAtColumn:i row:y
4766                            foregroundColumn:fgdCol
4767                            foregroundRow:fgdRow
4768                            backgroundColumn:bckCol
4769                            backgroundRow:bckRow
4770                            tileWidth:step
4771                            tileHeight:1];
4772             [angbandContext.changes markChangedBlockAtColumn:i row:y
4773                            width:step height:1];
4774         }
4775     }
4776
4777     /* Success */
4778     return (0);
4779 }
4780
4781 /**
4782  * Low level graphics.  Assumes valid input.
4783  *
4784  * Draw several ("n") chars, with an attr, at a given location.
4785  */
4786 static errr Term_text_cocoa(
4787     TERM_LEN x, TERM_LEN y, int n, TERM_COLOR a, concptr cp)
4788 {
4789     AngbandContext* angbandContext = (__bridge AngbandContext*) (Term->data);
4790
4791     [angbandContext.contents setUniformAttributeTextRunAtColumn:x
4792                    row:y n:n glyphs:cp attribute:a];
4793     [angbandContext.changes markChangedRangeAtColumn:x row:y width:n];
4794
4795     /* Success */
4796     return 0;
4797 }
4798
4799 #if 0
4800 /* From the Linux mbstowcs(3) man page:
4801  *   If dest is NULL, n is ignored, and the conversion  proceeds  as  above,
4802  *   except  that  the converted wide characters are not written out to mem‐
4803  *   ory, and that no length limit exists.
4804  */
4805 static size_t Term_mbcs_cocoa(wchar_t *dest, const char *src, int n)
4806 {
4807     int i;
4808     int count = 0;
4809
4810     /* Unicode code point to UTF-8
4811      *  0x0000-0x007f:   0xxxxxxx
4812      *  0x0080-0x07ff:   110xxxxx 10xxxxxx
4813      *  0x0800-0xffff:   1110xxxx 10xxxxxx 10xxxxxx
4814      * 0x10000-0x1fffff: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
4815      * Note that UTF-16 limits Unicode to 0x10ffff. This code is not
4816      * endian-agnostic.
4817      */
4818     for (i = 0; i < n || dest == NULL; i++) {
4819         if ((src[i] & 0x80) == 0) {
4820             if (dest != NULL) dest[count] = src[i];
4821             if (src[i] == 0) break;
4822         } else if ((src[i] & 0xe0) == 0xc0) {
4823             if (dest != NULL) dest[count] =
4824                             (((unsigned char)src[i] & 0x1f) << 6)|
4825                             ((unsigned char)src[i+1] & 0x3f);
4826             i++;
4827         } else if ((src[i] & 0xf0) == 0xe0) {
4828             if (dest != NULL) dest[count] =
4829                             (((unsigned char)src[i] & 0x0f) << 12) |
4830                             (((unsigned char)src[i+1] & 0x3f) << 6) |
4831                             ((unsigned char)src[i+2] & 0x3f);
4832             i += 2;
4833         } else if ((src[i] & 0xf8) == 0xf0) {
4834             if (dest != NULL) dest[count] =
4835                             (((unsigned char)src[i] & 0x0f) << 18) |
4836                             (((unsigned char)src[i+1] & 0x3f) << 12) |
4837                             (((unsigned char)src[i+2] & 0x3f) << 6) |
4838                             ((unsigned char)src[i+3] & 0x3f);
4839             i += 3;
4840         } else {
4841             /* Found an invalid multibyte sequence */
4842             return (size_t)-1;
4843         }
4844         count++;
4845     }
4846     return count;
4847 }
4848 #endif
4849
4850 /**
4851  * Handle redrawing for a change to the tile set, tile scaling, or main window
4852  * font.  Returns YES if the redrawing was initiated.  Otherwise returns NO.
4853  */
4854 static BOOL redraw_for_tiles_or_term0_font(void)
4855 {
4856     /*
4857      * In Angband 4.2, do_cmd_redraw() will always clear, but only provides
4858      * something to replace the erased content if a character has been
4859      * generated.  In Hengband, do_cmd_redraw() isn't safe to call unless a
4860      * character has been generated.  Therefore, only call it if a character
4861      * has been generated.
4862      */
4863     if (character_generated) {
4864         do_cmd_redraw();
4865         wakeup_event_loop();
4866         return YES;
4867     }
4868     return NO;
4869 }
4870
4871 /**
4872  * Post a nonsense event so that our event loop wakes up
4873  */
4874 static void wakeup_event_loop(void)
4875 {
4876     /* Big hack - send a nonsense event to make us update */
4877     NSEvent *event = [NSEvent otherEventWithType:NSApplicationDefined location:NSZeroPoint modifierFlags:0 timestamp:0 windowNumber:0 context:NULL subtype:AngbandEventWakeup data1:0 data2:0];
4878     [NSApp postEvent:event atStart:NO];
4879 }
4880
4881
4882 /**
4883  * Handle the "open_when_ready" flag
4884  */
4885 static void handle_open_when_ready(void)
4886 {
4887     /* Check the flag XXX XXX XXX make a function for this */
4888     if (open_when_ready && initialized && !game_in_progress)
4889     {
4890         /* Forget */
4891         open_when_ready = FALSE;
4892         
4893         /* Game is in progress */
4894         game_in_progress = TRUE;
4895         
4896         /* Wait for a keypress */
4897         pause_line(Term->hgt - 1);
4898     }
4899 }
4900
4901
4902 /**
4903  * Handle quit_when_ready, by Peter Ammon,
4904  * slightly modified to check inkey_flag.
4905  */
4906 static void quit_calmly(void)
4907 {
4908     /* Quit immediately if game's not started */
4909     if (!game_in_progress || !character_generated) quit(NULL);
4910
4911     /* Save the game and Quit (if it's safe) */
4912     if (inkey_flag)
4913     {
4914         /* Hack -- Forget messages and term */
4915         msg_flag = FALSE;
4916                 Term->mapped_flag = FALSE;
4917
4918         /* Save the game */
4919         do_cmd_save_game(FALSE);
4920         record_current_savefile();
4921
4922         /* Quit */
4923         quit(NULL);
4924     }
4925
4926     /* Wait until inkey_flag is set */
4927 }
4928
4929
4930
4931 /**
4932  * Returns YES if we contain an AngbandView (and hence should direct our events
4933  * to Angband)
4934  */
4935 static BOOL contains_angband_view(NSView *view)
4936 {
4937     if ([view isKindOfClass:[AngbandView class]]) return YES;
4938     for (NSView *subview in [view subviews]) {
4939         if (contains_angband_view(subview)) return YES;
4940     }
4941     return NO;
4942 }
4943
4944
4945 /**
4946  * Queue mouse presses if they occur in the map section of the main window.
4947  */
4948 static void AngbandHandleEventMouseDown( NSEvent *event )
4949 {
4950 #if 0
4951         AngbandContext *angbandContext = [[[event window] contentView] angbandContext];
4952         AngbandContext *mainAngbandContext =
4953             (__bridge AngbandContext*) (angband_term[0]->data);
4954
4955         if (mainAngbandContext.primaryWindow &&
4956             [[event window] windowNumber] ==
4957             [mainAngbandContext.primaryWindow windowNumber])
4958         {
4959                 int cols, rows, x, y;
4960                 Term_get_size(&cols, &rows);
4961                 NSSize tileSize = angbandContext.tileSize;
4962                 NSSize border = angbandContext.borderSize;
4963                 NSPoint windowPoint = [event locationInWindow];
4964
4965                 /* Adjust for border; add border height because window origin is at
4966                  * bottom */
4967                 windowPoint = NSMakePoint( windowPoint.x - border.width, windowPoint.y + border.height );
4968
4969                 NSPoint p = [[[event window] contentView] convertPoint: windowPoint fromView: nil];
4970                 x = floor( p.x / tileSize.width );
4971                 y = floor( p.y / tileSize.height );
4972
4973                 /* Being safe about this, since xcode doesn't seem to like the
4974                  * bool_hack stuff */
4975                 BOOL displayingMapInterface = ((int)inkey_flag != 0);
4976
4977                 /* Sidebar plus border == thirteen characters; top row is reserved. */
4978                 /* Coordinates run from (0,0) to (cols-1, rows-1). */
4979                 BOOL mouseInMapSection = (x > 13 && x <= cols - 1 && y > 0  && y <= rows - 2);
4980
4981                 /* If we are displaying a menu, allow clicks anywhere within
4982                  * the terminal bounds; if we are displaying the main game
4983                  * interface, only allow clicks in the map section */
4984                 if ((!displayingMapInterface && x >= 0 && x < cols &&
4985                      y >= 0 && y < rows) ||
4986                      (displayingMapInterface && mouseInMapSection))
4987                 {
4988                         /* [event buttonNumber] will return 0 for left click,
4989                          * 1 for right click, but this is safer */
4990                         int button = ([event type] == NSLeftMouseDown) ? 1 : 2;
4991
4992 #ifdef KC_MOD_ALT
4993                         NSUInteger eventModifiers = [event modifierFlags];
4994                         byte angbandModifiers = 0;
4995                         angbandModifiers |= (eventModifiers & NSShiftKeyMask) ? KC_MOD_SHIFT : 0;
4996                         angbandModifiers |= (eventModifiers & NSControlKeyMask) ? KC_MOD_CONTROL : 0;
4997                         angbandModifiers |= (eventModifiers & NSAlternateKeyMask) ? KC_MOD_ALT : 0;
4998                         button |= (angbandModifiers & 0x0F) << 4; /* encode modifiers in the button number (see Term_mousepress()) */
4999 #endif
5000
5001                         Term_mousepress(x, y, button);
5002                 }
5003         }
5004 #endif
5005
5006         /* Pass click through to permit focus change, resize, etc. */
5007         [NSApp sendEvent:event];
5008 }
5009
5010
5011
5012 /**
5013  * Encodes an NSEvent Angband-style, or forwards it along.  Returns YES if the
5014  * event was sent to Angband, NO if Cocoa (or nothing) handled it */
5015 static BOOL send_event(NSEvent *event)
5016 {
5017
5018     /* If the receiving window is not an Angband window, then do nothing */
5019     if (! contains_angband_view([[event window] contentView]))
5020     {
5021         [NSApp sendEvent:event];
5022         return NO;
5023     }
5024
5025     /* Analyze the event */
5026     switch ([event type])
5027     {
5028         case NSKeyDown:
5029         {
5030             /* Try performing a key equivalent */
5031             if ([[NSApp mainMenu] performKeyEquivalent:event]) break;
5032             
5033             unsigned modifiers = [event modifierFlags];
5034             
5035             /* Send all NSCommandKeyMasks through */
5036             if (modifiers & NSCommandKeyMask)
5037             {
5038                 [NSApp sendEvent:event];
5039                 break;
5040             }
5041             
5042             if (! [[event characters] length]) break;
5043             
5044             
5045             /* Extract some modifiers */
5046             int mc = !! (modifiers & NSControlKeyMask);
5047             int ms = !! (modifiers & NSShiftKeyMask);
5048             int mo = !! (modifiers & NSAlternateKeyMask);
5049             int kp = !! (modifiers & NSNumericPadKeyMask);
5050             
5051             
5052             /* Get the Angband char corresponding to this unichar */
5053             unichar c = [[event characters] characterAtIndex:0];
5054             char ch;
5055             /*
5056              * Have anything from the numeric keypad generate a macro
5057              * trigger so that shift or control modifiers can be passed.
5058              */
5059             if (c <= 0x7F && !kp)
5060             {
5061                 ch = (char) c;
5062             }
5063             else {
5064                 /*
5065                  * The rest of Hengband uses Angband 2.7's or so key handling:
5066                  * so for the rest do something like the encoding that
5067                  * main-win.c does:  send a macro trigger with the Unicode
5068                  * value encoded into printable ASCII characters.
5069                  */
5070                 ch = '\0';
5071             }
5072             
5073             /* override special keys */
5074             switch([event keyCode]) {
5075                 case kVK_Return: ch = '\r'; break;
5076                 case kVK_Escape: ch = 27; break;
5077                 case kVK_Tab: ch = '\t'; break;
5078                 case kVK_Delete: ch = '\b'; break;
5079                 case kVK_ANSI_KeypadEnter: ch = '\r'; kp = TRUE; break;
5080             }
5081
5082             /* Hide the mouse pointer */
5083             [NSCursor setHiddenUntilMouseMoves:YES];
5084             
5085             /* Enqueue it */
5086             if (ch != '\0')
5087             {
5088                 Term_keypress(ch);
5089             }
5090             else
5091             {
5092                 /*
5093                  * Could use the hexsym global but some characters overlap with
5094                  * those used to indicate modifiers.
5095                  */
5096                 const char encoded[16] = {
5097                     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b',
5098                     'c', 'd', 'e', 'f'
5099                 };
5100
5101                 /* Begin the macro trigger. */
5102                 Term_keypress(31);
5103
5104                 /* Send the modifiers. */
5105                 if (mc) Term_keypress('C');
5106                 if (ms) Term_keypress('S');
5107                 if (mo) Term_keypress('O');
5108                 if (kp) Term_keypress('K');
5109
5110                 do {
5111                     Term_keypress(encoded[c & 0xF]);
5112                     c >>= 4;
5113                 } while (c > 0);
5114
5115                 /* End the macro trigger. */
5116                 Term_keypress(13);
5117             }
5118             
5119             break;
5120         }
5121             
5122         case NSLeftMouseDown:
5123                 case NSRightMouseDown:
5124                         AngbandHandleEventMouseDown(event);
5125             break;
5126
5127         case NSApplicationDefined:
5128         {
5129             if ([event subtype] == AngbandEventWakeup)
5130             {
5131                 return YES;
5132             }
5133             break;
5134         }
5135             
5136         default:
5137             [NSApp sendEvent:event];
5138             return YES;
5139     }
5140     return YES;
5141 }
5142
5143 /**
5144  * Check for Events, return TRUE if we process any
5145  */
5146 static BOOL check_events(int wait)
5147 {
5148     BOOL result = YES;
5149
5150     @autoreleasepool {
5151         /* Handles the quit_when_ready flag */
5152         if (quit_when_ready) quit_calmly();
5153
5154         NSDate* endDate;
5155         if (wait == CHECK_EVENTS_WAIT) endDate = [NSDate distantFuture];
5156         else endDate = [NSDate distantPast];
5157
5158         NSEvent* event;
5159         for (;;) {
5160             if (quit_when_ready)
5161             {
5162                 /* send escape events until we quit */
5163                 Term_keypress(0x1B);
5164                 result = NO;
5165                 break;
5166             }
5167             else {
5168                 event = [NSApp nextEventMatchingMask:-1 untilDate:endDate
5169                                inMode:NSDefaultRunLoopMode dequeue:YES];
5170                 if (! event) {
5171                     result = NO;
5172                     break;
5173                 }
5174                 if (send_event(event)) break;
5175             }
5176         }
5177     }
5178
5179     return result;
5180 }
5181
5182 /**
5183  * Hook to tell the user something important
5184  */
5185 static void hook_plog(const char * str)
5186 {
5187     if (str)
5188     {
5189         NSString *msg = NSLocalizedStringWithDefaultValue(
5190             @"Warning", AngbandMessageCatalog, [NSBundle mainBundle],
5191             @"Warning", @"Alert text for generic warning");
5192         NSString *info = [NSString stringWithCString:str
5193 #ifdef JP
5194                                    encoding:NSJapaneseEUCStringEncoding
5195 #else
5196                                    encoding:NSMacOSRomanStringEncoding
5197 #endif
5198         ];
5199         NSAlert *alert = [[NSAlert alloc] init];
5200
5201         alert.messageText = msg;
5202         alert.informativeText = info;
5203         [alert runModal];
5204     }
5205 }
5206
5207
5208 /**
5209  * Hook to tell the user something, and then quit
5210  */
5211 static void hook_quit(const char * str)
5212 {
5213     for (int i = ANGBAND_TERM_MAX - 1; i >= 0; --i) {
5214         if (angband_term[i]) {
5215             term_nuke(angband_term[i]);
5216         }
5217     }
5218     [AngbandSoundCatalog clearSharedSounds];
5219     [AngbandContext setDefaultFont:nil];
5220     plog(str);
5221     exit(0);
5222 }
5223
5224 /**
5225  * Return the path for Angband's lib directory and bail if it isn't found. The
5226  * lib directory should be in the bundle's resources directory, since it's
5227  * copied when built.
5228  */
5229 static NSString* get_lib_directory(void)
5230 {
5231     NSString *bundleLibPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: AngbandDirectoryNameLib];
5232     BOOL isDirectory = NO;
5233     BOOL libExists = [[NSFileManager defaultManager] fileExistsAtPath: bundleLibPath isDirectory: &isDirectory];
5234
5235     if( !libExists || !isDirectory )
5236     {
5237         NSLog( @"%@: can't find %@/ in bundle: isDirectory: %d libExists: %d", @VERSION_NAME, AngbandDirectoryNameLib, isDirectory, libExists );
5238
5239         NSString *msg = NSLocalizedStringWithDefaultValue(
5240             @"Error.MissingResources",
5241             AngbandMessageCatalog,
5242             [NSBundle mainBundle],
5243             @"Missing Resources",
5244             @"Alert text for missing resources");
5245         NSString *info = NSLocalizedStringWithDefaultValue(
5246             @"Error.MissingAngbandLib",
5247             AngbandMessageCatalog,
5248             [NSBundle mainBundle],
5249             @"Hengband was unable to find required resources and must quit. Please report a bug on the Angband forums.",
5250             @"Alert informative message for missing Angband lib/ folder");
5251         NSString *quit_label = NSLocalizedStringWithDefaultValue(
5252             @"Label.Quit", AngbandMessageCatalog, [NSBundle mainBundle],
5253             @"Quit", @"Quit");
5254         NSAlert *alert = [[NSAlert alloc] init];
5255         /*
5256          * Note that NSCriticalAlertStyle was deprecated in 10.10.  The
5257          * replacement is NSAlertStyleCritical.
5258          */
5259         alert.alertStyle = NSCriticalAlertStyle;
5260         alert.messageText = msg;
5261         alert.informativeText = info;
5262         [alert addButtonWithTitle:quit_label];
5263         [alert runModal];
5264         exit(0);
5265     }
5266
5267     return bundleLibPath;
5268 }
5269
5270 /**
5271  * Return the path for the directory where Angband should look for its standard
5272  * user file tree.
5273  */
5274 static NSString* get_doc_directory(void)
5275 {
5276         NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
5277
5278 #if defined(SAFE_DIRECTORY)
5279         NSString *versionedDirectory = [NSString stringWithFormat: @"%@-%s", AngbandDirectoryNameBase, VERSION_STRING];
5280         return [documents stringByAppendingPathComponent: versionedDirectory];
5281 #else
5282         return [documents stringByAppendingPathComponent: AngbandDirectoryNameBase];
5283 #endif
5284 }
5285
5286 /**
5287  * Adjust directory paths as needed to correct for any differences needed by
5288  * Angband.  init_file_paths() currently requires that all paths provided have
5289  * a trailing slash and all other platforms honor this.
5290  *
5291  * \param originalPath The directory path to adjust.
5292  * \return A path suitable for Angband or nil if an error occurred.
5293  */
5294 static NSString* AngbandCorrectedDirectoryPath(NSString *originalPath)
5295 {
5296         if ([originalPath length] == 0) {
5297                 return nil;
5298         }
5299
5300         if (![originalPath hasSuffix: @"/"]) {
5301                 return [originalPath stringByAppendingString: @"/"];
5302         }
5303
5304         return originalPath;
5305 }
5306
5307 /**
5308  * Give Angband the base paths that should be used for the various directories
5309  * it needs. It will create any needed directories.
5310  */
5311 static void prepare_paths_and_directories(void)
5312 {
5313         char libpath[PATH_MAX + 1] = "\0";
5314         NSString *libDirectoryPath =
5315             AngbandCorrectedDirectoryPath(get_lib_directory());
5316         [libDirectoryPath getFileSystemRepresentation: libpath maxLength: sizeof(libpath)];
5317
5318         char basepath[PATH_MAX + 1] = "\0";
5319         NSString *angbandDocumentsPath =
5320             AngbandCorrectedDirectoryPath(get_doc_directory());
5321         [angbandDocumentsPath getFileSystemRepresentation: basepath maxLength: sizeof(basepath)];
5322
5323         init_file_paths(libpath, basepath);
5324         create_needed_dirs();
5325 }
5326
5327 /**
5328  * Create and initialize Angband terminal number "i".
5329  */
5330 static term *term_data_link(int i)
5331 {
5332     NSArray *terminalDefaults = [[NSUserDefaults standardUserDefaults]
5333                                     valueForKey: AngbandTerminalsDefaultsKey];
5334     NSInteger rows = 24;
5335     NSInteger columns = 80;
5336
5337     if (i < (int)[terminalDefaults count]) {
5338         NSDictionary *term = [terminalDefaults objectAtIndex:i];
5339         rows = [[term valueForKey: AngbandTerminalRowsDefaultsKey]
5340                    integerValue];
5341         columns = [[term valueForKey: AngbandTerminalColumnsDefaultsKey]
5342                       integerValue];
5343     }
5344
5345     /* Allocate */
5346     term *newterm = ZNEW(term);
5347
5348     /* Initialize the term */
5349     term_init(newterm, columns, rows, 256 /* keypresses, for some reason? */);
5350
5351     /* Use a "software" cursor */
5352     newterm->soft_cursor = TRUE;
5353
5354     /* Disable the per-row flush notifications since they are not used. */
5355     newterm->never_frosh = TRUE;
5356
5357     /*
5358      * Differentiate between BS/^h, Tab/^i, ... so ^h and ^j work under the
5359      * roguelike command set.
5360      */
5361     /* newterm->complex_input = TRUE; */
5362
5363     /* Erase with "white space" */
5364     newterm->attr_blank = TERM_WHITE;
5365     newterm->char_blank = ' ';
5366
5367     /* Prepare the init/nuke hooks */
5368     newterm->init_hook = Term_init_cocoa;
5369     newterm->nuke_hook = Term_nuke_cocoa;
5370
5371     /* Prepare the function hooks */
5372     newterm->xtra_hook = Term_xtra_cocoa;
5373     newterm->wipe_hook = Term_wipe_cocoa;
5374     newterm->curs_hook = Term_curs_cocoa;
5375     newterm->bigcurs_hook = Term_bigcurs_cocoa;
5376     newterm->text_hook = Term_text_cocoa;
5377     newterm->pict_hook = Term_pict_cocoa;
5378     /* newterm->mbcs_hook = Term_mbcs_cocoa; */
5379
5380     /* Global pointer */
5381     angband_term[i] = newterm;
5382
5383     return newterm;
5384 }
5385
5386 /**
5387  * Load preferences from preferences file for current host+current user+
5388  * current application.
5389  */
5390 static void load_prefs(void)
5391 {
5392     NSUserDefaults *defs = [NSUserDefaults angbandDefaults];
5393
5394     /* Make some default defaults */
5395     NSMutableArray *defaultTerms = [[NSMutableArray alloc] init];
5396
5397     /*
5398      * The following default rows/cols were determined experimentally by first
5399      * finding the ideal window/font size combinations. But because of awful
5400      * temporal coupling in Term_init_cocoa(), it's impossible to set up the
5401      * defaults there, so we do it this way.
5402      */
5403     for (NSUInteger i = 0; i < ANGBAND_TERM_MAX; i++) {
5404         int columns, rows;
5405         BOOL visible = YES;
5406
5407         switch (i) {
5408         case 0:
5409             columns = 129;
5410             rows = 32;
5411             break;
5412         case 1:
5413             columns = 84;
5414             rows = 20;
5415             break;
5416         case 2:
5417             columns = 42;
5418             rows = 24;
5419             break;
5420         case 3:
5421             columns = 42;
5422             rows = 20;
5423             break;
5424         case 4:
5425             columns = 42;
5426             rows = 16;
5427             break;
5428         case 5:
5429             columns = 84;
5430             rows = 20;
5431             break;
5432         default:
5433             columns = 80;
5434             rows = 24;
5435             visible = NO;
5436             break;
5437         }
5438
5439         NSDictionary *standardTerm =
5440             [NSDictionary dictionaryWithObjectsAndKeys:
5441                           [NSNumber numberWithInt: rows], AngbandTerminalRowsDefaultsKey,
5442                           [NSNumber numberWithInt: columns], AngbandTerminalColumnsDefaultsKey,
5443                           [NSNumber numberWithBool: visible], AngbandTerminalVisibleDefaultsKey,
5444                           nil];
5445         [defaultTerms addObject: standardTerm];
5446     }
5447
5448     NSDictionary *defaults = [[NSDictionary alloc] initWithObjectsAndKeys:
5449 #ifdef JP
5450                               @"Osaka", @"FontName",
5451 #else
5452                               @"Menlo", @"FontName",
5453 #endif
5454                               [NSNumber numberWithFloat:13.f], @"FontSize",
5455                               [NSNumber numberWithInt:60], AngbandFrameRateDefaultsKey,
5456                               [NSNumber numberWithBool:YES], AngbandSoundDefaultsKey,
5457                               [NSNumber numberWithInt:GRAPHICS_NONE], AngbandGraphicsDefaultsKey,
5458                               [NSNumber numberWithBool:YES], AngbandBigTileDefaultsKey,
5459                               defaultTerms, AngbandTerminalsDefaultsKey,
5460                               nil];
5461     [defs registerDefaults:defaults];
5462
5463     /* Preferred graphics mode */
5464     graf_mode_req = [defs integerForKey:AngbandGraphicsDefaultsKey];
5465     if (graphics_will_be_enabled() &&
5466         [defs boolForKey:AngbandBigTileDefaultsKey] == YES) {
5467         use_bigtile = TRUE;
5468         arg_bigtile = TRUE;
5469     } else {
5470         use_bigtile = FALSE;
5471         arg_bigtile = FALSE;
5472     }
5473
5474     /* Use sounds; set the Angband global */
5475     if ([defs boolForKey:AngbandSoundDefaultsKey] == YES) {
5476         use_sound = TRUE;
5477         [AngbandSoundCatalog sharedSounds].enabled = YES;
5478     } else {
5479         use_sound = FALSE;
5480         [AngbandSoundCatalog sharedSounds].enabled = NO;
5481     }
5482
5483     /* fps */
5484     frames_per_second = [defs integerForKey:AngbandFrameRateDefaultsKey];
5485
5486     /* Font */
5487     [AngbandContext
5488         setDefaultFont:[NSFont fontWithName:[defs valueForKey:@"FontName-0"]
5489                                size:[defs floatForKey:@"FontSize-0"]]];
5490     if (! [AngbandContext defaultFont])
5491         [AngbandContext
5492             setDefaultFont:[NSFont fontWithName:@"Menlo" size:13.]];
5493 }
5494
5495 /**
5496  * Play sound effects asynchronously.  Select a sound from any available
5497  * for the required event, and bridge to Cocoa to play it.
5498  */
5499 static void play_sound(int event)
5500 {
5501     [[AngbandSoundCatalog sharedSounds] playSound:event];
5502 }
5503
5504 /**
5505  * Allocate the primary Angband terminal and activate it.  Allocate the other
5506  * Angband terminals.
5507  */
5508 static void init_windows(void)
5509 {
5510     /* Create the primary window */
5511     term *primary = term_data_link(0);
5512
5513     /* Prepare to create any additional windows */
5514     for (int i = 1; i < ANGBAND_TERM_MAX; i++) {
5515         term_data_link(i);
5516     }
5517
5518     /* Activate the primary term */
5519     Term_activate(primary);
5520 }
5521
5522 /**
5523  * ------------------------------------------------------------------------
5524  * Main program
5525  * ------------------------------------------------------------------------ */
5526
5527 @implementation AngbandAppDelegate
5528
5529 @synthesize graphicsMenu=_graphicsMenu;
5530 @synthesize commandMenu=_commandMenu;
5531 @synthesize commandMenuTagMap=_commandMenuTagMap;
5532
5533 - (IBAction)newGame:sender
5534 {
5535     /* Game is in progress */
5536     game_in_progress = TRUE;
5537     new_game = TRUE;
5538 }
5539
5540 - (IBAction)editFont:sender
5541 {
5542     NSFontPanel *panel = [NSFontPanel sharedFontPanel];
5543     NSFont *termFont = [AngbandContext defaultFont];
5544
5545     int i;
5546     for (i=0; i < ANGBAND_TERM_MAX; i++) {
5547         AngbandContext *context =
5548             (__bridge AngbandContext*) (angband_term[i]->data);
5549         if ([context isKeyWindow]) {
5550             termFont = [context angbandViewFont];
5551             break;
5552         }
5553     }
5554
5555     [panel setPanelFont:termFont isMultiple:NO];
5556     [panel orderFront:self];
5557 }
5558
5559 /**
5560  * Implement NSObject's changeFont() method to receive a notification about the
5561  * changed font.  Note that, as of 10.14, changeFont() is deprecated in
5562  * NSObject - it will be removed at some point and the application delegate
5563  * will have to be declared as implementing the NSFontChanging protocol.
5564  */
5565 - (void)changeFont:(id)sender
5566 {
5567     int mainTerm;
5568     for (mainTerm=0; mainTerm < ANGBAND_TERM_MAX; mainTerm++) {
5569         AngbandContext *context =
5570             (__bridge AngbandContext*) (angband_term[mainTerm]->data);
5571         if ([context isKeyWindow]) {
5572             break;
5573         }
5574     }
5575
5576     /* Bug #1709: Only change font for angband windows */
5577     if (mainTerm == ANGBAND_TERM_MAX) return;
5578
5579     NSFont *oldFont = [AngbandContext defaultFont];
5580     NSFont *newFont = [sender convertFont:oldFont];
5581     if (! newFont) return; /*paranoia */
5582
5583     /* Store as the default font if we changed the first term */
5584     if (mainTerm == 0) {
5585         [AngbandContext setDefaultFont:newFont];
5586     }
5587
5588     /* Record it in the preferences */
5589     NSUserDefaults *defs = [NSUserDefaults angbandDefaults];
5590     [defs setValue:[newFont fontName] 
5591         forKey:[NSString stringWithFormat:@"FontName-%d", mainTerm]];
5592     [defs setFloat:[newFont pointSize]
5593         forKey:[NSString stringWithFormat:@"FontSize-%d", mainTerm]];
5594
5595     NSDisableScreenUpdates();
5596
5597     /* Update window */
5598     AngbandContext *angbandContext =
5599         (__bridge AngbandContext*) (angband_term[mainTerm]->data);
5600     [(id)angbandContext setSelectionFont:newFont adjustTerminal: YES];
5601
5602     NSEnableScreenUpdates();
5603
5604     if (mainTerm != 0 || ! redraw_for_tiles_or_term0_font()) {
5605         [(id)angbandContext requestRedraw];
5606     }
5607 }
5608
5609 - (IBAction)openGame:sender
5610 {
5611     @autoreleasepool {
5612         BOOL selectedSomething = NO;
5613         int panelResult;
5614
5615         /* Get where we think the save files are */
5616         NSURL *startingDirectoryURL =
5617             [NSURL fileURLWithPath:[NSString stringWithCString:ANGBAND_DIR_SAVE encoding:NSASCIIStringEncoding]
5618                    isDirectory:YES];
5619
5620         /* Set up an open panel */
5621         NSOpenPanel* panel = [NSOpenPanel openPanel];
5622         [panel setCanChooseFiles:YES];
5623         [panel setCanChooseDirectories:NO];
5624         [panel setResolvesAliases:YES];
5625         [panel setAllowsMultipleSelection:NO];
5626         [panel setTreatsFilePackagesAsDirectories:YES];
5627         [panel setDirectoryURL:startingDirectoryURL];
5628
5629         /* Run it */
5630         panelResult = [panel runModal];
5631         if (panelResult == NSOKButton)
5632         {
5633             NSArray* fileURLs = [panel URLs];
5634             if ([fileURLs count] > 0 && [[fileURLs objectAtIndex:0] isFileURL])
5635             {
5636                 NSURL* savefileURL = (NSURL *)[fileURLs objectAtIndex:0];
5637                 /*
5638                  * The path property doesn't do the right thing except for
5639                  * URLs with the file scheme. We had
5640                  * getFileSystemRepresentation here before, but that wasn't
5641                  * introduced until OS X 10.9.
5642                  */
5643                 selectedSomething = [[savefileURL path]
5644                                         getCString:savefile
5645                                         maxLength:sizeof savefile
5646                                         encoding:NSMacOSRomanStringEncoding];
5647             }
5648         }
5649
5650         if (selectedSomething)
5651         {
5652             /* Remember this so we can select it by default next time */
5653             record_current_savefile();
5654
5655             /* Game is in progress */
5656             game_in_progress = TRUE;
5657         }
5658     }
5659 }
5660
5661 - (IBAction)saveGame:sender
5662 {
5663     /* Hack -- Forget messages */
5664     msg_flag = FALSE;
5665     
5666     /* Save the game */
5667     do_cmd_save_game(FALSE);
5668     
5669     /*
5670      * Record the current save file so we can select it by default next time.
5671      * It's a little sketchy that this only happens when we save through the
5672      * menu; ideally game-triggered saves would trigger it too.
5673      */
5674     record_current_savefile();
5675 }
5676
5677 /**
5678  * Entry point for initializing Angband
5679  */
5680 - (void)beginGame
5681 {
5682     @autoreleasepool {
5683         /* Hooks in some "z-util.c" hooks */
5684         plog_aux = hook_plog;
5685         quit_aux = hook_quit;
5686
5687         /* Initialize file paths */
5688         prepare_paths_and_directories();
5689
5690         /* Note the "system" */
5691         ANGBAND_SYS = "coc";
5692
5693         /* Load possible graphics modes */
5694         init_graphics_modes();
5695
5696         /* Load preferences */
5697         load_prefs();
5698
5699         /* Prepare the windows */
5700         init_windows();
5701
5702         /* Set up game event handlers */
5703         /* init_display(); */
5704
5705         /* Register the sound hook */
5706         /* sound_hook = play_sound; */
5707
5708         /* Initialize some save file stuff */
5709         player_euid = geteuid();
5710         player_egid = getegid();
5711
5712         /* Initialise game */
5713         init_angband();
5714
5715         /* We are now initialized */
5716         initialized = TRUE;
5717
5718         /* Handle "open_when_ready" */
5719         handle_open_when_ready();
5720
5721         /* Handle pending events (most notably update) and flush input */
5722         Term_flush();
5723
5724         /*
5725          * Prompt the user; assume the splash screen is 80 x 23 and position
5726          * relative to that rather than center based on the full size of the
5727          * window.
5728          */
5729         int message_row = 23;
5730         Term_erase(0, message_row, 255);
5731         put_str(
5732 #ifdef JP
5733             "['ファイル' メニューから '新規' または '開く' を選択します]",
5734             message_row, (80 - 59) / 2
5735 #else
5736             "[Choose 'New' or 'Open' from the 'File' menu]",
5737             message_row, (80 - 45) / 2
5738 #endif
5739         );
5740         Term_fresh();
5741     }
5742
5743     while (!game_in_progress) {
5744         @autoreleasepool {
5745             NSEvent *event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:[NSDate distantFuture] inMode:NSDefaultRunLoopMode dequeue:YES];
5746             if (event) [NSApp sendEvent:event];
5747         }
5748     }
5749
5750     /*
5751      * Play a game -- "new_game" is set by "new", "open" or the open document
5752      * even handler as appropriate
5753      */
5754     Term_fresh();
5755     play_game(new_game);
5756
5757     quit(NULL);
5758 }
5759
5760 /**
5761  * Implement NSObject's validateMenuItem() method to override enabling or
5762  * disabling a menu item.  Note that, as of 10.14, validateMenuItem() is
5763  * deprecated in NSObject - it will be removed at some point and the
5764  * application delegate will have to be declared as implementing the
5765  * NSMenuItemValidation protocol.
5766  */
5767 - (BOOL)validateMenuItem:(NSMenuItem *)menuItem
5768 {
5769     SEL sel = [menuItem action];
5770     NSInteger tag = [menuItem tag];
5771
5772     if( tag >= AngbandWindowMenuItemTagBase && tag < AngbandWindowMenuItemTagBase + ANGBAND_TERM_MAX )
5773     {
5774         if( tag == AngbandWindowMenuItemTagBase )
5775         {
5776             /* The main window should always be available and visible */
5777             return YES;
5778         }
5779         else
5780         {
5781             /*
5782              * Another window is only usable after Term_init_cocoa() has
5783              * been called for it.  For Angband if window_flag[i] is nonzero
5784              * then that has happened for window i.  For Hengband, that is
5785              * not the case so also test angband_term[i]->data.
5786              */
5787             NSInteger subwindowNumber = tag - AngbandWindowMenuItemTagBase;
5788             return (angband_term[subwindowNumber]->data != 0
5789                     && window_flag[subwindowNumber] > 0);
5790         }
5791
5792         return NO;
5793     }
5794
5795     if (sel == @selector(newGame:))
5796     {
5797         return ! game_in_progress;
5798     }
5799     else if (sel == @selector(editFont:))
5800     {
5801         return YES;
5802     }
5803     else if (sel == @selector(openGame:))
5804     {
5805         return ! game_in_progress;
5806     }
5807     else if (sel == @selector(setRefreshRate:) &&
5808              [[menuItem parentItem] tag] == 150)
5809     {
5810         NSInteger fps = [[NSUserDefaults standardUserDefaults] integerForKey:AngbandFrameRateDefaultsKey];
5811         [menuItem setState: ([menuItem tag] == fps)];
5812         return YES;
5813     }
5814     else if( sel == @selector(setGraphicsMode:) )
5815     {
5816         NSInteger requestedGraphicsMode = [[NSUserDefaults standardUserDefaults] integerForKey:AngbandGraphicsDefaultsKey];
5817         [menuItem setState: (tag == requestedGraphicsMode)];
5818         return YES;
5819     }
5820     else if( sel == @selector(toggleSound:) )
5821     {
5822         BOOL is_on = [[NSUserDefaults standardUserDefaults]
5823                          boolForKey:AngbandSoundDefaultsKey];
5824
5825         [menuItem setState: ((is_on) ? NSOnState : NSOffState)];
5826         return YES;
5827     }
5828     else if (sel == @selector(toggleWideTiles:)) {
5829         BOOL is_on = [[NSUserDefaults standardUserDefaults]
5830                          boolForKey:AngbandBigTileDefaultsKey];
5831
5832         [menuItem setState: ((is_on) ? NSOnState : NSOffState)];
5833         return YES;
5834     }
5835     else if( sel == @selector(sendAngbandCommand:) ||
5836              sel == @selector(saveGame:) )
5837     {
5838         /*
5839          * we only want to be able to send commands during an active game
5840          * after the birth screens
5841          */
5842         return !!game_in_progress && character_generated;
5843     }
5844     else return YES;
5845 }
5846
5847
5848 - (IBAction)setRefreshRate:(NSMenuItem *)menuItem
5849 {
5850     frames_per_second = [menuItem tag];
5851     [[NSUserDefaults angbandDefaults] setInteger:frames_per_second forKey:AngbandFrameRateDefaultsKey];
5852 }
5853
5854 - (void)setGraphicsMode:(NSMenuItem *)sender
5855 {
5856     /* We stashed the graphics mode ID in the menu item's tag */
5857     graf_mode_req = [sender tag];
5858
5859     /* Stash it in UserDefaults */
5860     [[NSUserDefaults angbandDefaults] setInteger:graf_mode_req forKey:AngbandGraphicsDefaultsKey];
5861
5862     if (! graphics_will_be_enabled()) {
5863         if (use_bigtile) {
5864             arg_bigtile = FALSE;
5865         }
5866     } else if ([[NSUserDefaults angbandDefaults] boolForKey:AngbandBigTileDefaultsKey] == YES &&
5867                ! use_bigtile) {
5868         arg_bigtile = TRUE;
5869     }
5870
5871     if (arg_bigtile != use_bigtile) {
5872         Term_activate(angband_term[0]);
5873         Term_resize(angband_term[0]->wid, angband_term[0]->hgt);
5874     }
5875     redraw_for_tiles_or_term0_font();
5876 }
5877
5878 - (void)selectWindow: (id)sender
5879 {
5880     NSInteger subwindowNumber =
5881         [(NSMenuItem *)sender tag] - AngbandWindowMenuItemTagBase;
5882     AngbandContext *context =
5883         (__bridge AngbandContext*) (angband_term[subwindowNumber]->data);
5884     [context.primaryWindow makeKeyAndOrderFront: self];
5885     [context saveWindowVisibleToDefaults: YES];
5886 }
5887
5888 - (IBAction) toggleSound: (NSMenuItem *) sender
5889 {
5890     BOOL is_on = (sender.state == NSOnState);
5891
5892     /* Toggle the state and update the Angband global and preferences. */
5893     if (is_on) {
5894         sender.state = NSOffState;
5895         use_sound = FALSE;
5896         [AngbandSoundCatalog sharedSounds].enabled = NO;
5897     } else {
5898         sender.state = NSOnState;
5899         use_sound = TRUE;
5900         [AngbandSoundCatalog sharedSounds].enabled = YES;
5901     }
5902     [[NSUserDefaults angbandDefaults] setBool:(! is_on)
5903                                       forKey:AngbandSoundDefaultsKey];
5904 }
5905
5906 - (IBAction)toggleWideTiles:(NSMenuItem *) sender
5907 {
5908     BOOL is_on = (sender.state == NSOnState);
5909
5910     /* Toggle the state and update the Angband globals and preferences. */
5911     sender.state = (is_on) ? NSOffState : NSOnState;
5912     [[NSUserDefaults angbandDefaults] setBool:(! is_on)
5913                                       forKey:AngbandBigTileDefaultsKey];
5914     if (graphics_are_enabled()) {
5915         arg_bigtile = (is_on) ? FALSE : TRUE;
5916         if (arg_bigtile != use_bigtile) {
5917             Term_activate(angband_term[0]);
5918             Term_resize(angband_term[0]->wid, angband_term[0]->hgt);
5919             redraw_for_tiles_or_term0_font();
5920         }
5921     }
5922 }
5923
5924 - (void)prepareWindowsMenu
5925 {
5926     @autoreleasepool {
5927         /*
5928          * Get the window menu with default items and add a separator and
5929          * item for the main window.
5930          */
5931         NSMenu *windowsMenu = [[NSApplication sharedApplication] windowsMenu];
5932         [windowsMenu addItem: [NSMenuItem separatorItem]];
5933
5934         NSString *title1 = [NSString stringWithCString:angband_term_name[0]
5935 #ifdef JP
5936                                      encoding:NSJapaneseEUCStringEncoding
5937 #else
5938                                      encoding:NSMacOSRomanStringEncoding
5939 #endif
5940         ];
5941         NSMenuItem *angbandItem = [[NSMenuItem alloc] initWithTitle:title1 action: @selector(selectWindow:) keyEquivalent: @"0"];
5942         [angbandItem setTarget: self];
5943         [angbandItem setTag: AngbandWindowMenuItemTagBase];
5944         [windowsMenu addItem: angbandItem];
5945
5946         /* Add items for the additional term windows */
5947         for( NSInteger i = 1; i < ANGBAND_TERM_MAX; i++ )
5948         {
5949             NSString *title = [NSString stringWithCString:angband_term_name[i]
5950 #ifdef JP
5951                                         encoding:NSJapaneseEUCStringEncoding
5952 #else
5953                                         encoding:NSMacOSRomanStringEncoding
5954 #endif
5955             ];
5956             NSString *keyEquivalent =
5957                 [NSString stringWithFormat: @"%ld", (long)i];
5958             NSMenuItem *windowItem =
5959                 [[NSMenuItem alloc] initWithTitle: title
5960                                     action: @selector(selectWindow:)
5961                                     keyEquivalent: keyEquivalent];
5962             [windowItem setTarget: self];
5963             [windowItem setTag: AngbandWindowMenuItemTagBase + i];
5964             [windowsMenu addItem: windowItem];
5965         }
5966     }
5967 }
5968
5969 /**
5970  *  Send a command to Angband via a menu item. This places the appropriate key
5971  * down events into the queue so that it seems like the user pressed them
5972  * (instead of trying to use the term directly).
5973  */
5974 - (void)sendAngbandCommand: (id)sender
5975 {
5976     NSMenuItem *menuItem = (NSMenuItem *)sender;
5977     NSString *command = [self.commandMenuTagMap objectForKey: [NSNumber numberWithInteger: [menuItem tag]]];
5978     AngbandContext* context =
5979         (__bridge AngbandContext*) (angband_term[0]->data);
5980     NSInteger windowNumber = [context.primaryWindow windowNumber];
5981
5982     /* Send a \ to bypass keymaps */
5983     NSEvent *escape = [NSEvent keyEventWithType: NSKeyDown
5984                                        location: NSZeroPoint
5985                                   modifierFlags: 0
5986                                       timestamp: 0.0
5987                                    windowNumber: windowNumber
5988                                         context: nil
5989                                      characters: @"\\"
5990                     charactersIgnoringModifiers: @"\\"
5991                                       isARepeat: NO
5992                                         keyCode: 0];
5993     [[NSApplication sharedApplication] postEvent: escape atStart: NO];
5994
5995     /* Send the actual command (from the original command set) */
5996     NSEvent *keyDown = [NSEvent keyEventWithType: NSKeyDown
5997                                         location: NSZeroPoint
5998                                    modifierFlags: 0
5999                                        timestamp: 0.0
6000                                     windowNumber: windowNumber
6001                                          context: nil
6002                                       characters: command
6003                      charactersIgnoringModifiers: command
6004                                        isARepeat: NO
6005                                          keyCode: 0];
6006     [[NSApplication sharedApplication] postEvent: keyDown atStart: NO];
6007 }
6008
6009 /**
6010  *  Set up the command menu dynamically, based on CommandMenu.plist.
6011  */
6012 - (void)prepareCommandMenu
6013 {
6014     @autoreleasepool {
6015         NSString *commandMenuPath =
6016             [[NSBundle mainBundle] pathForResource: @"CommandMenu"
6017                                    ofType: @"plist"];
6018         NSArray *commandMenuItems =
6019             [[NSArray alloc] initWithContentsOfFile: commandMenuPath];
6020         NSMutableDictionary *angbandCommands =
6021             [[NSMutableDictionary alloc] init];
6022         NSString *tblname = @"CommandMenu";
6023         NSInteger tagOffset = 0;
6024
6025         for( NSDictionary *item in commandMenuItems )
6026         {
6027             BOOL useShiftModifier =
6028                 [[item valueForKey: @"ShiftModifier"] boolValue];
6029             BOOL useOptionModifier =
6030                 [[item valueForKey: @"OptionModifier"] boolValue];
6031             NSUInteger keyModifiers = NSCommandKeyMask;
6032             keyModifiers |= (useShiftModifier) ? NSShiftKeyMask : 0;
6033             keyModifiers |= (useOptionModifier) ? NSAlternateKeyMask : 0;
6034
6035             NSString *lookup = [item valueForKey: @"Title"];
6036             NSString *title = NSLocalizedStringWithDefaultValue(
6037                 lookup, tblname, [NSBundle mainBundle], lookup, @"");
6038             NSString *key = [item valueForKey: @"KeyEquivalent"];
6039             NSMenuItem *menuItem =
6040                 [[NSMenuItem alloc] initWithTitle: title
6041                                     action: @selector(sendAngbandCommand:)
6042                                     keyEquivalent: key];
6043             [menuItem setTarget: self];
6044             [menuItem setKeyEquivalentModifierMask: keyModifiers];
6045             [menuItem setTag: AngbandCommandMenuItemTagBase + tagOffset];
6046             [self.commandMenu addItem: menuItem];
6047
6048             NSString *angbandCommand = [item valueForKey: @"AngbandCommand"];
6049             [angbandCommands setObject: angbandCommand
6050                              forKey: [NSNumber numberWithInteger: [menuItem tag]]];
6051             tagOffset++;
6052         }
6053
6054         self.commandMenuTagMap = [[NSDictionary alloc]
6055                                      initWithDictionary: angbandCommands];
6056     }
6057 }
6058
6059 - (void)awakeFromNib
6060 {
6061     [super awakeFromNib];
6062
6063     [self prepareWindowsMenu];
6064     [self prepareCommandMenu];
6065 }
6066
6067 - (void)applicationDidFinishLaunching:sender
6068 {
6069     [self beginGame];
6070     
6071     /* Once beginGame finished, the game is over - that's how Angband works,
6072          * and we should quit */
6073     game_is_finished = TRUE;
6074     [NSApp terminate:self];
6075 }
6076
6077 - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
6078 {
6079     if (p_ptr->playing == FALSE || game_is_finished == TRUE)
6080     {
6081         quit_when_ready = true;
6082         return NSTerminateNow;
6083     }
6084     else if (! inkey_flag)
6085     {
6086         /* For compatibility with other ports, do not quit in this case */
6087         return NSTerminateCancel;
6088     }
6089     else
6090     {
6091         /* Stop playing */
6092         /* player->upkeep->playing = FALSE; */
6093
6094         /* Post an escape event so that we can return from our get-key-event
6095                  * function */
6096         wakeup_event_loop();
6097         quit_when_ready = true;
6098         /* Must return Cancel, not Later, because we need to get out of the
6099                  * run loop and back to Angband's loop */
6100         return NSTerminateCancel;
6101     }
6102 }
6103
6104 /**
6105  * Dynamically build the Graphics menu
6106  */
6107 - (void)menuNeedsUpdate:(NSMenu *)menu {
6108     
6109     /* Only the graphics menu is dynamic */
6110     if (! [menu isEqual:self.graphicsMenu])
6111         return;
6112     
6113     /* If it's non-empty, then we've already built it. Currently graphics modes
6114          * won't change once created; if they ever can we can remove this check.
6115      * Note that the check mark does change, but that's handled in
6116          * validateMenuItem: instead of menuNeedsUpdate: */
6117     if ([menu numberOfItems] > 0)
6118         return;
6119     
6120     /* This is the action for all these menu items */
6121     SEL action = @selector(setGraphicsMode:);
6122     
6123     /* Add an initial Classic ASCII menu item */
6124     NSString *tblname = @"GraphicsMenu";
6125     NSString *key = @"Classic ASCII";
6126     NSString *title = NSLocalizedStringWithDefaultValue(
6127         key, tblname, [NSBundle mainBundle], key, @"");
6128     NSMenuItem *classicItem = [menu addItemWithTitle:title action:action keyEquivalent:@""];
6129     [classicItem setTag:GRAPHICS_NONE];
6130     
6131     /* Walk through the list of graphics modes */
6132     if (graphics_modes) {
6133         NSInteger i;
6134
6135         for (i=0; graphics_modes[i].pNext; i++)
6136         {
6137             const graphics_mode *graf = &graphics_modes[i];
6138
6139             if (graf->grafID == GRAPHICS_NONE) {
6140                 continue;
6141             }
6142             /* Make the title. NSMenuItem throws on a nil title, so ensure it's
6143                    * not nil. */
6144             key = [[NSString alloc] initWithUTF8String:graf->menuname];
6145             title = NSLocalizedStringWithDefaultValue(
6146                 key, tblname, [NSBundle mainBundle], key, @"");
6147
6148             /* Make the item */
6149             NSMenuItem *item = [menu addItemWithTitle:title action:action keyEquivalent:@""];
6150             [item setTag:graf->grafID];
6151         }
6152     }
6153 }
6154
6155 /**
6156  * Delegate method that gets called if we're asked to open a file.
6157  */
6158 - (void)application:(NSApplication *)sender openFiles:(NSArray *)filenames
6159 {
6160     /* Can't open a file once we've started */
6161     if (game_in_progress) {
6162         [[NSApplication sharedApplication]
6163             replyToOpenOrPrint:NSApplicationDelegateReplyFailure];
6164         return;
6165     }
6166
6167     /* We can only open one file. Use the last one. */
6168     NSString *file = [filenames lastObject];
6169     if (! file) {
6170         [[NSApplication sharedApplication]
6171             replyToOpenOrPrint:NSApplicationDelegateReplyFailure];
6172         return;
6173     }
6174
6175     /* Put it in savefile */
6176     if (! [file getFileSystemRepresentation:savefile maxLength:sizeof savefile]) {
6177         [[NSApplication sharedApplication]
6178             replyToOpenOrPrint:NSApplicationDelegateReplyFailure];
6179         return;
6180     }
6181
6182     game_in_progress = TRUE;
6183
6184     /* Wake us up in case this arrives while we're sitting at the Welcome
6185          * screen! */
6186     wakeup_event_loop();
6187
6188     [[NSApplication sharedApplication]
6189         replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
6190 }
6191
6192 @end
6193
6194 int main(int argc, char* argv[])
6195 {
6196     NSApplicationMain(argc, (void*)argv);
6197     return (0);
6198 }
6199
6200 #endif /* MACINTOSH || MACH_O_COCOA */