chiark / gitweb /
The main grid outline in Pattern was asymmetric between the top/left
[sgt-puzzles.git] / osx.m
1 /*
2  * Mac OS X / Cocoa front end to puzzles.
3  *
4  * Actually unfinished things left to do:
5  *
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  * 
11  * Mac interface issues that possibly could be done better:
12  * 
13  *  - is there a better approach to frontend_default_colour?
14  *
15  *  - do we need any more options in the Window menu?
16  *
17  *  - can / should we be doing anything with the titles of the
18  *    configuration boxes?
19  * 
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"?
25  *
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
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.
32  *
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  *
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  * 
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.
67  */
68
69 #include <ctype.h>
70 #include <sys/time.h>
71 #import <Cocoa/Cocoa.h>
72 #include "puzzles.h"
73
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  */
82 NSMenu *typemenu;
83
84 /* ----------------------------------------------------------------------
85  * Miscellaneous support routines that aren't part of any object or
86  * clearly defined subsystem.
87  */
88
89 void fatal(char *fmt, ...)
90 {
91     va_list ap;
92     char errorbuf[2048];
93     NSAlert *alert;
94
95     va_start(ap, fmt);
96     vsnprintf(errorbuf, lenof(errorbuf), fmt, ap);
97     va_end(ap);
98
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     }
113     exit(1);
114 }
115
116 void frontend_default_colour(frontend *fe, float *output)
117 {
118     /* FIXME: Is there a system default we can tap into for this? */
119     output[0] = output[1] = output[2] = 0.8F;
120 }
121
122 void 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 /* ----------------------------------------------------------------------
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;
138 }
139 - (void)setPayload:(void *)d;
140 - (void *)getPayload;
141 @end
142 @implementation DataMenuItem
143 - (void)setPayload:(void *)d
144 {
145     payload = d;
146 }
147 - (void *)getPayload
148 {
149     return payload;
150 }
151 @end
152
153 /* ----------------------------------------------------------------------
154  * Utility routines for constructing OS X menus.
155  */
156
157 NSMenu *newmenu(const char *title)
158 {
159     return [[[NSMenu allocWithZone:[NSMenu menuZone]]
160              initWithTitle:[NSString stringWithCString:title]]
161             autorelease];
162 }
163
164 NSMenu *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
181 id 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
217 NSMenuItem *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 /* ----------------------------------------------------------------------
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
236 struct 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;
270     NSWindow *sheet;
271     config_item *cfg;
272     int cfg_which;
273     NSView **cfg_controls;
274     int cfg_ncontrols;
275     NSTextField *status;
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;
283 - (void)setStatusLine:(NSString *)text;
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
358 - (void)setupContentView
359 {
360     NSRect frame;
361     int w, h;
362
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
370     midend_size(me, &w, &h);
371     frame.size.width = w;
372     frame.size.height = h;
373
374     fe.image = [[NSImage alloc] initWithSize:frame.size];
375     [fe.image setFlipped:YES];
376     fe.view = [[MyImageView alloc] initWithFrame:frame];
377     [fe.view setImage:fe.image];
378     [fe.view setWindow:self];
379
380     midend_redraw(me);
381
382     [[self contentView] addSubview:fe.view];
383 }
384 - (id)initWithGame:(const game *)g
385 {
386     NSRect rect = { {0,0}, {0,0} }, rect2;
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
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
426     self = [super initWithContentRect:rect
427             styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
428                        NSClosableWindowMask)
429             backing:NSBackingStoreBuffered
430             defer:YES];
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
448     [self setupContentView];
449     if (status)
450         [[self contentView] addSubview:status];
451     [self setIgnoresMouseEvents:NO];
452
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
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
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];
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     if (status) {
621         NSRect frame = [status frame];
622         size.height += frame.size.height;
623         frame.size.width = size.width;
624         [status setFrame:frame];
625     }
626
627     NSDisableScreenUpdates();
628     [self setContentSize:size];
629     [self setupContentView];
630     NSEnableScreenUpdates();
631 }
632
633 - (void)presetGame:(id)sender
634 {
635     game_params *params = [sender getPayload];
636
637     midend_set_params(me, params);
638     midend_new_game(me);
639
640     [self resizeForNewGameParams];
641 }
642
643 - (void)startConfigureSheet:(int)which
644 {
645     NSButton *ok, *cancel;
646     int actw, acth, leftw, rightw, totalw, h, thish, y;
647     int k;
648     NSRect rect, tmprect;
649     const int SPACING = 16;
650     char *title;
651     config_item *i;
652     int cfg_controlsize;
653     NSTextField *tf;
654     NSButton *b;
655     NSPopUpButton *pb;
656
657     assert(sheet == NULL);
658
659     /*
660      * Every control we create here is going to have this size
661      * until we tell it to calculate a better one.
662      */
663     tmprect = NSMakeRect(0, 0, 100, 50);
664
665     /*
666      * Set up OK and Cancel buttons. (Actually, MacOS doesn't seem
667      * to be fond of generic OK and Cancel wording, so I'm going to
668      * rename them to something nicer.)
669      */
670     actw = acth = 0;
671
672     cancel = [[NSButton alloc] initWithFrame:tmprect];
673     [cancel setBezelStyle:NSRoundedBezelStyle];
674     [cancel setTitle:@"Abandon"];
675     [cancel setTarget:self];
676     [cancel setKeyEquivalent:@"\033"];
677     [cancel setAction:@selector(sheetCancelButton:)];
678     [cancel sizeToFit];
679     rect = [cancel frame];
680     if (actw < rect.size.width) actw = rect.size.width;
681     if (acth < rect.size.height) acth = rect.size.height;
682
683     ok = [[NSButton alloc] initWithFrame:tmprect];
684     [ok setBezelStyle:NSRoundedBezelStyle];
685     [ok setTitle:@"Accept"];
686     [ok setTarget:self];
687     [ok setKeyEquivalent:@"\r"];
688     [ok setAction:@selector(sheetOKButton:)];
689     [ok sizeToFit];
690     rect = [ok frame];
691     if (actw < rect.size.width) actw = rect.size.width;
692     if (acth < rect.size.height) acth = rect.size.height;
693
694     totalw = SPACING + 2 * actw;
695     h = 2 * SPACING + acth;
696
697     /*
698      * Now fetch the midend config data and go through it creating
699      * controls.
700      */
701     cfg = midend_get_config(me, which, &title);
702     sfree(title);                      /* FIXME: should we use this somehow? */
703     cfg_which = which;
704
705     cfg_ncontrols = cfg_controlsize = 0;
706     cfg_controls = NULL;
707     leftw = rightw = 0;
708     for (i = cfg; i->type != C_END; i++) {
709         if (cfg_controlsize < cfg_ncontrols + 5) {
710             cfg_controlsize = cfg_ncontrols + 32;
711             cfg_controls = sresize(cfg_controls, cfg_controlsize, NSView *);
712         }
713
714         thish = 0;
715
716         switch (i->type) {
717           case C_STRING:
718             /*
719              * Two NSTextFields, one being a label and the other
720              * being an edit box.
721              */
722
723             tf = [[NSTextField alloc] initWithFrame:tmprect];
724             [tf setEditable:NO];
725             [tf setSelectable:NO];
726             [tf setBordered:NO];
727             [tf setDrawsBackground:NO];
728             [[tf cell] setTitle:[NSString stringWithCString:i->name]];
729             [tf sizeToFit];
730             rect = [tf frame];
731             if (thish < rect.size.height + 1) thish = rect.size.height + 1;
732             if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
733             cfg_controls[cfg_ncontrols++] = tf;
734
735             /* We impose a minimum width on editable NSTextFields to
736              * stop them looking _completely_ silly. */
737             if (rightw < 75) rightw = 75;
738
739             tf = [[NSTextField alloc] initWithFrame:tmprect];
740             [tf setEditable:YES];
741             [tf setSelectable:YES];
742             [tf setBordered:YES];
743             [[tf cell] setTitle:[NSString stringWithCString:i->sval]];
744             [tf sizeToFit];
745             rect = [tf frame];
746             if (thish < rect.size.height + 1) thish = rect.size.height + 1;
747             if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
748             cfg_controls[cfg_ncontrols++] = tf;
749             break;
750
751           case C_BOOLEAN:
752             /*
753              * A checkbox is an NSButton with a type of
754              * NSSwitchButton.
755              */
756             b = [[NSButton alloc] initWithFrame:tmprect];
757             [b setBezelStyle:NSRoundedBezelStyle];
758             [b setButtonType:NSSwitchButton];
759             [b setTitle:[NSString stringWithCString:i->name]];
760             [b sizeToFit];
761             [b setState:(i->ival ? NSOnState : NSOffState)];
762             rect = [b frame];
763             if (totalw < rect.size.width + 1) totalw = rect.size.width + 1;
764             if (thish < rect.size.height + 1) thish = rect.size.height + 1;
765             cfg_controls[cfg_ncontrols++] = b;
766             break;
767
768           case C_CHOICES:
769             /*
770              * A pop-up menu control is an NSPopUpButton, which
771              * takes an embedded NSMenu. We also need an
772              * NSTextField to act as a label.
773              */
774
775             tf = [[NSTextField alloc] initWithFrame:tmprect];
776             [tf setEditable:NO];
777             [tf setSelectable:NO];
778             [tf setBordered:NO];
779             [tf setDrawsBackground:NO];
780             [[tf cell] setTitle:[NSString stringWithCString:i->name]];
781             [tf sizeToFit];
782             rect = [tf frame];
783             if (thish < rect.size.height + 1) thish = rect.size.height + 1;
784             if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
785             cfg_controls[cfg_ncontrols++] = tf;
786
787             pb = [[NSPopUpButton alloc] initWithFrame:tmprect pullsDown:NO];
788             [pb setBezelStyle:NSRoundedBezelStyle];
789             {
790                 char c, *p;
791
792                 p = i->sval;
793                 c = *p++;
794                 while (*p) {
795                     char *q;
796
797                     q = p;
798                     while (*p && *p != c) p++;
799
800                     [pb addItemWithTitle:[NSString stringWithCString:q
801                                           length:p-q]];
802
803                     if (*p) p++;
804                 }
805             }
806             [pb selectItemAtIndex:i->ival];
807             [pb sizeToFit];
808
809             rect = [pb frame];
810             if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
811             if (thish < rect.size.height + 1) thish = rect.size.height + 1;
812             cfg_controls[cfg_ncontrols++] = pb;
813             break;
814         }
815
816         h += SPACING + thish;
817     }
818
819     if (totalw < leftw + SPACING + rightw)
820         totalw = leftw + SPACING + rightw;
821     if (totalw > leftw + SPACING + rightw) {
822         int excess = totalw - (leftw + SPACING + rightw);
823         int leftexcess = leftw * excess / (leftw + rightw);
824         int rightexcess = excess - leftexcess;
825         leftw += leftexcess;
826         rightw += rightexcess;
827     }
828
829     /*
830      * Now go through the list again, setting the final position
831      * for each control.
832      */
833     k = 0;
834     y = h;
835     for (i = cfg; i->type != C_END; i++) {
836         y -= SPACING;
837         thish = 0;
838         switch (i->type) {
839           case C_STRING:
840           case C_CHOICES:
841             /*
842              * These two are treated identically, since both expect
843              * a control on the left and another on the right.
844              */
845             rect = [cfg_controls[k] frame];
846             if (thish < rect.size.height + 1)
847                 thish = rect.size.height + 1;
848             rect = [cfg_controls[k+1] frame];
849             if (thish < rect.size.height + 1)
850                 thish = rect.size.height + 1;
851             rect = [cfg_controls[k] frame];
852             rect.origin.y = y - thish/2 - rect.size.height/2;
853             rect.origin.x = SPACING;
854             rect.size.width = leftw;
855             [cfg_controls[k] setFrame:rect];
856             rect = [cfg_controls[k+1] frame];
857             rect.origin.y = y - thish/2 - rect.size.height/2;
858             rect.origin.x = 2 * SPACING + leftw;
859             rect.size.width = rightw;
860             [cfg_controls[k+1] setFrame:rect];
861             k += 2;
862             break;
863
864           case C_BOOLEAN:
865             rect = [cfg_controls[k] frame];
866             if (thish < rect.size.height + 1)
867                 thish = rect.size.height + 1;
868             rect.origin.y = y - thish/2 - rect.size.height/2;
869             rect.origin.x = SPACING;
870             rect.size.width = totalw;
871             [cfg_controls[k] setFrame:rect];
872             k++;
873             break;
874         }
875         y -= thish;
876     }
877
878     assert(k == cfg_ncontrols);
879
880     [cancel setFrame:NSMakeRect(SPACING+totalw/4-actw/2, SPACING, actw, acth)];
881     [ok setFrame:NSMakeRect(SPACING+3*totalw/4-actw/2, SPACING, actw, acth)];
882
883     sheet = [[NSWindow alloc]
884              initWithContentRect:NSMakeRect(0,0,totalw + 2*SPACING,h)
885              styleMask:NSTitledWindowMask | NSClosableWindowMask
886              backing:NSBackingStoreBuffered
887              defer:YES];
888
889     [[sheet contentView] addSubview:cancel];
890     [[sheet contentView] addSubview:ok];
891
892     for (k = 0; k < cfg_ncontrols; k++)
893         [[sheet contentView] addSubview:cfg_controls[k]];
894
895     [NSApp beginSheet:sheet modalForWindow:self
896      modalDelegate:nil didEndSelector:nil contextInfo:nil];
897 }
898
899 - (void)specificGame:(id)sender
900 {
901     [self startConfigureSheet:CFG_SEED];
902 }
903
904 - (void)customGameType:(id)sender
905 {
906     [self startConfigureSheet:CFG_SETTINGS];
907 }
908
909 - (void)sheetEndWithStatus:(BOOL)update
910 {
911     assert(sheet != NULL);
912     [NSApp endSheet:sheet];
913     [sheet orderOut:self];
914     sheet = NULL;
915     if (update) {
916         int k;
917         config_item *i;
918         char *error;
919
920         k = 0;
921         for (i = cfg; i->type != C_END; i++) {
922             switch (i->type) {
923               case C_STRING:
924                 sfree(i->sval);
925                 i->sval = dupstr([[[(id)cfg_controls[k+1] cell]
926                                    title] cString]);
927                 k += 2;
928                 break;
929               case C_BOOLEAN:
930                 i->ival = [(id)cfg_controls[k] state] == NSOnState;
931                 k++;
932                 break;
933               case C_CHOICES:
934                 i->ival = [(id)cfg_controls[k+1] indexOfSelectedItem];
935                 k += 2;
936                 break;
937             }
938         }
939
940         error = midend_set_config(me, cfg_which, cfg);
941         if (error) {
942             NSAlert *alert = [[[NSAlert alloc] init] autorelease];
943             [alert addButtonWithTitle:@"Bah"];
944             [alert setInformativeText:[NSString stringWithCString:error]];
945             [alert beginSheetModalForWindow:self modalDelegate:nil
946              didEndSelector:nil contextInfo:nil];
947         } else {
948             midend_new_game(me);
949             [self resizeForNewGameParams];
950         }
951     }
952     sfree(cfg_controls);
953     cfg_controls = NULL;
954 }
955 - (void)sheetOKButton:(id)sender
956 {
957     [self sheetEndWithStatus:YES];
958 }
959 - (void)sheetCancelButton:(id)sender
960 {
961     [self sheetEndWithStatus:NO];
962 }
963
964 - (void)setStatusLine:(NSString *)text
965 {
966     [[status cell] setTitle:text];
967 }
968
969 @end
970
971 /*
972  * Drawing routines called by the midend.
973  */
974 void draw_polygon(frontend *fe, int *coords, int npoints,
975                   int fill, int colour)
976 {
977     NSBezierPath *path = [NSBezierPath bezierPath];
978     int i;
979
980     [[NSGraphicsContext currentContext] setShouldAntialias:YES];
981
982     assert(colour >= 0 && colour < fe->ncolours);
983     [fe->colours[colour] set];
984
985     for (i = 0; i < npoints; i++) {
986         NSPoint p = { coords[i*2] + 0.5, coords[i*2+1] + 0.5 };
987         if (i == 0)
988             [path moveToPoint:p];
989         else
990             [path lineToPoint:p];
991     }
992
993     [path closePath];
994
995     if (fill)
996         [path fill];
997     else
998         [path stroke];
999 }
1000 void draw_line(frontend *fe, int x1, int y1, int x2, int y2, int colour)
1001 {
1002     NSBezierPath *path = [NSBezierPath bezierPath];
1003     NSPoint p1 = { x1 + 0.5, y1 + 0.5 }, p2 = { x2 + 0.5, y2 + 0.5 };
1004
1005     [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1006
1007     assert(colour >= 0 && colour < fe->ncolours);
1008     [fe->colours[colour] set];
1009
1010     [path moveToPoint:p1];
1011     [path lineToPoint:p2];
1012     [path stroke];
1013 }
1014 void draw_rect(frontend *fe, int x, int y, int w, int h, int colour)
1015 {
1016     NSRect r = { {x,y}, {w,h} };
1017
1018     [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1019
1020     assert(colour >= 0 && colour < fe->ncolours);
1021     [fe->colours[colour] set];
1022
1023     NSRectFill(r);
1024 }
1025 void draw_text(frontend *fe, int x, int y, int fonttype, int fontsize,
1026                int align, int colour, char *text)
1027 {
1028     NSString *string = [NSString stringWithCString:text];
1029     NSDictionary *attr;
1030     NSFont *font;
1031     NSSize size;
1032     NSPoint point;
1033
1034     [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1035
1036     assert(colour >= 0 && colour < fe->ncolours);
1037
1038     if (fonttype == FONT_FIXED)
1039         font = [NSFont userFixedPitchFontOfSize:fontsize];
1040     else
1041         font = [NSFont userFontOfSize:fontsize];
1042
1043     attr = [NSDictionary dictionaryWithObjectsAndKeys:
1044             fe->colours[colour], NSForegroundColorAttributeName,
1045             font, NSFontAttributeName, nil];
1046
1047     point.x = x;
1048     point.y = y;
1049
1050     size = [string sizeWithAttributes:attr];
1051     if (align & ALIGN_HRIGHT)
1052         point.x -= size.width;
1053     else if (align & ALIGN_HCENTRE)
1054         point.x -= size.width / 2;
1055     if (align & ALIGN_VCENTRE)
1056         point.y -= size.height / 2;
1057
1058     [string drawAtPoint:point withAttributes:attr];
1059 }
1060 void draw_update(frontend *fe, int x, int y, int w, int h)
1061 {
1062     /*
1063      * FIXME: It seems odd that nothing is required here, although
1064      * everything _seems_ to work with this routine empty. Possibly
1065      * we're always updating the entire window, and there's a
1066      * better way which would involve doing something in here?
1067      */
1068 }
1069 void clip(frontend *fe, int x, int y, int w, int h)
1070 {
1071     NSRect r = { {x,y}, {w,h} };
1072
1073     if (!fe->clipped)
1074         [[NSGraphicsContext currentContext] saveGraphicsState];
1075     [NSBezierPath clipRect:r];
1076     fe->clipped = TRUE;
1077 }
1078 void unclip(frontend *fe)
1079 {
1080     if (fe->clipped)
1081         [[NSGraphicsContext currentContext] restoreGraphicsState];
1082     fe->clipped = FALSE;
1083 }
1084 void start_draw(frontend *fe)
1085 {
1086     [fe->image lockFocus];
1087     fe->clipped = FALSE;
1088 }
1089 void end_draw(frontend *fe)
1090 {
1091     [fe->image unlockFocus];
1092     [fe->view setNeedsDisplay];
1093 }
1094
1095 void deactivate_timer(frontend *fe)
1096 {
1097     [fe->window deactivateTimer];
1098 }
1099 void activate_timer(frontend *fe)
1100 {
1101     [fe->window activateTimer];
1102 }
1103
1104 void status_bar(frontend *fe, char *text)
1105 {
1106     [fe->window setStatusLine:[NSString stringWithCString:text]];
1107 }
1108
1109 /* ----------------------------------------------------------------------
1110  * AppController: the object which receives the messages from all
1111  * menu selections that aren't standard OS X functions.
1112  */
1113 @interface AppController : NSObject
1114 {
1115 }
1116 - (IBAction)newGame:(id)sender;
1117 @end
1118
1119 @implementation AppController
1120
1121 - (IBAction)newGame:(id)sender
1122 {
1123     const game *g = [sender getPayload];
1124     id win;
1125
1126     win = [[GameWindow alloc] initWithGame:g];
1127     [win makeKeyAndOrderFront:self];
1128 }
1129
1130 - (NSMenu *)applicationDockMenu:(NSApplication *)sender
1131 {
1132     NSMenu *menu = newmenu("Dock Menu");
1133     {
1134         int i;
1135
1136         for (i = 0; i < gamecount; i++) {
1137             id item =
1138                 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1139                             menu, gamelist[i]->name, "", self,
1140                             @selector(newGame:));
1141             [item setPayload:(void *)gamelist[i]];
1142         }
1143     }
1144     return menu;
1145 }
1146
1147 @end
1148
1149 /* ----------------------------------------------------------------------
1150  * Main program. Constructs the menus and runs the application.
1151  */
1152 int main(int argc, char **argv)
1153 {
1154     NSAutoreleasePool *pool;
1155     NSMenu *menu;
1156     NSMenuItem *item;
1157     AppController *controller;
1158     NSImage *icon;
1159
1160     pool = [[NSAutoreleasePool alloc] init];
1161
1162     icon = [NSImage imageNamed:@"NSApplicationIcon"];
1163     [NSApplication sharedApplication];
1164     [NSApp setApplicationIconImage:icon];
1165
1166     controller = [[[AppController alloc] init] autorelease];
1167     [NSApp setDelegate:controller];
1168
1169     [NSApp setMainMenu: newmenu("Main Menu")];
1170
1171     menu = newsubmenu([NSApp mainMenu], "Apple Menu");
1172     [NSApp setServicesMenu:newsubmenu(menu, "Services")];
1173     [menu addItem:[NSMenuItem separatorItem]];
1174     item = newitem(menu, "Hide Puzzles", "h", NSApp, @selector(hide:));
1175     item = newitem(menu, "Hide Others", "o-h", NSApp, @selector(hideOtherApplications:));
1176     item = newitem(menu, "Show All", "", NSApp, @selector(unhideAllApplications:));
1177     [menu addItem:[NSMenuItem separatorItem]];
1178     item = newitem(menu, "Quit", "q", NSApp, @selector(terminate:));
1179     [NSApp setAppleMenu: menu];
1180
1181     menu = newsubmenu([NSApp mainMenu], "Open");
1182     {
1183         int i;
1184
1185         for (i = 0; i < gamecount; i++) {
1186             id item =
1187                 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1188                             menu, gamelist[i]->name, "", controller,
1189                             @selector(newGame:));
1190             [item setPayload:(void *)gamelist[i]];
1191         }
1192     }
1193
1194     menu = newsubmenu([NSApp mainMenu], "Game");
1195     item = newitem(menu, "New", "n", NULL, @selector(newGame:));
1196     item = newitem(menu, "Restart", "r", NULL, @selector(restartGame:));
1197     item = newitem(menu, "Specific", "", NULL, @selector(specificGame:));
1198     [menu addItem:[NSMenuItem separatorItem]];
1199     item = newitem(menu, "Undo", "z", NULL, @selector(undoMove:));
1200     item = newitem(menu, "Redo", "S-z", NULL, @selector(redoMove:));
1201     [menu addItem:[NSMenuItem separatorItem]];
1202     item = newitem(menu, "Close", "w", NULL, @selector(performClose:));
1203
1204     menu = newsubmenu([NSApp mainMenu], "Type");
1205     typemenu = menu;
1206     item = newitem(menu, "Custom", "", NULL, @selector(customGameType:));
1207
1208     menu = newsubmenu([NSApp mainMenu], "Window");
1209     [NSApp setWindowsMenu: menu];
1210     item = newitem(menu, "Minimise Window", "m", NULL, @selector(performMiniaturize:));
1211
1212     [NSApp run];
1213     [pool release];
1214 }