Cleanup: rename random_init() to random_new(), because it actually
[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
dafd6cf6 95/*
96 * Forward reference.
97 */
98extern const struct drawing_api osx_drawing;
99
e7fabdfa 100/* ----------------------------------------------------------------------
101 * Miscellaneous support routines that aren't part of any object or
102 * clearly defined subsystem.
103 */
104
9494d866 105void fatal(char *fmt, ...)
106{
9494d866 107 va_list ap;
e7fabdfa 108 char errorbuf[2048];
109 NSAlert *alert;
9494d866 110
111 va_start(ap, fmt);
e7fabdfa 112 vsnprintf(errorbuf, lenof(errorbuf), fmt, ap);
9494d866 113 va_end(ap);
114
e7fabdfa 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 }
9494d866 129 exit(1);
130}
131
132void frontend_default_colour(frontend *fe, float *output)
133{
e7fabdfa 134 /* FIXME: Is there a system default we can tap into for this? */
9494d866 135 output[0] = output[1] = output[2] = 0.8F;
136}
9494d866 137
138void 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
668be019 146static void savefile_write(void *wctx, void *buf, int len)
147{
148 FILE *fp = (FILE *)wctx;
149 fwrite(buf, 1, len, fp);
150}
151
152static 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
dafd6cf6 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 */
165void document_add_puzzle(document *doc, const game *game, game_params *par,
166 game_state *st, game_state *st2)
167{
168}
169
9494d866 170/* ----------------------------------------------------------------------
7e04cb48 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;
7e04cb48 178}
179- (void)setPayload:(void *)d;
7e04cb48 180- (void *)getPayload;
181@end
182@implementation DataMenuItem
7e04cb48 183- (void)setPayload:(void *)d
184{
185 payload = d;
186}
7e04cb48 187- (void *)getPayload
188{
189 return payload;
190}
7e04cb48 191@end
192
193/* ----------------------------------------------------------------------
e1107f8b 194 * Utility routines for constructing OS X menus.
195 */
196
197NSMenu *newmenu(const char *title)
198{
199 return [[[NSMenu allocWithZone:[NSMenu menuZone]]
200 initWithTitle:[NSString stringWithCString:title]]
201 autorelease];
202}
203
204NSMenu *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
221id 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
257NSMenuItem *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/* ----------------------------------------------------------------------
97098757 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/* ----------------------------------------------------------------------
9494d866 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
368struct 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;
dafd6cf6 398 midend *me;
9494d866 399 struct frontend fe;
400 struct timeval last_time;
401 NSTimer *timer;
e1107f8b 402 NSWindow *sheet;
403 config_item *cfg;
404 int cfg_which;
405 NSView **cfg_controls;
406 int cfg_ncontrols;
a5102461 407 NSTextField *status;
9494d866 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;
48dcdd62 415- (void)setStatusLine:(char *)text;
668be019 416- (void)resizeForNewGameParams;
9494d866 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
7e04cb48 491- (void)setupContentView
492{
a5102461 493 NSRect frame;
7e04cb48 494 int w, h;
495
a5102461 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
1e3e152d 503 w = h = INT_MAX;
504 midend_size(me, &w, &h, FALSE);
a5102461 505 frame.size.width = w;
506 frame.size.height = h;
7e04cb48 507
a5102461 508 fe.image = [[NSImage alloc] initWithSize:frame.size];
7e04cb48 509 [fe.image setFlipped:YES];
a5102461 510 fe.view = [[MyImageView alloc] initWithFrame:frame];
7e04cb48 511 [fe.view setImage:fe.image];
512 [fe.view setWindow:self];
513
514 midend_redraw(me);
515
a5102461 516 [[self contentView] addSubview:fe.view];
7e04cb48 517}
9494d866 518- (id)initWithGame:(const game *)g
519{
a5102461 520 NSRect rect = { {0,0}, {0,0} }, rect2;
9494d866 521 int w, h;
522
523 ourgame = g;
524
525 fe.window = self;
526
c3b4e35a 527 me = midend_new(&fe, ourgame, &osx_drawing, &fe);
9494d866 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);
1e3e152d 535 w = h = INT_MAX;
536 midend_size(me, &w, &h, FALSE);
9494d866 537 rect.size.width = w;
538 rect.size.height = h;
539
a5102461 540 /*
541 * Create the status bar, which will just be an NSTextField.
542 */
543 if (ourgame->wants_statusbar()) {
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
9494d866 561 self = [super initWithContentRect:rect
562 styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
563 NSClosableWindowMask)
564 backing:NSBackingStoreBuffered
e1107f8b 565 defer:YES];
9494d866 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
7e04cb48 583 [self setupContentView];
a5102461 584 if (status)
585 [[self contentView] addSubview:status];
9494d866 586 [self setIgnoresMouseEvents:NO];
587
9494d866 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) {
65a92074 624 int mods = FALSE;
9494d866 625 switch (c) {
626 case NSUpArrowFunctionKey:
627 c = CURSOR_UP;
65a92074 628 mods = TRUE;
9494d866 629 break;
630 case NSDownArrowFunctionKey:
631 c = CURSOR_DOWN;
65a92074 632 mods = TRUE;
9494d866 633 break;
634 case NSLeftArrowFunctionKey:
635 c = CURSOR_LEFT;
65a92074 636 mods = TRUE;
9494d866 637 break;
638 case NSRightArrowFunctionKey:
639 c = CURSOR_RIGHT;
65a92074 640 mods = TRUE;
9494d866 641 break;
642 default:
643 continue;
644 }
65a92074 645
646 if (mods) {
647 if ([ev modifierFlags] & NSShiftKeyMask)
648 c |= MOD_SHFT;
649 if ([ev modifierFlags] & NSControlKeyMask)
650 c |= MOD_CTRL;
651 }
9494d866 652 }
653
3c833d45 654 if (c >= '0' && c <= '9' && ([ev modifierFlags] & NSNumericPadKeyMask))
655 c |= MOD_NUM_KEYPAD;
656
9494d866 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
668be019 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
00461804 703- (void)newGame:(id)sender
704{
705 [self processButton:'n' x:-1 y:-1];
706}
707- (void)restartGame:(id)sender
708{
7f89707c 709 midend_restart_game(me);
00461804 710}
668be019 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}
00461804 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
9b4b03d3 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
2ac6d24e 782- (void)solveGame:(id)sender
783{
784 char *msg;
2ac6d24e 785
786 msg = midend_solve(me);
787
668be019 788 if (msg)
789 [self showError:msg];
2ac6d24e 790}
791
9b4b03d3 792- (BOOL)validateMenuItem:(NSMenuItem *)item
793{
794 if ([item action] == @selector(copy:))
795 return (ourgame->can_format_as_text ? YES : NO);
2ac6d24e 796 else if ([item action] == @selector(solveGame:))
797 return (ourgame->can_solve ? YES : NO);
9b4b03d3 798 else
799 return [super validateMenuItem:item];
800}
801
7e04cb48 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];
7e04cb48 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
1e3e152d 859 w = h = INT_MAX;
860 midend_size(me, &w, &h, FALSE);
7e04cb48 861 size.width = w;
862 size.height = h;
863
2411c162 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
7e04cb48 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
e1107f8b 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
e1107f8b 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];
6958e513 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
e1107f8b 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{
1185e3c5 1152 [self startConfigureSheet:CFG_DESC];
1153}
1154
1155- (void)specificRandomGame:(id)sender
1156{
e1107f8b 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];
e7fabdfa 1199 [alert addButtonWithTitle:@"Bah"];
e1107f8b 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
48dcdd62 1220- (void)setStatusLine:(char *)text
a5102461 1221{
48dcdd62 1222 char *rewritten = midend_rewrite_statusbar(me, text);
1223 [[status cell] setTitle:[NSString stringWithCString:rewritten]];
1224 sfree(rewritten);
a5102461 1225}
1226
9494d866 1227@end
1228
1229/*
1230 * Drawing routines called by the midend.
1231 */
dafd6cf6 1232static void osx_draw_polygon(void *handle, int *coords, int npoints,
1233 int fillcolour, int outlinecolour)
9494d866 1234{
dafd6cf6 1235 frontend *fe = (frontend *)handle;
9494d866 1236 NSBezierPath *path = [NSBezierPath bezierPath];
1237 int i;
1238
1239 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1240
9494d866 1241 for (i = 0; i < npoints; i++) {
1242 NSPoint p = { coords[i*2] + 0.5, coords[i*2+1] + 0.5 };
1243 if (i == 0)
1244 [path moveToPoint:p];
1245 else
1246 [path lineToPoint:p];
1247 }
1248
1249 [path closePath];
1250
28b5987d 1251 if (fillcolour >= 0) {
1252 assert(fillcolour >= 0 && fillcolour < fe->ncolours);
1253 [fe->colours[fillcolour] set];
9494d866 1254 [path fill];
28b5987d 1255 }
1256
1257 assert(outlinecolour >= 0 && outlinecolour < fe->ncolours);
1258 [fe->colours[outlinecolour] set];
1259 [path stroke];
9494d866 1260}
dafd6cf6 1261static void osx_draw_circle(void *handle, int cx, int cy, int radius,
1262 int fillcolour, int outlinecolour)
550efd7f 1263{
dafd6cf6 1264 frontend *fe = (frontend *)handle;
550efd7f 1265 NSBezierPath *path = [NSBezierPath bezierPath];
1266
1267 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1268
550efd7f 1269 [path appendBezierPathWithArcWithCenter:NSMakePoint(cx + 0.5, cy + 0.5)
1270 radius:radius startAngle:0.0 endAngle:360.0];
1271
1272 [path closePath];
1273
28b5987d 1274 if (fillcolour >= 0) {
1275 assert(fillcolour >= 0 && fillcolour < fe->ncolours);
1276 [fe->colours[fillcolour] set];
550efd7f 1277 [path fill];
28b5987d 1278 }
1279
1280 assert(outlinecolour >= 0 && outlinecolour < fe->ncolours);
1281 [fe->colours[outlinecolour] set];
1282 [path stroke];
550efd7f 1283}
dafd6cf6 1284static void osx_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
9494d866 1285{
dafd6cf6 1286 frontend *fe = (frontend *)handle;
9494d866 1287 NSBezierPath *path = [NSBezierPath bezierPath];
1288 NSPoint p1 = { x1 + 0.5, y1 + 0.5 }, p2 = { x2 + 0.5, y2 + 0.5 };
1289
1290 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1291
1292 assert(colour >= 0 && colour < fe->ncolours);
1293 [fe->colours[colour] set];
1294
1295 [path moveToPoint:p1];
1296 [path lineToPoint:p2];
1297 [path stroke];
1298}
dafd6cf6 1299static void osx_draw_rect(void *handle, int x, int y, int w, int h, int colour)
9494d866 1300{
dafd6cf6 1301 frontend *fe = (frontend *)handle;
9494d866 1302 NSRect r = { {x,y}, {w,h} };
dafd6cf6 1303
9494d866 1304 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1305
1306 assert(colour >= 0 && colour < fe->ncolours);
1307 [fe->colours[colour] set];
1308
1309 NSRectFill(r);
1310}
dafd6cf6 1311static void osx_draw_text(void *handle, int x, int y, int fonttype,
1312 int fontsize, int align, int colour, char *text)
9494d866 1313{
dafd6cf6 1314 frontend *fe = (frontend *)handle;
9494d866 1315 NSString *string = [NSString stringWithCString:text];
1316 NSDictionary *attr;
1317 NSFont *font;
1318 NSSize size;
1319 NSPoint point;
1320
1321 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1322
1323 assert(colour >= 0 && colour < fe->ncolours);
1324
1325 if (fonttype == FONT_FIXED)
1326 font = [NSFont userFixedPitchFontOfSize:fontsize];
1327 else
1328 font = [NSFont userFontOfSize:fontsize];
1329
1330 attr = [NSDictionary dictionaryWithObjectsAndKeys:
1331 fe->colours[colour], NSForegroundColorAttributeName,
1332 font, NSFontAttributeName, nil];
1333
1334 point.x = x;
1335 point.y = y;
1336
1337 size = [string sizeWithAttributes:attr];
1338 if (align & ALIGN_HRIGHT)
1339 point.x -= size.width;
1340 else if (align & ALIGN_HCENTRE)
1341 point.x -= size.width / 2;
1342 if (align & ALIGN_VCENTRE)
1343 point.y -= size.height / 2;
86e60e3d 1344 else
1345 point.y -= size.height;
9494d866 1346
1347 [string drawAtPoint:point withAttributes:attr];
1348}
3161048d 1349struct blitter {
1350 int w, h;
1351 int x, y;
1352 NSImage *img;
1353};
dafd6cf6 1354static blitter *osx_blitter_new(void *handle, int w, int h)
3161048d 1355{
1356 blitter *bl = snew(blitter);
1357 bl->x = bl->y = -1;
1358 bl->w = w;
1359 bl->h = h;
1360 bl->img = [[NSImage alloc] initWithSize:NSMakeSize(w, h)];
1361 [bl->img setFlipped:YES];
1362 return bl;
1363}
dafd6cf6 1364static void osx_blitter_free(void *handle, blitter *bl)
3161048d 1365{
1366 [bl->img release];
1367 sfree(bl);
1368}
dafd6cf6 1369static void osx_blitter_save(void *handle, blitter *bl, int x, int y)
3161048d 1370{
dafd6cf6 1371 frontend *fe = (frontend *)handle;
3161048d 1372 [fe->image unlockFocus];
1373 [bl->img lockFocus];
1374 [fe->image drawInRect:NSMakeRect(0, 0, bl->w, bl->h)
1375 fromRect:NSMakeRect(x, y, bl->w, bl->h)
1376 operation:NSCompositeCopy fraction:1.0];
1377 [bl->img unlockFocus];
1378 [fe->image lockFocus];
1379 bl->x = x;
1380 bl->y = y;
1381}
dafd6cf6 1382static void osx_blitter_load(void *handle, blitter *bl, int x, int y)
3161048d 1383{
c3b4e35a 1384 /* frontend *fe = (frontend *)handle; */
3161048d 1385 if (x == BLITTER_FROMSAVED && y == BLITTER_FROMSAVED) {
1386 x = bl->x;
1387 y = bl->y;
1388 }
1389 [bl->img drawInRect:NSMakeRect(x, y, bl->w, bl->h)
1390 fromRect:NSMakeRect(0, 0, bl->w, bl->h)
1391 operation:NSCompositeCopy fraction:1.0];
1392}
dafd6cf6 1393static void osx_draw_update(void *handle, int x, int y, int w, int h)
9494d866 1394{
dafd6cf6 1395 frontend *fe = (frontend *)handle;
364722d2 1396 [fe->view setNeedsDisplayInRect:NSMakeRect(x,y,w,h)];
9494d866 1397}
dafd6cf6 1398static void osx_clip(void *handle, int x, int y, int w, int h)
9494d866 1399{
dafd6cf6 1400 frontend *fe = (frontend *)handle;
9494d866 1401 NSRect r = { {x,y}, {w,h} };
dafd6cf6 1402
9494d866 1403 if (!fe->clipped)
1404 [[NSGraphicsContext currentContext] saveGraphicsState];
1405 [NSBezierPath clipRect:r];
1406 fe->clipped = TRUE;
1407}
dafd6cf6 1408static void osx_unclip(void *handle)
9494d866 1409{
dafd6cf6 1410 frontend *fe = (frontend *)handle;
9494d866 1411 if (fe->clipped)
1412 [[NSGraphicsContext currentContext] restoreGraphicsState];
1413 fe->clipped = FALSE;
1414}
dafd6cf6 1415static void osx_start_draw(void *handle)
9494d866 1416{
dafd6cf6 1417 frontend *fe = (frontend *)handle;
9494d866 1418 [fe->image lockFocus];
1419 fe->clipped = FALSE;
1420}
dafd6cf6 1421static void osx_end_draw(void *handle)
9494d866 1422{
dafd6cf6 1423 frontend *fe = (frontend *)handle;
9494d866 1424 [fe->image unlockFocus];
9494d866 1425}
dafd6cf6 1426static void osx_status_bar(void *handle, char *text)
1427{
1428 frontend *fe = (frontend *)handle;
1429 [fe->window setStatusLine:text];
1430}
1431
1432const struct drawing_api osx_drawing = {
1433 osx_draw_text,
1434 osx_draw_rect,
1435 osx_draw_line,
c3b4e35a 1436 osx_draw_polygon,
dafd6cf6 1437 osx_draw_circle,
1438 osx_draw_update,
1439 osx_clip,
1440 osx_unclip,
1441 osx_start_draw,
1442 osx_end_draw,
1443 osx_status_bar,
1444 osx_blitter_new,
1445 osx_blitter_free,
1446 osx_blitter_save,
1447 osx_blitter_load,
1448 NULL, NULL, NULL, NULL, NULL, NULL, /* {begin,end}_{doc,page,puzzle} */
1449 NULL, /* line_width */
1450};
9494d866 1451
1452void deactivate_timer(frontend *fe)
1453{
1454 [fe->window deactivateTimer];
1455}
1456void activate_timer(frontend *fe)
1457{
1458 [fe->window activateTimer];
1459}
1460
1461/* ----------------------------------------------------------------------
9494d866 1462 * AppController: the object which receives the messages from all
1463 * menu selections that aren't standard OS X functions.
1464 */
1465@interface AppController : NSObject
1466{
1467}
bacaa96e 1468- (void)newGameWindow:(id)sender;
97098757 1469- (void)about:(id)sender;
9494d866 1470@end
1471
1472@implementation AppController
1473
bacaa96e 1474- (void)newGameWindow:(id)sender
9494d866 1475{
7e04cb48 1476 const game *g = [sender getPayload];
9494d866 1477 id win;
1478
1479 win = [[GameWindow alloc] initWithGame:g];
1480 [win makeKeyAndOrderFront:self];
1481}
1482
97098757 1483- (void)about:(id)sender
1484{
1485 id win;
1486
1487 win = [[AboutBox alloc] init];
1488 [win makeKeyAndOrderFront:self];
1489}
1490
3041164c 1491- (NSMenu *)applicationDockMenu:(NSApplication *)sender
1492{
1493 NSMenu *menu = newmenu("Dock Menu");
1494 {
1495 int i;
1496
1497 for (i = 0; i < gamecount; i++) {
1498 id item =
1499 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1500 menu, gamelist[i]->name, "", self,
bacaa96e 1501 @selector(newGameWindow:));
3041164c 1502 [item setPayload:(void *)gamelist[i]];
1503 }
1504 }
1505 return menu;
1506}
1507
9494d866 1508@end
1509
1510/* ----------------------------------------------------------------------
1511 * Main program. Constructs the menus and runs the application.
1512 */
1513int main(int argc, char **argv)
1514{
1515 NSAutoreleasePool *pool;
1516 NSMenu *menu;
1517 NSMenuItem *item;
1518 AppController *controller;
a96edf8a 1519 NSImage *icon;
9494d866 1520
1521 pool = [[NSAutoreleasePool alloc] init];
a96edf8a 1522
1523 icon = [NSImage imageNamed:@"NSApplicationIcon"];
9494d866 1524 [NSApplication sharedApplication];
a96edf8a 1525 [NSApp setApplicationIconImage:icon];
9494d866 1526
1527 controller = [[[AppController alloc] init] autorelease];
3041164c 1528 [NSApp setDelegate:controller];
9494d866 1529
1530 [NSApp setMainMenu: newmenu("Main Menu")];
1531
1532 menu = newsubmenu([NSApp mainMenu], "Apple Menu");
97098757 1533 item = newitem(menu, "About Puzzles", "", NULL, @selector(about:));
1534 [menu addItem:[NSMenuItem separatorItem]];
9494d866 1535 [NSApp setServicesMenu:newsubmenu(menu, "Services")];
1536 [menu addItem:[NSMenuItem separatorItem]];
1537 item = newitem(menu, "Hide Puzzles", "h", NSApp, @selector(hide:));
1538 item = newitem(menu, "Hide Others", "o-h", NSApp, @selector(hideOtherApplications:));
1539 item = newitem(menu, "Show All", "", NSApp, @selector(unhideAllApplications:));
1540 [menu addItem:[NSMenuItem separatorItem]];
1541 item = newitem(menu, "Quit", "q", NSApp, @selector(terminate:));
1542 [NSApp setAppleMenu: menu];
1543
bacaa96e 1544 menu = newsubmenu([NSApp mainMenu], "File");
668be019 1545 item = newitem(menu, "Open", "o", NULL, @selector(loadSavedGame:));
1546 item = newitem(menu, "Save As", "s", NULL, @selector(saveGame:));
bacaa96e 1547 item = newitem(menu, "New Game", "n", NULL, @selector(newGame:));
1548 item = newitem(menu, "Restart Game", "r", NULL, @selector(restartGame:));
1549 item = newitem(menu, "Specific Game", "", NULL, @selector(specificGame:));
1185e3c5 1550 item = newitem(menu, "Specific Random Seed", "", NULL,
1551 @selector(specificRandomGame:));
bacaa96e 1552 [menu addItem:[NSMenuItem separatorItem]];
9494d866 1553 {
bacaa96e 1554 NSMenu *submenu = newsubmenu(menu, "New Window");
9494d866 1555 int i;
1556
1557 for (i = 0; i < gamecount; i++) {
1558 id item =
7e04cb48 1559 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
bacaa96e 1560 submenu, gamelist[i]->name, "", controller,
1561 @selector(newGameWindow:));
7e04cb48 1562 [item setPayload:(void *)gamelist[i]];
9494d866 1563 }
1564 }
00461804 1565 [menu addItem:[NSMenuItem separatorItem]];
bacaa96e 1566 item = newitem(menu, "Close", "w", NULL, @selector(performClose:));
1567
1568 menu = newsubmenu([NSApp mainMenu], "Edit");
00461804 1569 item = newitem(menu, "Undo", "z", NULL, @selector(undoMove:));
1570 item = newitem(menu, "Redo", "S-z", NULL, @selector(redoMove:));
1571 [menu addItem:[NSMenuItem separatorItem]];
8b738d61 1572 item = newitem(menu, "Cut", "x", NULL, @selector(cut:));
9b4b03d3 1573 item = newitem(menu, "Copy", "c", NULL, @selector(copy:));
8b738d61 1574 item = newitem(menu, "Paste", "v", NULL, @selector(paste:));
2ac6d24e 1575 [menu addItem:[NSMenuItem separatorItem]];
1576 item = newitem(menu, "Solve", "S-s", NULL, @selector(solveGame:));
00461804 1577
1578 menu = newsubmenu([NSApp mainMenu], "Type");
7e04cb48 1579 typemenu = menu;
00461804 1580 item = newitem(menu, "Custom", "", NULL, @selector(customGameType:));
1581
1582 menu = newsubmenu([NSApp mainMenu], "Window");
9494d866 1583 [NSApp setWindowsMenu: menu];
00461804 1584 item = newitem(menu, "Minimise Window", "m", NULL, @selector(performMiniaturize:));
9494d866 1585
fccfd04d 1586 menu = newsubmenu([NSApp mainMenu], "Help");
171ee031 1587 item = newitem(menu, "Puzzles Help", "?", NSApp, @selector(showHelp:));
fccfd04d 1588
9494d866 1589 [NSApp run];
1590 [pool release];
1591}