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