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