/
main-crb.c
4003 lines (3240 loc) · 99.1 KB
/
main-crb.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* File: main-crb.c
* Purpose: Provide support for OS X, version 10.3 and later.
*
* Copyright (c) 2003 pelpel
* Copyright (c) 2003,2004,2005 Robert Ruehlmann
* Copyright (c) 2007,2008 pete mack
* Copyright (c) 2008 Rowan Beentje
*
* Cameron Browne (2010) added code to GetTileImage() to avoid image tiles
* interpolating across tile boundaries and leaking into neighbours.
*
* Some excerpts quoted under fair use from works by Ben Harrison,
* Keith Randall, Peter Ammon, and Ron Anderson.
*
* This work is free software; you can redistribute it and/or modify it
* under the terms of either:
*
* a) the GNU General Public License as published by the Free Software
* Foundation, version 2, or
*
* b) the "Angband licence":
* This software may be copied and distributed for educational, research,
* and not for profit purposes provided that this copyright and statement
* are included in all such copies. Other copyrights may also apply.
*/
#include "angband.h"
/*
* Notes:
*
* (pelpel) Characters in the ASCII mode are clipped by their bounding
* rects to reduce redraw artefacts that were quite annoying in certain
* font-point combos.
*
*
* (pete mack) Nearly all quickdraw removed to improve performance from
* interleaved Quickdraw and CGContext events. (Hence the really ugly
* ATSU font metrics.)
* IMPORTANT: If you need to use QuickDraw, make sure to call hibernate()
* and SetPort() first. This will keep the graphics state consistent.
*
* (pete mack) If you wish to add additional heirarchical menus, the following
* must hold:
* All menus and submenus must have unique ids.
* All menus must have IDs greater than 0 and less than MAX_MENU_ID
* All submenus must have greater IDs than their parents.
*
*
* Important Resources in the resource file:
*
* FREF 130 = ANGBAND_CREATOR / 'APPL' (application)
* FREF 129 = ANGBAND_CREATOR / 'SAVE' (save file)
* FREF 130 = ANGBAND_CREATOR / 'TEXT' (bone file, generic text file)
* FREF 131 = ANGBAND_CREATOR / 'DATA' (binary image file, score file)
*
*/
/* -------------------------------------------------------
* PORTING YOUR VARIANT
* ------------------------------------------------------
* 0. Requires installation of XCode. The framework .h files are otherwise
* absent. New changes also require use of NIB (xml) files, which
* are most easily edited with Interface Builder. (XCode package.)
* This reduces the amount of hand-coded menu creation by an order of magnitude.
*
*
* 1. Compiling the binary
*
* You might wish to disable some SET_UID features for various reasons:
* to have user folder within the lib folder, savefile names etc.
*
* 2. Installation
*
* The "angband" binary must be arranged this way for it to work:
*
* lib/ <- the lib folder
* Angband (OS X).app/
* Contents/
* MacOS/
* angband <- the binary you've just compiled
* Info.plist <- to be explained below
* Resources/
* Angband.icns
* Data.icns
* Edit.icns
* Save.icns
* 8x8.png <- 8x8 tiles
* 16x16.png <- 16x16 tiles
* angband.rsrc <- see below
*
* Graphics resources are moved out of the resource fork and become ordinary
* PNG files. Make sure to set its resolution to 72 dpi (<- VERY important)
* while keeping vertical and horizontal scaling factor to 100% (<- VERY
* important), when you convert tiles in any formats to PNG. This means
* that the real size of an image must shrink or grow when you change it's dpi.
* Graphics files must be of type png, because OSX 10.3 doesn't do
* a good job with composited images.
*
* Transparency now uses the alpha channel, rather than a background color.
*
* ---(end of OS X + gcc porting note)--------------------------------------
*
* Because the default font-size combination causes redraw artefact problem
* (some characters, even in monospace fonts, have negative left bearings),
* I [pelpel] introduced rather crude hack to clip all character drawings within
* their bounding rects. If you don't like this, please comment out the line
* #define CLIP_HACK
* below. The alternative, #define OVERWRITE_HACK, is based on Julian Lighton's
* brilliant suggestion, but it doesn't work as expected. This is because
* DrawText can render the same character with _different_ pixel width,
* depending on relative position of a character to the pen. Fonts do look
* very nice on the Mac, but too nice I'd say, in case of Angband.
*
* The check for return values of AEProcessAppleEvent is intentionally ignored.
*
* Changes 2006 (pete mack)
* - Removed conditional code. Removed non-quicktime sound.
* - Reorganized event model to use Carbon events and dispatching.
* - Removed old font menus & calculations; replaced with Apple font panel.
* - Removed Quickdraw graphics; replaced with CGContext (Quartz) graphics.
* - Removed Quickdraw text; replaced with CGFont. ATSUI is used for
* finding fonts, font metrics, and Glyph information for fast rendering
* of variable-width fonts.
*/
#ifdef MACH_O_CARBON
#include <Cocoa/Cocoa.h>
#include <Carbon/Carbon.h>
#include <QuickTime/QuickTime.h>
#include <CoreServices/CoreServices.h>
#include <CoreFoundation/CoreFoundation.h>
#include "osx/osx_tables.h"
/* Default creator signature */
#ifndef huge
#define huge size_t
#endif
/*
* Width in pixels of white borders around the black screen.
*/
#define BORDER_WID 1
static const bool show_events = 0;
/*
* A rather crude fix to reduce amount of redraw artifacts.
* Some fixed width fonts (i.e. Monaco) has characters with negative
* left bearings, so Term_wipe_mac or overwriting cannot completely
* erase them.
*/
#define CLIP_HACK 0 /* */
static const int use_clip_hack = CLIP_HACK;
/*
* Minimum font size
*/
#define MIN_FONT 8
/*
* Another redraw artifact killer, based on suggestion by Julian Lighton
*/
#define OVERWRITE_HACK (0)
/*
* These hacks should never be enabled at the same time.
* Clip-hack renders overwrite-hack meaningless, and
* it will cause use of an unitialized variable. - pete mack.
*/
static const int use_overwrite_hack = (OVERWRITE_HACK && !CLIP_HACK);
/*
* Maximum number of windows.
*/
#define MAX_TERM_DATA 8
/* graphics_modes index of current graphics mode */
static int graf_mode = 0;
/* Tile dimensions of the current graphics mode */
static int graf_height = 0;
static int graf_width = 0;
typedef struct GlyphInfo GlyphInfo;
typedef struct term_data term_data;
/*
* Extra "term" data
*/
struct term_data
{
term *t;
WindowRef w;
GlyphInfo *ginfo;
Rect wr; /* Absolute bounds of window (for save/restore) */
Rect r; /* Canvas bounds of window (for mouse addressing &c) */
CGRect bounds; /* Relative bounds of border-clipped canvas. */
int spacing; /* Text padding (in pixels) for tiling wider than text */
char title[255]; /* Window title. */
s16b mapped; /* Active state. */
s16b rows; /* rows in picture */
s16b cols; /* columns in picture. */
char font_name[200]; /* Name of font for storage. */
ATSUFontID font_id;
float font_size; /* Scaled ATSU font size. */
s16b font_wid;
s16b font_hgt;
s16b tile_wid;
s16b tile_hgt;
s16b size_wid; /* Window size in x. */
s16b size_hgt; /* Window size in y. */
};
struct GlyphInfo
{
UInt32 refcount;
char psname[1000];
ATSUFontID font_id;
CGFontRef fontRef;
float font_size;
ATSUStyle style;
ATSUTextLayout layout;
float font_wid; /* max character advance. */
s32b ascent;
s32b descent;
bool monospace;
float offsets[256][3];
float heights[256][3];
float widths[256];
};
static GlyphInfo glyph_data[MAX_TERM_DATA+1];
static WindowRef aboutDialog;
static bool CheckEvents(int wait);
static OSStatus RevalidateGraphics(term_data *td, bool reset_tilesize);
static char *locate_lib(char *buf, size_t size);
static void graphics_aux(int op);
static void Term_wipe_mac_aux(int x, int y, int n);
inline static void term_data_color(int a);
static void install_handlers(WindowRef w);
static void graphics_tiles_nuke(void);
static void play_sound(int num);
static void redrawRecentItemsMenu();
/*
* Available values for 'wait'
*/
#define CHECK_EVENTS_DRAIN -1
#define CHECK_EVENTS_NO_WAIT 0
#define CHECK_EVENTS_WAIT 1
/*
* Delay handling of double-clicked savefiles
*/
bool open_when_ready = FALSE;
/*
* Delay handling of pre-emptive "quit" event
*/
bool quit_when_ready = FALSE;
static long mac_os_version;
/* Out-of-band color identifiers */
/* True black (TERM_BLACK may be altered) */
#define COLOR_BLACK (256)
/* No current color */
#define COLOR_INVALID (-1)
/*
* Keeps track of who owns the QD CGContext, and it's current state.
* Always use this to change the active graphics port.
* (It is a parallel structure to the Term variable.)
*/
struct ActivePort {
WindowRef active;
CGContextRef ctx;
int color; /* Current fill colorcode */
/* CGColorRef color_info[256+1]; */
float color_info[256+1][3];
};
static struct ActivePort focus; /* initialized to 0 */
/*
* An array of term_data's
*/
static term_data data[MAX_TERM_DATA];
/*
* Note when "open"/"new" become valid
*/
static bool initialized = FALSE;
/*
* A mutable array for Recent Items
*/
CFMutableArrayRef recentItemsArrayRef = NULL;
/*
* Support the improved game command handling
*/
static game_command cmd = { CMD_NULL, 0 };
static MenuRef MyGetMenuHandle_aux(int menuID, bool first)
{
static MenuRef menuRefs[MAX_MENU_ID];
if(menuID <= 0 || menuID >= MAX_MENU_ID) return 0;
if(menuRefs[menuID]) return menuRefs[menuID];
MenuRef m = GetMenuHandle(menuID);
if(m) {
menuRefs[menuID] = m;
return m;
}
/*
* First heirarchical call, find and initialize all menu IDs.
* Subsequent misses will attempt to update the menuRefs array.
* This will work for any depth heirarchy, so long as child menus have
* higher IDs than their parents.
*
* Invariant: all MenuRefs with ID < MenuID(tmp) have been initialized.
*/
for(int id = 1; id < MAX_MENU_ID; id++)
{
/* Recursion depth is 1 */
if(first) m = MyGetMenuHandle_aux(id, false);
if(!m) continue;
menuRefs[id] = m;
for(int i = 0; i < N_ELEMENTS(menuRefs); i++) {
MenuRef tmp = 0;
GetMenuItemHierarchicalMenu (m, i, &tmp);
if(tmp) {
menuRefs[GetMenuID(tmp)] = tmp;
}
}
}
return menuRefs[menuID];
}
/*
* Provide a flat namespace for OS X menus and submenus.
* It's a nuisance doing this via heirarchical calls all the time.
*/
inline static MenuRef MyGetMenuHandle(int menuID)
{
return MyGetMenuHandle_aux(menuID, true);
}
/*
* Convert a pathname to a corresponding FSSpec.
* Returns noErr on success.
*/
static OSErr path_to_spec(const char *path, FSSpec *spec)
{
OSErr err;
FSRef ref;
/* Convert pathname to FSRef ... */
err = FSPathMakeRef((byte*) path, &ref, NULL);
if (err != noErr) return (err);
/* ... then FSRef to FSSpec */
err = FSGetCatalogInfo(&ref, kFSCatInfoNone, NULL, NULL, spec, NULL);
/* Inform caller of success or failure */
return (err);
}
/*
* Convert a FSSpec to a corresponding pathname.
* Returns noErr on success.
*/
static OSErr spec_to_path(const FSSpec *spec, char *buf, size_t size)
{
OSErr err;
FSRef ref;
/* Convert FSSpec to FSRef ... */
err = FSpMakeFSRef(spec, &ref);
if (err != noErr) return (err);
/* ... then FSRef to pathname */
err = FSRefMakePath(&ref, (byte*)buf, size);
/* Inform caller of success or failure */
return (err);
}
/*
* [via path_to_spec]
* Set creator and filetype of a file specified by POSIX-style pathname.
* Returns 0 on success, -1 in case of errors.
*/
void fsetfileinfo(cptr pathname, u32b fcreator, u32b ftype)
{
OSErr err;
FSSpec spec;
FInfo info;
/* Convert pathname to FSSpec */
if (path_to_spec(pathname, &spec) != noErr) return;
/* Obtain current finder info of the file */
if (FSpGetFInfo(&spec, &info) != noErr) return;
/* Overwrite creator and type */
info.fdCreator = fcreator;
info.fdType = ftype;
err = FSpSetFInfo(&spec, &info);
/* Done */
return;
}
/*
* Activate a given window, if necessary. This should normally
* be called by Term_activate, when the z-term is updating it's
* state. It should also be called prior to any updates when
* the window CGContext has been closed by hibernate()
*/
static void activate(WindowRef w)
{
/* Activate */
if(focus.active && focus.ctx) {
CGContextSynchronize(focus.ctx);
if(focus.active != w) {
/* Change window context */
QDEndCGContext(GetWindowPort(focus.active), &focus.ctx);
focus.ctx = 0;
}
}
/* Activate */
if (w && focus.ctx == 0) {
focus.color = COLOR_INVALID;
term_data *td = (term_data*)GetWRefCon(w);
/* Start queueing graphics events. */
/* and set up the context */
QDBeginCGContext(GetWindowPort(w), &focus.ctx);
/* Shift the origin to inside the border, and use inverted y axis. */
CGAffineTransform m;
m = CGAffineTransformMake(BORDER_WID, 0, 0, -1,
BORDER_WID, BORDER_WID+td->bounds.size.height);
CGContextConcatCTM (focus.ctx, m);
CGContextClipToRect(focus.ctx, td->bounds);
CGContextSetShouldAntialias (focus.ctx, antialias);
CGContextSetInterpolationQuality(focus.ctx, kCGInterpolationNone);
/* Invert the text so it's no longer mirrored in y. */
/* Origin is at still at the bottom of the line, so the ascent must */
/* be subtracted at display-time. (Not added, because the coordinate */
/* system is also flipped.) */
m = CGAffineTransformMake(1, 0, 0, -1, 0, 0);
CGContextSetTextMatrix(focus.ctx, m);
CFStringRef font_name = CFStringCreateWithCString(
kCFAllocatorDefault,
td->ginfo->psname,
kCFStringEncodingISOLatin1);
td->ginfo->fontRef = CGFontCreateWithFontName(font_name);
CGContextSetFont(focus.ctx, td->ginfo->fontRef);
CGContextSetFontSize(focus.ctx, td->font_size);
CFRelease(font_name);
if(td->ginfo->monospace) {
CGContextSetCharacterSpacing(focus.ctx,
td->tile_wid - td->ginfo->font_wid);
}
else {
const ATSUAttributeTag itags[] = { kATSUCGContextTag,
kATSUImposeWidthTag };
Fixed advance = (1<<16)*(td->tile_wid - td->font_wid);
void *ivals[] = { &focus.ctx, &advance };
const ByteCount isizes[] = {sizeof(focus.ctx), sizeof(advance) };
ATSUSetAttributes(td->ginfo->style, 2, itags, isizes, ivals);
}
}
/* Remember */
focus.active = w;
}
/*
* Temporarily give up control of the Quickdraw port.
* Call when the window becomes inactive.
* Call when the graphics state changes in any way, to
* invalidate the current CGContext and force an update.
*/
static void hibernate()
{
if(focus.ctx != 0)
QDEndCGContext(GetWindowPort(focus.active), &focus.ctx);
focus.ctx = 0;
}
/*
* Display a warning message
*/
static void mac_warning(cptr warning)
{
CFStringRef msg;
msg = CFStringCreateWithCString(NULL, warning, kCFStringEncodingISOLatin1);
DialogRef dlg = 0;
CreateStandardAlert(kAlertCautionAlert, msg, CFSTR(""), NULL, &dlg);
DialogItemIndex itemIndex;
RunStandardAlert(dlg, NULL, &itemIndex);
/* DisposeDialog(dlg); // NO! */
CFRelease(msg);
}
/*
* Notice fully up-to-date status of the main window
*/
static void validate_main_window(void)
{
WindowRef w;
Rect r;
/* Get the main window */
w = data[0].w;
/* Get its rectangle */
GetPortBounds(GetWindowPort(w), &r);
/* Validate it */
ValidWindowRect(w, &r);
}
/*** Some generic functions ***/
/*
* Update color_info with the current values in angband_color_table
*/
static void update_color_info(void)
{
focus.color = COLOR_INVALID;
focus.color_info[COLOR_BLACK][0] = 0;
focus.color_info[COLOR_BLACK][1] = 0;
focus.color_info[COLOR_BLACK][2] = 0;
/* Update colors */
for (int i = 0; i < 256; i++)
{
float r = angband_color_table[i][1];
float g = angband_color_table[i][2];
float b = angband_color_table[i][3];
r = r == 255 ? 1 : r / 256;
g = g == 255 ? 1 : g / 256;
b = b == 255 ? 1 : b / 256;
focus.color_info[i][0] = r;
focus.color_info[i][1] = g;
focus.color_info[i][2] = b;
}
}
/*
* Activate a color (0 to 256)
* -1 is invalid, 256 is true black.
*/
inline static void term_data_color(int a)
{
if(!focus.ctx) activate(focus.active);
if( a == COLOR_INVALID) {
focus.color = a;
}
else if (focus.color != a) /* Assumes the window exists. */
{
focus.color = a;
/* CGContextSetFillColorWithColor(focus.ctx, focus.color_info[a]); */
CGContextSetRGBFillColor(focus.ctx, focus.color_info[a][0],
focus.color_info[a][1], focus.color_info[a][2], 1);
}
}
/*
* Get font metrics
*/
static GlyphInfo *get_glyph_info(ATSUFontID fid, float size)
{
GlyphInfo *info;
/* One extra, so a term_data can fetch before it frees. */
for(info = glyph_data; info <= glyph_data+MAX_TERM_DATA; info++)
{
if(info->font_id == fid && info->font_size == size)
{
info->refcount++;
return info;
}
}
/* One is always available. */
info = glyph_data;
for(int c = 0; info->refcount != 0; info++, c++)
assert(c <= MAX_TERM_DATA);
info->style = 0;
info->layout = 0;
/* ICK */
info->font_size = size;
info->font_id = fid;
OSStatus err = ATSUCreateStyle(&info->style);
require_noerr(err, CantInitialize);
Fixed fsize = (Fixed)(size*(1<<16));
const ByteCount isizes[] = {sizeof(fid), sizeof(fsize) };
void *ivals[] = { &fid, &fsize };
const ATSUAttributeTag itags[] = { kATSUFontTag,
kATSUSizeTag };
ATSUSetAttributes(info->style, 2, itags, isizes, ivals);
err = ATSUCreateTextLayout(&info->layout);
require_noerr(err, CantInitialize);
/* Dummy text, required to initialize run style. */
UniChar text[1] = {'@'};
ATSUSetTextPointerLocation(info->layout, text, 0, 1, 1);
ATSUSetRunStyle(info->layout, info->style, 0, 1);
ByteCount oCount = 0;
FontNameCode oCode;
err = ATSUGetIndFontName(fid, 6, sizeof(info->psname), info->psname,
&oCount, &oCode, 0, 0, 0);
require_noerr(err, CantInitialize);
if(oCount == 0 || strlen(info->psname) == 0)
goto CantInitialize;
info->psname[oCount] = 0;
/* Is font mono-space? */
err = ATSUCreateTextLayout(&info->layout);
require_noerr(err, CantInitialize);
ATSUSetRunStyle(info->layout, info->style, 0, 0);
info->monospace = true;
info->font_wid = 0;
info->ascent = 0;
info->descent = 0;
for(int i = 0; i < 256; i++) {
OSStatus err;
text[0] = i;
Fixed start = 0, stop = 0, ascent = 0, descent = 0;
ATSUSetTextPointerLocation(info->layout, text, 0, 1, 1);
/* SetRunStyle doesn't honor runs in layouts of size 0. */
if(i == 0) ATSUSetRunStyle(info->layout, info->style, 0, 1);
err = ATSUGetUnjustifiedBounds(info->layout, 0, 1, &start, &stop,
&ascent, &descent);
if(info->ascent < ascent) info->ascent = ascent;
if(info->descent < descent) info->descent = descent;
info->widths[i] = (stop - start)/(1<<16);
if(info->font_wid == 0) info->font_wid = stop - start;
else if((info->font_wid != stop - start) && (stop - start != 0)) {
info->monospace = false;
}
if(info->font_wid < stop - start) {
info->font_wid = stop - start;
}
}
/* Scale the rough font metrics to screen dimensions. */
/* Assumes 72dpi resolution. */
info->ascent = (info->ascent + (1<<16)-1)>>16;
info->descent = (info->descent + (1<<16)-1)>>16;
info->font_wid = (info->font_wid)/(1<<16);
info->refcount++;
return info;
CantInitialize:
if(info->layout) ATSUDisposeTextLayout(info->layout);
if(info->style) ATSUDisposeStyle(info->style);
info->style = 0;
info->layout = 0;
return 0;
}
static void release_glyph_info(GlyphInfo *info)
{
if(!info) return;
assert(info->refcount > 0);
info->refcount--;
if(0 == info->refcount) {
ATSUDisposeStyle(info->style);
info->style = 0;
CGFontRelease(info->fontRef);
info->fontRef = 0;
}
}
/*
* Hack -- Apply and Verify the "font" info
*
* This should usually be followed by "term_data_check_size()"
*
* XXX XXX To force (re)initialisation of td->tile_wid and td->tile_hgt
* you have to reset them to zero before this function is called.
* XXX XXX This is automatic when the program starts because the term_data
* array is WIPE'd by term_data_hack, but isn't in the other cases, i.e.
* font, font style and size changes.
*/
static void term_data_check_font(term_data *td)
{
GlyphInfo *info = get_glyph_info(td->font_id, td->font_size);
if(!info) return;
release_glyph_info(td->ginfo);
td->ginfo = info;
td->font_wid = (info->font_wid +.999);
td->font_hgt = info->ascent + info->descent;
my_strcpy(td->font_name, info->psname, sizeof(td->font_name));
/* Set default tile size */
if (td->tile_wid == 0) td->tile_wid = td->font_wid;
if (td->tile_hgt == 0) td->tile_hgt = td->font_hgt;
}
/*
* Hack -- Apply and Verify the "size" info
*/
static void term_data_check_size(term_data *td)
{
if (td == &data[0])
{
/* Enforce minimal size for the main game window */
if (td->cols < 80) td->cols = 80;
if (td->rows < 24) td->rows = 24;
}
else
{
/* Information windows can be much smaller */
if (td->cols < 10) td->cols = 10;
if (td->rows < 5) td->rows = 5;
}
/* Enforce maximal sizes */
if (td->cols > 255) td->cols = 255;
if (td->rows > 255) td->rows = 255;
/* Minimal tile size */
bool dirty = false;
if (td->tile_wid < td->font_wid) {
td->tile_wid = td->font_wid;
dirty = true;
}
if (td->tile_hgt < td->font_hgt) {
td->tile_hgt = td->font_hgt;
dirty = true;
}
if(dirty) graphics_tiles_nuke();
/* Calculate full window size */
td->size_wid = td->cols * td->tile_wid + BORDER_WID * 2;
td->size_hgt = td->rows * td->tile_hgt + BORDER_WID;
hibernate();
BitMap tScreen;
/* Get current screen */
(void)GetQDGlobalsScreenBits(&tScreen);
/* Verify the bottom */
if (td->r.top > tScreen.bounds.bottom - td->size_hgt)
{
td->r.top = tScreen.bounds.bottom - td->size_hgt;
}
/* Verify the top */
if (td->r.top < tScreen.bounds.top + 2*GetMBarHeight())
{
td->r.top = tScreen.bounds.top + 2*GetMBarHeight();
}
/* Verify the right */
if (td->r.left > tScreen.bounds.right - td->size_wid)
{
td->r.left = tScreen.bounds.right - td->size_wid;
}
/* Verify the left */
if (td->r.left < tScreen.bounds.left)
{
td->r.left = tScreen.bounds.left;
}
/* Calculate bottom right corner */
td->r.right = td->r.left + td->size_wid;
td->r.bottom = td->r.top + td->size_hgt;
td->bounds = (CGRect) {{0, 0},
{td->cols * td->tile_wid, td->rows * td->tile_hgt}};
/* Assume no graphics, monospace */
td->t->higher_pict = FALSE;
td->t->always_pict = FALSE;
/* Handle graphics */
if (!td->ginfo->monospace) {
/* Draw every character */
td->t->always_pict = TRUE;
}
else if (use_graphics)
{
/* Use higher pict whenever possible */
td->t->higher_pict = TRUE;
}
}
/*
* resize a term_data
*
* This should normally be followed by "term_data_redraw()"
*/
static void term_data_resize(term_data *td)
{
/* Invalidate the current CGContext. */
hibernate();
/*
* Actually resize the window
*
* ResizeWindow is the preferred API call, but it cannot
* be used here.
*/
SizeWindow(td->w, td->size_wid, td->size_hgt, 0);
/* Cheat a little -- can't use the active view to redraw its own border. */
CGContextRef tmpCtx;
QDBeginCGContext(GetWindowPort(td->w), &tmpCtx);
CGContextSetRGBStrokeColor(tmpCtx, 1, 1, 1, 1);
CGRect wbounds = {{0, 0}, {td->bounds.size.width+2*BORDER_WID,
td->bounds.size.height+BORDER_WID+2}};
CGContextStrokeRect(tmpCtx, wbounds);
QDEndCGContext(GetWindowPort(td->w), &tmpCtx);
}
/*
* Hack -- redraw a term_data
*
* Note that "Term_redraw()" calls "TERM_XTRA_CLEAR"
*/
static void term_data_redraw(term_data *td)
{
term *old = Term;
/* Activate the term */
Term_activate(td->t);
/* Redraw the contents */
Term_redraw();
/* Flush the output */
Term_fresh();
Term_activate(old);
}
/*
* Graphics support
*/
/*
* PICT id / file name of image tiles
*/
static const char *pict_id = NULL;
/*
* Frame
* Wrapper for CGImages of the current tile set.
*
*/
static struct
{
/* The reference image at the original scale. */
CGImageRef image;
/* Numbers of rows and columns in a tileset, */
int cols;
int rows;
/*
* Tile images.
* These are generated once at each tile scaling. Since
* there are many unused tiles, and since generating tiles takes
* a long time, they are generated only on demand.
* The tiles at the current scaling.
* Foreground tiles are RGBA
* Background tiles are RGB only.
* This is detected by DrawTile--background images have the same
* tile-id for both foreground and background.
* Stride is number of columns.
*/
CGImageRef *tile_images;
} frame = {0};
/*
* Rendevous for font update events.
*/
static struct
{
WindowRef focus; /* The most recently focused window. (NOT the fontpanel.) */
} fontInfo;
/*
* Replacement for BitMap (from QD2Qz porting guide)
*/
void DrawSubimage (CGContextRef context, CGRect dst,
CGImageRef image, CGRect src)
{
/* the default drawing rectangle */
float w = (float) CGImageGetWidth(image);
float h = (float) CGImageGetHeight(image);
CGRect drawRect = {{0, 0}, {w, h}};
if (!CGRectEqualToRect (src, dst))
{
float sx = CGRectGetWidth(dst) / CGRectGetWidth(src);
float sy = CGRectGetHeight(dst) / CGRectGetHeight(src);
float dx = CGRectGetMinX(dst) - (CGRectGetMinX(src) * sx);
float dy = CGRectGetMinY(dst) - (CGRectGetMinY(src) * sy);
drawRect = (CGRect) {{dx, dy}, {w*sx, h*sy}};
}
CGContextSaveGState (context);
CGContextClipToRect (context, dst);
/* Don't display images upside down. (Works like SetTextMatrix) */
HIViewDrawCGImage (context, &drawRect, image);
/* CGContextDrawImage (context, &drawRect, image); */
CGContextRestoreGState (context);
}
/*
* Copy an image with tiles of size src into a new one with
* tiles of size dst. Interpolation will not cross tile borders.
*/
static CGImageRef GetTileImage(int row, int col, bool has_alpha)