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