GNUstep compatibility: add a missing #include.
[sgt/puzzles] / osx.m
1 /*
2 * Mac OS X / Cocoa front end to puzzles.
3 *
4 * Still to do:
5 *
6 * - I'd like to be able to call up context help for a specific
7 * game at a time.
8 *
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?
14 *
15 * - can / should we be doing anything with the titles of the
16 * configuration boxes?
17 *
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"?
23 * + there's a standard _policy_ on window placement, given in
24 * the HI guidelines. Have to implement it ourselves though,
25 * bah.
26 *
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
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.
33 *
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...
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.
50 *
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 *
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
66 * thought.
67 *
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.
78 */
79
80 #define COMBINED /* we put all the puzzles in one binary in this port */
81
82 #include <ctype.h>
83 #include <time.h>
84 #include <sys/time.h>
85 #import <Cocoa/Cocoa.h>
86 #include "puzzles.h"
87
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 */
96 NSMenu *typemenu;
97
98 /*
99 * Forward reference.
100 */
101 extern const struct drawing_api osx_drawing;
102
103 /* ----------------------------------------------------------------------
104 * Miscellaneous support routines that aren't part of any object or
105 * clearly defined subsystem.
106 */
107
108 void fatal(char *fmt, ...)
109 {
110 va_list ap;
111 char errorbuf[2048];
112 NSAlert *alert;
113
114 va_start(ap, fmt);
115 vsnprintf(errorbuf, lenof(errorbuf), fmt, ap);
116 va_end(ap);
117
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"];
129 [alert setInformativeText:[NSString stringWithUTF8String:errorbuf]];
130 [alert runModal];
131 }
132 exit(1);
133 }
134
135 void frontend_default_colour(frontend *fe, float *output)
136 {
137 /* FIXME: Is there a system default we can tap into for this? */
138 output[0] = output[1] = output[2] = 0.8F;
139 }
140
141 void 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
149 static void savefile_write(void *wctx, void *buf, int len)
150 {
151 FILE *fp = (FILE *)wctx;
152 fwrite(buf, 1, len, fp);
153 }
154
155 static 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
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 */
168 void document_add_puzzle(document *doc, const game *game, game_params *par,
169 game_state *st, game_state *st2)
170 {
171 }
172
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
185 /* ----------------------------------------------------------------------
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;
193 }
194 - (void)setPayload:(void *)d;
195 - (void *)getPayload;
196 @end
197 @implementation DataMenuItem
198 - (void)setPayload:(void *)d
199 {
200 payload = d;
201 }
202 - (void *)getPayload
203 {
204 return payload;
205 }
206 @end
207
208 /* ----------------------------------------------------------------------
209 * Utility routines for constructing OS X menus.
210 */
211
212 NSMenu *newmenu(const char *title)
213 {
214 return [[[NSMenu allocWithZone:[NSMenu menuZone]]
215 initWithTitle:[NSString stringWithUTF8String:title]]
216 autorelease];
217 }
218
219 NSMenu *newsubmenu(NSMenu *parent, const char *title)
220 {
221 NSMenuItem *item;
222 NSMenu *child;
223
224 item = [[[NSMenuItem allocWithZone:[NSMenu menuZone]]
225 initWithTitle:[NSString stringWithUTF8String:title]
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
236 id 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
255 item = [[item initWithTitle:[NSString stringWithUTF8String:title]
256 action:NULL
257 keyEquivalent:[NSString stringWithUTF8String:key]]
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
272 NSMenuItem *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 /* ----------------------------------------------------------------------
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];
331 [tf setStringValue:[NSString stringWithUTF8String:ver]];
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 /* ----------------------------------------------------------------------
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
383 struct frontend {
384 GameWindow *window;
385 NSImage *image;
386 MyImageView *view;
387 NSColor **colours;
388 int ncolours;
389 int clipped;
390 int w, h;
391 };
392
393 @interface MyImageView : NSImageView
394 {
395 GameWindow *ourwin;
396 }
397 - (void)setWindow:(GameWindow *)win;
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;
413 midend *me;
414 struct frontend fe;
415 struct timeval last_time;
416 NSTimer *timer;
417 NSWindow *sheet;
418 config_item *cfg;
419 int cfg_which;
420 NSView **cfg_controls;
421 int cfg_ncontrols;
422 NSTextField *status;
423 }
424 - (id)initWithGame:(const game *)g;
425 - (void)dealloc;
426 - (void)processButton:(int)b x:(int)x y:(int)y;
427 - (void)processKey:(int)b;
428 - (void)keyDown:(NSEvent *)ev;
429 - (void)activateTimer;
430 - (void)deactivateTimer;
431 - (void)setStatusLine:(char *)text;
432 - (void)resizeForNewGameParams;
433 - (void)updateTypeMenuTick;
434 @end
435
436 @implementation MyImageView
437
438 - (void)setWindow:(GameWindow *)win
439 {
440 ourwin = win;
441 }
442
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
503 - (void)setupContentView
504 {
505 NSRect frame;
506 int w, h;
507
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
515 w = h = INT_MAX;
516 midend_size(me, &w, &h, FALSE);
517 frame.size.width = w;
518 frame.size.height = h;
519 fe.w = w;
520 fe.h = h;
521
522 fe.image = [[NSImage alloc] initWithSize:frame.size];
523 fe.view = [[MyImageView alloc] initWithFrame:frame];
524 [fe.view setImage:fe.image];
525 [fe.view setWindow:self];
526
527 midend_redraw(me);
528
529 [[self contentView] addSubview:fe.view];
530 }
531 - (id)initWithGame:(const game *)g
532 {
533 NSRect rect = { {0,0}, {0,0} }, rect2;
534 int w, h;
535
536 ourgame = g;
537
538 fe.window = self;
539
540 me = midend_new(&fe, ourgame, &osx_drawing, &fe);
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);
548 w = h = INT_MAX;
549 midend_size(me, &w, &h, FALSE);
550 rect.size.width = w;
551 rect.size.height = h;
552 fe.w = w;
553 fe.h = h;
554
555 /*
556 * Create the status bar, which will just be an NSTextField.
557 */
558 if (midend_wants_statusbar(me)) {
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
576 self = [super initWithContentRect:rect
577 styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
578 NSClosableWindowMask)
579 backing:NSBackingStoreBuffered
580 defer:YES];
581 [self setTitle:[NSString stringWithUTF8String:ourgame->name]];
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
598 [self setupContentView];
599 if (status)
600 [[self contentView] addSubview:status];
601 [self setIgnoresMouseEvents:NO];
602
603 [self center]; /* :-) */
604
605 return self;
606 }
607
608 - (void)dealloc
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);
616 [super dealloc];
617 }
618
619 - (void)processButton:(int)b x:(int)x y:(int)y
620 {
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))
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) {
645 int mods = FALSE;
646 switch (c) {
647 case NSUpArrowFunctionKey:
648 c = CURSOR_UP;
649 mods = TRUE;
650 break;
651 case NSDownArrowFunctionKey:
652 c = CURSOR_DOWN;
653 mods = TRUE;
654 break;
655 case NSLeftArrowFunctionKey:
656 c = CURSOR_LEFT;
657 mods = TRUE;
658 break;
659 case NSRightArrowFunctionKey:
660 c = CURSOR_RIGHT;
661 mods = TRUE;
662 break;
663 default:
664 continue;
665 }
666
667 if (mods) {
668 if ([ev modifierFlags] & NSShiftKeyMask)
669 c |= MOD_SHFT;
670 if ([ev modifierFlags] & NSControlKeyMask)
671 c |= MOD_CTRL;
672 }
673 }
674
675 if (c >= '0' && c <= '9' && ([ev modifierFlags] & NSNumericPadKeyMask))
676 c |= MOD_NUM_KEYPAD;
677
678 [self processKey:c];
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
713 - (void)showError:(char *)message
714 {
715 NSAlert *alert;
716
717 alert = [[[NSAlert alloc] init] autorelease];
718 [alert addButtonWithTitle:@"Bah"];
719 [alert setInformativeText:[NSString stringWithUTF8String:message]];
720 [alert beginSheetModalForWindow:self modalDelegate:nil
721 didEndSelector:NULL contextInfo:nil];
722 }
723
724 - (void)newGame:(id)sender
725 {
726 [self processKey:'n'];
727 }
728 - (void)restartGame:(id)sender
729 {
730 midend_restart_game(me);
731 }
732 - (void)saveGame:(id)sender
733 {
734 NSSavePanel *sp = [NSSavePanel savePanel];
735
736 if ([sp runModal] == NSFileHandlingPanelOKButton) {
737 const char *name = [[sp filename] UTF8String];
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];
778 [self updateTypeMenuTick];
779 }
780 }
781 - (void)undoMove:(id)sender
782 {
783 [self processKey:'u'];
784 }
785 - (void)redoMove:(id)sender
786 {
787 [self processKey:'r'&0x1F];
788 }
789
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];
798 [pb setString:[NSString stringWithUTF8String:text]
799 forType:NSStringPboardType];
800 } else
801 NSBeep();
802 }
803
804 - (void)solveGame:(id)sender
805 {
806 char *msg;
807
808 msg = midend_solve(me);
809
810 if (msg)
811 [self showError:msg];
812 }
813
814 - (BOOL)validateMenuItem:(NSMenuItem *)item
815 {
816 if ([item action] == @selector(copy:))
817 return (ourgame->can_format_as_text_ever &&
818 midend_can_format_as_text_now(me) ? YES : NO);
819 else if ([item action] == @selector(solveGame:))
820 return (ourgame->can_solve ? YES : NO);
821 else
822 return [super validateMenuItem:item];
823 }
824
825 - (void)clearTypeMenu
826 {
827 while ([typemenu numberOfItems] > 1)
828 [typemenu removeItemAtIndex:0];
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)];
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]
864 initWithTitle:[NSString stringWithUTF8String:name]
865 action:NULL keyEquivalent:@""]
866 autorelease];
867
868 [item setEnabled:YES];
869 [item setTarget:self];
870 [item setAction:@selector(presetGame:)];
871 [item setPayload:params];
872
873 [typemenu insertItem:item atIndex:0];
874 }
875 }
876
877 [self updateTypeMenuTick];
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
897 w = h = INT_MAX;
898 midend_size(me, &w, &h, FALSE);
899 size.width = w;
900 size.height = h;
901 fe.w = w;
902 fe.h = h;
903
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
911 #ifndef GNUSTEP
912 NSDisableScreenUpdates();
913 #endif
914 [self setContentSize:size];
915 [self setupContentView];
916 #ifndef GNUSTEP
917 NSEnableScreenUpdates();
918 #endif
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];
929 [self updateTypeMenuTick];
930 }
931
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];
1017 [[tf cell] setTitle:[NSString stringWithUTF8String:i->name]];
1018 [tf sizeToFit];
1019 rect = [tf frame];
1020 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1021 if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
1022 cfg_controls[cfg_ncontrols++] = tf;
1023
1024 tf = [[NSTextField alloc] initWithFrame:tmprect];
1025 [tf setEditable:YES];
1026 [tf setSelectable:YES];
1027 [tf setBordered:YES];
1028 [[tf cell] setTitle:[NSString stringWithUTF8String:i->sval]];
1029 [tf sizeToFit];
1030 rect = [tf frame];
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
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];
1055 [b setTitle:[NSString stringWithUTF8String:i->name]];
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];
1076 [[tf cell] setTitle:[NSString stringWithUTF8String:i->name]];
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) {
1091 char cc, *q;
1092
1093 q = p;
1094 while (*p && *p != c) p++;
1095
1096 cc = *p;
1097 *p = '\0';
1098 [pb addItemWithTitle:[NSString stringWithUTF8String:q]];
1099 *p = cc;
1100
1101 if (*p) p++;
1102 }
1103 }
1104 [pb selectItemAtIndex:i->ival];
1105 [pb sizeToFit];
1106
1107 rect = [pb frame];
1108 if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
1109 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1110 cfg_controls[cfg_ncontrols++] = pb;
1111 break;
1112 }
1113
1114 h += SPACING + thish;
1115 }
1116
1117 if (totalw < leftw + SPACING + rightw)
1118 totalw = leftw + SPACING + rightw;
1119 if (totalw > leftw + SPACING + rightw) {
1120 int excess = totalw - (leftw + SPACING + rightw);
1121 int leftexcess = leftw * excess / (leftw + rightw);
1122 int rightexcess = excess - leftexcess;
1123 leftw += leftexcess;
1124 rightw += rightexcess;
1125 }
1126
1127 /*
1128 * Now go through the list again, setting the final position
1129 * for each control.
1130 */
1131 k = 0;
1132 y = h;
1133 for (i = cfg; i->type != C_END; i++) {
1134 y -= SPACING;
1135 thish = 0;
1136 switch (i->type) {
1137 case C_STRING:
1138 case C_CHOICES:
1139 /*
1140 * These two are treated identically, since both expect
1141 * a control on the left and another on the right.
1142 */
1143 rect = [cfg_controls[k] frame];
1144 if (thish < rect.size.height + 1)
1145 thish = rect.size.height + 1;
1146 rect = [cfg_controls[k+1] frame];
1147 if (thish < rect.size.height + 1)
1148 thish = rect.size.height + 1;
1149 rect = [cfg_controls[k] frame];
1150 rect.origin.y = y - thish/2 - rect.size.height/2;
1151 rect.origin.x = SPACING;
1152 rect.size.width = leftw;
1153 [cfg_controls[k] setFrame:rect];
1154 rect = [cfg_controls[k+1] frame];
1155 rect.origin.y = y - thish/2 - rect.size.height/2;
1156 rect.origin.x = 2 * SPACING + leftw;
1157 rect.size.width = rightw;
1158 [cfg_controls[k+1] setFrame:rect];
1159 k += 2;
1160 break;
1161
1162 case C_BOOLEAN:
1163 rect = [cfg_controls[k] frame];
1164 if (thish < rect.size.height + 1)
1165 thish = rect.size.height + 1;
1166 rect.origin.y = y - thish/2 - rect.size.height/2;
1167 rect.origin.x = SPACING;
1168 rect.size.width = totalw;
1169 [cfg_controls[k] setFrame:rect];
1170 k++;
1171 break;
1172 }
1173 y -= thish;
1174 }
1175
1176 assert(k == cfg_ncontrols);
1177
1178 [cancel setFrame:NSMakeRect(SPACING+totalw/4-actw/2, SPACING, actw, acth)];
1179 [ok setFrame:NSMakeRect(SPACING+3*totalw/4-actw/2, SPACING, actw, acth)];
1180
1181 sheet = [[NSWindow alloc]
1182 initWithContentRect:NSMakeRect(0,0,totalw + 2*SPACING,h)
1183 styleMask:NSTitledWindowMask | NSClosableWindowMask
1184 backing:NSBackingStoreBuffered
1185 defer:YES];
1186
1187 [[sheet contentView] addSubview:cancel];
1188 [[sheet contentView] addSubview:ok];
1189
1190 for (k = 0; k < cfg_ncontrols; k++)
1191 [[sheet contentView] addSubview:cfg_controls[k]];
1192
1193 [NSApp beginSheet:sheet modalForWindow:self
1194 modalDelegate:nil didEndSelector:NULL contextInfo:nil];
1195 }
1196
1197 - (void)specificGame:(id)sender
1198 {
1199 [self startConfigureSheet:CFG_DESC];
1200 }
1201
1202 - (void)specificRandomGame:(id)sender
1203 {
1204 [self startConfigureSheet:CFG_SEED];
1205 }
1206
1207 - (void)customGameType:(id)sender
1208 {
1209 [self startConfigureSheet:CFG_SETTINGS];
1210 }
1211
1212 - (void)sheetEndWithStatus:(BOOL)update
1213 {
1214 assert(sheet != NULL);
1215 [NSApp endSheet:sheet];
1216 [sheet orderOut:self];
1217 sheet = NULL;
1218 if (update) {
1219 int k;
1220 config_item *i;
1221 char *error;
1222
1223 k = 0;
1224 for (i = cfg; i->type != C_END; i++) {
1225 switch (i->type) {
1226 case C_STRING:
1227 sfree(i->sval);
1228 i->sval = dupstr([[[(id)cfg_controls[k+1] cell]
1229 title] UTF8String]);
1230 k += 2;
1231 break;
1232 case C_BOOLEAN:
1233 i->ival = [(id)cfg_controls[k] state] == NSOnState;
1234 k++;
1235 break;
1236 case C_CHOICES:
1237 i->ival = [(id)cfg_controls[k+1] indexOfSelectedItem];
1238 k += 2;
1239 break;
1240 }
1241 }
1242
1243 error = midend_set_config(me, cfg_which, cfg);
1244 if (error) {
1245 NSAlert *alert = [[[NSAlert alloc] init] autorelease];
1246 [alert addButtonWithTitle:@"Bah"];
1247 [alert setInformativeText:[NSString stringWithUTF8String:error]];
1248 [alert beginSheetModalForWindow:self modalDelegate:nil
1249 didEndSelector:NULL contextInfo:nil];
1250 } else {
1251 midend_new_game(me);
1252 [self resizeForNewGameParams];
1253 [self updateTypeMenuTick];
1254 }
1255 }
1256 sfree(cfg_controls);
1257 cfg_controls = NULL;
1258 }
1259 - (void)sheetOKButton:(id)sender
1260 {
1261 [self sheetEndWithStatus:YES];
1262 }
1263 - (void)sheetCancelButton:(id)sender
1264 {
1265 [self sheetEndWithStatus:NO];
1266 }
1267
1268 - (void)setStatusLine:(char *)text
1269 {
1270 [[status cell] setTitle:[NSString stringWithUTF8String:text]];
1271 }
1272
1273 @end
1274
1275 /*
1276 * Drawing routines called by the midend.
1277 */
1278 static void osx_draw_polygon(void *handle, int *coords, int npoints,
1279 int fillcolour, int outlinecolour)
1280 {
1281 frontend *fe = (frontend *)handle;
1282 NSBezierPath *path = [NSBezierPath bezierPath];
1283 int i;
1284
1285 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1286
1287 for (i = 0; i < npoints; i++) {
1288 NSPoint p = { coords[i*2] + 0.5, fe->h - coords[i*2+1] - 0.5 };
1289 if (i == 0)
1290 [path moveToPoint:p];
1291 else
1292 [path lineToPoint:p];
1293 }
1294
1295 [path closePath];
1296
1297 if (fillcolour >= 0) {
1298 assert(fillcolour >= 0 && fillcolour < fe->ncolours);
1299 [fe->colours[fillcolour] set];
1300 [path fill];
1301 }
1302
1303 assert(outlinecolour >= 0 && outlinecolour < fe->ncolours);
1304 [fe->colours[outlinecolour] set];
1305 [path stroke];
1306 }
1307 static void osx_draw_circle(void *handle, int cx, int cy, int radius,
1308 int fillcolour, int outlinecolour)
1309 {
1310 frontend *fe = (frontend *)handle;
1311 NSBezierPath *path = [NSBezierPath bezierPath];
1312
1313 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1314
1315 [path appendBezierPathWithArcWithCenter:NSMakePoint(cx+0.5, fe->h-cy-0.5)
1316 radius:radius startAngle:0.0 endAngle:360.0];
1317
1318 [path closePath];
1319
1320 if (fillcolour >= 0) {
1321 assert(fillcolour >= 0 && fillcolour < fe->ncolours);
1322 [fe->colours[fillcolour] set];
1323 [path fill];
1324 }
1325
1326 assert(outlinecolour >= 0 && outlinecolour < fe->ncolours);
1327 [fe->colours[outlinecolour] set];
1328 [path stroke];
1329 }
1330 static void osx_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
1331 {
1332 frontend *fe = (frontend *)handle;
1333 NSBezierPath *path = [NSBezierPath bezierPath];
1334 NSPoint p1 = { x1 + 0.5, fe->h - y1 - 0.5 };
1335 NSPoint p2 = { x2 + 0.5, fe->h - y2 - 0.5 };
1336
1337 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1338
1339 assert(colour >= 0 && colour < fe->ncolours);
1340 [fe->colours[colour] set];
1341
1342 [path moveToPoint:p1];
1343 [path lineToPoint:p2];
1344 [path stroke];
1345 }
1346 static void osx_draw_rect(void *handle, int x, int y, int w, int h, int colour)
1347 {
1348 frontend *fe = (frontend *)handle;
1349 NSRect r = { {x, fe->h - y - h}, {w,h} };
1350
1351 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1352
1353 assert(colour >= 0 && colour < fe->ncolours);
1354 [fe->colours[colour] set];
1355
1356 NSRectFill(r);
1357 }
1358 static void osx_draw_text(void *handle, int x, int y, int fonttype,
1359 int fontsize, int align, int colour, char *text)
1360 {
1361 frontend *fe = (frontend *)handle;
1362 NSString *string = [NSString stringWithUTF8String:text];
1363 NSDictionary *attr;
1364 NSFont *font;
1365 NSSize size;
1366 NSPoint point;
1367
1368 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1369
1370 assert(colour >= 0 && colour < fe->ncolours);
1371
1372 if (fonttype == FONT_FIXED)
1373 font = [NSFont userFixedPitchFontOfSize:fontsize];
1374 else
1375 font = [NSFont userFontOfSize:fontsize];
1376
1377 attr = [NSDictionary dictionaryWithObjectsAndKeys:
1378 fe->colours[colour], NSForegroundColorAttributeName,
1379 font, NSFontAttributeName, nil];
1380
1381 point.x = x;
1382 point.y = fe->h - y;
1383
1384 size = [string sizeWithAttributes:attr];
1385 if (align & ALIGN_HRIGHT)
1386 point.x -= size.width;
1387 else if (align & ALIGN_HCENTRE)
1388 point.x -= size.width / 2;
1389 if (align & ALIGN_VCENTRE)
1390 point.y -= size.height / 2;
1391
1392 [string drawAtPoint:point withAttributes:attr];
1393 }
1394 static char *osx_text_fallback(void *handle, const char *const *strings,
1395 int nstrings)
1396 {
1397 /*
1398 * We assume OS X can cope with any UTF-8 likely to be emitted
1399 * by a puzzle.
1400 */
1401 return dupstr(strings[0]);
1402 }
1403 struct blitter {
1404 int w, h;
1405 int x, y;
1406 NSImage *img;
1407 };
1408 static blitter *osx_blitter_new(void *handle, int w, int h)
1409 {
1410 blitter *bl = snew(blitter);
1411 bl->x = bl->y = -1;
1412 bl->w = w;
1413 bl->h = h;
1414 bl->img = [[NSImage alloc] initWithSize:NSMakeSize(w, h)];
1415 return bl;
1416 }
1417 static void osx_blitter_free(void *handle, blitter *bl)
1418 {
1419 [bl->img release];
1420 sfree(bl);
1421 }
1422 static void osx_blitter_save(void *handle, blitter *bl, int x, int y)
1423 {
1424 frontend *fe = (frontend *)handle;
1425 int sx, sy, sX, sY, dx, dy, dX, dY;
1426 [fe->image unlockFocus];
1427 [bl->img lockFocus];
1428
1429 /*
1430 * Find the intersection of the source and destination rectangles,
1431 * so as to avoid trying to copy from outside the source image,
1432 * which GNUstep dislikes.
1433 *
1434 * Lower-case x,y coordinates are bottom left box corners;
1435 * upper-case X,Y are the top right.
1436 */
1437 sx = x; sy = fe->h - y - bl->h;
1438 sX = sx + bl->w; sY = sy + bl->h;
1439 dx = dy = 0;
1440 dX = bl->w; dY = bl->h;
1441 if (sx < 0) {
1442 dx += -sx;
1443 sx = 0;
1444 }
1445 if (sy < 0) {
1446 dy += -sy;
1447 sy = 0;
1448 }
1449 if (sX > fe->w) {
1450 dX -= (sX - fe->w);
1451 sX = fe->w;
1452 }
1453 if (sY > fe->h) {
1454 dY -= (sY - fe->h);
1455 sY = fe->h;
1456 }
1457
1458 [fe->image drawInRect:NSMakeRect(dx, dy, dX-dx, dY-dy)
1459 fromRect:NSMakeRect(sx, sy, sX-sx, sY-sy)
1460 operation:NSCompositeCopy fraction:1.0];
1461 [bl->img unlockFocus];
1462 [fe->image lockFocus];
1463 bl->x = x;
1464 bl->y = y;
1465 }
1466 static void osx_blitter_load(void *handle, blitter *bl, int x, int y)
1467 {
1468 frontend *fe = (frontend *)handle;
1469 if (x == BLITTER_FROMSAVED && y == BLITTER_FROMSAVED) {
1470 x = bl->x;
1471 y = bl->y;
1472 }
1473 [bl->img drawInRect:NSMakeRect(x, fe->h - y - bl->h, bl->w, bl->h)
1474 fromRect:NSMakeRect(0, 0, bl->w, bl->h)
1475 operation:NSCompositeCopy fraction:1.0];
1476 }
1477 static void osx_draw_update(void *handle, int x, int y, int w, int h)
1478 {
1479 frontend *fe = (frontend *)handle;
1480 [fe->view setNeedsDisplayInRect:NSMakeRect(x, fe->h - y - h, w, h)];
1481 }
1482 static void osx_clip(void *handle, int x, int y, int w, int h)
1483 {
1484 frontend *fe = (frontend *)handle;
1485 NSRect r = { {x, fe->h - y - h}, {w, h} };
1486
1487 if (!fe->clipped)
1488 [[NSGraphicsContext currentContext] saveGraphicsState];
1489 [NSBezierPath clipRect:r];
1490 fe->clipped = TRUE;
1491 }
1492 static void osx_unclip(void *handle)
1493 {
1494 frontend *fe = (frontend *)handle;
1495 if (fe->clipped)
1496 [[NSGraphicsContext currentContext] restoreGraphicsState];
1497 fe->clipped = FALSE;
1498 }
1499 static void osx_start_draw(void *handle)
1500 {
1501 frontend *fe = (frontend *)handle;
1502 [fe->image lockFocus];
1503 fe->clipped = FALSE;
1504 }
1505 static void osx_end_draw(void *handle)
1506 {
1507 frontend *fe = (frontend *)handle;
1508 [fe->image unlockFocus];
1509 }
1510 static void osx_status_bar(void *handle, char *text)
1511 {
1512 frontend *fe = (frontend *)handle;
1513 [fe->window setStatusLine:text];
1514 }
1515
1516 const struct drawing_api osx_drawing = {
1517 osx_draw_text,
1518 osx_draw_rect,
1519 osx_draw_line,
1520 osx_draw_polygon,
1521 osx_draw_circle,
1522 osx_draw_update,
1523 osx_clip,
1524 osx_unclip,
1525 osx_start_draw,
1526 osx_end_draw,
1527 osx_status_bar,
1528 osx_blitter_new,
1529 osx_blitter_free,
1530 osx_blitter_save,
1531 osx_blitter_load,
1532 NULL, NULL, NULL, NULL, NULL, NULL, /* {begin,end}_{doc,page,puzzle} */
1533 NULL, NULL, /* line_width, line_dotted */
1534 osx_text_fallback,
1535 };
1536
1537 void deactivate_timer(frontend *fe)
1538 {
1539 [fe->window deactivateTimer];
1540 }
1541 void activate_timer(frontend *fe)
1542 {
1543 [fe->window activateTimer];
1544 }
1545
1546 /* ----------------------------------------------------------------------
1547 * AppController: the object which receives the messages from all
1548 * menu selections that aren't standard OS X functions.
1549 */
1550 @interface AppController : NSObject
1551 {
1552 }
1553 - (void)newGameWindow:(id)sender;
1554 - (void)about:(id)sender;
1555 @end
1556
1557 @implementation AppController
1558
1559 - (void)newGameWindow:(id)sender
1560 {
1561 const game *g = [sender getPayload];
1562 id win;
1563
1564 win = [[GameWindow alloc] initWithGame:g];
1565 [win makeKeyAndOrderFront:self];
1566 }
1567
1568 - (void)about:(id)sender
1569 {
1570 id win;
1571
1572 win = [[AboutBox alloc] init];
1573 [win makeKeyAndOrderFront:self];
1574 }
1575
1576 - (NSMenu *)applicationDockMenu:(NSApplication *)sender
1577 {
1578 NSMenu *menu = newmenu("Dock Menu");
1579 {
1580 int i;
1581
1582 for (i = 0; i < gamecount; i++) {
1583 id item =
1584 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1585 menu, gamelist[i]->name, "", self,
1586 @selector(newGameWindow:));
1587 [item setPayload:(void *)gamelist[i]];
1588 }
1589 }
1590 return menu;
1591 }
1592
1593 @end
1594
1595 /* ----------------------------------------------------------------------
1596 * Main program. Constructs the menus and runs the application.
1597 */
1598 int main(int argc, char **argv)
1599 {
1600 NSAutoreleasePool *pool;
1601 NSMenu *menu;
1602 AppController *controller;
1603 NSImage *icon;
1604
1605 pool = [[NSAutoreleasePool alloc] init];
1606
1607 icon = [NSImage imageNamed:@"NSApplicationIcon"];
1608 [NSApplication sharedApplication];
1609 [NSApp setApplicationIconImage:icon];
1610
1611 controller = [[[AppController alloc] init] autorelease];
1612 [NSApp setDelegate:controller];
1613
1614 [NSApp setMainMenu: newmenu("Main Menu")];
1615
1616 menu = newsubmenu([NSApp mainMenu], "Apple Menu");
1617 newitem(menu, "About Puzzles", "", NULL, @selector(about:));
1618 [menu addItem:[NSMenuItem separatorItem]];
1619 [NSApp setServicesMenu:newsubmenu(menu, "Services")];
1620 [menu addItem:[NSMenuItem separatorItem]];
1621 newitem(menu, "Hide Puzzles", "h", NSApp, @selector(hide:));
1622 newitem(menu, "Hide Others", "o-h", NSApp, @selector(hideOtherApplications:));
1623 newitem(menu, "Show All", "", NSApp, @selector(unhideAllApplications:));
1624 [menu addItem:[NSMenuItem separatorItem]];
1625 newitem(menu, "Quit", "q", NSApp, @selector(terminate:));
1626 [NSApp setAppleMenu: menu];
1627
1628 menu = newsubmenu([NSApp mainMenu], "File");
1629 newitem(menu, "Open", "o", NULL, @selector(loadSavedGame:));
1630 newitem(menu, "Save As", "s", NULL, @selector(saveGame:));
1631 newitem(menu, "New Game", "n", NULL, @selector(newGame:));
1632 newitem(menu, "Restart Game", "r", NULL, @selector(restartGame:));
1633 newitem(menu, "Specific Game", "", NULL, @selector(specificGame:));
1634 newitem(menu, "Specific Random Seed", "", NULL,
1635 @selector(specificRandomGame:));
1636 [menu addItem:[NSMenuItem separatorItem]];
1637 {
1638 NSMenu *submenu = newsubmenu(menu, "New Window");
1639 int i;
1640
1641 for (i = 0; i < gamecount; i++) {
1642 id item =
1643 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1644 submenu, gamelist[i]->name, "", controller,
1645 @selector(newGameWindow:));
1646 [item setPayload:(void *)gamelist[i]];
1647 }
1648 }
1649 [menu addItem:[NSMenuItem separatorItem]];
1650 newitem(menu, "Close", "w", NULL, @selector(performClose:));
1651
1652 menu = newsubmenu([NSApp mainMenu], "Edit");
1653 newitem(menu, "Undo", "z", NULL, @selector(undoMove:));
1654 newitem(menu, "Redo", "S-z", NULL, @selector(redoMove:));
1655 [menu addItem:[NSMenuItem separatorItem]];
1656 newitem(menu, "Cut", "x", NULL, @selector(cut:));
1657 newitem(menu, "Copy", "c", NULL, @selector(copy:));
1658 newitem(menu, "Paste", "v", NULL, @selector(paste:));
1659 [menu addItem:[NSMenuItem separatorItem]];
1660 newitem(menu, "Solve", "S-s", NULL, @selector(solveGame:));
1661
1662 menu = newsubmenu([NSApp mainMenu], "Type");
1663 typemenu = menu;
1664 newitem(menu, "Custom", "", NULL, @selector(customGameType:));
1665
1666 menu = newsubmenu([NSApp mainMenu], "Window");
1667 [NSApp setWindowsMenu: menu];
1668 newitem(menu, "Minimise Window", "m", NULL, @selector(performMiniaturize:));
1669
1670 menu = newsubmenu([NSApp mainMenu], "Help");
1671 newitem(menu, "Puzzles Help", "?", NSApp, @selector(showHelp:));
1672
1673 [NSApp run];
1674 [pool release];
1675
1676 return 0;
1677 }