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
82 #import <Cocoa/Cocoa.h>
85 /* ----------------------------------------------------------------------
90 * The `Type' menu. We frob this dynamically to allow the user to
91 * choose a preset set of settings from the current game.
95 /* ----------------------------------------------------------------------
96 * Miscellaneous support routines that aren't part of any object or
97 * clearly defined subsystem.
100 void fatal(char *fmt, ...)
107 vsnprintf(errorbuf, lenof(errorbuf), fmt, ap);
110 alert = [NSAlert alloc];
112 * We may have come here because we ran out of memory, in which
113 * case it's entirely likely that that alloc will fail, so we
114 * should have a fallback of some sort.
117 fprintf(stderr, "fatal error (and NSAlert failed): %s\n", errorbuf);
119 alert = [[alert init] autorelease];
120 [alert addButtonWithTitle:@"Oh dear"];
121 [alert setInformativeText:[NSString stringWithCString:errorbuf]];
127 void frontend_default_colour(frontend *fe, float *output)
129 /* FIXME: Is there a system default we can tap into for this? */
130 output[0] = output[1] = output[2] = 0.8F;
133 void get_random_seed(void **randseed, int *randseedsize)
135 time_t *tp = snew(time_t);
137 *randseed = (void *)tp;
138 *randseedsize = sizeof(time_t);
141 /* ----------------------------------------------------------------------
142 * Tiny extension to NSMenuItem which carries a payload of a `void
143 * *', allowing several menu items to invoke the same message but
144 * pass different data through it.
146 @interface DataMenuItem : NSMenuItem
150 - (void)setPayload:(void *)d;
151 - (void *)getPayload;
153 @implementation DataMenuItem
154 - (void)setPayload:(void *)d
164 /* ----------------------------------------------------------------------
165 * Utility routines for constructing OS X menus.
168 NSMenu *newmenu(const char *title)
170 return [[[NSMenu allocWithZone:[NSMenu menuZone]]
171 initWithTitle:[NSString stringWithCString:title]]
175 NSMenu *newsubmenu(NSMenu *parent, const char *title)
180 item = [[[NSMenuItem allocWithZone:[NSMenu menuZone]]
181 initWithTitle:[NSString stringWithCString:title]
185 child = newmenu(title);
186 [item setEnabled:YES];
187 [item setSubmenu:child];
188 [parent addItem:item];
192 id initnewitem(NSMenuItem *item, NSMenu *parent, const char *title,
193 const char *key, id target, SEL action)
195 unsigned mask = NSCommandKeyMask;
197 if (key[strcspn(key, "-")]) {
198 while (*key && *key != '-') {
199 int c = tolower((unsigned char)*key);
201 mask |= NSShiftKeyMask;
202 } else if (c == 'o' || c == 'a') {
203 mask |= NSAlternateKeyMask;
211 item = [[item initWithTitle:[NSString stringWithCString:title]
213 keyEquivalent:[NSString stringWithCString:key]]
217 [item setKeyEquivalentModifierMask: mask];
219 [item setEnabled:YES];
220 [item setTarget:target];
221 [item setAction:action];
223 [parent addItem:item];
228 NSMenuItem *newitem(NSMenu *parent, char *title, char *key,
229 id target, SEL action)
231 return initnewitem([NSMenuItem allocWithZone:[NSMenu menuZone]],
232 parent, title, key, target, action);
235 /* ----------------------------------------------------------------------
241 @interface AboutBox : NSWindow
247 @implementation AboutBox
255 NSFont *font1 = [NSFont systemFontOfSize:0];
256 NSFont *font2 = [NSFont boldSystemFontOfSize:[font1 pointSize] * 1.1];
257 const int border = 24;
262 * Construct the controls that go in the About box.
265 iv = [[NSImageView alloc] initWithFrame:NSMakeRect(0,0,64,64)];
266 [iv setImage:[NSImage imageNamed:@"NSApplicationIcon"]];
267 views[nviews++] = iv;
269 tf = [[NSTextField alloc]
270 initWithFrame:NSMakeRect(0,0,400,1)];
272 [tf setSelectable:NO];
274 [tf setDrawsBackground:NO];
276 [tf setStringValue:@"Simon Tatham's Portable Puzzle Collection"];
278 views[nviews++] = tf;
280 tf = [[NSTextField alloc]
281 initWithFrame:NSMakeRect(0,0,400,1)];
283 [tf setSelectable:NO];
285 [tf setDrawsBackground:NO];
287 [tf setStringValue:[NSString stringWithCString:ver]];
289 views[nviews++] = tf;
292 * Lay the controls out.
294 totalrect = NSMakeRect(0,0,0,0);
295 for (i = 0; i < nviews; i++) {
296 NSRect r = [views[i] frame];
297 if (totalrect.size.width < r.size.width)
298 totalrect.size.width = r.size.width;
299 totalrect.size.height += border + r.size.height;
301 totalrect.size.width += 2 * border;
302 totalrect.size.height += border;
303 y = totalrect.size.height;
304 for (i = 0; i < nviews; i++) {
305 NSRect r = [views[i] frame];
306 r.origin.x = (totalrect.size.width - r.size.width) / 2;
307 y -= border + r.size.height;
309 [views[i] setFrame:r];
312 self = [super initWithContentRect:totalrect
313 styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
314 NSClosableWindowMask)
315 backing:NSBackingStoreBuffered
318 for (i = 0; i < nviews; i++)
319 [[self contentView] addSubview:views[i]];
321 [self center]; /* :-) */
327 /* ----------------------------------------------------------------------
328 * The front end presented to midend.c.
330 * This is mostly a subclass of NSWindow. The actual `frontend'
331 * structure passed to the midend contains a variety of pointers,
332 * including that window object but also including the image we
333 * draw on, an ImageView to display it in the window, and so on.
348 @interface MyImageView : NSImageView
352 - (void)setWindow:(GameWindow *)win;
354 - (void)mouseEvent:(NSEvent *)ev button:(int)b;
355 - (void)mouseDown:(NSEvent *)ev;
356 - (void)mouseDragged:(NSEvent *)ev;
357 - (void)mouseUp:(NSEvent *)ev;
358 - (void)rightMouseDown:(NSEvent *)ev;
359 - (void)rightMouseDragged:(NSEvent *)ev;
360 - (void)rightMouseUp:(NSEvent *)ev;
361 - (void)otherMouseDown:(NSEvent *)ev;
362 - (void)otherMouseDragged:(NSEvent *)ev;
363 - (void)otherMouseUp:(NSEvent *)ev;
366 @interface GameWindow : NSWindow
371 struct timeval last_time;
376 NSView **cfg_controls;
380 - (id)initWithGame:(const game *)g;
382 - (void)processButton:(int)b x:(int)x y:(int)y;
383 - (void)keyDown:(NSEvent *)ev;
384 - (void)activateTimer;
385 - (void)deactivateTimer;
386 - (void)setStatusLine:(char *)text;
389 @implementation MyImageView
391 - (void)setWindow:(GameWindow *)win
401 - (void)mouseEvent:(NSEvent *)ev button:(int)b
403 NSPoint point = [self convertPoint:[ev locationInWindow] fromView:nil];
404 [ourwin processButton:b x:point.x y:point.y];
407 - (void)mouseDown:(NSEvent *)ev
409 unsigned mod = [ev modifierFlags];
410 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_BUTTON :
411 (mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
414 - (void)mouseDragged:(NSEvent *)ev
416 unsigned mod = [ev modifierFlags];
417 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_DRAG :
418 (mod & NSShiftKeyMask) ? MIDDLE_DRAG :
421 - (void)mouseUp:(NSEvent *)ev
423 unsigned mod = [ev modifierFlags];
424 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_RELEASE :
425 (mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
428 - (void)rightMouseDown:(NSEvent *)ev
430 unsigned mod = [ev modifierFlags];
431 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
434 - (void)rightMouseDragged:(NSEvent *)ev
436 unsigned mod = [ev modifierFlags];
437 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_DRAG :
440 - (void)rightMouseUp:(NSEvent *)ev
442 unsigned mod = [ev modifierFlags];
443 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
446 - (void)otherMouseDown:(NSEvent *)ev
448 [self mouseEvent:ev button:MIDDLE_BUTTON];
450 - (void)otherMouseDragged:(NSEvent *)ev
452 [self mouseEvent:ev button:MIDDLE_DRAG];
454 - (void)otherMouseUp:(NSEvent *)ev
456 [self mouseEvent:ev button:MIDDLE_RELEASE];
460 @implementation GameWindow
461 - (void)setupContentView
467 frame = [status frame];
468 frame.origin.y = frame.size.height;
474 midend_size(me, &w, &h, FALSE);
475 frame.size.width = w;
476 frame.size.height = h;
478 fe.image = [[NSImage alloc] initWithSize:frame.size];
479 [fe.image setFlipped:YES];
480 fe.view = [[MyImageView alloc] initWithFrame:frame];
481 [fe.view setImage:fe.image];
482 [fe.view setWindow:self];
486 [[self contentView] addSubview:fe.view];
488 - (id)initWithGame:(const game *)g
490 NSRect rect = { {0,0}, {0,0} }, rect2;
497 me = midend_new(&fe, ourgame);
499 * If we ever need to open a fresh window using a provided game
500 * ID, I think the right thing is to move most of this method
501 * into a new initWithGame:gameID: method, and have
502 * initWithGame: simply call that one and pass it NULL.
506 midend_size(me, &w, &h, FALSE);
508 rect.size.height = h;
511 * Create the status bar, which will just be an NSTextField.
513 if (ourgame->wants_statusbar()) {
514 status = [[NSTextField alloc] initWithFrame:NSMakeRect(0,0,100,50)];
515 [status setEditable:NO];
516 [status setSelectable:NO];
517 [status setBordered:YES];
518 [status setBezeled:YES];
519 [status setBezelStyle:NSTextFieldSquareBezel];
520 [status setDrawsBackground:YES];
521 [[status cell] setTitle:@""];
523 rect2 = [status frame];
524 rect.size.height += rect2.size.height;
525 rect2.size.width = rect.size.width;
526 rect2.origin.x = rect2.origin.y = 0;
527 [status setFrame:rect2];
531 self = [super initWithContentRect:rect
532 styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
533 NSClosableWindowMask)
534 backing:NSBackingStoreBuffered
536 [self setTitle:[NSString stringWithCString:ourgame->name]];
542 colours = midend_colours(me, &ncolours);
543 fe.ncolours = ncolours;
544 fe.colours = snewn(ncolours, NSColor *);
546 for (i = 0; i < ncolours; i++) {
547 fe.colours[i] = [[NSColor colorWithDeviceRed:colours[i*3]
548 green:colours[i*3+1] blue:colours[i*3+2]
553 [self setupContentView];
555 [[self contentView] addSubview:status];
556 [self setIgnoresMouseEvents:NO];
558 [self center]; /* :-) */
566 for (i = 0; i < fe.ncolours; i++) {
567 [fe.colours[i] release];
571 return [super dealloc];
574 - (void)processButton:(int)b x:(int)x y:(int)y
576 if (!midend_process_key(me, x, y, b))
580 - (void)keyDown:(NSEvent *)ev
582 NSString *s = [ev characters];
583 int i, n = [s length];
585 for (i = 0; i < n; i++) {
586 int c = [s characterAtIndex:i];
589 * ASCII gets passed straight to midend_process_key.
590 * Anything above that has to be translated to our own
591 * function key codes.
596 case NSUpArrowFunctionKey:
600 case NSDownArrowFunctionKey:
604 case NSLeftArrowFunctionKey:
608 case NSRightArrowFunctionKey:
617 if ([ev modifierFlags] & NSShiftKeyMask)
619 if ([ev modifierFlags] & NSControlKeyMask)
624 if (c >= '0' && c <= '9' && ([ev modifierFlags] & NSNumericPadKeyMask))
627 [self processButton:c x:-1 y:-1];
631 - (void)activateTimer
636 timer = [NSTimer scheduledTimerWithTimeInterval:0.02
637 target:self selector:@selector(timerTick:)
638 userInfo:nil repeats:YES];
639 gettimeofday(&last_time, NULL);
642 - (void)deactivateTimer
651 - (void)timerTick:(id)sender
655 gettimeofday(&now, NULL);
656 elapsed = ((now.tv_usec - last_time.tv_usec) * 0.000001F +
657 (now.tv_sec - last_time.tv_sec));
658 midend_timer(me, elapsed);
662 - (void)newGame:(id)sender
664 [self processButton:'n' x:-1 y:-1];
666 - (void)restartGame:(id)sender
668 midend_restart_game(me);
670 - (void)undoMove:(id)sender
672 [self processButton:'u' x:-1 y:-1];
674 - (void)redoMove:(id)sender
676 [self processButton:'r'&0x1F x:-1 y:-1];
679 - (void)copy:(id)sender
683 if ((text = midend_text_format(me)) != NULL) {
684 NSPasteboard *pb = [NSPasteboard generalPasteboard];
685 NSArray *a = [NSArray arrayWithObject:NSStringPboardType];
686 [pb declareTypes:a owner:nil];
687 [pb setString:[NSString stringWithCString:text]
688 forType:NSStringPboardType];
693 - (void)solveGame:(id)sender
698 msg = midend_solve(me);
701 alert = [[[NSAlert alloc] init] autorelease];
702 [alert addButtonWithTitle:@"Bah"];
703 [alert setInformativeText:[NSString stringWithCString:msg]];
704 [alert beginSheetModalForWindow:self modalDelegate:nil
705 didEndSelector:nil contextInfo:nil];
709 - (BOOL)validateMenuItem:(NSMenuItem *)item
711 if ([item action] == @selector(copy:))
712 return (ourgame->can_format_as_text ? YES : NO);
713 else if ([item action] == @selector(solveGame:))
714 return (ourgame->can_solve ? YES : NO);
716 return [super validateMenuItem:item];
719 - (void)clearTypeMenu
721 while ([typemenu numberOfItems] > 1)
722 [typemenu removeItemAtIndex:0];
725 - (void)becomeKeyWindow
729 [self clearTypeMenu];
731 [super becomeKeyWindow];
733 n = midend_num_presets(me);
736 [typemenu insertItem:[NSMenuItem separatorItem] atIndex:0];
742 midend_fetch_preset(me, n, &name, ¶ms);
744 item = [[[DataMenuItem alloc]
745 initWithTitle:[NSString stringWithCString:name]
746 action:NULL keyEquivalent:@""]
749 [item setEnabled:YES];
750 [item setTarget:self];
751 [item setAction:@selector(presetGame:)];
752 [item setPayload:params];
754 [typemenu insertItem:item atIndex:0];
759 - (void)resignKeyWindow
761 [self clearTypeMenu];
762 [super resignKeyWindow];
767 [self clearTypeMenu];
771 - (void)resizeForNewGameParams
777 midend_size(me, &w, &h, FALSE);
782 NSRect frame = [status frame];
783 size.height += frame.size.height;
784 frame.size.width = size.width;
785 [status setFrame:frame];
788 NSDisableScreenUpdates();
789 [self setContentSize:size];
790 [self setupContentView];
791 NSEnableScreenUpdates();
794 - (void)presetGame:(id)sender
796 game_params *params = [sender getPayload];
798 midend_set_params(me, params);
801 [self resizeForNewGameParams];
804 - (void)startConfigureSheet:(int)which
806 NSButton *ok, *cancel;
807 int actw, acth, leftw, rightw, totalw, h, thish, y;
809 NSRect rect, tmprect;
810 const int SPACING = 16;
818 assert(sheet == NULL);
821 * Every control we create here is going to have this size
822 * until we tell it to calculate a better one.
824 tmprect = NSMakeRect(0, 0, 100, 50);
827 * Set up OK and Cancel buttons. (Actually, MacOS doesn't seem
828 * to be fond of generic OK and Cancel wording, so I'm going to
829 * rename them to something nicer.)
833 cancel = [[NSButton alloc] initWithFrame:tmprect];
834 [cancel setBezelStyle:NSRoundedBezelStyle];
835 [cancel setTitle:@"Abandon"];
836 [cancel setTarget:self];
837 [cancel setKeyEquivalent:@"\033"];
838 [cancel setAction:@selector(sheetCancelButton:)];
840 rect = [cancel frame];
841 if (actw < rect.size.width) actw = rect.size.width;
842 if (acth < rect.size.height) acth = rect.size.height;
844 ok = [[NSButton alloc] initWithFrame:tmprect];
845 [ok setBezelStyle:NSRoundedBezelStyle];
846 [ok setTitle:@"Accept"];
848 [ok setKeyEquivalent:@"\r"];
849 [ok setAction:@selector(sheetOKButton:)];
852 if (actw < rect.size.width) actw = rect.size.width;
853 if (acth < rect.size.height) acth = rect.size.height;
855 totalw = SPACING + 2 * actw;
856 h = 2 * SPACING + acth;
859 * Now fetch the midend config data and go through it creating
862 cfg = midend_get_config(me, which, &title);
863 sfree(title); /* FIXME: should we use this somehow? */
866 cfg_ncontrols = cfg_controlsize = 0;
869 for (i = cfg; i->type != C_END; i++) {
870 if (cfg_controlsize < cfg_ncontrols + 5) {
871 cfg_controlsize = cfg_ncontrols + 32;
872 cfg_controls = sresize(cfg_controls, cfg_controlsize, NSView *);
880 * Two NSTextFields, one being a label and the other
884 tf = [[NSTextField alloc] initWithFrame:tmprect];
886 [tf setSelectable:NO];
888 [tf setDrawsBackground:NO];
889 [[tf cell] setTitle:[NSString stringWithCString:i->name]];
892 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
893 if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
894 cfg_controls[cfg_ncontrols++] = tf;
896 tf = [[NSTextField alloc] initWithFrame:tmprect];
897 [tf setEditable:YES];
898 [tf setSelectable:YES];
899 [tf setBordered:YES];
900 [[tf cell] setTitle:[NSString stringWithCString:i->sval]];
904 * We impose a minimum and maximum width on editable
905 * NSTextFields. If we allow them to size themselves to
906 * the contents of the text within them, then they will
907 * look very silly if that text is only one or two
908 * characters, and equally silly if it's an absolutely
909 * enormous Rectangles or Pattern game ID!
911 if (rect.size.width < 75) rect.size.width = 75;
912 if (rect.size.width > 400) rect.size.width = 400;
914 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
915 if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
916 cfg_controls[cfg_ncontrols++] = tf;
921 * A checkbox is an NSButton with a type of
924 b = [[NSButton alloc] initWithFrame:tmprect];
925 [b setBezelStyle:NSRoundedBezelStyle];
926 [b setButtonType:NSSwitchButton];
927 [b setTitle:[NSString stringWithCString:i->name]];
929 [b setState:(i->ival ? NSOnState : NSOffState)];
931 if (totalw < rect.size.width + 1) totalw = rect.size.width + 1;
932 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
933 cfg_controls[cfg_ncontrols++] = b;
938 * A pop-up menu control is an NSPopUpButton, which
939 * takes an embedded NSMenu. We also need an
940 * NSTextField to act as a label.
943 tf = [[NSTextField alloc] initWithFrame:tmprect];
945 [tf setSelectable:NO];
947 [tf setDrawsBackground:NO];
948 [[tf cell] setTitle:[NSString stringWithCString:i->name]];
951 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
952 if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
953 cfg_controls[cfg_ncontrols++] = tf;
955 pb = [[NSPopUpButton alloc] initWithFrame:tmprect pullsDown:NO];
956 [pb setBezelStyle:NSRoundedBezelStyle];
966 while (*p && *p != c) p++;
968 [pb addItemWithTitle:[NSString stringWithCString:q
974 [pb selectItemAtIndex:i->ival];
978 if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
979 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
980 cfg_controls[cfg_ncontrols++] = pb;
984 h += SPACING + thish;
987 if (totalw < leftw + SPACING + rightw)
988 totalw = leftw + SPACING + rightw;
989 if (totalw > leftw + SPACING + rightw) {
990 int excess = totalw - (leftw + SPACING + rightw);
991 int leftexcess = leftw * excess / (leftw + rightw);
992 int rightexcess = excess - leftexcess;
994 rightw += rightexcess;
998 * Now go through the list again, setting the final position
1003 for (i = cfg; i->type != C_END; i++) {
1010 * These two are treated identically, since both expect
1011 * a control on the left and another on the right.
1013 rect = [cfg_controls[k] frame];
1014 if (thish < rect.size.height + 1)
1015 thish = rect.size.height + 1;
1016 rect = [cfg_controls[k+1] frame];
1017 if (thish < rect.size.height + 1)
1018 thish = rect.size.height + 1;
1019 rect = [cfg_controls[k] frame];
1020 rect.origin.y = y - thish/2 - rect.size.height/2;
1021 rect.origin.x = SPACING;
1022 rect.size.width = leftw;
1023 [cfg_controls[k] setFrame:rect];
1024 rect = [cfg_controls[k+1] frame];
1025 rect.origin.y = y - thish/2 - rect.size.height/2;
1026 rect.origin.x = 2 * SPACING + leftw;
1027 rect.size.width = rightw;
1028 [cfg_controls[k+1] setFrame:rect];
1033 rect = [cfg_controls[k] frame];
1034 if (thish < rect.size.height + 1)
1035 thish = rect.size.height + 1;
1036 rect.origin.y = y - thish/2 - rect.size.height/2;
1037 rect.origin.x = SPACING;
1038 rect.size.width = totalw;
1039 [cfg_controls[k] setFrame:rect];
1046 assert(k == cfg_ncontrols);
1048 [cancel setFrame:NSMakeRect(SPACING+totalw/4-actw/2, SPACING, actw, acth)];
1049 [ok setFrame:NSMakeRect(SPACING+3*totalw/4-actw/2, SPACING, actw, acth)];
1051 sheet = [[NSWindow alloc]
1052 initWithContentRect:NSMakeRect(0,0,totalw + 2*SPACING,h)
1053 styleMask:NSTitledWindowMask | NSClosableWindowMask
1054 backing:NSBackingStoreBuffered
1057 [[sheet contentView] addSubview:cancel];
1058 [[sheet contentView] addSubview:ok];
1060 for (k = 0; k < cfg_ncontrols; k++)
1061 [[sheet contentView] addSubview:cfg_controls[k]];
1063 [NSApp beginSheet:sheet modalForWindow:self
1064 modalDelegate:nil didEndSelector:nil contextInfo:nil];
1067 - (void)specificGame:(id)sender
1069 [self startConfigureSheet:CFG_DESC];
1072 - (void)specificRandomGame:(id)sender
1074 [self startConfigureSheet:CFG_SEED];
1077 - (void)customGameType:(id)sender
1079 [self startConfigureSheet:CFG_SETTINGS];
1082 - (void)sheetEndWithStatus:(BOOL)update
1084 assert(sheet != NULL);
1085 [NSApp endSheet:sheet];
1086 [sheet orderOut:self];
1094 for (i = cfg; i->type != C_END; i++) {
1098 i->sval = dupstr([[[(id)cfg_controls[k+1] cell]
1103 i->ival = [(id)cfg_controls[k] state] == NSOnState;
1107 i->ival = [(id)cfg_controls[k+1] indexOfSelectedItem];
1113 error = midend_set_config(me, cfg_which, cfg);
1115 NSAlert *alert = [[[NSAlert alloc] init] autorelease];
1116 [alert addButtonWithTitle:@"Bah"];
1117 [alert setInformativeText:[NSString stringWithCString:error]];
1118 [alert beginSheetModalForWindow:self modalDelegate:nil
1119 didEndSelector:nil contextInfo:nil];
1121 midend_new_game(me);
1122 [self resizeForNewGameParams];
1125 sfree(cfg_controls);
1126 cfg_controls = NULL;
1128 - (void)sheetOKButton:(id)sender
1130 [self sheetEndWithStatus:YES];
1132 - (void)sheetCancelButton:(id)sender
1134 [self sheetEndWithStatus:NO];
1137 - (void)setStatusLine:(char *)text
1139 char *rewritten = midend_rewrite_statusbar(me, text);
1140 [[status cell] setTitle:[NSString stringWithCString:rewritten]];
1147 * Drawing routines called by the midend.
1149 void draw_polygon(frontend *fe, int *coords, int npoints,
1150 int fill, int colour)
1152 NSBezierPath *path = [NSBezierPath bezierPath];
1155 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1157 assert(colour >= 0 && colour < fe->ncolours);
1158 [fe->colours[colour] set];
1160 for (i = 0; i < npoints; i++) {
1161 NSPoint p = { coords[i*2] + 0.5, coords[i*2+1] + 0.5 };
1163 [path moveToPoint:p];
1165 [path lineToPoint:p];
1175 void draw_circle(frontend *fe, int cx, int cy, int radius,
1176 int fill, int colour)
1178 NSBezierPath *path = [NSBezierPath bezierPath];
1180 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1182 assert(colour >= 0 && colour < fe->ncolours);
1183 [fe->colours[colour] set];
1185 [path appendBezierPathWithArcWithCenter:NSMakePoint(cx + 0.5, cy + 0.5)
1186 radius:radius startAngle:0.0 endAngle:360.0];
1195 void draw_line(frontend *fe, int x1, int y1, int x2, int y2, int colour)
1197 NSBezierPath *path = [NSBezierPath bezierPath];
1198 NSPoint p1 = { x1 + 0.5, y1 + 0.5 }, p2 = { x2 + 0.5, y2 + 0.5 };
1200 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1202 assert(colour >= 0 && colour < fe->ncolours);
1203 [fe->colours[colour] set];
1205 [path moveToPoint:p1];
1206 [path lineToPoint:p2];
1209 void draw_rect(frontend *fe, int x, int y, int w, int h, int colour)
1211 NSRect r = { {x,y}, {w,h} };
1213 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1215 assert(colour >= 0 && colour < fe->ncolours);
1216 [fe->colours[colour] set];
1220 void draw_text(frontend *fe, int x, int y, int fonttype, int fontsize,
1221 int align, int colour, char *text)
1223 NSString *string = [NSString stringWithCString:text];
1229 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1231 assert(colour >= 0 && colour < fe->ncolours);
1233 if (fonttype == FONT_FIXED)
1234 font = [NSFont userFixedPitchFontOfSize:fontsize];
1236 font = [NSFont userFontOfSize:fontsize];
1238 attr = [NSDictionary dictionaryWithObjectsAndKeys:
1239 fe->colours[colour], NSForegroundColorAttributeName,
1240 font, NSFontAttributeName, nil];
1245 size = [string sizeWithAttributes:attr];
1246 if (align & ALIGN_HRIGHT)
1247 point.x -= size.width;
1248 else if (align & ALIGN_HCENTRE)
1249 point.x -= size.width / 2;
1250 if (align & ALIGN_VCENTRE)
1251 point.y -= size.height / 2;
1253 [string drawAtPoint:point withAttributes:attr];
1260 blitter *blitter_new(int w, int h)
1262 blitter *bl = snew(blitter);
1266 bl->img = [[NSImage alloc] initWithSize:NSMakeSize(w, h)];
1267 [bl->img setFlipped:YES];
1270 void blitter_free(blitter *bl)
1275 void blitter_save(frontend *fe, blitter *bl, int x, int y)
1277 [fe->image unlockFocus];
1278 [bl->img lockFocus];
1279 [fe->image drawInRect:NSMakeRect(0, 0, bl->w, bl->h)
1280 fromRect:NSMakeRect(x, y, bl->w, bl->h)
1281 operation:NSCompositeCopy fraction:1.0];
1282 [bl->img unlockFocus];
1283 [fe->image lockFocus];
1287 void blitter_load(frontend *fe, blitter *bl, int x, int y)
1289 if (x == BLITTER_FROMSAVED && y == BLITTER_FROMSAVED) {
1293 [bl->img drawInRect:NSMakeRect(x, y, bl->w, bl->h)
1294 fromRect:NSMakeRect(0, 0, bl->w, bl->h)
1295 operation:NSCompositeCopy fraction:1.0];
1297 void draw_update(frontend *fe, int x, int y, int w, int h)
1299 [fe->view setNeedsDisplayInRect:NSMakeRect(x,y,w,h)];
1301 void clip(frontend *fe, int x, int y, int w, int h)
1303 NSRect r = { {x,y}, {w,h} };
1306 [[NSGraphicsContext currentContext] saveGraphicsState];
1307 [NSBezierPath clipRect:r];
1310 void unclip(frontend *fe)
1313 [[NSGraphicsContext currentContext] restoreGraphicsState];
1314 fe->clipped = FALSE;
1316 void start_draw(frontend *fe)
1318 [fe->image lockFocus];
1319 fe->clipped = FALSE;
1321 void end_draw(frontend *fe)
1323 [fe->image unlockFocus];
1326 void deactivate_timer(frontend *fe)
1328 [fe->window deactivateTimer];
1330 void activate_timer(frontend *fe)
1332 [fe->window activateTimer];
1335 void status_bar(frontend *fe, char *text)
1337 [fe->window setStatusLine:text];
1340 /* ----------------------------------------------------------------------
1341 * AppController: the object which receives the messages from all
1342 * menu selections that aren't standard OS X functions.
1344 @interface AppController : NSObject
1347 - (void)newGameWindow:(id)sender;
1348 - (void)about:(id)sender;
1351 @implementation AppController
1353 - (void)newGameWindow:(id)sender
1355 const game *g = [sender getPayload];
1358 win = [[GameWindow alloc] initWithGame:g];
1359 [win makeKeyAndOrderFront:self];
1362 - (void)about:(id)sender
1366 win = [[AboutBox alloc] init];
1367 [win makeKeyAndOrderFront:self];
1370 - (NSMenu *)applicationDockMenu:(NSApplication *)sender
1372 NSMenu *menu = newmenu("Dock Menu");
1376 for (i = 0; i < gamecount; i++) {
1378 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1379 menu, gamelist[i]->name, "", self,
1380 @selector(newGameWindow:));
1381 [item setPayload:(void *)gamelist[i]];
1389 /* ----------------------------------------------------------------------
1390 * Main program. Constructs the menus and runs the application.
1392 int main(int argc, char **argv)
1394 NSAutoreleasePool *pool;
1397 AppController *controller;
1400 pool = [[NSAutoreleasePool alloc] init];
1402 icon = [NSImage imageNamed:@"NSApplicationIcon"];
1403 [NSApplication sharedApplication];
1404 [NSApp setApplicationIconImage:icon];
1406 controller = [[[AppController alloc] init] autorelease];
1407 [NSApp setDelegate:controller];
1409 [NSApp setMainMenu: newmenu("Main Menu")];
1411 menu = newsubmenu([NSApp mainMenu], "Apple Menu");
1412 item = newitem(menu, "About Puzzles", "", NULL, @selector(about:));
1413 [menu addItem:[NSMenuItem separatorItem]];
1414 [NSApp setServicesMenu:newsubmenu(menu, "Services")];
1415 [menu addItem:[NSMenuItem separatorItem]];
1416 item = newitem(menu, "Hide Puzzles", "h", NSApp, @selector(hide:));
1417 item = newitem(menu, "Hide Others", "o-h", NSApp, @selector(hideOtherApplications:));
1418 item = newitem(menu, "Show All", "", NSApp, @selector(unhideAllApplications:));
1419 [menu addItem:[NSMenuItem separatorItem]];
1420 item = newitem(menu, "Quit", "q", NSApp, @selector(terminate:));
1421 [NSApp setAppleMenu: menu];
1423 menu = newsubmenu([NSApp mainMenu], "File");
1424 item = newitem(menu, "New Game", "n", NULL, @selector(newGame:));
1425 item = newitem(menu, "Restart Game", "r", NULL, @selector(restartGame:));
1426 item = newitem(menu, "Specific Game", "", NULL, @selector(specificGame:));
1427 item = newitem(menu, "Specific Random Seed", "", NULL,
1428 @selector(specificRandomGame:));
1429 [menu addItem:[NSMenuItem separatorItem]];
1431 NSMenu *submenu = newsubmenu(menu, "New Window");
1434 for (i = 0; i < gamecount; i++) {
1436 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1437 submenu, gamelist[i]->name, "", controller,
1438 @selector(newGameWindow:));
1439 [item setPayload:(void *)gamelist[i]];
1442 [menu addItem:[NSMenuItem separatorItem]];
1443 item = newitem(menu, "Close", "w", NULL, @selector(performClose:));
1445 menu = newsubmenu([NSApp mainMenu], "Edit");
1446 item = newitem(menu, "Undo", "z", NULL, @selector(undoMove:));
1447 item = newitem(menu, "Redo", "S-z", NULL, @selector(redoMove:));
1448 [menu addItem:[NSMenuItem separatorItem]];
1449 item = newitem(menu, "Cut", "x", NULL, @selector(cut:));
1450 item = newitem(menu, "Copy", "c", NULL, @selector(copy:));
1451 item = newitem(menu, "Paste", "v", NULL, @selector(paste:));
1452 [menu addItem:[NSMenuItem separatorItem]];
1453 item = newitem(menu, "Solve", "S-s", NULL, @selector(solveGame:));
1455 menu = newsubmenu([NSApp mainMenu], "Type");
1457 item = newitem(menu, "Custom", "", NULL, @selector(customGameType:));
1459 menu = newsubmenu([NSApp mainMenu], "Window");
1460 [NSApp setWindowsMenu: menu];
1461 item = newitem(menu, "Minimise Window", "m", NULL, @selector(performMiniaturize:));
1463 menu = newsubmenu([NSApp mainMenu], "Help");
1464 item = newitem(menu, "Puzzles Help", "?", NSApp, @selector(showHelp:));