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