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