chiark / gitweb /
I've found NSView's setNeedsDisplayInRect: method, which is
[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)clearTypeMenu
575 {
576     while ([typemenu numberOfItems] > 1)
577         [typemenu removeItemAtIndex:0];
578 }
579
580 - (void)becomeKeyWindow
581 {
582     int n;
583
584     [self clearTypeMenu];
585
586     [super becomeKeyWindow];
587
588     n = midend_num_presets(me);
589
590     if (n > 0) {
591         [typemenu insertItem:[NSMenuItem separatorItem] atIndex:0];
592         while (n--) {
593             char *name;
594             game_params *params;
595             DataMenuItem *item;
596
597             midend_fetch_preset(me, n, &name, &params);
598
599             item = [[[DataMenuItem alloc]
600                      initWithTitle:[NSString stringWithCString:name]
601                      action:NULL keyEquivalent:@""]
602                     autorelease];
603
604             [item setEnabled:YES];
605             [item setTarget:self];
606             [item setAction:@selector(presetGame:)];
607             [item setPayload:params];
608
609             [typemenu insertItem:item atIndex:0];
610         }
611     }
612 }
613
614 - (void)resignKeyWindow
615 {
616     [self clearTypeMenu];
617     [super resignKeyWindow];
618 }
619
620 - (void)close
621 {
622     [self clearTypeMenu];
623     [super close];
624 }
625
626 - (void)resizeForNewGameParams
627 {
628     NSSize size = {0,0};
629     int w, h;
630
631     midend_size(me, &w, &h);
632     size.width = w;
633     size.height = h;
634
635     if (status) {
636         NSRect frame = [status frame];
637         size.height += frame.size.height;
638         frame.size.width = size.width;
639         [status setFrame:frame];
640     }
641
642     NSDisableScreenUpdates();
643     [self setContentSize:size];
644     [self setupContentView];
645     NSEnableScreenUpdates();
646 }
647
648 - (void)presetGame:(id)sender
649 {
650     game_params *params = [sender getPayload];
651
652     midend_set_params(me, params);
653     midend_new_game(me);
654
655     [self resizeForNewGameParams];
656 }
657
658 - (void)startConfigureSheet:(int)which
659 {
660     NSButton *ok, *cancel;
661     int actw, acth, leftw, rightw, totalw, h, thish, y;
662     int k;
663     NSRect rect, tmprect;
664     const int SPACING = 16;
665     char *title;
666     config_item *i;
667     int cfg_controlsize;
668     NSTextField *tf;
669     NSButton *b;
670     NSPopUpButton *pb;
671
672     assert(sheet == NULL);
673
674     /*
675      * Every control we create here is going to have this size
676      * until we tell it to calculate a better one.
677      */
678     tmprect = NSMakeRect(0, 0, 100, 50);
679
680     /*
681      * Set up OK and Cancel buttons. (Actually, MacOS doesn't seem
682      * to be fond of generic OK and Cancel wording, so I'm going to
683      * rename them to something nicer.)
684      */
685     actw = acth = 0;
686
687     cancel = [[NSButton alloc] initWithFrame:tmprect];
688     [cancel setBezelStyle:NSRoundedBezelStyle];
689     [cancel setTitle:@"Abandon"];
690     [cancel setTarget:self];
691     [cancel setKeyEquivalent:@"\033"];
692     [cancel setAction:@selector(sheetCancelButton:)];
693     [cancel sizeToFit];
694     rect = [cancel frame];
695     if (actw < rect.size.width) actw = rect.size.width;
696     if (acth < rect.size.height) acth = rect.size.height;
697
698     ok = [[NSButton alloc] initWithFrame:tmprect];
699     [ok setBezelStyle:NSRoundedBezelStyle];
700     [ok setTitle:@"Accept"];
701     [ok setTarget:self];
702     [ok setKeyEquivalent:@"\r"];
703     [ok setAction:@selector(sheetOKButton:)];
704     [ok sizeToFit];
705     rect = [ok frame];
706     if (actw < rect.size.width) actw = rect.size.width;
707     if (acth < rect.size.height) acth = rect.size.height;
708
709     totalw = SPACING + 2 * actw;
710     h = 2 * SPACING + acth;
711
712     /*
713      * Now fetch the midend config data and go through it creating
714      * controls.
715      */
716     cfg = midend_get_config(me, which, &title);
717     sfree(title);                      /* FIXME: should we use this somehow? */
718     cfg_which = which;
719
720     cfg_ncontrols = cfg_controlsize = 0;
721     cfg_controls = NULL;
722     leftw = rightw = 0;
723     for (i = cfg; i->type != C_END; i++) {
724         if (cfg_controlsize < cfg_ncontrols + 5) {
725             cfg_controlsize = cfg_ncontrols + 32;
726             cfg_controls = sresize(cfg_controls, cfg_controlsize, NSView *);
727         }
728
729         thish = 0;
730
731         switch (i->type) {
732           case C_STRING:
733             /*
734              * Two NSTextFields, one being a label and the other
735              * being an edit box.
736              */
737
738             tf = [[NSTextField alloc] initWithFrame:tmprect];
739             [tf setEditable:NO];
740             [tf setSelectable:NO];
741             [tf setBordered:NO];
742             [tf setDrawsBackground:NO];
743             [[tf cell] setTitle:[NSString stringWithCString:i->name]];
744             [tf sizeToFit];
745             rect = [tf frame];
746             if (thish < rect.size.height + 1) thish = rect.size.height + 1;
747             if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
748             cfg_controls[cfg_ncontrols++] = tf;
749
750             tf = [[NSTextField alloc] initWithFrame:tmprect];
751             [tf setEditable:YES];
752             [tf setSelectable:YES];
753             [tf setBordered:YES];
754             [[tf cell] setTitle:[NSString stringWithCString:i->sval]];
755             [tf sizeToFit];
756             rect = [tf frame];
757             /*
758              * We impose a minimum and maximum width on editable
759              * NSTextFields. If we allow them to size themselves to
760              * the contents of the text within them, then they will
761              * look very silly if that text is only one or two
762              * characters, and equally silly if it's an absolutely
763              * enormous Rectangles or Pattern game ID!
764              */
765             if (rect.size.width < 75) rect.size.width = 75;
766             if (rect.size.width > 400) rect.size.width = 400;
767
768             if (thish < rect.size.height + 1) thish = rect.size.height + 1;
769             if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
770             cfg_controls[cfg_ncontrols++] = tf;
771             break;
772
773           case C_BOOLEAN:
774             /*
775              * A checkbox is an NSButton with a type of
776              * NSSwitchButton.
777              */
778             b = [[NSButton alloc] initWithFrame:tmprect];
779             [b setBezelStyle:NSRoundedBezelStyle];
780             [b setButtonType:NSSwitchButton];
781             [b setTitle:[NSString stringWithCString:i->name]];
782             [b sizeToFit];
783             [b setState:(i->ival ? NSOnState : NSOffState)];
784             rect = [b frame];
785             if (totalw < rect.size.width + 1) totalw = rect.size.width + 1;
786             if (thish < rect.size.height + 1) thish = rect.size.height + 1;
787             cfg_controls[cfg_ncontrols++] = b;
788             break;
789
790           case C_CHOICES:
791             /*
792              * A pop-up menu control is an NSPopUpButton, which
793              * takes an embedded NSMenu. We also need an
794              * NSTextField to act as a label.
795              */
796
797             tf = [[NSTextField alloc] initWithFrame:tmprect];
798             [tf setEditable:NO];
799             [tf setSelectable:NO];
800             [tf setBordered:NO];
801             [tf setDrawsBackground:NO];
802             [[tf cell] setTitle:[NSString stringWithCString:i->name]];
803             [tf sizeToFit];
804             rect = [tf frame];
805             if (thish < rect.size.height + 1) thish = rect.size.height + 1;
806             if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
807             cfg_controls[cfg_ncontrols++] = tf;
808
809             pb = [[NSPopUpButton alloc] initWithFrame:tmprect pullsDown:NO];
810             [pb setBezelStyle:NSRoundedBezelStyle];
811             {
812                 char c, *p;
813
814                 p = i->sval;
815                 c = *p++;
816                 while (*p) {
817                     char *q;
818
819                     q = p;
820                     while (*p && *p != c) p++;
821
822                     [pb addItemWithTitle:[NSString stringWithCString:q
823                                           length:p-q]];
824
825                     if (*p) p++;
826                 }
827             }
828             [pb selectItemAtIndex:i->ival];
829             [pb sizeToFit];
830
831             rect = [pb frame];
832             if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
833             if (thish < rect.size.height + 1) thish = rect.size.height + 1;
834             cfg_controls[cfg_ncontrols++] = pb;
835             break;
836         }
837
838         h += SPACING + thish;
839     }
840
841     if (totalw < leftw + SPACING + rightw)
842         totalw = leftw + SPACING + rightw;
843     if (totalw > leftw + SPACING + rightw) {
844         int excess = totalw - (leftw + SPACING + rightw);
845         int leftexcess = leftw * excess / (leftw + rightw);
846         int rightexcess = excess - leftexcess;
847         leftw += leftexcess;
848         rightw += rightexcess;
849     }
850
851     /*
852      * Now go through the list again, setting the final position
853      * for each control.
854      */
855     k = 0;
856     y = h;
857     for (i = cfg; i->type != C_END; i++) {
858         y -= SPACING;
859         thish = 0;
860         switch (i->type) {
861           case C_STRING:
862           case C_CHOICES:
863             /*
864              * These two are treated identically, since both expect
865              * a control on the left and another on the right.
866              */
867             rect = [cfg_controls[k] frame];
868             if (thish < rect.size.height + 1)
869                 thish = rect.size.height + 1;
870             rect = [cfg_controls[k+1] frame];
871             if (thish < rect.size.height + 1)
872                 thish = rect.size.height + 1;
873             rect = [cfg_controls[k] frame];
874             rect.origin.y = y - thish/2 - rect.size.height/2;
875             rect.origin.x = SPACING;
876             rect.size.width = leftw;
877             [cfg_controls[k] setFrame:rect];
878             rect = [cfg_controls[k+1] frame];
879             rect.origin.y = y - thish/2 - rect.size.height/2;
880             rect.origin.x = 2 * SPACING + leftw;
881             rect.size.width = rightw;
882             [cfg_controls[k+1] setFrame:rect];
883             k += 2;
884             break;
885
886           case C_BOOLEAN:
887             rect = [cfg_controls[k] frame];
888             if (thish < rect.size.height + 1)
889                 thish = rect.size.height + 1;
890             rect.origin.y = y - thish/2 - rect.size.height/2;
891             rect.origin.x = SPACING;
892             rect.size.width = totalw;
893             [cfg_controls[k] setFrame:rect];
894             k++;
895             break;
896         }
897         y -= thish;
898     }
899
900     assert(k == cfg_ncontrols);
901
902     [cancel setFrame:NSMakeRect(SPACING+totalw/4-actw/2, SPACING, actw, acth)];
903     [ok setFrame:NSMakeRect(SPACING+3*totalw/4-actw/2, SPACING, actw, acth)];
904
905     sheet = [[NSWindow alloc]
906              initWithContentRect:NSMakeRect(0,0,totalw + 2*SPACING,h)
907              styleMask:NSTitledWindowMask | NSClosableWindowMask
908              backing:NSBackingStoreBuffered
909              defer:YES];
910
911     [[sheet contentView] addSubview:cancel];
912     [[sheet contentView] addSubview:ok];
913
914     for (k = 0; k < cfg_ncontrols; k++)
915         [[sheet contentView] addSubview:cfg_controls[k]];
916
917     [NSApp beginSheet:sheet modalForWindow:self
918      modalDelegate:nil didEndSelector:nil contextInfo:nil];
919 }
920
921 - (void)specificGame:(id)sender
922 {
923     [self startConfigureSheet:CFG_SEED];
924 }
925
926 - (void)customGameType:(id)sender
927 {
928     [self startConfigureSheet:CFG_SETTINGS];
929 }
930
931 - (void)sheetEndWithStatus:(BOOL)update
932 {
933     assert(sheet != NULL);
934     [NSApp endSheet:sheet];
935     [sheet orderOut:self];
936     sheet = NULL;
937     if (update) {
938         int k;
939         config_item *i;
940         char *error;
941
942         k = 0;
943         for (i = cfg; i->type != C_END; i++) {
944             switch (i->type) {
945               case C_STRING:
946                 sfree(i->sval);
947                 i->sval = dupstr([[[(id)cfg_controls[k+1] cell]
948                                    title] cString]);
949                 k += 2;
950                 break;
951               case C_BOOLEAN:
952                 i->ival = [(id)cfg_controls[k] state] == NSOnState;
953                 k++;
954                 break;
955               case C_CHOICES:
956                 i->ival = [(id)cfg_controls[k+1] indexOfSelectedItem];
957                 k += 2;
958                 break;
959             }
960         }
961
962         error = midend_set_config(me, cfg_which, cfg);
963         if (error) {
964             NSAlert *alert = [[[NSAlert alloc] init] autorelease];
965             [alert addButtonWithTitle:@"Bah"];
966             [alert setInformativeText:[NSString stringWithCString:error]];
967             [alert beginSheetModalForWindow:self modalDelegate:nil
968              didEndSelector:nil contextInfo:nil];
969         } else {
970             midend_new_game(me);
971             [self resizeForNewGameParams];
972         }
973     }
974     sfree(cfg_controls);
975     cfg_controls = NULL;
976 }
977 - (void)sheetOKButton:(id)sender
978 {
979     [self sheetEndWithStatus:YES];
980 }
981 - (void)sheetCancelButton:(id)sender
982 {
983     [self sheetEndWithStatus:NO];
984 }
985
986 - (void)setStatusLine:(NSString *)text
987 {
988     [[status cell] setTitle:text];
989 }
990
991 @end
992
993 /*
994  * Drawing routines called by the midend.
995  */
996 void draw_polygon(frontend *fe, int *coords, int npoints,
997                   int fill, int colour)
998 {
999     NSBezierPath *path = [NSBezierPath bezierPath];
1000     int i;
1001
1002     [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1003
1004     assert(colour >= 0 && colour < fe->ncolours);
1005     [fe->colours[colour] set];
1006
1007     for (i = 0; i < npoints; i++) {
1008         NSPoint p = { coords[i*2] + 0.5, coords[i*2+1] + 0.5 };
1009         if (i == 0)
1010             [path moveToPoint:p];
1011         else
1012             [path lineToPoint:p];
1013     }
1014
1015     [path closePath];
1016
1017     if (fill)
1018         [path fill];
1019     else
1020         [path stroke];
1021 }
1022 void draw_line(frontend *fe, int x1, int y1, int x2, int y2, int colour)
1023 {
1024     NSBezierPath *path = [NSBezierPath bezierPath];
1025     NSPoint p1 = { x1 + 0.5, y1 + 0.5 }, p2 = { x2 + 0.5, y2 + 0.5 };
1026
1027     [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1028
1029     assert(colour >= 0 && colour < fe->ncolours);
1030     [fe->colours[colour] set];
1031
1032     [path moveToPoint:p1];
1033     [path lineToPoint:p2];
1034     [path stroke];
1035 }
1036 void draw_rect(frontend *fe, int x, int y, int w, int h, int colour)
1037 {
1038     NSRect r = { {x,y}, {w,h} };
1039
1040     [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1041
1042     assert(colour >= 0 && colour < fe->ncolours);
1043     [fe->colours[colour] set];
1044
1045     NSRectFill(r);
1046 }
1047 void draw_text(frontend *fe, int x, int y, int fonttype, int fontsize,
1048                int align, int colour, char *text)
1049 {
1050     NSString *string = [NSString stringWithCString:text];
1051     NSDictionary *attr;
1052     NSFont *font;
1053     NSSize size;
1054     NSPoint point;
1055
1056     [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1057
1058     assert(colour >= 0 && colour < fe->ncolours);
1059
1060     if (fonttype == FONT_FIXED)
1061         font = [NSFont userFixedPitchFontOfSize:fontsize];
1062     else
1063         font = [NSFont userFontOfSize:fontsize];
1064
1065     attr = [NSDictionary dictionaryWithObjectsAndKeys:
1066             fe->colours[colour], NSForegroundColorAttributeName,
1067             font, NSFontAttributeName, nil];
1068
1069     point.x = x;
1070     point.y = y;
1071
1072     size = [string sizeWithAttributes:attr];
1073     if (align & ALIGN_HRIGHT)
1074         point.x -= size.width;
1075     else if (align & ALIGN_HCENTRE)
1076         point.x -= size.width / 2;
1077     if (align & ALIGN_VCENTRE)
1078         point.y -= size.height / 2;
1079
1080     [string drawAtPoint:point withAttributes:attr];
1081 }
1082 void draw_update(frontend *fe, int x, int y, int w, int h)
1083 {
1084     [fe->view setNeedsDisplayInRect:NSMakeRect(x,y,w,h)];
1085 }
1086 void clip(frontend *fe, int x, int y, int w, int h)
1087 {
1088     NSRect r = { {x,y}, {w,h} };
1089
1090     if (!fe->clipped)
1091         [[NSGraphicsContext currentContext] saveGraphicsState];
1092     [NSBezierPath clipRect:r];
1093     fe->clipped = TRUE;
1094 }
1095 void unclip(frontend *fe)
1096 {
1097     if (fe->clipped)
1098         [[NSGraphicsContext currentContext] restoreGraphicsState];
1099     fe->clipped = FALSE;
1100 }
1101 void start_draw(frontend *fe)
1102 {
1103     [fe->image lockFocus];
1104     fe->clipped = FALSE;
1105 }
1106 void end_draw(frontend *fe)
1107 {
1108     [fe->image unlockFocus];
1109 }
1110
1111 void deactivate_timer(frontend *fe)
1112 {
1113     [fe->window deactivateTimer];
1114 }
1115 void activate_timer(frontend *fe)
1116 {
1117     [fe->window activateTimer];
1118 }
1119
1120 void status_bar(frontend *fe, char *text)
1121 {
1122     [fe->window setStatusLine:[NSString stringWithCString:text]];
1123 }
1124
1125 /* ----------------------------------------------------------------------
1126  * AppController: the object which receives the messages from all
1127  * menu selections that aren't standard OS X functions.
1128  */
1129 @interface AppController : NSObject
1130 {
1131 }
1132 - (void)newGame:(id)sender;
1133 @end
1134
1135 @implementation AppController
1136
1137 - (void)newGame:(id)sender
1138 {
1139     const game *g = [sender getPayload];
1140     id win;
1141
1142     win = [[GameWindow alloc] initWithGame:g];
1143     [win makeKeyAndOrderFront:self];
1144 }
1145
1146 - (NSMenu *)applicationDockMenu:(NSApplication *)sender
1147 {
1148     NSMenu *menu = newmenu("Dock Menu");
1149     {
1150         int i;
1151
1152         for (i = 0; i < gamecount; i++) {
1153             id item =
1154                 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1155                             menu, gamelist[i]->name, "", self,
1156                             @selector(newGame:));
1157             [item setPayload:(void *)gamelist[i]];
1158         }
1159     }
1160     return menu;
1161 }
1162
1163 @end
1164
1165 /* ----------------------------------------------------------------------
1166  * Main program. Constructs the menus and runs the application.
1167  */
1168 int main(int argc, char **argv)
1169 {
1170     NSAutoreleasePool *pool;
1171     NSMenu *menu;
1172     NSMenuItem *item;
1173     AppController *controller;
1174     NSImage *icon;
1175
1176     pool = [[NSAutoreleasePool alloc] init];
1177
1178     icon = [NSImage imageNamed:@"NSApplicationIcon"];
1179     [NSApplication sharedApplication];
1180     [NSApp setApplicationIconImage:icon];
1181
1182     controller = [[[AppController alloc] init] autorelease];
1183     [NSApp setDelegate:controller];
1184
1185     [NSApp setMainMenu: newmenu("Main Menu")];
1186
1187     menu = newsubmenu([NSApp mainMenu], "Apple Menu");
1188     [NSApp setServicesMenu:newsubmenu(menu, "Services")];
1189     [menu addItem:[NSMenuItem separatorItem]];
1190     item = newitem(menu, "Hide Puzzles", "h", NSApp, @selector(hide:));
1191     item = newitem(menu, "Hide Others", "o-h", NSApp, @selector(hideOtherApplications:));
1192     item = newitem(menu, "Show All", "", NSApp, @selector(unhideAllApplications:));
1193     [menu addItem:[NSMenuItem separatorItem]];
1194     item = newitem(menu, "Quit", "q", NSApp, @selector(terminate:));
1195     [NSApp setAppleMenu: menu];
1196
1197     menu = newsubmenu([NSApp mainMenu], "Open");
1198     {
1199         int i;
1200
1201         for (i = 0; i < gamecount; i++) {
1202             id item =
1203                 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1204                             menu, gamelist[i]->name, "", controller,
1205                             @selector(newGame:));
1206             [item setPayload:(void *)gamelist[i]];
1207         }
1208     }
1209
1210     menu = newsubmenu([NSApp mainMenu], "Game");
1211     item = newitem(menu, "New", "n", NULL, @selector(newGame:));
1212     item = newitem(menu, "Restart", "r", NULL, @selector(restartGame:));
1213     item = newitem(menu, "Specific", "", NULL, @selector(specificGame:));
1214     [menu addItem:[NSMenuItem separatorItem]];
1215     item = newitem(menu, "Undo", "z", NULL, @selector(undoMove:));
1216     item = newitem(menu, "Redo", "S-z", NULL, @selector(redoMove:));
1217     [menu addItem:[NSMenuItem separatorItem]];
1218     item = newitem(menu, "Close", "w", NULL, @selector(performClose:));
1219
1220     menu = newsubmenu([NSApp mainMenu], "Type");
1221     typemenu = menu;
1222     item = newitem(menu, "Custom", "", NULL, @selector(customGameType:));
1223
1224     menu = newsubmenu([NSApp mainMenu], "Window");
1225     [NSApp setWindowsMenu: menu];
1226     item = newitem(menu, "Minimise Window", "m", NULL, @selector(performMiniaturize:));
1227
1228     menu = newsubmenu([NSApp mainMenu], "Help");
1229     item = newitem(menu, "Puzzles Help", "?", NSApp, @selector(showHelp:));
1230
1231     [NSApp run];
1232     [pool release];
1233 }