2 * Mac OS X / Cocoa front end to puzzles.
6 * - I'd like to be able to call up context help for a specific
9 * Mac interface issues that possibly could be done better:
11 * - is there a better approach to frontend_default_colour?
13 * - do we need any more options in the Window menu?
15 * - can / should we be doing anything with the titles of the
16 * configuration boxes?
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
23 * + there's a standard _policy_ on window placement, given in
24 * the HI guidelines. Have to implement it ourselves though,
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.
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
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.
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.
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
68 * Grotty implementation details that could probably be improved:
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
75 * - Resizing is currently very bad; rather than bother to work
76 * out how to resize the NSImageView, I just splatter and
80 #define COMBINED /* we put all the puzzles in one binary in this port */
85 #import <Cocoa/Cocoa.h>
88 /* ----------------------------------------------------------------------
93 * The `Type' menu. We frob this dynamically to allow the user to
94 * choose a preset set of settings from the current game.
101 extern const struct drawing_api osx_drawing;
104 * The NSApplication shared instance, which I'll want to refer to from
105 * a few places here and there.
109 /* ----------------------------------------------------------------------
110 * Miscellaneous support routines that aren't part of any object or
111 * clearly defined subsystem.
114 void fatal(char *fmt, ...)
121 vsnprintf(errorbuf, lenof(errorbuf), fmt, ap);
124 alert = [NSAlert alloc];
126 * We may have come here because we ran out of memory, in which
127 * case it's entirely likely that that alloc will fail, so we
128 * should have a fallback of some sort.
131 fprintf(stderr, "fatal error (and NSAlert failed): %s\n", errorbuf);
133 alert = [[alert init] autorelease];
134 [alert addButtonWithTitle:@"Oh dear"];
135 [alert setInformativeText:[NSString stringWithUTF8String:errorbuf]];
141 void frontend_default_colour(frontend *fe, float *output)
143 /* FIXME: Is there a system default we can tap into for this? */
144 output[0] = output[1] = output[2] = 0.8F;
147 void get_random_seed(void **randseed, int *randseedsize)
149 time_t *tp = snew(time_t);
151 *randseed = (void *)tp;
152 *randseedsize = sizeof(time_t);
155 static void savefile_write(void *wctx, void *buf, int len)
157 FILE *fp = (FILE *)wctx;
158 fwrite(buf, 1, len, fp);
161 static int savefile_read(void *wctx, void *buf, int len)
163 FILE *fp = (FILE *)wctx;
166 ret = fread(buf, 1, len, fp);
171 * Since this front end does not support printing (yet), we need
172 * this stub to satisfy the reference in midend_print_puzzle().
174 void document_add_puzzle(document *doc, const game *game, game_params *par,
175 game_state *st, game_state *st2)
180 * setAppleMenu isn't listed in the NSApplication header, but an
181 * NSApp responds to it, so we're adding it here to silence
182 * warnings. (This was removed from the headers in 10.4, so we
183 * only need to include it for 10.4+.)
185 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1040
186 @interface NSApplication(NSAppleMenu)
187 - (void)setAppleMenu:(NSMenu *)menu;
191 /* ----------------------------------------------------------------------
192 * Tiny extension to NSMenuItem which carries a payload of a `void
193 * *', allowing several menu items to invoke the same message but
194 * pass different data through it.
196 @interface DataMenuItem : NSMenuItem
200 - (void)setPayload:(void *)d;
201 - (void *)getPayload;
203 @implementation DataMenuItem
204 - (void)setPayload:(void *)d
214 /* ----------------------------------------------------------------------
215 * Utility routines for constructing OS X menus.
218 NSMenu *newmenu(const char *title)
220 return [[[NSMenu allocWithZone:[NSMenu menuZone]]
221 initWithTitle:[NSString stringWithUTF8String:title]]
225 NSMenu *newsubmenu(NSMenu *parent, const char *title)
230 item = [[[NSMenuItem allocWithZone:[NSMenu menuZone]]
231 initWithTitle:[NSString stringWithUTF8String:title]
235 child = newmenu(title);
236 [item setEnabled:YES];
237 [item setSubmenu:child];
238 [parent addItem:item];
242 id initnewitem(NSMenuItem *item, NSMenu *parent, const char *title,
243 const char *key, id target, SEL action)
245 unsigned mask = NSCommandKeyMask;
247 if (key[strcspn(key, "-")]) {
248 while (*key && *key != '-') {
249 int c = tolower((unsigned char)*key);
251 mask |= NSShiftKeyMask;
252 } else if (c == 'o' || c == 'a') {
253 mask |= NSAlternateKeyMask;
261 item = [[item initWithTitle:[NSString stringWithUTF8String:title]
263 keyEquivalent:[NSString stringWithUTF8String:key]]
267 [item setKeyEquivalentModifierMask: mask];
269 [item setEnabled:YES];
270 [item setTarget:target];
271 [item setAction:action];
273 [parent addItem:item];
278 NSMenuItem *newitem(NSMenu *parent, char *title, char *key,
279 id target, SEL action)
281 return initnewitem([NSMenuItem allocWithZone:[NSMenu menuZone]],
282 parent, title, key, target, action);
285 /* ----------------------------------------------------------------------
291 @interface AboutBox : NSWindow
297 @implementation AboutBox
305 NSFont *font1 = [NSFont systemFontOfSize:0];
306 NSFont *font2 = [NSFont boldSystemFontOfSize:[font1 pointSize] * 1.1];
307 const int border = 24;
312 * Construct the controls that go in the About box.
315 iv = [[NSImageView alloc] initWithFrame:NSMakeRect(0,0,64,64)];
316 [iv setImage:[NSImage imageNamed:@"NSApplicationIcon"]];
317 views[nviews++] = iv;
319 tf = [[NSTextField alloc]
320 initWithFrame:NSMakeRect(0,0,400,1)];
322 [tf setSelectable:NO];
324 [tf setDrawsBackground:NO];
326 [tf setStringValue:@"Simon Tatham's Portable Puzzle Collection"];
328 views[nviews++] = tf;
330 tf = [[NSTextField alloc]
331 initWithFrame:NSMakeRect(0,0,400,1)];
333 [tf setSelectable:NO];
335 [tf setDrawsBackground:NO];
337 [tf setStringValue:[NSString stringWithUTF8String:ver]];
339 views[nviews++] = tf;
342 * Lay the controls out.
344 totalrect = NSMakeRect(0,0,0,0);
345 for (i = 0; i < nviews; i++) {
346 NSRect r = [views[i] frame];
347 if (totalrect.size.width < r.size.width)
348 totalrect.size.width = r.size.width;
349 totalrect.size.height += border + r.size.height;
351 totalrect.size.width += 2 * border;
352 totalrect.size.height += border;
353 y = totalrect.size.height;
354 for (i = 0; i < nviews; i++) {
355 NSRect r = [views[i] frame];
356 r.origin.x = (totalrect.size.width - r.size.width) / 2;
357 y -= border + r.size.height;
359 [views[i] setFrame:r];
362 self = [super initWithContentRect:totalrect
363 styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
364 NSClosableWindowMask)
365 backing:NSBackingStoreBuffered
368 for (i = 0; i < nviews; i++)
369 [[self contentView] addSubview:views[i]];
371 [self center]; /* :-) */
377 /* ----------------------------------------------------------------------
378 * The front end presented to midend.c.
380 * This is mostly a subclass of NSWindow. The actual `frontend'
381 * structure passed to the midend contains a variety of pointers,
382 * including that window object but also including the image we
383 * draw on, an ImageView to display it in the window, and so on.
399 @interface MyImageView : NSImageView
403 - (void)setWindow:(GameWindow *)win;
404 - (void)mouseEvent:(NSEvent *)ev button:(int)b;
405 - (void)mouseDown:(NSEvent *)ev;
406 - (void)mouseDragged:(NSEvent *)ev;
407 - (void)mouseUp:(NSEvent *)ev;
408 - (void)rightMouseDown:(NSEvent *)ev;
409 - (void)rightMouseDragged:(NSEvent *)ev;
410 - (void)rightMouseUp:(NSEvent *)ev;
411 - (void)otherMouseDown:(NSEvent *)ev;
412 - (void)otherMouseDragged:(NSEvent *)ev;
413 - (void)otherMouseUp:(NSEvent *)ev;
416 @interface GameWindow : NSWindow
421 struct timeval last_time;
426 NSView **cfg_controls;
430 - (id)initWithGame:(const game *)g;
432 - (void)processButton:(int)b x:(int)x y:(int)y;
433 - (void)processKey:(int)b;
434 - (void)keyDown:(NSEvent *)ev;
435 - (void)activateTimer;
436 - (void)deactivateTimer;
437 - (void)setStatusLine:(char *)text;
438 - (void)resizeForNewGameParams;
439 - (void)updateTypeMenuTick;
442 @implementation MyImageView
444 - (void)setWindow:(GameWindow *)win
449 - (void)mouseEvent:(NSEvent *)ev button:(int)b
451 NSPoint point = [self convertPoint:[ev locationInWindow] fromView:nil];
452 [ourwin processButton:b x:point.x y:point.y];
455 - (void)mouseDown:(NSEvent *)ev
457 unsigned mod = [ev modifierFlags];
458 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_BUTTON :
459 (mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
462 - (void)mouseDragged:(NSEvent *)ev
464 unsigned mod = [ev modifierFlags];
465 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_DRAG :
466 (mod & NSShiftKeyMask) ? MIDDLE_DRAG :
469 - (void)mouseUp:(NSEvent *)ev
471 unsigned mod = [ev modifierFlags];
472 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_RELEASE :
473 (mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
476 - (void)rightMouseDown:(NSEvent *)ev
478 unsigned mod = [ev modifierFlags];
479 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
482 - (void)rightMouseDragged:(NSEvent *)ev
484 unsigned mod = [ev modifierFlags];
485 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_DRAG :
488 - (void)rightMouseUp:(NSEvent *)ev
490 unsigned mod = [ev modifierFlags];
491 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
494 - (void)otherMouseDown:(NSEvent *)ev
496 [self mouseEvent:ev button:MIDDLE_BUTTON];
498 - (void)otherMouseDragged:(NSEvent *)ev
500 [self mouseEvent:ev button:MIDDLE_DRAG];
502 - (void)otherMouseUp:(NSEvent *)ev
504 [self mouseEvent:ev button:MIDDLE_RELEASE];
508 @implementation GameWindow
509 - (void)setupContentView
515 frame = [status frame];
516 frame.origin.y = frame.size.height;
522 midend_size(me, &w, &h, FALSE);
523 frame.size.width = w;
524 frame.size.height = h;
528 fe.image = [[NSImage alloc] initWithSize:frame.size];
529 fe.view = [[MyImageView alloc] initWithFrame:frame];
530 [fe.view setImage:fe.image];
531 [fe.view setWindow:self];
535 [[self contentView] addSubview:fe.view];
537 - (id)initWithGame:(const game *)g
539 NSRect rect = { {0,0}, {0,0} }, rect2;
546 me = midend_new(&fe, ourgame, &osx_drawing, &fe);
548 * If we ever need to open a fresh window using a provided game
549 * ID, I think the right thing is to move most of this method
550 * into a new initWithGame:gameID: method, and have
551 * initWithGame: simply call that one and pass it NULL.
555 midend_size(me, &w, &h, FALSE);
557 rect.size.height = h;
562 * Create the status bar, which will just be an NSTextField.
564 if (midend_wants_statusbar(me)) {
565 status = [[NSTextField alloc] initWithFrame:NSMakeRect(0,0,100,50)];
566 [status setEditable:NO];
567 [status setSelectable:NO];
568 [status setBordered:YES];
569 [status setBezeled:YES];
570 [status setBezelStyle:NSTextFieldSquareBezel];
571 [status setDrawsBackground:YES];
572 [[status cell] setTitle:@""];
574 rect2 = [status frame];
575 rect.size.height += rect2.size.height;
576 rect2.size.width = rect.size.width;
577 rect2.origin.x = rect2.origin.y = 0;
578 [status setFrame:rect2];
582 self = [super initWithContentRect:rect
583 styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
584 NSClosableWindowMask)
585 backing:NSBackingStoreBuffered
587 [self setTitle:[NSString stringWithUTF8String:ourgame->name]];
593 colours = midend_colours(me, &ncolours);
594 fe.ncolours = ncolours;
595 fe.colours = snewn(ncolours, NSColor *);
597 for (i = 0; i < ncolours; i++) {
598 fe.colours[i] = [[NSColor colorWithDeviceRed:colours[i*3]
599 green:colours[i*3+1] blue:colours[i*3+2]
604 [self setupContentView];
606 [[self contentView] addSubview:status];
607 [self setIgnoresMouseEvents:NO];
609 [self center]; /* :-) */
617 for (i = 0; i < fe.ncolours; i++) {
618 [fe.colours[i] release];
625 - (void)processButton:(int)b x:(int)x y:(int)y
627 if (!midend_process_key(me, x, fe.h - 1 - y, b))
631 - (void)processKey:(int)b
633 if (!midend_process_key(me, -1, -1, b))
637 - (void)keyDown:(NSEvent *)ev
639 NSString *s = [ev characters];
640 int i, n = [s length];
642 for (i = 0; i < n; i++) {
643 int c = [s characterAtIndex:i];
646 * ASCII gets passed straight to midend_process_key.
647 * Anything above that has to be translated to our own
648 * function key codes.
653 case NSUpArrowFunctionKey:
657 case NSDownArrowFunctionKey:
661 case NSLeftArrowFunctionKey:
665 case NSRightArrowFunctionKey:
674 if ([ev modifierFlags] & NSShiftKeyMask)
676 if ([ev modifierFlags] & NSControlKeyMask)
681 if (c >= '0' && c <= '9' && ([ev modifierFlags] & NSNumericPadKeyMask))
688 - (void)activateTimer
693 timer = [NSTimer scheduledTimerWithTimeInterval:0.02
694 target:self selector:@selector(timerTick:)
695 userInfo:nil repeats:YES];
696 gettimeofday(&last_time, NULL);
699 - (void)deactivateTimer
708 - (void)timerTick:(id)sender
712 gettimeofday(&now, NULL);
713 elapsed = ((now.tv_usec - last_time.tv_usec) * 0.000001F +
714 (now.tv_sec - last_time.tv_sec));
715 midend_timer(me, elapsed);
719 - (void)showError:(char *)message
723 alert = [[[NSAlert alloc] init] autorelease];
724 [alert addButtonWithTitle:@"Bah"];
725 [alert setInformativeText:[NSString stringWithUTF8String:message]];
726 [alert beginSheetModalForWindow:self modalDelegate:nil
727 didEndSelector:NULL contextInfo:nil];
730 - (void)newGame:(id)sender
732 [self processKey:'n'];
734 - (void)restartGame:(id)sender
736 midend_restart_game(me);
738 - (void)saveGame:(id)sender
740 NSSavePanel *sp = [NSSavePanel savePanel];
742 if ([sp runModal] == NSFileHandlingPanelOKButton) {
743 const char *name = [[sp filename] UTF8String];
745 FILE *fp = fopen(name, "w");
748 [self showError:"Unable to open save file"];
752 midend_serialise(me, savefile_write, fp);
757 - (void)loadSavedGame:(id)sender
759 NSOpenPanel *op = [NSOpenPanel openPanel];
761 [op setAllowsMultipleSelection:NO];
763 if ([op runModalForTypes:nil] == NSOKButton) {
764 const char *name = [[[op filenames] objectAtIndex:0] cString];
767 FILE *fp = fopen(name, "r");
770 [self showError:"Unable to open saved game file"];
774 err = midend_deserialise(me, savefile_read, fp);
779 [self showError:err];
783 [self resizeForNewGameParams];
784 [self updateTypeMenuTick];
787 - (void)undoMove:(id)sender
789 [self processKey:'u'];
791 - (void)redoMove:(id)sender
793 [self processKey:'r'&0x1F];
796 - (void)copy:(id)sender
800 if ((text = midend_text_format(me)) != NULL) {
801 NSPasteboard *pb = [NSPasteboard generalPasteboard];
802 NSArray *a = [NSArray arrayWithObject:NSStringPboardType];
803 [pb declareTypes:a owner:nil];
804 [pb setString:[NSString stringWithUTF8String:text]
805 forType:NSStringPboardType];
810 - (void)solveGame:(id)sender
814 msg = midend_solve(me);
817 [self showError:msg];
820 - (BOOL)validateMenuItem:(NSMenuItem *)item
822 if ([item action] == @selector(copy:))
823 return (ourgame->can_format_as_text_ever &&
824 midend_can_format_as_text_now(me) ? YES : NO);
825 else if ([item action] == @selector(solveGame:))
826 return (ourgame->can_solve ? YES : NO);
828 return [super validateMenuItem:item];
831 - (void)clearTypeMenu
833 while ([typemenu numberOfItems] > 1)
834 [typemenu removeItemAtIndex:0];
835 [[typemenu itemAtIndex:0] setState:NSOffState];
838 - (void)updateTypeMenuTick
842 total = [typemenu numberOfItems];
843 n = midend_which_preset(me);
845 n = total - 1; /* that's always where "Custom" lives */
846 for (i = 0; i < total; i++)
847 [[typemenu itemAtIndex:i] setState:(i == n ? NSOnState : NSOffState)];
850 - (void)becomeKeyWindow
854 [self clearTypeMenu];
856 [super becomeKeyWindow];
858 n = midend_num_presets(me);
861 [typemenu insertItem:[NSMenuItem separatorItem] atIndex:0];
867 midend_fetch_preset(me, n, &name, ¶ms);
869 item = [[[DataMenuItem alloc]
870 initWithTitle:[NSString stringWithUTF8String:name]
871 action:NULL keyEquivalent:@""]
874 [item setEnabled:YES];
875 [item setTarget:self];
876 [item setAction:@selector(presetGame:)];
877 [item setPayload:params];
879 [typemenu insertItem:item atIndex:0];
883 [self updateTypeMenuTick];
886 - (void)resignKeyWindow
888 [self clearTypeMenu];
889 [super resignKeyWindow];
894 [self clearTypeMenu];
898 - (void)resizeForNewGameParams
904 midend_size(me, &w, &h, FALSE);
911 NSRect frame = [status frame];
912 size.height += frame.size.height;
913 frame.size.width = size.width;
914 [status setFrame:frame];
918 NSDisableScreenUpdates();
920 [self setContentSize:size];
921 [self setupContentView];
923 NSEnableScreenUpdates();
927 - (void)presetGame:(id)sender
929 game_params *params = [sender getPayload];
931 midend_set_params(me, params);
934 [self resizeForNewGameParams];
935 [self updateTypeMenuTick];
938 - (void)startConfigureSheet:(int)which
940 NSButton *ok, *cancel;
941 int actw, acth, leftw, rightw, totalw, h, thish, y;
943 NSRect rect, tmprect;
944 const int SPACING = 16;
952 assert(sheet == NULL);
955 * Every control we create here is going to have this size
956 * until we tell it to calculate a better one.
958 tmprect = NSMakeRect(0, 0, 100, 50);
961 * Set up OK and Cancel buttons. (Actually, MacOS doesn't seem
962 * to be fond of generic OK and Cancel wording, so I'm going to
963 * rename them to something nicer.)
967 cancel = [[NSButton alloc] initWithFrame:tmprect];
968 [cancel setBezelStyle:NSRoundedBezelStyle];
969 [cancel setTitle:@"Abandon"];
970 [cancel setTarget:self];
971 [cancel setKeyEquivalent:@"\033"];
972 [cancel setAction:@selector(sheetCancelButton:)];
974 rect = [cancel frame];
975 if (actw < rect.size.width) actw = rect.size.width;
976 if (acth < rect.size.height) acth = rect.size.height;
978 ok = [[NSButton alloc] initWithFrame:tmprect];
979 [ok setBezelStyle:NSRoundedBezelStyle];
980 [ok setTitle:@"Accept"];
982 [ok setKeyEquivalent:@"\r"];
983 [ok setAction:@selector(sheetOKButton:)];
986 if (actw < rect.size.width) actw = rect.size.width;
987 if (acth < rect.size.height) acth = rect.size.height;
989 totalw = SPACING + 2 * actw;
990 h = 2 * SPACING + acth;
993 * Now fetch the midend config data and go through it creating
996 cfg = midend_get_config(me, which, &title);
997 sfree(title); /* FIXME: should we use this somehow? */
1000 cfg_ncontrols = cfg_controlsize = 0;
1001 cfg_controls = NULL;
1003 for (i = cfg; i->type != C_END; i++) {
1004 if (cfg_controlsize < cfg_ncontrols + 5) {
1005 cfg_controlsize = cfg_ncontrols + 32;
1006 cfg_controls = sresize(cfg_controls, cfg_controlsize, NSView *);
1014 * Two NSTextFields, one being a label and the other
1015 * being an edit box.
1018 tf = [[NSTextField alloc] initWithFrame:tmprect];
1019 [tf setEditable:NO];
1020 [tf setSelectable:NO];
1021 [tf setBordered:NO];
1022 [tf setDrawsBackground:NO];
1023 [[tf cell] setTitle:[NSString stringWithUTF8String:i->name]];
1026 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1027 if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
1028 cfg_controls[cfg_ncontrols++] = tf;
1030 tf = [[NSTextField alloc] initWithFrame:tmprect];
1031 [tf setEditable:YES];
1032 [tf setSelectable:YES];
1033 [tf setBordered:YES];
1034 [[tf cell] setTitle:[NSString stringWithUTF8String:i->sval]];
1038 * We impose a minimum and maximum width on editable
1039 * NSTextFields. If we allow them to size themselves to
1040 * the contents of the text within them, then they will
1041 * look very silly if that text is only one or two
1042 * characters, and equally silly if it's an absolutely
1043 * enormous Rectangles or Pattern game ID!
1045 if (rect.size.width < 75) rect.size.width = 75;
1046 if (rect.size.width > 400) rect.size.width = 400;
1048 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1049 if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
1050 cfg_controls[cfg_ncontrols++] = tf;
1055 * A checkbox is an NSButton with a type of
1058 b = [[NSButton alloc] initWithFrame:tmprect];
1059 [b setBezelStyle:NSRoundedBezelStyle];
1060 [b setButtonType:NSSwitchButton];
1061 [b setTitle:[NSString stringWithUTF8String:i->name]];
1063 [b setState:(i->ival ? NSOnState : NSOffState)];
1065 if (totalw < rect.size.width + 1) totalw = rect.size.width + 1;
1066 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1067 cfg_controls[cfg_ncontrols++] = b;
1072 * A pop-up menu control is an NSPopUpButton, which
1073 * takes an embedded NSMenu. We also need an
1074 * NSTextField to act as a label.
1077 tf = [[NSTextField alloc] initWithFrame:tmprect];
1078 [tf setEditable:NO];
1079 [tf setSelectable:NO];
1080 [tf setBordered:NO];
1081 [tf setDrawsBackground:NO];
1082 [[tf cell] setTitle:[NSString stringWithUTF8String:i->name]];
1085 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1086 if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
1087 cfg_controls[cfg_ncontrols++] = tf;
1089 pb = [[NSPopUpButton alloc] initWithFrame:tmprect pullsDown:NO];
1090 [pb setBezelStyle:NSRoundedBezelStyle];
1100 while (*p && *p != c) p++;
1102 copy = snewn((p-q) + 1, char);
1103 memcpy(copy, q, p-q);
1105 [pb addItemWithTitle:[NSString stringWithUTF8String:copy]];
1111 [pb selectItemAtIndex:i->ival];
1115 if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
1116 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1117 cfg_controls[cfg_ncontrols++] = pb;
1121 h += SPACING + thish;
1124 if (totalw < leftw + SPACING + rightw)
1125 totalw = leftw + SPACING + rightw;
1126 if (totalw > leftw + SPACING + rightw) {
1127 int excess = totalw - (leftw + SPACING + rightw);
1128 int leftexcess = leftw * excess / (leftw + rightw);
1129 int rightexcess = excess - leftexcess;
1130 leftw += leftexcess;
1131 rightw += rightexcess;
1135 * Now go through the list again, setting the final position
1140 for (i = cfg; i->type != C_END; i++) {
1147 * These two are treated identically, since both expect
1148 * a control on the left and another on the right.
1150 rect = [cfg_controls[k] frame];
1151 if (thish < rect.size.height + 1)
1152 thish = rect.size.height + 1;
1153 rect = [cfg_controls[k+1] frame];
1154 if (thish < rect.size.height + 1)
1155 thish = rect.size.height + 1;
1156 rect = [cfg_controls[k] frame];
1157 rect.origin.y = y - thish/2 - rect.size.height/2;
1158 rect.origin.x = SPACING;
1159 rect.size.width = leftw;
1160 [cfg_controls[k] setFrame:rect];
1161 rect = [cfg_controls[k+1] frame];
1162 rect.origin.y = y - thish/2 - rect.size.height/2;
1163 rect.origin.x = 2 * SPACING + leftw;
1164 rect.size.width = rightw;
1165 [cfg_controls[k+1] setFrame:rect];
1170 rect = [cfg_controls[k] frame];
1171 if (thish < rect.size.height + 1)
1172 thish = rect.size.height + 1;
1173 rect.origin.y = y - thish/2 - rect.size.height/2;
1174 rect.origin.x = SPACING;
1175 rect.size.width = totalw;
1176 [cfg_controls[k] setFrame:rect];
1183 assert(k == cfg_ncontrols);
1185 [cancel setFrame:NSMakeRect(SPACING+totalw/4-actw/2, SPACING, actw, acth)];
1186 [ok setFrame:NSMakeRect(SPACING+3*totalw/4-actw/2, SPACING, actw, acth)];
1188 sheet = [[NSWindow alloc]
1189 initWithContentRect:NSMakeRect(0,0,totalw + 2*SPACING,h)
1190 styleMask:NSTitledWindowMask | NSClosableWindowMask
1191 backing:NSBackingStoreBuffered
1194 [[sheet contentView] addSubview:cancel];
1195 [[sheet contentView] addSubview:ok];
1197 for (k = 0; k < cfg_ncontrols; k++)
1198 [[sheet contentView] addSubview:cfg_controls[k]];
1200 [app beginSheet:sheet modalForWindow:self
1201 modalDelegate:nil didEndSelector:NULL contextInfo:nil];
1204 - (void)specificGame:(id)sender
1206 [self startConfigureSheet:CFG_DESC];
1209 - (void)specificRandomGame:(id)sender
1211 [self startConfigureSheet:CFG_SEED];
1214 - (void)customGameType:(id)sender
1216 [self startConfigureSheet:CFG_SETTINGS];
1219 - (void)sheetEndWithStatus:(BOOL)update
1221 assert(sheet != NULL);
1222 [app endSheet:sheet];
1223 [sheet orderOut:self];
1231 for (i = cfg; i->type != C_END; i++) {
1235 i->sval = dupstr([[[(id)cfg_controls[k+1] cell]
1236 title] UTF8String]);
1240 i->ival = [(id)cfg_controls[k] state] == NSOnState;
1244 i->ival = [(id)cfg_controls[k+1] indexOfSelectedItem];
1250 error = midend_set_config(me, cfg_which, cfg);
1252 NSAlert *alert = [[[NSAlert alloc] init] autorelease];
1253 [alert addButtonWithTitle:@"Bah"];
1254 [alert setInformativeText:[NSString stringWithUTF8String:error]];
1255 [alert beginSheetModalForWindow:self modalDelegate:nil
1256 didEndSelector:NULL contextInfo:nil];
1258 midend_new_game(me);
1259 [self resizeForNewGameParams];
1260 [self updateTypeMenuTick];
1263 sfree(cfg_controls);
1264 cfg_controls = NULL;
1266 - (void)sheetOKButton:(id)sender
1268 [self sheetEndWithStatus:YES];
1270 - (void)sheetCancelButton:(id)sender
1272 [self sheetEndWithStatus:NO];
1275 - (void)setStatusLine:(char *)text
1277 [[status cell] setTitle:[NSString stringWithUTF8String:text]];
1283 * Drawing routines called by the midend.
1285 static void osx_draw_polygon(void *handle, int *coords, int npoints,
1286 int fillcolour, int outlinecolour)
1288 frontend *fe = (frontend *)handle;
1289 NSBezierPath *path = [NSBezierPath bezierPath];
1292 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1294 for (i = 0; i < npoints; i++) {
1295 NSPoint p = { coords[i*2] + 0.5, fe->h - coords[i*2+1] - 0.5 };
1297 [path moveToPoint:p];
1299 [path lineToPoint:p];
1304 if (fillcolour >= 0) {
1305 assert(fillcolour >= 0 && fillcolour < fe->ncolours);
1306 [fe->colours[fillcolour] set];
1310 assert(outlinecolour >= 0 && outlinecolour < fe->ncolours);
1311 [fe->colours[outlinecolour] set];
1314 static void osx_draw_circle(void *handle, int cx, int cy, int radius,
1315 int fillcolour, int outlinecolour)
1317 frontend *fe = (frontend *)handle;
1318 NSBezierPath *path = [NSBezierPath bezierPath];
1320 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1322 [path appendBezierPathWithArcWithCenter:NSMakePoint(cx+0.5, fe->h-cy-0.5)
1323 radius:radius startAngle:0.0 endAngle:360.0];
1327 if (fillcolour >= 0) {
1328 assert(fillcolour >= 0 && fillcolour < fe->ncolours);
1329 [fe->colours[fillcolour] set];
1333 assert(outlinecolour >= 0 && outlinecolour < fe->ncolours);
1334 [fe->colours[outlinecolour] set];
1337 static void osx_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
1339 frontend *fe = (frontend *)handle;
1340 NSBezierPath *path = [NSBezierPath bezierPath];
1341 NSPoint p1 = { x1 + 0.5, fe->h - y1 - 0.5 };
1342 NSPoint p2 = { x2 + 0.5, fe->h - y2 - 0.5 };
1344 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1346 assert(colour >= 0 && colour < fe->ncolours);
1347 [fe->colours[colour] set];
1349 [path moveToPoint:p1];
1350 [path lineToPoint:p2];
1352 NSRectFill(NSMakeRect(x1, fe->h-y1-1, 1, 1));
1353 NSRectFill(NSMakeRect(x2, fe->h-y2-1, 1, 1));
1355 static void osx_draw_rect(void *handle, int x, int y, int w, int h, int colour)
1357 frontend *fe = (frontend *)handle;
1358 NSRect r = { {x, fe->h - y - h}, {w,h} };
1360 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1362 assert(colour >= 0 && colour < fe->ncolours);
1363 [fe->colours[colour] set];
1367 static void osx_draw_text(void *handle, int x, int y, int fonttype,
1368 int fontsize, int align, int colour, char *text)
1370 frontend *fe = (frontend *)handle;
1371 NSString *string = [NSString stringWithUTF8String:text];
1377 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1379 assert(colour >= 0 && colour < fe->ncolours);
1381 if (fonttype == FONT_FIXED)
1382 font = [NSFont userFixedPitchFontOfSize:fontsize];
1384 font = [NSFont userFontOfSize:fontsize];
1386 attr = [NSDictionary dictionaryWithObjectsAndKeys:
1387 fe->colours[colour], NSForegroundColorAttributeName,
1388 font, NSFontAttributeName, nil];
1391 point.y = fe->h - y;
1393 size = [string sizeWithAttributes:attr];
1394 if (align & ALIGN_HRIGHT)
1395 point.x -= size.width;
1396 else if (align & ALIGN_HCENTRE)
1397 point.x -= size.width / 2;
1398 if (align & ALIGN_VCENTRE)
1399 point.y -= size.height / 2;
1401 [string drawAtPoint:point withAttributes:attr];
1403 static char *osx_text_fallback(void *handle, const char *const *strings,
1407 * We assume OS X can cope with any UTF-8 likely to be emitted
1410 return dupstr(strings[0]);
1417 static blitter *osx_blitter_new(void *handle, int w, int h)
1419 blitter *bl = snew(blitter);
1423 bl->img = [[NSImage alloc] initWithSize:NSMakeSize(w, h)];
1426 static void osx_blitter_free(void *handle, blitter *bl)
1431 static void osx_blitter_save(void *handle, blitter *bl, int x, int y)
1433 frontend *fe = (frontend *)handle;
1434 int sx, sy, sX, sY, dx, dy, dX, dY;
1435 [fe->image unlockFocus];
1436 [bl->img lockFocus];
1439 * Find the intersection of the source and destination rectangles,
1440 * so as to avoid trying to copy from outside the source image,
1441 * which GNUstep dislikes.
1443 * Lower-case x,y coordinates are bottom left box corners;
1444 * upper-case X,Y are the top right.
1446 sx = x; sy = fe->h - y - bl->h;
1447 sX = sx + bl->w; sY = sy + bl->h;
1449 dX = bl->w; dY = bl->h;
1467 [fe->image drawInRect:NSMakeRect(dx, dy, dX-dx, dY-dy)
1468 fromRect:NSMakeRect(sx, sy, sX-sx, sY-sy)
1469 operation:NSCompositeCopy fraction:1.0];
1470 [bl->img unlockFocus];
1471 [fe->image lockFocus];
1475 static void osx_blitter_load(void *handle, blitter *bl, int x, int y)
1477 frontend *fe = (frontend *)handle;
1478 if (x == BLITTER_FROMSAVED && y == BLITTER_FROMSAVED) {
1482 [bl->img drawInRect:NSMakeRect(x, fe->h - y - bl->h, bl->w, bl->h)
1483 fromRect:NSMakeRect(0, 0, bl->w, bl->h)
1484 operation:NSCompositeCopy fraction:1.0];
1486 static void osx_draw_update(void *handle, int x, int y, int w, int h)
1488 frontend *fe = (frontend *)handle;
1489 [fe->view setNeedsDisplayInRect:NSMakeRect(x, fe->h - y - h, w, h)];
1491 static void osx_clip(void *handle, int x, int y, int w, int h)
1493 frontend *fe = (frontend *)handle;
1494 NSRect r = { {x, fe->h - y - h}, {w, h} };
1497 [[NSGraphicsContext currentContext] saveGraphicsState];
1498 [NSBezierPath clipRect:r];
1501 static void osx_unclip(void *handle)
1503 frontend *fe = (frontend *)handle;
1505 [[NSGraphicsContext currentContext] restoreGraphicsState];
1506 fe->clipped = FALSE;
1508 static void osx_start_draw(void *handle)
1510 frontend *fe = (frontend *)handle;
1511 [fe->image lockFocus];
1512 fe->clipped = FALSE;
1514 static void osx_end_draw(void *handle)
1516 frontend *fe = (frontend *)handle;
1517 [fe->image unlockFocus];
1519 static void osx_status_bar(void *handle, char *text)
1521 frontend *fe = (frontend *)handle;
1522 [fe->window setStatusLine:text];
1525 const struct drawing_api osx_drawing = {
1541 NULL, NULL, NULL, NULL, NULL, NULL, /* {begin,end}_{doc,page,puzzle} */
1542 NULL, NULL, /* line_width, line_dotted */
1546 void deactivate_timer(frontend *fe)
1548 [fe->window deactivateTimer];
1550 void activate_timer(frontend *fe)
1552 [fe->window activateTimer];
1555 /* ----------------------------------------------------------------------
1556 * AppController: the object which receives the messages from all
1557 * menu selections that aren't standard OS X functions.
1559 @interface AppController : NSObject <NSApplicationDelegate>
1562 - (void)newGameWindow:(id)sender;
1563 - (void)about:(id)sender;
1566 @implementation AppController
1568 - (void)newGameWindow:(id)sender
1570 const game *g = [sender getPayload];
1573 win = [[GameWindow alloc] initWithGame:g];
1574 [win makeKeyAndOrderFront:self];
1577 - (void)about:(id)sender
1581 win = [[AboutBox alloc] init];
1582 [win makeKeyAndOrderFront:self];
1585 - (NSMenu *)applicationDockMenu:(NSApplication *)sender
1587 NSMenu *menu = newmenu("Dock Menu");
1591 for (i = 0; i < gamecount; i++) {
1593 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1594 menu, gamelist[i]->name, "", self,
1595 @selector(newGameWindow:));
1596 [item setPayload:(void *)gamelist[i]];
1604 /* ----------------------------------------------------------------------
1605 * Main program. Constructs the menus and runs the application.
1607 int main(int argc, char **argv)
1609 NSAutoreleasePool *pool;
1611 AppController *controller;
1614 pool = [[NSAutoreleasePool alloc] init];
1616 icon = [NSImage imageNamed:@"NSApplicationIcon"];
1617 app = [NSApplication sharedApplication];
1618 [app setApplicationIconImage:icon];
1620 controller = [[[AppController alloc] init] autorelease];
1621 [app setDelegate:controller];
1623 [app setMainMenu: newmenu("Main Menu")];
1625 menu = newsubmenu([app mainMenu], "Apple Menu");
1626 newitem(menu, "About Puzzles", "", NULL, @selector(about:));
1627 [menu addItem:[NSMenuItem separatorItem]];
1628 [app setServicesMenu:newsubmenu(menu, "Services")];
1629 [menu addItem:[NSMenuItem separatorItem]];
1630 newitem(menu, "Hide Puzzles", "h", app, @selector(hide:));
1631 newitem(menu, "Hide Others", "o-h", app, @selector(hideOtherApplications:));
1632 newitem(menu, "Show All", "", app, @selector(unhideAllApplications:));
1633 [menu addItem:[NSMenuItem separatorItem]];
1634 newitem(menu, "Quit", "q", app, @selector(terminate:));
1635 [app setAppleMenu: menu];
1637 menu = newsubmenu([app mainMenu], "File");
1638 newitem(menu, "Open", "o", NULL, @selector(loadSavedGame:));
1639 newitem(menu, "Save As", "s", NULL, @selector(saveGame:));
1640 newitem(menu, "New Game", "n", NULL, @selector(newGame:));
1641 newitem(menu, "Restart Game", "r", NULL, @selector(restartGame:));
1642 newitem(menu, "Specific Game", "", NULL, @selector(specificGame:));
1643 newitem(menu, "Specific Random Seed", "", NULL,
1644 @selector(specificRandomGame:));
1645 [menu addItem:[NSMenuItem separatorItem]];
1647 NSMenu *submenu = newsubmenu(menu, "New Window");
1650 for (i = 0; i < gamecount; i++) {
1652 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1653 submenu, gamelist[i]->name, "", controller,
1654 @selector(newGameWindow:));
1655 [item setPayload:(void *)gamelist[i]];
1658 [menu addItem:[NSMenuItem separatorItem]];
1659 newitem(menu, "Close", "w", NULL, @selector(performClose:));
1661 menu = newsubmenu([app mainMenu], "Edit");
1662 newitem(menu, "Undo", "z", NULL, @selector(undoMove:));
1663 newitem(menu, "Redo", "S-z", NULL, @selector(redoMove:));
1664 [menu addItem:[NSMenuItem separatorItem]];
1665 newitem(menu, "Cut", "x", NULL, @selector(cut:));
1666 newitem(menu, "Copy", "c", NULL, @selector(copy:));
1667 newitem(menu, "Paste", "v", NULL, @selector(paste:));
1668 [menu addItem:[NSMenuItem separatorItem]];
1669 newitem(menu, "Solve", "S-s", NULL, @selector(solveGame:));
1671 menu = newsubmenu([app mainMenu], "Type");
1673 newitem(menu, "Custom", "", NULL, @selector(customGameType:));
1675 menu = newsubmenu([app mainMenu], "Window");
1676 [app setWindowsMenu: menu];
1677 newitem(menu, "Minimise Window", "m", NULL, @selector(performMiniaturize:));
1679 menu = newsubmenu([app mainMenu], "Help");
1680 newitem(menu, "Puzzles Help", "?", app, @selector(showHelp:));