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