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