Improve fatal error handling.
[sgt/puzzles] / osx.m
CommitLineData
9494d866 1/*
2 * Mac OS X / Cocoa front end to puzzles.
00461804 3 *
a5102461 4 * Actually unfinished things left to do:
00461804 5 *
a5102461 6 * - Find out how to do help, and do some. We have a help file; at
7 * _worst_ this should involve a new Halibut back end, but I
8 * think help is HTML round here anyway so perhaps we can work
9 * with what we already have.
10 *
a5102461 11 * - Why are the right and bottom edges of the Pattern grid one
12 * pixel thinner than they should be?
13 *
14 * Mac interface issues that possibly could be done better:
15 *
16 * - is there a better approach to frontend_default_colour?
17 *
18 * - do we need any more options in the Window menu?
00461804 19 *
9494d866 20 * - not sure what I should be doing about default window
21 * placement. Centring new windows is a bit feeble, but what's
22 * better? Is there a standard way to tell the OS "here's the
23 * _size_ of window I want, now use your best judgment about the
24 * initial position"?
00461804 25 *
9494d866 26 * - a brief frob of the Mac numeric keypad suggests that it
27 * generates numbers no matter what you do. I wonder if I should
28 * try to figure out a way of detecting keypad codes so I can
6d634196 29 * implement UP_LEFT and friends. Alternatively, perhaps I
30 * should simply assign the number keys to UP_LEFT et al?
31 * They're not in use for anything else right now.
00461804 32 *
00461804 33 * - see if we can do anything to one-button-ise the multi-button
34 * dependent puzzle UIs:
35 * - Pattern is a _little_ unwieldy but not too bad (since
36 * generally you never need the middle button unless you've
37 * made a mistake, so it's just click versus command-click).
38 * - Net is utterly vile; having normal click be one rotate and
39 * command-click be the other introduces a horrid asymmetry,
40 * and yet requiring a shift key for _each_ click would be
41 * even worse because rotation feels as if it ought to be the
42 * default action. I fear this is why the Flash Net had the
43 * UI it did...
44 *
e1107f8b 45 * - Should we _return_ to a game configuration sheet once an
46 * error is reported by midend_set_config, to allow the user to
47 * correct the one faulty input and keep the other five OK ones?
48 * The Apple `one sheet at a time' restriction would require me
49 * to do this by closing the config sheet, opening the alert
50 * sheet, and then reopening the config sheet when the alert is
51 * closed; and the human interface types, who presumably
52 * invented the one-sheet-at-a-time rule for good reasons, might
53 * look with disfavour on me trying to get round them to fake a
54 * nested sheet. On the other hand I think there are good
55 * practical reasons for wanting it that way. Uncertain.
56 *
7e04cb48 57 * Grotty implementation details that could probably be improved:
58 *
59 * - I am _utterly_ unconvinced that NSImageView was the right way
60 * to go about having a window with a reliable backing store! It
61 * just doesn't feel right; NSImageView is a _control_. Is there
62 * a simpler way?
63 *
64 * - Resizing is currently very bad; rather than bother to work
65 * out how to resize the NSImageView, I just splatter and
66 * recreate it.
9494d866 67 */
68
69#include <ctype.h>
70#include <sys/time.h>
71#import <Cocoa/Cocoa.h>
72#include "puzzles.h"
73
e7fabdfa 74/* ----------------------------------------------------------------------
75 * Global variables.
76 */
77
78/*
79 * The `Type' menu. We frob this dynamically to allow the user to
80 * choose a preset set of settings from the current game.
81 */
82NSMenu *typemenu;
83
84/* ----------------------------------------------------------------------
85 * Miscellaneous support routines that aren't part of any object or
86 * clearly defined subsystem.
87 */
88
9494d866 89void fatal(char *fmt, ...)
90{
9494d866 91 va_list ap;
e7fabdfa 92 char errorbuf[2048];
93 NSAlert *alert;
9494d866 94
95 va_start(ap, fmt);
e7fabdfa 96 vsnprintf(errorbuf, lenof(errorbuf), fmt, ap);
9494d866 97 va_end(ap);
98
e7fabdfa 99 alert = [NSAlert alloc];
100 /*
101 * We may have come here because we ran out of memory, in which
102 * case it's entirely likely that that alloc will fail, so we
103 * should have a fallback of some sort.
104 */
105 if (!alert) {
106 fprintf(stderr, "fatal error (and NSAlert failed): %s\n", errorbuf);
107 } else {
108 alert = [[alert init] autorelease];
109 [alert addButtonWithTitle:@"Oh dear"];
110 [alert setInformativeText:[NSString stringWithCString:errorbuf]];
111 [alert runModal];
112 }
9494d866 113 exit(1);
114}
115
116void frontend_default_colour(frontend *fe, float *output)
117{
e7fabdfa 118 /* FIXME: Is there a system default we can tap into for this? */
9494d866 119 output[0] = output[1] = output[2] = 0.8F;
120}
9494d866 121
122void get_random_seed(void **randseed, int *randseedsize)
123{
124 time_t *tp = snew(time_t);
125 time(tp);
126 *randseed = (void *)tp;
127 *randseedsize = sizeof(time_t);
128}
129
130/* ----------------------------------------------------------------------
7e04cb48 131 * Tiny extension to NSMenuItem which carries a payload of a `void
132 * *', allowing several menu items to invoke the same message but
133 * pass different data through it.
134 */
135@interface DataMenuItem : NSMenuItem
136{
137 void *payload;
7e04cb48 138}
139- (void)setPayload:(void *)d;
7e04cb48 140- (void *)getPayload;
141@end
142@implementation DataMenuItem
7e04cb48 143- (void)setPayload:(void *)d
144{
145 payload = d;
146}
7e04cb48 147- (void *)getPayload
148{
149 return payload;
150}
7e04cb48 151@end
152
153/* ----------------------------------------------------------------------
e1107f8b 154 * Utility routines for constructing OS X menus.
155 */
156
157NSMenu *newmenu(const char *title)
158{
159 return [[[NSMenu allocWithZone:[NSMenu menuZone]]
160 initWithTitle:[NSString stringWithCString:title]]
161 autorelease];
162}
163
164NSMenu *newsubmenu(NSMenu *parent, const char *title)
165{
166 NSMenuItem *item;
167 NSMenu *child;
168
169 item = [[[NSMenuItem allocWithZone:[NSMenu menuZone]]
170 initWithTitle:[NSString stringWithCString:title]
171 action:NULL
172 keyEquivalent:@""]
173 autorelease];
174 child = newmenu(title);
175 [item setEnabled:YES];
176 [item setSubmenu:child];
177 [parent addItem:item];
178 return child;
179}
180
181id initnewitem(NSMenuItem *item, NSMenu *parent, const char *title,
182 const char *key, id target, SEL action)
183{
184 unsigned mask = NSCommandKeyMask;
185
186 if (key[strcspn(key, "-")]) {
187 while (*key && *key != '-') {
188 int c = tolower((unsigned char)*key);
189 if (c == 's') {
190 mask |= NSShiftKeyMask;
191 } else if (c == 'o' || c == 'a') {
192 mask |= NSAlternateKeyMask;
193 }
194 key++;
195 }
196 if (*key)
197 key++;
198 }
199
200 item = [[item initWithTitle:[NSString stringWithCString:title]
201 action:NULL
202 keyEquivalent:[NSString stringWithCString:key]]
203 autorelease];
204
205 if (*key)
206 [item setKeyEquivalentModifierMask: mask];
207
208 [item setEnabled:YES];
209 [item setTarget:target];
210 [item setAction:action];
211
212 [parent addItem:item];
213
214 return item;
215}
216
217NSMenuItem *newitem(NSMenu *parent, char *title, char *key,
218 id target, SEL action)
219{
220 return initnewitem([NSMenuItem allocWithZone:[NSMenu menuZone]],
221 parent, title, key, target, action);
222}
223
224/* ----------------------------------------------------------------------
9494d866 225 * The front end presented to midend.c.
226 *
227 * This is mostly a subclass of NSWindow. The actual `frontend'
228 * structure passed to the midend contains a variety of pointers,
229 * including that window object but also including the image we
230 * draw on, an ImageView to display it in the window, and so on.
231 */
232
233@class GameWindow;
234@class MyImageView;
235
236struct frontend {
237 GameWindow *window;
238 NSImage *image;
239 MyImageView *view;
240 NSColor **colours;
241 int ncolours;
242 int clipped;
243};
244
245@interface MyImageView : NSImageView
246{
247 GameWindow *ourwin;
248}
249- (void)setWindow:(GameWindow *)win;
250- (BOOL)isFlipped;
251- (void)mouseEvent:(NSEvent *)ev button:(int)b;
252- (void)mouseDown:(NSEvent *)ev;
253- (void)mouseDragged:(NSEvent *)ev;
254- (void)mouseUp:(NSEvent *)ev;
255- (void)rightMouseDown:(NSEvent *)ev;
256- (void)rightMouseDragged:(NSEvent *)ev;
257- (void)rightMouseUp:(NSEvent *)ev;
258- (void)otherMouseDown:(NSEvent *)ev;
259- (void)otherMouseDragged:(NSEvent *)ev;
260- (void)otherMouseUp:(NSEvent *)ev;
261@end
262
263@interface GameWindow : NSWindow
264{
265 const game *ourgame;
266 midend_data *me;
267 struct frontend fe;
268 struct timeval last_time;
269 NSTimer *timer;
e1107f8b 270 NSWindow *sheet;
271 config_item *cfg;
272 int cfg_which;
273 NSView **cfg_controls;
274 int cfg_ncontrols;
a5102461 275 NSTextField *status;
9494d866 276}
277- (id)initWithGame:(const game *)g;
278- dealloc;
279- (void)processButton:(int)b x:(int)x y:(int)y;
280- (void)keyDown:(NSEvent *)ev;
281- (void)activateTimer;
282- (void)deactivateTimer;
a5102461 283- (void)setStatusLine:(NSString *)text;
9494d866 284@end
285
286@implementation MyImageView
287
288- (void)setWindow:(GameWindow *)win
289{
290 ourwin = win;
291}
292
293- (BOOL)isFlipped
294{
295 return YES;
296}
297
298- (void)mouseEvent:(NSEvent *)ev button:(int)b
299{
300 NSPoint point = [self convertPoint:[ev locationInWindow] fromView:nil];
301 [ourwin processButton:b x:point.x y:point.y];
302}
303
304- (void)mouseDown:(NSEvent *)ev
305{
306 unsigned mod = [ev modifierFlags];
307 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_BUTTON :
308 (mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
309 LEFT_BUTTON)];
310}
311- (void)mouseDragged:(NSEvent *)ev
312{
313 unsigned mod = [ev modifierFlags];
314 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_DRAG :
315 (mod & NSShiftKeyMask) ? MIDDLE_DRAG :
316 LEFT_DRAG)];
317}
318- (void)mouseUp:(NSEvent *)ev
319{
320 unsigned mod = [ev modifierFlags];
321 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_RELEASE :
322 (mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
323 LEFT_RELEASE)];
324}
325- (void)rightMouseDown:(NSEvent *)ev
326{
327 unsigned mod = [ev modifierFlags];
328 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
329 RIGHT_BUTTON)];
330}
331- (void)rightMouseDragged:(NSEvent *)ev
332{
333 unsigned mod = [ev modifierFlags];
334 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_DRAG :
335 RIGHT_DRAG)];
336}
337- (void)rightMouseUp:(NSEvent *)ev
338{
339 unsigned mod = [ev modifierFlags];
340 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
341 RIGHT_RELEASE)];
342}
343- (void)otherMouseDown:(NSEvent *)ev
344{
345 [self mouseEvent:ev button:MIDDLE_BUTTON];
346}
347- (void)otherMouseDragged:(NSEvent *)ev
348{
349 [self mouseEvent:ev button:MIDDLE_DRAG];
350}
351- (void)otherMouseUp:(NSEvent *)ev
352{
353 [self mouseEvent:ev button:MIDDLE_RELEASE];
354}
355@end
356
357@implementation GameWindow
7e04cb48 358- (void)setupContentView
359{
a5102461 360 NSRect frame;
7e04cb48 361 int w, h;
362
a5102461 363 if (status) {
364 frame = [status frame];
365 frame.origin.y = frame.size.height;
366 } else
367 frame.origin.y = 0;
368 frame.origin.x = 0;
369
7e04cb48 370 midend_size(me, &w, &h);
a5102461 371 frame.size.width = w;
372 frame.size.height = h;
7e04cb48 373
a5102461 374 fe.image = [[NSImage alloc] initWithSize:frame.size];
7e04cb48 375 [fe.image setFlipped:YES];
a5102461 376 fe.view = [[MyImageView alloc] initWithFrame:frame];
7e04cb48 377 [fe.view setImage:fe.image];
378 [fe.view setWindow:self];
379
380 midend_redraw(me);
381
a5102461 382 [[self contentView] addSubview:fe.view];
7e04cb48 383}
9494d866 384- (id)initWithGame:(const game *)g
385{
a5102461 386 NSRect rect = { {0,0}, {0,0} }, rect2;
9494d866 387 int w, h;
388
389 ourgame = g;
390
391 fe.window = self;
392
393 me = midend_new(&fe, ourgame);
394 /*
395 * If we ever need to open a fresh window using a provided game
396 * ID, I think the right thing is to move most of this method
397 * into a new initWithGame:gameID: method, and have
398 * initWithGame: simply call that one and pass it NULL.
399 */
400 midend_new_game(me);
401 midend_size(me, &w, &h);
402 rect.size.width = w;
403 rect.size.height = h;
404
a5102461 405 /*
406 * Create the status bar, which will just be an NSTextField.
407 */
408 if (ourgame->wants_statusbar()) {
409 status = [[NSTextField alloc] initWithFrame:NSMakeRect(0,0,100,50)];
410 [status setEditable:NO];
411 [status setSelectable:NO];
412 [status setBordered:YES];
413 [status setBezeled:YES];
414 [status setBezelStyle:NSTextFieldSquareBezel];
415 [status setDrawsBackground:YES];
416 [[status cell] setTitle:@""];
417 [status sizeToFit];
418 rect2 = [status frame];
419 rect.size.height += rect2.size.height;
420 rect2.size.width = rect.size.width;
421 rect2.origin.x = rect2.origin.y = 0;
422 [status setFrame:rect2];
423 } else
424 status = nil;
425
9494d866 426 self = [super initWithContentRect:rect
427 styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
428 NSClosableWindowMask)
429 backing:NSBackingStoreBuffered
e1107f8b 430 defer:YES];
9494d866 431 [self setTitle:[NSString stringWithCString:ourgame->name]];
432
433 {
434 float *colours;
435 int i, ncolours;
436
437 colours = midend_colours(me, &ncolours);
438 fe.ncolours = ncolours;
439 fe.colours = snewn(ncolours, NSColor *);
440
441 for (i = 0; i < ncolours; i++) {
442 fe.colours[i] = [[NSColor colorWithDeviceRed:colours[i*3]
443 green:colours[i*3+1] blue:colours[i*3+2]
444 alpha:1.0] retain];
445 }
446 }
447
7e04cb48 448 [self setupContentView];
a5102461 449 if (status)
450 [[self contentView] addSubview:status];
9494d866 451 [self setIgnoresMouseEvents:NO];
452
9494d866 453 [self center]; /* :-) */
454
455 return self;
456}
457
458- dealloc
459{
460 int i;
461 for (i = 0; i < fe.ncolours; i++) {
462 [fe.colours[i] release];
463 }
464 sfree(fe.colours);
465 midend_free(me);
466 return [super dealloc];
467}
468
469- (void)processButton:(int)b x:(int)x y:(int)y
470{
471 if (!midend_process_key(me, x, y, b))
472 [self close];
473}
474
475- (void)keyDown:(NSEvent *)ev
476{
477 NSString *s = [ev characters];
478 int i, n = [s length];
479
480 for (i = 0; i < n; i++) {
481 int c = [s characterAtIndex:i];
482
483 /*
484 * ASCII gets passed straight to midend_process_key.
485 * Anything above that has to be translated to our own
486 * function key codes.
487 */
488 if (c >= 0x80) {
489 switch (c) {
490 case NSUpArrowFunctionKey:
491 c = CURSOR_UP;
492 break;
493 case NSDownArrowFunctionKey:
494 c = CURSOR_DOWN;
495 break;
496 case NSLeftArrowFunctionKey:
497 c = CURSOR_LEFT;
498 break;
499 case NSRightArrowFunctionKey:
500 c = CURSOR_RIGHT;
501 break;
502 default:
503 continue;
504 }
505 }
506
507 [self processButton:c x:-1 y:-1];
508 }
509}
510
511- (void)activateTimer
512{
513 if (timer != nil)
514 return;
515
516 timer = [NSTimer scheduledTimerWithTimeInterval:0.02
517 target:self selector:@selector(timerTick:)
518 userInfo:nil repeats:YES];
519 gettimeofday(&last_time, NULL);
520}
521
522- (void)deactivateTimer
523{
524 if (timer == nil)
525 return;
526
527 [timer invalidate];
528 timer = nil;
529}
530
531- (void)timerTick:(id)sender
532{
533 struct timeval now;
534 float elapsed;
535 gettimeofday(&now, NULL);
536 elapsed = ((now.tv_usec - last_time.tv_usec) * 0.000001F +
537 (now.tv_sec - last_time.tv_sec));
538 midend_timer(me, elapsed);
539 last_time = now;
540}
541
00461804 542- (void)newGame:(id)sender
543{
544 [self processButton:'n' x:-1 y:-1];
545}
546- (void)restartGame:(id)sender
547{
548 [self processButton:'r' x:-1 y:-1];
549}
550- (void)undoMove:(id)sender
551{
552 [self processButton:'u' x:-1 y:-1];
553}
554- (void)redoMove:(id)sender
555{
556 [self processButton:'r'&0x1F x:-1 y:-1];
557}
558
7e04cb48 559- (void)clearTypeMenu
560{
561 while ([typemenu numberOfItems] > 1)
562 [typemenu removeItemAtIndex:0];
563}
564
565- (void)becomeKeyWindow
566{
567 int n;
568
569 [self clearTypeMenu];
570
571 [super becomeKeyWindow];
572
573 n = midend_num_presets(me);
574
575 if (n > 0) {
576 [typemenu insertItem:[NSMenuItem separatorItem] atIndex:0];
577 while (n--) {
578 char *name;
579 game_params *params;
580 DataMenuItem *item;
581
582 midend_fetch_preset(me, n, &name, &params);
583
584 item = [[[DataMenuItem alloc]
585 initWithTitle:[NSString stringWithCString:name]
586 action:NULL keyEquivalent:@""]
587 autorelease];
588
589 [item setEnabled:YES];
590 [item setTarget:self];
591 [item setAction:@selector(presetGame:)];
592 [item setPayload:params];
7e04cb48 593
594 [typemenu insertItem:item atIndex:0];
595 }
596 }
597}
598
599- (void)resignKeyWindow
600{
601 [self clearTypeMenu];
602 [super resignKeyWindow];
603}
604
605- (void)close
606{
607 [self clearTypeMenu];
608 [super close];
609}
610
611- (void)resizeForNewGameParams
612{
613 NSSize size = {0,0};
614 int w, h;
615
616 midend_size(me, &w, &h);
617 size.width = w;
618 size.height = h;
619
620 NSDisableScreenUpdates();
621 [self setContentSize:size];
622 [self setupContentView];
623 NSEnableScreenUpdates();
624}
625
626- (void)presetGame:(id)sender
627{
628 game_params *params = [sender getPayload];
629
630 midend_set_params(me, params);
631 midend_new_game(me);
632
633 [self resizeForNewGameParams];
634}
635
e1107f8b 636- (void)startConfigureSheet:(int)which
637{
638 NSButton *ok, *cancel;
639 int actw, acth, leftw, rightw, totalw, h, thish, y;
640 int k;
641 NSRect rect, tmprect;
642 const int SPACING = 16;
643 char *title;
644 config_item *i;
645 int cfg_controlsize;
646 NSTextField *tf;
647 NSButton *b;
648 NSPopUpButton *pb;
649
650 assert(sheet == NULL);
651
652 /*
653 * Every control we create here is going to have this size
654 * until we tell it to calculate a better one.
655 */
656 tmprect = NSMakeRect(0, 0, 100, 50);
657
658 /*
659 * Set up OK and Cancel buttons. (Actually, MacOS doesn't seem
660 * to be fond of generic OK and Cancel wording, so I'm going to
661 * rename them to something nicer.)
662 */
663 actw = acth = 0;
664
665 cancel = [[NSButton alloc] initWithFrame:tmprect];
666 [cancel setBezelStyle:NSRoundedBezelStyle];
667 [cancel setTitle:@"Abandon"];
668 [cancel setTarget:self];
669 [cancel setKeyEquivalent:@"\033"];
670 [cancel setAction:@selector(sheetCancelButton:)];
671 [cancel sizeToFit];
672 rect = [cancel frame];
673 if (actw < rect.size.width) actw = rect.size.width;
674 if (acth < rect.size.height) acth = rect.size.height;
675
676 ok = [[NSButton alloc] initWithFrame:tmprect];
677 [ok setBezelStyle:NSRoundedBezelStyle];
678 [ok setTitle:@"Accept"];
679 [ok setTarget:self];
680 [ok setKeyEquivalent:@"\r"];
681 [ok setAction:@selector(sheetOKButton:)];
682 [ok sizeToFit];
683 rect = [ok frame];
684 if (actw < rect.size.width) actw = rect.size.width;
685 if (acth < rect.size.height) acth = rect.size.height;
686
687 totalw = SPACING + 2 * actw;
688 h = 2 * SPACING + acth;
689
690 /*
691 * Now fetch the midend config data and go through it creating
692 * controls.
693 */
694 cfg = midend_get_config(me, which, &title);
695 sfree(title); /* FIXME: should we use this somehow? */
696 cfg_which = which;
697
698 cfg_ncontrols = cfg_controlsize = 0;
699 cfg_controls = NULL;
700 leftw = rightw = 0;
701 for (i = cfg; i->type != C_END; i++) {
702 if (cfg_controlsize < cfg_ncontrols + 5) {
703 cfg_controlsize = cfg_ncontrols + 32;
704 cfg_controls = sresize(cfg_controls, cfg_controlsize, NSView *);
705 }
706
707 thish = 0;
708
709 switch (i->type) {
710 case C_STRING:
711 /*
712 * Two NSTextFields, one being a label and the other
713 * being an edit box.
714 */
715
716 tf = [[NSTextField alloc] initWithFrame:tmprect];
717 [tf setEditable:NO];
718 [tf setSelectable:NO];
719 [tf setBordered:NO];
720 [tf setDrawsBackground:NO];
721 [[tf cell] setTitle:[NSString stringWithCString:i->name]];
722 [tf sizeToFit];
723 rect = [tf frame];
724 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
725 if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
726 cfg_controls[cfg_ncontrols++] = tf;
727
728 /* We impose a minimum width on editable NSTextFields to
729 * stop them looking _completely_ silly. */
730 if (rightw < 75) rightw = 75;
731
732 tf = [[NSTextField alloc] initWithFrame:tmprect];
733 [tf setEditable:YES];
734 [tf setSelectable:YES];
735 [tf setBordered:YES];
736 [[tf cell] setTitle:[NSString stringWithCString:i->sval]];
737 [tf sizeToFit];
738 rect = [tf frame];
739 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
740 if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
741 cfg_controls[cfg_ncontrols++] = tf;
742 break;
743
744 case C_BOOLEAN:
745 /*
746 * A checkbox is an NSButton with a type of
747 * NSSwitchButton.
748 */
749 b = [[NSButton alloc] initWithFrame:tmprect];
750 [b setBezelStyle:NSRoundedBezelStyle];
751 [b setButtonType:NSSwitchButton];
752 [b setTitle:[NSString stringWithCString:i->name]];
753 [b sizeToFit];
754 [b setState:(i->ival ? NSOnState : NSOffState)];
755 rect = [b frame];
756 if (totalw < rect.size.width + 1) totalw = rect.size.width + 1;
757 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
758 cfg_controls[cfg_ncontrols++] = b;
759 break;
760
761 case C_CHOICES:
762 /*
763 * A pop-up menu control is an NSPopUpButton, which
764 * takes an embedded NSMenu. We also need an
765 * NSTextField to act as a label.
766 */
767
768 tf = [[NSTextField alloc] initWithFrame:tmprect];
769 [tf setEditable:NO];
770 [tf setSelectable:NO];
771 [tf setBordered:NO];
772 [tf setDrawsBackground:NO];
773 [[tf cell] setTitle:[NSString stringWithCString:i->name]];
774 [tf sizeToFit];
775 rect = [tf frame];
776 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
777 if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
778 cfg_controls[cfg_ncontrols++] = tf;
779
780 pb = [[NSPopUpButton alloc] initWithFrame:tmprect pullsDown:NO];
781 [pb setBezelStyle:NSRoundedBezelStyle];
782 {
783 char c, *p;
784
785 p = i->sval;
786 c = *p++;
787 while (*p) {
788 char *q;
789
790 q = p;
791 while (*p && *p != c) p++;
792
793 [pb addItemWithTitle:[NSString stringWithCString:q
794 length:p-q]];
795
796 if (*p) p++;
797 }
798 }
799 [pb selectItemAtIndex:i->ival];
800 [pb sizeToFit];
801
802 rect = [pb frame];
803 if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
804 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
805 cfg_controls[cfg_ncontrols++] = pb;
806 break;
807 }
808
809 h += SPACING + thish;
810 }
811
812 if (totalw < leftw + SPACING + rightw)
813 totalw = leftw + SPACING + rightw;
814 if (totalw > leftw + SPACING + rightw) {
815 int excess = totalw - (leftw + SPACING + rightw);
816 int leftexcess = leftw * excess / (leftw + rightw);
817 int rightexcess = excess - leftexcess;
818 leftw += leftexcess;
819 rightw += rightexcess;
820 }
821
822 /*
823 * Now go through the list again, setting the final position
824 * for each control.
825 */
826 k = 0;
827 y = h;
828 for (i = cfg; i->type != C_END; i++) {
829 y -= SPACING;
830 thish = 0;
831 switch (i->type) {
832 case C_STRING:
833 case C_CHOICES:
834 /*
835 * These two are treated identically, since both expect
836 * a control on the left and another on the right.
837 */
838 rect = [cfg_controls[k] frame];
839 if (thish < rect.size.height + 1)
840 thish = rect.size.height + 1;
841 rect = [cfg_controls[k+1] frame];
842 if (thish < rect.size.height + 1)
843 thish = rect.size.height + 1;
844 rect = [cfg_controls[k] frame];
845 rect.origin.y = y - thish/2 - rect.size.height/2;
846 rect.origin.x = SPACING;
847 rect.size.width = leftw;
848 [cfg_controls[k] setFrame:rect];
849 rect = [cfg_controls[k+1] frame];
850 rect.origin.y = y - thish/2 - rect.size.height/2;
851 rect.origin.x = 2 * SPACING + leftw;
852 rect.size.width = rightw;
853 [cfg_controls[k+1] setFrame:rect];
854 k += 2;
855 break;
856
857 case C_BOOLEAN:
858 rect = [cfg_controls[k] frame];
859 if (thish < rect.size.height + 1)
860 thish = rect.size.height + 1;
861 rect.origin.y = y - thish/2 - rect.size.height/2;
862 rect.origin.x = SPACING;
863 rect.size.width = totalw;
864 [cfg_controls[k] setFrame:rect];
865 k++;
866 break;
867 }
868 y -= thish;
869 }
870
871 assert(k == cfg_ncontrols);
872
873 [cancel setFrame:NSMakeRect(SPACING+totalw/4-actw/2, SPACING, actw, acth)];
874 [ok setFrame:NSMakeRect(SPACING+3*totalw/4-actw/2, SPACING, actw, acth)];
875
876 sheet = [[NSWindow alloc]
877 initWithContentRect:NSMakeRect(0,0,totalw + 2*SPACING,h)
878 styleMask:NSTitledWindowMask | NSClosableWindowMask
879 backing:NSBackingStoreBuffered
880 defer:YES];
881
882 [[sheet contentView] addSubview:cancel];
883 [[sheet contentView] addSubview:ok];
884
885 for (k = 0; k < cfg_ncontrols; k++)
886 [[sheet contentView] addSubview:cfg_controls[k]];
887
888 [NSApp beginSheet:sheet modalForWindow:self
889 modalDelegate:nil didEndSelector:nil contextInfo:nil];
890}
891
892- (void)specificGame:(id)sender
893{
894 [self startConfigureSheet:CFG_SEED];
895}
896
897- (void)customGameType:(id)sender
898{
899 [self startConfigureSheet:CFG_SETTINGS];
900}
901
902- (void)sheetEndWithStatus:(BOOL)update
903{
904 assert(sheet != NULL);
905 [NSApp endSheet:sheet];
906 [sheet orderOut:self];
907 sheet = NULL;
908 if (update) {
909 int k;
910 config_item *i;
911 char *error;
912
913 k = 0;
914 for (i = cfg; i->type != C_END; i++) {
915 switch (i->type) {
916 case C_STRING:
917 sfree(i->sval);
918 i->sval = dupstr([[[(id)cfg_controls[k+1] cell]
919 title] cString]);
920 k += 2;
921 break;
922 case C_BOOLEAN:
923 i->ival = [(id)cfg_controls[k] state] == NSOnState;
924 k++;
925 break;
926 case C_CHOICES:
927 i->ival = [(id)cfg_controls[k+1] indexOfSelectedItem];
928 k += 2;
929 break;
930 }
931 }
932
933 error = midend_set_config(me, cfg_which, cfg);
934 if (error) {
935 NSAlert *alert = [[[NSAlert alloc] init] autorelease];
e7fabdfa 936 [alert addButtonWithTitle:@"Bah"];
e1107f8b 937 [alert setInformativeText:[NSString stringWithCString:error]];
938 [alert beginSheetModalForWindow:self modalDelegate:nil
939 didEndSelector:nil contextInfo:nil];
940 } else {
941 midend_new_game(me);
942 [self resizeForNewGameParams];
943 }
944 }
945 sfree(cfg_controls);
946 cfg_controls = NULL;
947}
948- (void)sheetOKButton:(id)sender
949{
950 [self sheetEndWithStatus:YES];
951}
952- (void)sheetCancelButton:(id)sender
953{
954 [self sheetEndWithStatus:NO];
955}
956
a5102461 957- (void)setStatusLine:(NSString *)text
958{
959 [[status cell] setTitle:text];
960}
961
9494d866 962@end
963
964/*
965 * Drawing routines called by the midend.
966 */
967void draw_polygon(frontend *fe, int *coords, int npoints,
968 int fill, int colour)
969{
970 NSBezierPath *path = [NSBezierPath bezierPath];
971 int i;
972
973 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
974
975 assert(colour >= 0 && colour < fe->ncolours);
976 [fe->colours[colour] set];
977
978 for (i = 0; i < npoints; i++) {
979 NSPoint p = { coords[i*2] + 0.5, coords[i*2+1] + 0.5 };
980 if (i == 0)
981 [path moveToPoint:p];
982 else
983 [path lineToPoint:p];
984 }
985
986 [path closePath];
987
988 if (fill)
989 [path fill];
990 else
991 [path stroke];
992}
993void draw_line(frontend *fe, int x1, int y1, int x2, int y2, int colour)
994{
995 NSBezierPath *path = [NSBezierPath bezierPath];
996 NSPoint p1 = { x1 + 0.5, y1 + 0.5 }, p2 = { x2 + 0.5, y2 + 0.5 };
997
998 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
999
1000 assert(colour >= 0 && colour < fe->ncolours);
1001 [fe->colours[colour] set];
1002
1003 [path moveToPoint:p1];
1004 [path lineToPoint:p2];
1005 [path stroke];
1006}
1007void draw_rect(frontend *fe, int x, int y, int w, int h, int colour)
1008{
1009 NSRect r = { {x,y}, {w,h} };
1010
1011 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1012
1013 assert(colour >= 0 && colour < fe->ncolours);
1014 [fe->colours[colour] set];
1015
1016 NSRectFill(r);
1017}
1018void draw_text(frontend *fe, int x, int y, int fonttype, int fontsize,
1019 int align, int colour, char *text)
1020{
1021 NSString *string = [NSString stringWithCString:text];
1022 NSDictionary *attr;
1023 NSFont *font;
1024 NSSize size;
1025 NSPoint point;
1026
1027 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1028
1029 assert(colour >= 0 && colour < fe->ncolours);
1030
1031 if (fonttype == FONT_FIXED)
1032 font = [NSFont userFixedPitchFontOfSize:fontsize];
1033 else
1034 font = [NSFont userFontOfSize:fontsize];
1035
1036 attr = [NSDictionary dictionaryWithObjectsAndKeys:
1037 fe->colours[colour], NSForegroundColorAttributeName,
1038 font, NSFontAttributeName, nil];
1039
1040 point.x = x;
1041 point.y = y;
1042
1043 size = [string sizeWithAttributes:attr];
1044 if (align & ALIGN_HRIGHT)
1045 point.x -= size.width;
1046 else if (align & ALIGN_HCENTRE)
1047 point.x -= size.width / 2;
1048 if (align & ALIGN_VCENTRE)
1049 point.y -= size.height / 2;
1050
1051 [string drawAtPoint:point withAttributes:attr];
1052}
1053void draw_update(frontend *fe, int x, int y, int w, int h)
1054{
e7fabdfa 1055 /*
1056 * FIXME: It seems odd that nothing is required here, although
1057 * everything _seems_ to work with this routine empty. Possibly
1058 * we're always updating the entire window, and there's a
1059 * better way which would involve doing something in here?
1060 */
9494d866 1061}
1062void clip(frontend *fe, int x, int y, int w, int h)
1063{
1064 NSRect r = { {x,y}, {w,h} };
1065
1066 if (!fe->clipped)
1067 [[NSGraphicsContext currentContext] saveGraphicsState];
1068 [NSBezierPath clipRect:r];
1069 fe->clipped = TRUE;
1070}
1071void unclip(frontend *fe)
1072{
1073 if (fe->clipped)
1074 [[NSGraphicsContext currentContext] restoreGraphicsState];
1075 fe->clipped = FALSE;
1076}
1077void start_draw(frontend *fe)
1078{
1079 [fe->image lockFocus];
1080 fe->clipped = FALSE;
1081}
1082void end_draw(frontend *fe)
1083{
1084 [fe->image unlockFocus];
1085 [fe->view setNeedsDisplay];
1086}
1087
1088void deactivate_timer(frontend *fe)
1089{
1090 [fe->window deactivateTimer];
1091}
1092void activate_timer(frontend *fe)
1093{
1094 [fe->window activateTimer];
1095}
1096
a5102461 1097void status_bar(frontend *fe, char *text)
1098{
1099 [fe->window setStatusLine:[NSString stringWithCString:text]];
1100}
1101
9494d866 1102/* ----------------------------------------------------------------------
9494d866 1103 * AppController: the object which receives the messages from all
1104 * menu selections that aren't standard OS X functions.
1105 */
1106@interface AppController : NSObject
1107{
1108}
1109- (IBAction)newGame:(id)sender;
1110@end
1111
1112@implementation AppController
1113
1114- (IBAction)newGame:(id)sender
1115{
7e04cb48 1116 const game *g = [sender getPayload];
9494d866 1117 id win;
1118
1119 win = [[GameWindow alloc] initWithGame:g];
1120 [win makeKeyAndOrderFront:self];
1121}
1122
3041164c 1123- (NSMenu *)applicationDockMenu:(NSApplication *)sender
1124{
1125 NSMenu *menu = newmenu("Dock Menu");
1126 {
1127 int i;
1128
1129 for (i = 0; i < gamecount; i++) {
1130 id item =
1131 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1132 menu, gamelist[i]->name, "", self,
1133 @selector(newGame:));
1134 [item setPayload:(void *)gamelist[i]];
1135 }
1136 }
1137 return menu;
1138}
1139
9494d866 1140@end
1141
1142/* ----------------------------------------------------------------------
1143 * Main program. Constructs the menus and runs the application.
1144 */
1145int main(int argc, char **argv)
1146{
1147 NSAutoreleasePool *pool;
1148 NSMenu *menu;
1149 NSMenuItem *item;
1150 AppController *controller;
a96edf8a 1151 NSImage *icon;
9494d866 1152
1153 pool = [[NSAutoreleasePool alloc] init];
a96edf8a 1154
1155 icon = [NSImage imageNamed:@"NSApplicationIcon"];
9494d866 1156 [NSApplication sharedApplication];
a96edf8a 1157 [NSApp setApplicationIconImage:icon];
9494d866 1158
1159 controller = [[[AppController alloc] init] autorelease];
3041164c 1160 [NSApp setDelegate:controller];
9494d866 1161
1162 [NSApp setMainMenu: newmenu("Main Menu")];
1163
1164 menu = newsubmenu([NSApp mainMenu], "Apple Menu");
1165 [NSApp setServicesMenu:newsubmenu(menu, "Services")];
1166 [menu addItem:[NSMenuItem separatorItem]];
1167 item = newitem(menu, "Hide Puzzles", "h", NSApp, @selector(hide:));
1168 item = newitem(menu, "Hide Others", "o-h", NSApp, @selector(hideOtherApplications:));
1169 item = newitem(menu, "Show All", "", NSApp, @selector(unhideAllApplications:));
1170 [menu addItem:[NSMenuItem separatorItem]];
1171 item = newitem(menu, "Quit", "q", NSApp, @selector(terminate:));
1172 [NSApp setAppleMenu: menu];
1173
00461804 1174 menu = newsubmenu([NSApp mainMenu], "Open");
9494d866 1175 {
1176 int i;
1177
1178 for (i = 0; i < gamecount; i++) {
1179 id item =
7e04cb48 1180 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
9494d866 1181 menu, gamelist[i]->name, "", controller,
1182 @selector(newGame:));
7e04cb48 1183 [item setPayload:(void *)gamelist[i]];
9494d866 1184 }
1185 }
1186
00461804 1187 menu = newsubmenu([NSApp mainMenu], "Game");
1188 item = newitem(menu, "New", "n", NULL, @selector(newGame:));
1189 item = newitem(menu, "Restart", "r", NULL, @selector(restartGame:));
1190 item = newitem(menu, "Specific", "", NULL, @selector(specificGame:));
1191 [menu addItem:[NSMenuItem separatorItem]];
1192 item = newitem(menu, "Undo", "z", NULL, @selector(undoMove:));
1193 item = newitem(menu, "Redo", "S-z", NULL, @selector(redoMove:));
1194 [menu addItem:[NSMenuItem separatorItem]];
1195 item = newitem(menu, "Close", "w", NULL, @selector(performClose:));
1196
1197 menu = newsubmenu([NSApp mainMenu], "Type");
7e04cb48 1198 typemenu = menu;
00461804 1199 item = newitem(menu, "Custom", "", NULL, @selector(customGameType:));
1200
1201 menu = newsubmenu([NSApp mainMenu], "Window");
9494d866 1202 [NSApp setWindowsMenu: menu];
00461804 1203 item = newitem(menu, "Minimise Window", "m", NULL, @selector(performMiniaturize:));
9494d866 1204
1205 [NSApp run];
1206 [pool release];
1207}