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