chiark / gitweb /
Syntactic fixes by Zach Wily to make the OS X build work under 10.5.
[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  * Forward reference.
97  */
98 extern const struct drawing_api osx_drawing;
99
100 /* ----------------------------------------------------------------------
101  * Miscellaneous support routines that aren't part of any object or
102  * clearly defined subsystem.
103  */
104
105 void fatal(char *fmt, ...)
106 {
107     va_list ap;
108     char errorbuf[2048];
109     NSAlert *alert;
110
111     va_start(ap, fmt);
112     vsnprintf(errorbuf, lenof(errorbuf), fmt, ap);
113     va_end(ap);
114
115     alert = [NSAlert alloc];
116     /*
117      * We may have come here because we ran out of memory, in which
118      * case it's entirely likely that that alloc will fail, so we
119      * should have a fallback of some sort.
120      */
121     if (!alert) {
122         fprintf(stderr, "fatal error (and NSAlert failed): %s\n", errorbuf);
123     } else {
124         alert = [[alert init] autorelease];
125         [alert addButtonWithTitle:@"Oh dear"];
126         [alert setInformativeText:[NSString stringWithCString:errorbuf]];
127         [alert runModal];
128     }
129     exit(1);
130 }
131
132 void frontend_default_colour(frontend *fe, float *output)
133 {
134     /* FIXME: Is there a system default we can tap into for this? */
135     output[0] = output[1] = output[2] = 0.8F;
136 }
137
138 void get_random_seed(void **randseed, int *randseedsize)
139 {
140     time_t *tp = snew(time_t);
141     time(tp);
142     *randseed = (void *)tp;
143     *randseedsize = sizeof(time_t);
144 }
145
146 static void savefile_write(void *wctx, void *buf, int len)
147 {
148     FILE *fp = (FILE *)wctx;
149     fwrite(buf, 1, len, fp);
150 }
151
152 static int savefile_read(void *wctx, void *buf, int len)
153 {
154     FILE *fp = (FILE *)wctx;
155     int ret;
156
157     ret = fread(buf, 1, len, fp);
158     return (ret == len);
159 }
160
161 /*
162  * Since this front end does not support printing (yet), we need
163  * this stub to satisfy the reference in midend_print_puzzle().
164  */
165 void document_add_puzzle(document *doc, const game *game, game_params *par,
166                          game_state *st, game_state *st2)
167 {
168 }
169
170 /*
171  * setAppleMenu isn't listed in the NSApplication header, but an
172  * NSApp responds to it, so we're adding it here to silence
173  * warnings. (This was removed from the headers in 10.4, so we
174  * only need to include it for 10.4+.)
175  */
176 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1040
177 @interface NSApplication(NSAppleMenu)
178 - (void)setAppleMenu:(NSMenu *)menu;
179 @end
180 #endif
181
182 /* ----------------------------------------------------------------------
183  * Tiny extension to NSMenuItem which carries a payload of a `void
184  * *', allowing several menu items to invoke the same message but
185  * pass different data through it.
186  */
187 @interface DataMenuItem : NSMenuItem
188 {
189     void *payload;
190 }
191 - (void)setPayload:(void *)d;
192 - (void *)getPayload;
193 @end
194 @implementation DataMenuItem
195 - (void)setPayload:(void *)d
196 {
197     payload = d;
198 }
199 - (void *)getPayload
200 {
201     return payload;
202 }
203 @end
204
205 /* ----------------------------------------------------------------------
206  * Utility routines for constructing OS X menus.
207  */
208
209 NSMenu *newmenu(const char *title)
210 {
211     return [[[NSMenu allocWithZone:[NSMenu menuZone]]
212              initWithTitle:[NSString stringWithCString:title]]
213             autorelease];
214 }
215
216 NSMenu *newsubmenu(NSMenu *parent, const char *title)
217 {
218     NSMenuItem *item;
219     NSMenu *child;
220
221     item = [[[NSMenuItem allocWithZone:[NSMenu menuZone]]
222              initWithTitle:[NSString stringWithCString:title]
223              action:NULL
224              keyEquivalent:@""]
225             autorelease];
226     child = newmenu(title);
227     [item setEnabled:YES];
228     [item setSubmenu:child];
229     [parent addItem:item];
230     return child;
231 }
232
233 id initnewitem(NSMenuItem *item, NSMenu *parent, const char *title,
234                const char *key, id target, SEL action)
235 {
236     unsigned mask = NSCommandKeyMask;
237
238     if (key[strcspn(key, "-")]) {
239         while (*key && *key != '-') {
240             int c = tolower((unsigned char)*key);
241             if (c == 's') {
242                 mask |= NSShiftKeyMask;
243             } else if (c == 'o' || c == 'a') {
244                 mask |= NSAlternateKeyMask;
245             }
246             key++;
247         }
248         if (*key)
249             key++;
250     }
251
252     item = [[item initWithTitle:[NSString stringWithCString:title]
253              action:NULL
254              keyEquivalent:[NSString stringWithCString:key]]
255             autorelease];
256
257     if (*key)
258         [item setKeyEquivalentModifierMask: mask];
259
260     [item setEnabled:YES];
261     [item setTarget:target];
262     [item setAction:action];
263
264     [parent addItem:item];
265
266     return item;
267 }
268
269 NSMenuItem *newitem(NSMenu *parent, char *title, char *key,
270                     id target, SEL action)
271 {
272     return initnewitem([NSMenuItem allocWithZone:[NSMenu menuZone]],
273                        parent, title, key, target, action);
274 }
275
276 /* ----------------------------------------------------------------------
277  * About box.
278  */
279
280 @class AboutBox;
281
282 @interface AboutBox : NSWindow
283 {
284 }
285 - (id)init;
286 @end
287
288 @implementation AboutBox
289 - (id)init
290 {
291     NSRect totalrect;
292     NSView *views[16];
293     int nviews = 0;
294     NSImageView *iv;
295     NSTextField *tf;
296     NSFont *font1 = [NSFont systemFontOfSize:0];
297     NSFont *font2 = [NSFont boldSystemFontOfSize:[font1 pointSize] * 1.1];
298     const int border = 24;
299     int i;
300     double y;
301
302     /*
303      * Construct the controls that go in the About box.
304      */
305
306     iv = [[NSImageView alloc] initWithFrame:NSMakeRect(0,0,64,64)];
307     [iv setImage:[NSImage imageNamed:@"NSApplicationIcon"]];
308     views[nviews++] = iv;
309
310     tf = [[NSTextField alloc]
311           initWithFrame:NSMakeRect(0,0,400,1)];
312     [tf setEditable:NO];
313     [tf setSelectable:NO];
314     [tf setBordered:NO];
315     [tf setDrawsBackground:NO];
316     [tf setFont:font2];
317     [tf setStringValue:@"Simon Tatham's Portable Puzzle Collection"];
318     [tf sizeToFit];
319     views[nviews++] = tf;
320
321     tf = [[NSTextField alloc]
322           initWithFrame:NSMakeRect(0,0,400,1)];
323     [tf setEditable:NO];
324     [tf setSelectable:NO];
325     [tf setBordered:NO];
326     [tf setDrawsBackground:NO];
327     [tf setFont:font1];
328     [tf setStringValue:[NSString stringWithCString:ver]];
329     [tf sizeToFit];
330     views[nviews++] = tf;
331
332     /*
333      * Lay the controls out.
334      */
335     totalrect = NSMakeRect(0,0,0,0);
336     for (i = 0; i < nviews; i++) {
337         NSRect r = [views[i] frame];
338         if (totalrect.size.width < r.size.width)
339             totalrect.size.width = r.size.width;
340         totalrect.size.height += border + r.size.height;
341     }
342     totalrect.size.width += 2 * border;
343     totalrect.size.height += border;
344     y = totalrect.size.height;
345     for (i = 0; i < nviews; i++) {
346         NSRect r = [views[i] frame];
347         r.origin.x = (totalrect.size.width - r.size.width) / 2;
348         y -= border + r.size.height;
349         r.origin.y = y;
350         [views[i] setFrame:r];
351     }
352
353     self = [super initWithContentRect:totalrect
354             styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
355                        NSClosableWindowMask)
356             backing:NSBackingStoreBuffered
357             defer:YES];
358
359     for (i = 0; i < nviews; i++)
360         [[self contentView] addSubview:views[i]];
361
362     [self center];                     /* :-) */
363
364     return self;
365 }
366 @end
367
368 /* ----------------------------------------------------------------------
369  * The front end presented to midend.c.
370  * 
371  * This is mostly a subclass of NSWindow. The actual `frontend'
372  * structure passed to the midend contains a variety of pointers,
373  * including that window object but also including the image we
374  * draw on, an ImageView to display it in the window, and so on.
375  */
376
377 @class GameWindow;
378 @class MyImageView;
379
380 struct frontend {
381     GameWindow *window;
382     NSImage *image;
383     MyImageView *view;
384     NSColor **colours;
385     int ncolours;
386     int clipped;
387 };
388
389 @interface MyImageView : NSImageView
390 {
391     GameWindow *ourwin;
392 }
393 - (void)setWindow:(GameWindow *)win;
394 - (BOOL)isFlipped;
395 - (void)mouseEvent:(NSEvent *)ev button:(int)b;
396 - (void)mouseDown:(NSEvent *)ev;
397 - (void)mouseDragged:(NSEvent *)ev;
398 - (void)mouseUp:(NSEvent *)ev;
399 - (void)rightMouseDown:(NSEvent *)ev;
400 - (void)rightMouseDragged:(NSEvent *)ev;
401 - (void)rightMouseUp:(NSEvent *)ev;
402 - (void)otherMouseDown:(NSEvent *)ev;
403 - (void)otherMouseDragged:(NSEvent *)ev;
404 - (void)otherMouseUp:(NSEvent *)ev;
405 @end
406
407 @interface GameWindow : NSWindow
408 {
409     const game *ourgame;
410     midend *me;
411     struct frontend fe;
412     struct timeval last_time;
413     NSTimer *timer;
414     NSWindow *sheet;
415     config_item *cfg;
416     int cfg_which;
417     NSView **cfg_controls;
418     int cfg_ncontrols;
419     NSTextField *status;
420 }
421 - (id)initWithGame:(const game *)g;
422 - (void)dealloc;
423 - (void)processButton:(int)b x:(int)x y:(int)y;
424 - (void)keyDown:(NSEvent *)ev;
425 - (void)activateTimer;
426 - (void)deactivateTimer;
427 - (void)setStatusLine:(char *)text;
428 - (void)resizeForNewGameParams;
429 @end
430
431 @implementation MyImageView
432
433 - (void)setWindow:(GameWindow *)win
434 {
435     ourwin = win;
436 }
437
438 - (BOOL)isFlipped
439 {
440     return YES;
441 }
442
443 - (void)mouseEvent:(NSEvent *)ev button:(int)b
444 {
445     NSPoint point = [self convertPoint:[ev locationInWindow] fromView:nil];
446     [ourwin processButton:b x:point.x y:point.y];
447 }
448
449 - (void)mouseDown:(NSEvent *)ev
450 {
451     unsigned mod = [ev modifierFlags];
452     [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_BUTTON :
453                                 (mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
454                                 LEFT_BUTTON)];
455 }
456 - (void)mouseDragged:(NSEvent *)ev
457 {
458     unsigned mod = [ev modifierFlags];
459     [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_DRAG :
460                                 (mod & NSShiftKeyMask) ? MIDDLE_DRAG :
461                                 LEFT_DRAG)];
462 }
463 - (void)mouseUp:(NSEvent *)ev
464 {
465     unsigned mod = [ev modifierFlags];
466     [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_RELEASE :
467                                 (mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
468                                 LEFT_RELEASE)];
469 }
470 - (void)rightMouseDown:(NSEvent *)ev
471 {
472     unsigned mod = [ev modifierFlags];
473     [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
474                                 RIGHT_BUTTON)];
475 }
476 - (void)rightMouseDragged:(NSEvent *)ev
477 {
478     unsigned mod = [ev modifierFlags];
479     [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_DRAG :
480                                 RIGHT_DRAG)];
481 }
482 - (void)rightMouseUp:(NSEvent *)ev
483 {
484     unsigned mod = [ev modifierFlags];
485     [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
486                                 RIGHT_RELEASE)];
487 }
488 - (void)otherMouseDown:(NSEvent *)ev
489 {
490     [self mouseEvent:ev button:MIDDLE_BUTTON];
491 }
492 - (void)otherMouseDragged:(NSEvent *)ev
493 {
494     [self mouseEvent:ev button:MIDDLE_DRAG];
495 }
496 - (void)otherMouseUp:(NSEvent *)ev
497 {
498     [self mouseEvent:ev button:MIDDLE_RELEASE];
499 }
500 @end
501
502 @implementation GameWindow
503 - (void)setupContentView
504 {
505     NSRect frame;
506     int w, h;
507
508     if (status) {
509         frame = [status frame];
510         frame.origin.y = frame.size.height;
511     } else
512         frame.origin.y = 0;
513     frame.origin.x = 0;
514
515     w = h = INT_MAX;
516     midend_size(me, &w, &h, FALSE);
517     frame.size.width = w;
518     frame.size.height = h;
519
520     fe.image = [[NSImage alloc] initWithSize:frame.size];
521     [fe.image setFlipped:YES];
522     fe.view = [[MyImageView alloc] initWithFrame:frame];
523     [fe.view setImage:fe.image];
524     [fe.view setWindow:self];
525
526     midend_redraw(me);
527
528     [[self contentView] addSubview:fe.view];
529 }
530 - (id)initWithGame:(const game *)g
531 {
532     NSRect rect = { {0,0}, {0,0} }, rect2;
533     int w, h;
534
535     ourgame = g;
536
537     fe.window = self;
538
539     me = midend_new(&fe, ourgame, &osx_drawing, &fe);
540     /*
541      * If we ever need to open a fresh window using a provided game
542      * ID, I think the right thing is to move most of this method
543      * into a new initWithGame:gameID: method, and have
544      * initWithGame: simply call that one and pass it NULL.
545      */
546     midend_new_game(me);
547     w = h = INT_MAX;
548     midend_size(me, &w, &h, FALSE);
549     rect.size.width = w;
550     rect.size.height = h;
551
552     /*
553      * Create the status bar, which will just be an NSTextField.
554      */
555     if (midend_wants_statusbar(me)) {
556         status = [[NSTextField alloc] initWithFrame:NSMakeRect(0,0,100,50)];
557         [status setEditable:NO];
558         [status setSelectable:NO];
559         [status setBordered:YES];
560         [status setBezeled:YES];
561         [status setBezelStyle:NSTextFieldSquareBezel];
562         [status setDrawsBackground:YES];
563         [[status cell] setTitle:@""];
564         [status sizeToFit];
565         rect2 = [status frame];
566         rect.size.height += rect2.size.height;
567         rect2.size.width = rect.size.width;
568         rect2.origin.x = rect2.origin.y = 0;
569         [status setFrame:rect2];
570     } else
571         status = nil;
572
573     self = [super initWithContentRect:rect
574             styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
575                        NSClosableWindowMask)
576             backing:NSBackingStoreBuffered
577             defer:YES];
578     [self setTitle:[NSString stringWithCString:ourgame->name]];
579
580     {
581         float *colours;
582         int i, ncolours;
583
584         colours = midend_colours(me, &ncolours);
585         fe.ncolours = ncolours;
586         fe.colours = snewn(ncolours, NSColor *);
587
588         for (i = 0; i < ncolours; i++) {
589             fe.colours[i] = [[NSColor colorWithDeviceRed:colours[i*3]
590                               green:colours[i*3+1] blue:colours[i*3+2]
591                               alpha:1.0] retain];
592         }
593     }
594
595     [self setupContentView];
596     if (status)
597         [[self contentView] addSubview:status];
598     [self setIgnoresMouseEvents:NO];
599
600     [self center];                     /* :-) */
601
602     return self;
603 }
604
605 - (void)dealloc
606 {
607     int i;
608     for (i = 0; i < fe.ncolours; i++) {
609         [fe.colours[i] release];
610     }
611     sfree(fe.colours);
612     midend_free(me);
613     [super dealloc];
614 }
615
616 - (void)processButton:(int)b x:(int)x y:(int)y
617 {
618     if (!midend_process_key(me, x, y, b))
619         [self close];
620 }
621
622 - (void)keyDown:(NSEvent *)ev
623 {
624     NSString *s = [ev characters];
625     int i, n = [s length];
626
627     for (i = 0; i < n; i++) {
628         int c = [s characterAtIndex:i];
629
630         /*
631          * ASCII gets passed straight to midend_process_key.
632          * Anything above that has to be translated to our own
633          * function key codes.
634          */
635         if (c >= 0x80) {
636             int mods = FALSE;
637             switch (c) {
638               case NSUpArrowFunctionKey:
639                 c = CURSOR_UP;
640                 mods = TRUE;
641                 break;
642               case NSDownArrowFunctionKey:
643                 c = CURSOR_DOWN;
644                 mods = TRUE;
645                 break;
646               case NSLeftArrowFunctionKey:
647                 c = CURSOR_LEFT;
648                 mods = TRUE;
649                 break;
650               case NSRightArrowFunctionKey:
651                 c = CURSOR_RIGHT;
652                 mods = TRUE;
653                 break;
654               default:
655                 continue;
656             }
657
658             if (mods) {
659                 if ([ev modifierFlags] & NSShiftKeyMask)
660                     c |= MOD_SHFT;
661                 if ([ev modifierFlags] & NSControlKeyMask)
662                     c |= MOD_CTRL;
663             }
664         }
665
666         if (c >= '0' && c <= '9' && ([ev modifierFlags] & NSNumericPadKeyMask))
667             c |= MOD_NUM_KEYPAD;
668
669         [self processButton:c x:-1 y:-1];
670     }
671 }
672
673 - (void)activateTimer
674 {
675     if (timer != nil)
676         return;
677
678     timer = [NSTimer scheduledTimerWithTimeInterval:0.02
679              target:self selector:@selector(timerTick:)
680              userInfo:nil repeats:YES];
681     gettimeofday(&last_time, NULL);
682 }
683
684 - (void)deactivateTimer
685 {
686     if (timer == nil)
687         return;
688
689     [timer invalidate];
690     timer = nil;
691 }
692
693 - (void)timerTick:(id)sender
694 {
695     struct timeval now;
696     float elapsed;
697     gettimeofday(&now, NULL);
698     elapsed = ((now.tv_usec - last_time.tv_usec) * 0.000001F +
699                (now.tv_sec - last_time.tv_sec));
700     midend_timer(me, elapsed);
701     last_time = now;
702 }
703
704 - (void)showError:(char *)message
705 {
706     NSAlert *alert;
707
708     alert = [[[NSAlert alloc] init] autorelease];
709     [alert addButtonWithTitle:@"Bah"];
710     [alert setInformativeText:[NSString stringWithCString:message]];
711     [alert beginSheetModalForWindow:self modalDelegate:nil
712      didEndSelector:nil contextInfo:nil];
713 }
714
715 - (void)newGame:(id)sender
716 {
717     [self processButton:'n' x:-1 y:-1];
718 }
719 - (void)restartGame:(id)sender
720 {
721     midend_restart_game(me);
722 }
723 - (void)saveGame:(id)sender
724 {
725     NSSavePanel *sp = [NSSavePanel savePanel];
726
727     if ([sp runModal] == NSFileHandlingPanelOKButton) {
728        const char *name = [[sp filename] UTF8String];
729
730         FILE *fp = fopen(name, "w");
731
732         if (!fp) {
733             [self showError:"Unable to open save file"];
734             return;
735         }
736
737         midend_serialise(me, savefile_write, fp);
738
739         fclose(fp);
740     }
741 }
742 - (void)loadSavedGame:(id)sender
743 {
744     NSOpenPanel *op = [NSOpenPanel openPanel];
745
746     [op setAllowsMultipleSelection:NO];
747
748     if ([op runModalForTypes:nil] == NSOKButton) {
749         const char *name = [[[op filenames] objectAtIndex:0] cString];
750         char *err;
751
752         FILE *fp = fopen(name, "r");
753
754         if (!fp) {
755             [self showError:"Unable to open saved game file"];
756             return;
757         }
758
759         err = midend_deserialise(me, savefile_read, fp);
760
761         fclose(fp);
762
763         if (err) {
764             [self showError:err];
765             return;
766         }
767
768         [self resizeForNewGameParams];
769     }
770 }
771 - (void)undoMove:(id)sender
772 {
773     [self processButton:'u' x:-1 y:-1];
774 }
775 - (void)redoMove:(id)sender
776 {
777     [self processButton:'r'&0x1F x:-1 y:-1];
778 }
779
780 - (void)copy:(id)sender
781 {
782     char *text;
783
784     if ((text = midend_text_format(me)) != NULL) {
785         NSPasteboard *pb = [NSPasteboard generalPasteboard];
786         NSArray *a = [NSArray arrayWithObject:NSStringPboardType];
787         [pb declareTypes:a owner:nil];
788         [pb setString:[NSString stringWithCString:text]
789          forType:NSStringPboardType];
790     } else
791         NSBeep();
792 }
793
794 - (void)solveGame:(id)sender
795 {
796     char *msg;
797
798     msg = midend_solve(me);
799
800     if (msg)
801         [self showError:msg];
802 }
803
804 - (BOOL)validateMenuItem:(NSMenuItem *)item
805 {
806     if ([item action] == @selector(copy:))
807         return (ourgame->can_format_as_text ? YES : NO);
808     else if ([item action] == @selector(solveGame:))
809         return (ourgame->can_solve ? YES : NO);
810     else
811         return [super validateMenuItem:item];
812 }
813
814 - (void)clearTypeMenu
815 {
816     while ([typemenu numberOfItems] > 1)
817         [typemenu removeItemAtIndex:0];
818 }
819
820 - (void)becomeKeyWindow
821 {
822     int n;
823
824     [self clearTypeMenu];
825
826     [super becomeKeyWindow];
827
828     n = midend_num_presets(me);
829
830     if (n > 0) {
831         [typemenu insertItem:[NSMenuItem separatorItem] atIndex:0];
832         while (n--) {
833             char *name;
834             game_params *params;
835             DataMenuItem *item;
836
837             midend_fetch_preset(me, n, &name, &params);
838
839             item = [[[DataMenuItem alloc]
840                      initWithTitle:[NSString stringWithCString:name]
841                      action:NULL keyEquivalent:@""]
842                     autorelease];
843
844             [item setEnabled:YES];
845             [item setTarget:self];
846             [item setAction:@selector(presetGame:)];
847             [item setPayload:params];
848
849             [typemenu insertItem:item atIndex:0];
850         }
851     }
852 }
853
854 - (void)resignKeyWindow
855 {
856     [self clearTypeMenu];
857     [super resignKeyWindow];
858 }
859
860 - (void)close
861 {
862     [self clearTypeMenu];
863     [super close];
864 }
865
866 - (void)resizeForNewGameParams
867 {
868     NSSize size = {0,0};
869     int w, h;
870
871     w = h = INT_MAX;
872     midend_size(me, &w, &h, FALSE);
873     size.width = w;
874     size.height = h;
875
876     if (status) {
877         NSRect frame = [status frame];
878         size.height += frame.size.height;
879         frame.size.width = size.width;
880         [status setFrame:frame];
881     }
882
883     NSDisableScreenUpdates();
884     [self setContentSize:size];
885     [self setupContentView];
886     NSEnableScreenUpdates();
887 }
888
889 - (void)presetGame:(id)sender
890 {
891     game_params *params = [sender getPayload];
892
893     midend_set_params(me, params);
894     midend_new_game(me);
895
896     [self resizeForNewGameParams];
897 }
898
899 - (void)startConfigureSheet:(int)which
900 {
901     NSButton *ok, *cancel;
902     int actw, acth, leftw, rightw, totalw, h, thish, y;
903     int k;
904     NSRect rect, tmprect;
905     const int SPACING = 16;
906     char *title;
907     config_item *i;
908     int cfg_controlsize;
909     NSTextField *tf;
910     NSButton *b;
911     NSPopUpButton *pb;
912
913     assert(sheet == NULL);
914
915     /*
916      * Every control we create here is going to have this size
917      * until we tell it to calculate a better one.
918      */
919     tmprect = NSMakeRect(0, 0, 100, 50);
920
921     /*
922      * Set up OK and Cancel buttons. (Actually, MacOS doesn't seem
923      * to be fond of generic OK and Cancel wording, so I'm going to
924      * rename them to something nicer.)
925      */
926     actw = acth = 0;
927
928     cancel = [[NSButton alloc] initWithFrame:tmprect];
929     [cancel setBezelStyle:NSRoundedBezelStyle];
930     [cancel setTitle:@"Abandon"];
931     [cancel setTarget:self];
932     [cancel setKeyEquivalent:@"\033"];
933     [cancel setAction:@selector(sheetCancelButton:)];
934     [cancel sizeToFit];
935     rect = [cancel frame];
936     if (actw < rect.size.width) actw = rect.size.width;
937     if (acth < rect.size.height) acth = rect.size.height;
938
939     ok = [[NSButton alloc] initWithFrame:tmprect];
940     [ok setBezelStyle:NSRoundedBezelStyle];
941     [ok setTitle:@"Accept"];
942     [ok setTarget:self];
943     [ok setKeyEquivalent:@"\r"];
944     [ok setAction:@selector(sheetOKButton:)];
945     [ok sizeToFit];
946     rect = [ok frame];
947     if (actw < rect.size.width) actw = rect.size.width;
948     if (acth < rect.size.height) acth = rect.size.height;
949
950     totalw = SPACING + 2 * actw;
951     h = 2 * SPACING + acth;
952
953     /*
954      * Now fetch the midend config data and go through it creating
955      * controls.
956      */
957     cfg = midend_get_config(me, which, &title);
958     sfree(title);                      /* FIXME: should we use this somehow? */
959     cfg_which = which;
960
961     cfg_ncontrols = cfg_controlsize = 0;
962     cfg_controls = NULL;
963     leftw = rightw = 0;
964     for (i = cfg; i->type != C_END; i++) {
965         if (cfg_controlsize < cfg_ncontrols + 5) {
966             cfg_controlsize = cfg_ncontrols + 32;
967             cfg_controls = sresize(cfg_controls, cfg_controlsize, NSView *);
968         }
969
970         thish = 0;
971
972         switch (i->type) {
973           case C_STRING:
974             /*
975              * Two NSTextFields, one being a label and the other
976              * being an edit box.
977              */
978
979             tf = [[NSTextField alloc] initWithFrame:tmprect];
980             [tf setEditable:NO];
981             [tf setSelectable:NO];
982             [tf setBordered:NO];
983             [tf setDrawsBackground:NO];
984             [[tf cell] setTitle:[NSString stringWithCString:i->name]];
985             [tf sizeToFit];
986             rect = [tf frame];
987             if (thish < rect.size.height + 1) thish = rect.size.height + 1;
988             if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
989             cfg_controls[cfg_ncontrols++] = tf;
990
991             tf = [[NSTextField alloc] initWithFrame:tmprect];
992             [tf setEditable:YES];
993             [tf setSelectable:YES];
994             [tf setBordered:YES];
995             [[tf cell] setTitle:[NSString stringWithCString:i->sval]];
996             [tf sizeToFit];
997             rect = [tf frame];
998             /*
999              * We impose a minimum and maximum width on editable
1000              * NSTextFields. If we allow them to size themselves to
1001              * the contents of the text within them, then they will
1002              * look very silly if that text is only one or two
1003              * characters, and equally silly if it's an absolutely
1004              * enormous Rectangles or Pattern game ID!
1005              */
1006             if (rect.size.width < 75) rect.size.width = 75;
1007             if (rect.size.width > 400) rect.size.width = 400;
1008
1009             if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1010             if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
1011             cfg_controls[cfg_ncontrols++] = tf;
1012             break;
1013
1014           case C_BOOLEAN:
1015             /*
1016              * A checkbox is an NSButton with a type of
1017              * NSSwitchButton.
1018              */
1019             b = [[NSButton alloc] initWithFrame:tmprect];
1020             [b setBezelStyle:NSRoundedBezelStyle];
1021             [b setButtonType:NSSwitchButton];
1022             [b setTitle:[NSString stringWithCString:i->name]];
1023             [b sizeToFit];
1024             [b setState:(i->ival ? NSOnState : NSOffState)];
1025             rect = [b frame];
1026             if (totalw < rect.size.width + 1) totalw = rect.size.width + 1;
1027             if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1028             cfg_controls[cfg_ncontrols++] = b;
1029             break;
1030
1031           case C_CHOICES:
1032             /*
1033              * A pop-up menu control is an NSPopUpButton, which
1034              * takes an embedded NSMenu. We also need an
1035              * NSTextField to act as a label.
1036              */
1037
1038             tf = [[NSTextField alloc] initWithFrame:tmprect];
1039             [tf setEditable:NO];
1040             [tf setSelectable:NO];
1041             [tf setBordered:NO];
1042             [tf setDrawsBackground:NO];
1043             [[tf cell] setTitle:[NSString stringWithCString:i->name]];
1044             [tf sizeToFit];
1045             rect = [tf frame];
1046             if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1047             if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
1048             cfg_controls[cfg_ncontrols++] = tf;
1049
1050             pb = [[NSPopUpButton alloc] initWithFrame:tmprect pullsDown:NO];
1051             [pb setBezelStyle:NSRoundedBezelStyle];
1052             {
1053                 char c, *p;
1054
1055                 p = i->sval;
1056                 c = *p++;
1057                 while (*p) {
1058                     char *q;
1059
1060                     q = p;
1061                     while (*p && *p != c) p++;
1062
1063                     [pb addItemWithTitle:[NSString stringWithCString:q
1064                                           length:p-q]];
1065
1066                     if (*p) p++;
1067                 }
1068             }
1069             [pb selectItemAtIndex:i->ival];
1070             [pb sizeToFit];
1071
1072             rect = [pb frame];
1073             if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
1074             if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1075             cfg_controls[cfg_ncontrols++] = pb;
1076             break;
1077         }
1078
1079         h += SPACING + thish;
1080     }
1081
1082     if (totalw < leftw + SPACING + rightw)
1083         totalw = leftw + SPACING + rightw;
1084     if (totalw > leftw + SPACING + rightw) {
1085         int excess = totalw - (leftw + SPACING + rightw);
1086         int leftexcess = leftw * excess / (leftw + rightw);
1087         int rightexcess = excess - leftexcess;
1088         leftw += leftexcess;
1089         rightw += rightexcess;
1090     }
1091
1092     /*
1093      * Now go through the list again, setting the final position
1094      * for each control.
1095      */
1096     k = 0;
1097     y = h;
1098     for (i = cfg; i->type != C_END; i++) {
1099         y -= SPACING;
1100         thish = 0;
1101         switch (i->type) {
1102           case C_STRING:
1103           case C_CHOICES:
1104             /*
1105              * These two are treated identically, since both expect
1106              * a control on the left and another on the right.
1107              */
1108             rect = [cfg_controls[k] frame];
1109             if (thish < rect.size.height + 1)
1110                 thish = rect.size.height + 1;
1111             rect = [cfg_controls[k+1] frame];
1112             if (thish < rect.size.height + 1)
1113                 thish = rect.size.height + 1;
1114             rect = [cfg_controls[k] frame];
1115             rect.origin.y = y - thish/2 - rect.size.height/2;
1116             rect.origin.x = SPACING;
1117             rect.size.width = leftw;
1118             [cfg_controls[k] setFrame:rect];
1119             rect = [cfg_controls[k+1] frame];
1120             rect.origin.y = y - thish/2 - rect.size.height/2;
1121             rect.origin.x = 2 * SPACING + leftw;
1122             rect.size.width = rightw;
1123             [cfg_controls[k+1] setFrame:rect];
1124             k += 2;
1125             break;
1126
1127           case C_BOOLEAN:
1128             rect = [cfg_controls[k] frame];
1129             if (thish < rect.size.height + 1)
1130                 thish = rect.size.height + 1;
1131             rect.origin.y = y - thish/2 - rect.size.height/2;
1132             rect.origin.x = SPACING;
1133             rect.size.width = totalw;
1134             [cfg_controls[k] setFrame:rect];
1135             k++;
1136             break;
1137         }
1138         y -= thish;
1139     }
1140
1141     assert(k == cfg_ncontrols);
1142
1143     [cancel setFrame:NSMakeRect(SPACING+totalw/4-actw/2, SPACING, actw, acth)];
1144     [ok setFrame:NSMakeRect(SPACING+3*totalw/4-actw/2, SPACING, actw, acth)];
1145
1146     sheet = [[NSWindow alloc]
1147              initWithContentRect:NSMakeRect(0,0,totalw + 2*SPACING,h)
1148              styleMask:NSTitledWindowMask | NSClosableWindowMask
1149              backing:NSBackingStoreBuffered
1150              defer:YES];
1151
1152     [[sheet contentView] addSubview:cancel];
1153     [[sheet contentView] addSubview:ok];
1154
1155     for (k = 0; k < cfg_ncontrols; k++)
1156         [[sheet contentView] addSubview:cfg_controls[k]];
1157
1158     [NSApp beginSheet:sheet modalForWindow:self
1159      modalDelegate:nil didEndSelector:nil contextInfo:nil];
1160 }
1161
1162 - (void)specificGame:(id)sender
1163 {
1164     [self startConfigureSheet:CFG_DESC];
1165 }
1166
1167 - (void)specificRandomGame:(id)sender
1168 {
1169     [self startConfigureSheet:CFG_SEED];
1170 }
1171
1172 - (void)customGameType:(id)sender
1173 {
1174     [self startConfigureSheet:CFG_SETTINGS];
1175 }
1176
1177 - (void)sheetEndWithStatus:(BOOL)update
1178 {
1179     assert(sheet != NULL);
1180     [NSApp endSheet:sheet];
1181     [sheet orderOut:self];
1182     sheet = NULL;
1183     if (update) {
1184         int k;
1185         config_item *i;
1186         char *error;
1187
1188         k = 0;
1189         for (i = cfg; i->type != C_END; i++) {
1190             switch (i->type) {
1191               case C_STRING:
1192                 sfree(i->sval);
1193                 i->sval = dupstr([[[(id)cfg_controls[k+1] cell]
1194                                   title] UTF8String]);
1195                 k += 2;
1196                 break;
1197               case C_BOOLEAN:
1198                 i->ival = [(id)cfg_controls[k] state] == NSOnState;
1199                 k++;
1200                 break;
1201               case C_CHOICES:
1202                 i->ival = [(id)cfg_controls[k+1] indexOfSelectedItem];
1203                 k += 2;
1204                 break;
1205             }
1206         }
1207
1208         error = midend_set_config(me, cfg_which, cfg);
1209         if (error) {
1210             NSAlert *alert = [[[NSAlert alloc] init] autorelease];
1211             [alert addButtonWithTitle:@"Bah"];
1212             [alert setInformativeText:[NSString stringWithCString:error]];
1213             [alert beginSheetModalForWindow:self modalDelegate:nil
1214              didEndSelector:nil contextInfo:nil];
1215         } else {
1216             midend_new_game(me);
1217             [self resizeForNewGameParams];
1218         }
1219     }
1220     sfree(cfg_controls);
1221     cfg_controls = NULL;
1222 }
1223 - (void)sheetOKButton:(id)sender
1224 {
1225     [self sheetEndWithStatus:YES];
1226 }
1227 - (void)sheetCancelButton:(id)sender
1228 {
1229     [self sheetEndWithStatus:NO];
1230 }
1231
1232 - (void)setStatusLine:(char *)text
1233 {
1234     [[status cell] setTitle:[NSString stringWithCString:text]];
1235 }
1236
1237 @end
1238
1239 /*
1240  * Drawing routines called by the midend.
1241  */
1242 static void osx_draw_polygon(void *handle, int *coords, int npoints,
1243                              int fillcolour, int outlinecolour)
1244 {
1245     frontend *fe = (frontend *)handle;
1246     NSBezierPath *path = [NSBezierPath bezierPath];
1247     int i;
1248
1249     [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1250
1251     for (i = 0; i < npoints; i++) {
1252         NSPoint p = { coords[i*2] + 0.5, coords[i*2+1] + 0.5 };
1253         if (i == 0)
1254             [path moveToPoint:p];
1255         else
1256             [path lineToPoint:p];
1257     }
1258
1259     [path closePath];
1260
1261     if (fillcolour >= 0) {
1262         assert(fillcolour >= 0 && fillcolour < fe->ncolours);
1263         [fe->colours[fillcolour] set];
1264         [path fill];
1265     }
1266
1267     assert(outlinecolour >= 0 && outlinecolour < fe->ncolours);
1268     [fe->colours[outlinecolour] set];
1269     [path stroke];
1270 }
1271 static void osx_draw_circle(void *handle, int cx, int cy, int radius,
1272                             int fillcolour, int outlinecolour)
1273 {
1274     frontend *fe = (frontend *)handle;
1275     NSBezierPath *path = [NSBezierPath bezierPath];
1276
1277     [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1278
1279     [path appendBezierPathWithArcWithCenter:NSMakePoint(cx + 0.5, cy + 0.5)
1280         radius:radius startAngle:0.0 endAngle:360.0];
1281
1282     [path closePath];
1283
1284     if (fillcolour >= 0) {
1285         assert(fillcolour >= 0 && fillcolour < fe->ncolours);
1286         [fe->colours[fillcolour] set];
1287         [path fill];
1288     }
1289
1290     assert(outlinecolour >= 0 && outlinecolour < fe->ncolours);
1291     [fe->colours[outlinecolour] set];
1292     [path stroke];
1293 }
1294 static void osx_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
1295 {
1296     frontend *fe = (frontend *)handle;
1297     NSBezierPath *path = [NSBezierPath bezierPath];
1298     NSPoint p1 = { x1 + 0.5, y1 + 0.5 }, p2 = { x2 + 0.5, y2 + 0.5 };
1299
1300     [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1301
1302     assert(colour >= 0 && colour < fe->ncolours);
1303     [fe->colours[colour] set];
1304
1305     [path moveToPoint:p1];
1306     [path lineToPoint:p2];
1307     [path stroke];
1308 }
1309 static void osx_draw_rect(void *handle, int x, int y, int w, int h, int colour)
1310 {
1311     frontend *fe = (frontend *)handle;
1312     NSRect r = { {x,y}, {w,h} };
1313     
1314     [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1315
1316     assert(colour >= 0 && colour < fe->ncolours);
1317     [fe->colours[colour] set];
1318
1319     NSRectFill(r);
1320 }
1321 static void osx_draw_text(void *handle, int x, int y, int fonttype,
1322                           int fontsize, int align, int colour, char *text)
1323 {
1324     frontend *fe = (frontend *)handle;
1325     NSString *string = [NSString stringWithCString:text];
1326     NSDictionary *attr;
1327     NSFont *font;
1328     NSSize size;
1329     NSPoint point;
1330
1331     [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1332
1333     assert(colour >= 0 && colour < fe->ncolours);
1334
1335     if (fonttype == FONT_FIXED)
1336         font = [NSFont userFixedPitchFontOfSize:fontsize];
1337     else
1338         font = [NSFont userFontOfSize:fontsize];
1339
1340     attr = [NSDictionary dictionaryWithObjectsAndKeys:
1341             fe->colours[colour], NSForegroundColorAttributeName,
1342             font, NSFontAttributeName, nil];
1343
1344     point.x = x;
1345     point.y = y;
1346
1347     size = [string sizeWithAttributes:attr];
1348     if (align & ALIGN_HRIGHT)
1349         point.x -= size.width;
1350     else if (align & ALIGN_HCENTRE)
1351         point.x -= size.width / 2;
1352     if (align & ALIGN_VCENTRE)
1353         point.y -= size.height / 2;
1354     else
1355         point.y -= size.height;
1356
1357     [string drawAtPoint:point withAttributes:attr];
1358 }
1359 struct blitter {
1360     int w, h;
1361     int x, y;
1362     NSImage *img;
1363 };
1364 static blitter *osx_blitter_new(void *handle, int w, int h)
1365 {
1366     blitter *bl = snew(blitter);
1367     bl->x = bl->y = -1;
1368     bl->w = w;
1369     bl->h = h;
1370     bl->img = [[NSImage alloc] initWithSize:NSMakeSize(w, h)];
1371     [bl->img setFlipped:YES];
1372     return bl;
1373 }
1374 static void osx_blitter_free(void *handle, blitter *bl)
1375 {
1376     [bl->img release];
1377     sfree(bl);
1378 }
1379 static void osx_blitter_save(void *handle, blitter *bl, int x, int y)
1380 {
1381     frontend *fe = (frontend *)handle;
1382     [fe->image unlockFocus];
1383     [bl->img lockFocus];
1384     [fe->image drawInRect:NSMakeRect(0, 0, bl->w, bl->h)
1385         fromRect:NSMakeRect(x, y, bl->w, bl->h)
1386         operation:NSCompositeCopy fraction:1.0];
1387     [bl->img unlockFocus];
1388     [fe->image lockFocus];
1389     bl->x = x;
1390     bl->y = y;
1391 }
1392 static void osx_blitter_load(void *handle, blitter *bl, int x, int y)
1393 {
1394     /* frontend *fe = (frontend *)handle; */
1395     if (x == BLITTER_FROMSAVED && y == BLITTER_FROMSAVED) {
1396         x = bl->x;
1397         y = bl->y;
1398     }
1399     [bl->img drawInRect:NSMakeRect(x, y, bl->w, bl->h)
1400         fromRect:NSMakeRect(0, 0, bl->w, bl->h)
1401         operation:NSCompositeCopy fraction:1.0];
1402 }
1403 static void osx_draw_update(void *handle, int x, int y, int w, int h)
1404 {
1405     frontend *fe = (frontend *)handle;
1406     [fe->view setNeedsDisplayInRect:NSMakeRect(x,y,w,h)];
1407 }
1408 static void osx_clip(void *handle, int x, int y, int w, int h)
1409 {
1410     frontend *fe = (frontend *)handle;
1411     NSRect r = { {x,y}, {w,h} };
1412     
1413     if (!fe->clipped)
1414         [[NSGraphicsContext currentContext] saveGraphicsState];
1415     [NSBezierPath clipRect:r];
1416     fe->clipped = TRUE;
1417 }
1418 static void osx_unclip(void *handle)
1419 {
1420     frontend *fe = (frontend *)handle;
1421     if (fe->clipped)
1422         [[NSGraphicsContext currentContext] restoreGraphicsState];
1423     fe->clipped = FALSE;
1424 }
1425 static void osx_start_draw(void *handle)
1426 {
1427     frontend *fe = (frontend *)handle;
1428     [fe->image lockFocus];
1429     fe->clipped = FALSE;
1430 }
1431 static void osx_end_draw(void *handle)
1432 {
1433     frontend *fe = (frontend *)handle;
1434     [fe->image unlockFocus];
1435 }
1436 static void osx_status_bar(void *handle, char *text)
1437 {
1438     frontend *fe = (frontend *)handle;
1439     [fe->window setStatusLine:text];
1440 }
1441
1442 const struct drawing_api osx_drawing = {
1443     osx_draw_text,
1444     osx_draw_rect,
1445     osx_draw_line,
1446     osx_draw_polygon,
1447     osx_draw_circle,
1448     osx_draw_update,
1449     osx_clip,
1450     osx_unclip,
1451     osx_start_draw,
1452     osx_end_draw,
1453     osx_status_bar,
1454     osx_blitter_new,
1455     osx_blitter_free,
1456     osx_blitter_save,
1457     osx_blitter_load,
1458     NULL, NULL, NULL, NULL, NULL, NULL, /* {begin,end}_{doc,page,puzzle} */
1459     NULL,                              /* line_width */
1460 };
1461
1462 void deactivate_timer(frontend *fe)
1463 {
1464     [fe->window deactivateTimer];
1465 }
1466 void activate_timer(frontend *fe)
1467 {
1468     [fe->window activateTimer];
1469 }
1470
1471 /* ----------------------------------------------------------------------
1472  * AppController: the object which receives the messages from all
1473  * menu selections that aren't standard OS X functions.
1474  */
1475 @interface AppController : NSObject
1476 {
1477 }
1478 - (void)newGameWindow:(id)sender;
1479 - (void)about:(id)sender;
1480 @end
1481
1482 @implementation AppController
1483
1484 - (void)newGameWindow:(id)sender
1485 {
1486     const game *g = [sender getPayload];
1487     id win;
1488
1489     win = [[GameWindow alloc] initWithGame:g];
1490     [win makeKeyAndOrderFront:self];
1491 }
1492
1493 - (void)about:(id)sender
1494 {
1495     id win;
1496
1497     win = [[AboutBox alloc] init];
1498     [win makeKeyAndOrderFront:self];    
1499 }
1500
1501 - (NSMenu *)applicationDockMenu:(NSApplication *)sender
1502 {
1503     NSMenu *menu = newmenu("Dock Menu");
1504     {
1505         int i;
1506
1507         for (i = 0; i < gamecount; i++) {
1508             id item =
1509                 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1510                             menu, gamelist[i]->name, "", self,
1511                             @selector(newGameWindow:));
1512             [item setPayload:(void *)gamelist[i]];
1513         }
1514     }
1515     return menu;
1516 }
1517
1518 @end
1519
1520 /* ----------------------------------------------------------------------
1521  * Main program. Constructs the menus and runs the application.
1522  */
1523 int main(int argc, char **argv)
1524 {
1525     NSAutoreleasePool *pool;
1526     NSMenu *menu;
1527     NSMenuItem *item;
1528     AppController *controller;
1529     NSImage *icon;
1530
1531     pool = [[NSAutoreleasePool alloc] init];
1532
1533     icon = [NSImage imageNamed:@"NSApplicationIcon"];
1534     [NSApplication sharedApplication];
1535     [NSApp setApplicationIconImage:icon];
1536
1537     controller = [[[AppController alloc] init] autorelease];
1538     [NSApp setDelegate:controller];
1539
1540     [NSApp setMainMenu: newmenu("Main Menu")];
1541
1542     menu = newsubmenu([NSApp mainMenu], "Apple Menu");
1543     item = newitem(menu, "About Puzzles", "", NULL, @selector(about:));
1544     [menu addItem:[NSMenuItem separatorItem]];
1545     [NSApp setServicesMenu:newsubmenu(menu, "Services")];
1546     [menu addItem:[NSMenuItem separatorItem]];
1547     item = newitem(menu, "Hide Puzzles", "h", NSApp, @selector(hide:));
1548     item = newitem(menu, "Hide Others", "o-h", NSApp, @selector(hideOtherApplications:));
1549     item = newitem(menu, "Show All", "", NSApp, @selector(unhideAllApplications:));
1550     [menu addItem:[NSMenuItem separatorItem]];
1551     item = newitem(menu, "Quit", "q", NSApp, @selector(terminate:));
1552     [NSApp setAppleMenu: menu];
1553
1554     menu = newsubmenu([NSApp mainMenu], "File");
1555     item = newitem(menu, "Open", "o", NULL, @selector(loadSavedGame:));
1556     item = newitem(menu, "Save As", "s", NULL, @selector(saveGame:));
1557     item = newitem(menu, "New Game", "n", NULL, @selector(newGame:));
1558     item = newitem(menu, "Restart Game", "r", NULL, @selector(restartGame:));
1559     item = newitem(menu, "Specific Game", "", NULL, @selector(specificGame:));
1560     item = newitem(menu, "Specific Random Seed", "", NULL,
1561                    @selector(specificRandomGame:));
1562     [menu addItem:[NSMenuItem separatorItem]];
1563     {
1564         NSMenu *submenu = newsubmenu(menu, "New Window");
1565         int i;
1566
1567         for (i = 0; i < gamecount; i++) {
1568             id item =
1569                 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1570                             submenu, gamelist[i]->name, "", controller,
1571                             @selector(newGameWindow:));
1572             [item setPayload:(void *)gamelist[i]];
1573         }
1574     }
1575     [menu addItem:[NSMenuItem separatorItem]];
1576     item = newitem(menu, "Close", "w", NULL, @selector(performClose:));
1577
1578     menu = newsubmenu([NSApp mainMenu], "Edit");
1579     item = newitem(menu, "Undo", "z", NULL, @selector(undoMove:));
1580     item = newitem(menu, "Redo", "S-z", NULL, @selector(redoMove:));
1581     [menu addItem:[NSMenuItem separatorItem]];
1582     item = newitem(menu, "Cut", "x", NULL, @selector(cut:));
1583     item = newitem(menu, "Copy", "c", NULL, @selector(copy:));
1584     item = newitem(menu, "Paste", "v", NULL, @selector(paste:));
1585     [menu addItem:[NSMenuItem separatorItem]];
1586     item = newitem(menu, "Solve", "S-s", NULL, @selector(solveGame:));
1587
1588     menu = newsubmenu([NSApp mainMenu], "Type");
1589     typemenu = menu;
1590     item = newitem(menu, "Custom", "", NULL, @selector(customGameType:));
1591
1592     menu = newsubmenu([NSApp mainMenu], "Window");
1593     [NSApp setWindowsMenu: menu];
1594     item = newitem(menu, "Minimise Window", "m", NULL, @selector(performMiniaturize:));
1595
1596     menu = newsubmenu([NSApp mainMenu], "Help");
1597     item = newitem(menu, "Puzzles Help", "?", NSApp, @selector(showHelp:));
1598
1599     [NSApp run];
1600     [pool release];
1601
1602     return 0;
1603 }