Debian Codegraph @

src/main-cocoa.m

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