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