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;
473 midend_size(me, &w, &h);
474 frame.size.width = w;
475 frame.size.height = h;
477 fe.image = [[NSImage alloc] initWithSize:frame.size];
478 [fe.image setFlipped:YES];
479 fe.view = [[MyImageView alloc] initWithFrame:frame];
480 [fe.view setImage:fe.image];
481 [fe.view setWindow:self];
485 [[self contentView] addSubview:fe.view];
487 - (id)initWithGame:(const game *)g
489 NSRect rect = { {0,0}, {0,0} }, rect2;
496 me = midend_new(&fe, ourgame);
498 * If we ever need to open a fresh window using a provided game
499 * ID, I think the right thing is to move most of this method
500 * into a new initWithGame:gameID: method, and have
501 * initWithGame: simply call that one and pass it NULL.
504 midend_size(me, &w, &h);
506 rect.size.height = h;
509 * Create the status bar, which will just be an NSTextField.
511 if (ourgame->wants_statusbar()) {
512 status = [[NSTextField alloc] initWithFrame:NSMakeRect(0,0,100,50)];
513 [status setEditable:NO];
514 [status setSelectable:NO];
515 [status setBordered:YES];
516 [status setBezeled:YES];
517 [status setBezelStyle:NSTextFieldSquareBezel];
518 [status setDrawsBackground:YES];
519 [[status cell] setTitle:@""];
521 rect2 = [status frame];
522 rect.size.height += rect2.size.height;
523 rect2.size.width = rect.size.width;
524 rect2.origin.x = rect2.origin.y = 0;
525 [status setFrame:rect2];
529 self = [super initWithContentRect:rect
530 styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
531 NSClosableWindowMask)
532 backing:NSBackingStoreBuffered
534 [self setTitle:[NSString stringWithCString:ourgame->name]];
540 colours = midend_colours(me, &ncolours);
541 fe.ncolours = ncolours;
542 fe.colours = snewn(ncolours, NSColor *);
544 for (i = 0; i < ncolours; i++) {
545 fe.colours[i] = [[NSColor colorWithDeviceRed:colours[i*3]
546 green:colours[i*3+1] blue:colours[i*3+2]
551 [self setupContentView];
553 [[self contentView] addSubview:status];
554 [self setIgnoresMouseEvents:NO];
556 [self center]; /* :-) */
564 for (i = 0; i < fe.ncolours; i++) {
565 [fe.colours[i] release];
569 return [super dealloc];
572 - (void)processButton:(int)b x:(int)x y:(int)y
574 if (!midend_process_key(me, x, y, b))
578 - (void)keyDown:(NSEvent *)ev
580 NSString *s = [ev characters];
581 int i, n = [s length];
583 for (i = 0; i < n; i++) {
584 int c = [s characterAtIndex:i];
587 * ASCII gets passed straight to midend_process_key.
588 * Anything above that has to be translated to our own
589 * function key codes.
594 case NSUpArrowFunctionKey:
598 case NSDownArrowFunctionKey:
602 case NSLeftArrowFunctionKey:
606 case NSRightArrowFunctionKey:
615 if ([ev modifierFlags] & NSShiftKeyMask)
617 if ([ev modifierFlags] & NSControlKeyMask)
622 if (c >= '0' && c <= '9' && ([ev modifierFlags] & NSNumericPadKeyMask))
625 [self processButton:c x:-1 y:-1];
629 - (void)activateTimer
634 timer = [NSTimer scheduledTimerWithTimeInterval:0.02
635 target:self selector:@selector(timerTick:)
636 userInfo:nil repeats:YES];
637 gettimeofday(&last_time, NULL);
640 - (void)deactivateTimer
649 - (void)timerTick:(id)sender
653 gettimeofday(&now, NULL);
654 elapsed = ((now.tv_usec - last_time.tv_usec) * 0.000001F +
655 (now.tv_sec - last_time.tv_sec));
656 midend_timer(me, elapsed);
660 - (void)newGame:(id)sender
662 [self processButton:'n' x:-1 y:-1];
664 - (void)restartGame:(id)sender
666 midend_restart_game(me);
668 - (void)undoMove:(id)sender
670 [self processButton:'u' x:-1 y:-1];
672 - (void)redoMove:(id)sender
674 [self processButton:'r'&0x1F x:-1 y:-1];
677 - (void)copy:(id)sender
681 if ((text = midend_text_format(me)) != NULL) {
682 NSPasteboard *pb = [NSPasteboard generalPasteboard];
683 NSArray *a = [NSArray arrayWithObject:NSStringPboardType];
684 [pb declareTypes:a owner:nil];
685 [pb setString:[NSString stringWithCString:text]
686 forType:NSStringPboardType];
691 - (void)solveGame:(id)sender
696 msg = midend_solve(me);
699 alert = [[[NSAlert alloc] init] autorelease];
700 [alert addButtonWithTitle:@"Bah"];
701 [alert setInformativeText:[NSString stringWithCString:msg]];
702 [alert beginSheetModalForWindow:self modalDelegate:nil
703 didEndSelector:nil contextInfo:nil];
707 - (BOOL)validateMenuItem:(NSMenuItem *)item
709 if ([item action] == @selector(copy:))
710 return (ourgame->can_format_as_text ? YES : NO);
711 else if ([item action] == @selector(solveGame:))
712 return (ourgame->can_solve ? YES : NO);
714 return [super validateMenuItem:item];
717 - (void)clearTypeMenu
719 while ([typemenu numberOfItems] > 1)
720 [typemenu removeItemAtIndex:0];
723 - (void)becomeKeyWindow
727 [self clearTypeMenu];
729 [super becomeKeyWindow];
731 n = midend_num_presets(me);
734 [typemenu insertItem:[NSMenuItem separatorItem] atIndex:0];
740 midend_fetch_preset(me, n, &name, ¶ms);
742 item = [[[DataMenuItem alloc]
743 initWithTitle:[NSString stringWithCString:name]
744 action:NULL keyEquivalent:@""]
747 [item setEnabled:YES];
748 [item setTarget:self];
749 [item setAction:@selector(presetGame:)];
750 [item setPayload:params];
752 [typemenu insertItem:item atIndex:0];
757 - (void)resignKeyWindow
759 [self clearTypeMenu];
760 [super resignKeyWindow];
765 [self clearTypeMenu];
769 - (void)resizeForNewGameParams
774 midend_size(me, &w, &h);
779 NSRect frame = [status frame];
780 size.height += frame.size.height;
781 frame.size.width = size.width;
782 [status setFrame:frame];
785 NSDisableScreenUpdates();
786 [self setContentSize:size];
787 [self setupContentView];
788 NSEnableScreenUpdates();
791 - (void)presetGame:(id)sender
793 game_params *params = [sender getPayload];
795 midend_set_params(me, params);
798 [self resizeForNewGameParams];
801 - (void)startConfigureSheet:(int)which
803 NSButton *ok, *cancel;
804 int actw, acth, leftw, rightw, totalw, h, thish, y;
806 NSRect rect, tmprect;
807 const int SPACING = 16;
815 assert(sheet == NULL);
818 * Every control we create here is going to have this size
819 * until we tell it to calculate a better one.
821 tmprect = NSMakeRect(0, 0, 100, 50);
824 * Set up OK and Cancel buttons. (Actually, MacOS doesn't seem
825 * to be fond of generic OK and Cancel wording, so I'm going to
826 * rename them to something nicer.)
830 cancel = [[NSButton alloc] initWithFrame:tmprect];
831 [cancel setBezelStyle:NSRoundedBezelStyle];
832 [cancel setTitle:@"Abandon"];
833 [cancel setTarget:self];
834 [cancel setKeyEquivalent:@"\033"];
835 [cancel setAction:@selector(sheetCancelButton:)];
837 rect = [cancel frame];
838 if (actw < rect.size.width) actw = rect.size.width;
839 if (acth < rect.size.height) acth = rect.size.height;
841 ok = [[NSButton alloc] initWithFrame:tmprect];
842 [ok setBezelStyle:NSRoundedBezelStyle];
843 [ok setTitle:@"Accept"];
845 [ok setKeyEquivalent:@"\r"];
846 [ok setAction:@selector(sheetOKButton:)];
849 if (actw < rect.size.width) actw = rect.size.width;
850 if (acth < rect.size.height) acth = rect.size.height;
852 totalw = SPACING + 2 * actw;
853 h = 2 * SPACING + acth;
856 * Now fetch the midend config data and go through it creating
859 cfg = midend_get_config(me, which, &title);
860 sfree(title); /* FIXME: should we use this somehow? */
863 cfg_ncontrols = cfg_controlsize = 0;
866 for (i = cfg; i->type != C_END; i++) {
867 if (cfg_controlsize < cfg_ncontrols + 5) {
868 cfg_controlsize = cfg_ncontrols + 32;
869 cfg_controls = sresize(cfg_controls, cfg_controlsize, NSView *);
877 * Two NSTextFields, one being a label and the other
881 tf = [[NSTextField alloc] initWithFrame:tmprect];
883 [tf setSelectable:NO];
885 [tf setDrawsBackground:NO];
886 [[tf cell] setTitle:[NSString stringWithCString:i->name]];
889 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
890 if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
891 cfg_controls[cfg_ncontrols++] = tf;
893 tf = [[NSTextField alloc] initWithFrame:tmprect];
894 [tf setEditable:YES];
895 [tf setSelectable:YES];
896 [tf setBordered:YES];
897 [[tf cell] setTitle:[NSString stringWithCString:i->sval]];
901 * We impose a minimum and maximum width on editable
902 * NSTextFields. If we allow them to size themselves to
903 * the contents of the text within them, then they will
904 * look very silly if that text is only one or two
905 * characters, and equally silly if it's an absolutely
906 * enormous Rectangles or Pattern game ID!
908 if (rect.size.width < 75) rect.size.width = 75;
909 if (rect.size.width > 400) rect.size.width = 400;
911 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
912 if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
913 cfg_controls[cfg_ncontrols++] = tf;
918 * A checkbox is an NSButton with a type of
921 b = [[NSButton alloc] initWithFrame:tmprect];
922 [b setBezelStyle:NSRoundedBezelStyle];
923 [b setButtonType:NSSwitchButton];
924 [b setTitle:[NSString stringWithCString:i->name]];
926 [b setState:(i->ival ? NSOnState : NSOffState)];
928 if (totalw < rect.size.width + 1) totalw = rect.size.width + 1;
929 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
930 cfg_controls[cfg_ncontrols++] = b;
935 * A pop-up menu control is an NSPopUpButton, which
936 * takes an embedded NSMenu. We also need an
937 * NSTextField to act as a label.
940 tf = [[NSTextField alloc] initWithFrame:tmprect];
942 [tf setSelectable:NO];
944 [tf setDrawsBackground:NO];
945 [[tf cell] setTitle:[NSString stringWithCString:i->name]];
948 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
949 if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
950 cfg_controls[cfg_ncontrols++] = tf;
952 pb = [[NSPopUpButton alloc] initWithFrame:tmprect pullsDown:NO];
953 [pb setBezelStyle:NSRoundedBezelStyle];
963 while (*p && *p != c) p++;
965 [pb addItemWithTitle:[NSString stringWithCString:q
971 [pb selectItemAtIndex:i->ival];
975 if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
976 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
977 cfg_controls[cfg_ncontrols++] = pb;
981 h += SPACING + thish;
984 if (totalw < leftw + SPACING + rightw)
985 totalw = leftw + SPACING + rightw;
986 if (totalw > leftw + SPACING + rightw) {
987 int excess = totalw - (leftw + SPACING + rightw);
988 int leftexcess = leftw * excess / (leftw + rightw);
989 int rightexcess = excess - leftexcess;
991 rightw += rightexcess;
995 * Now go through the list again, setting the final position
1000 for (i = cfg; i->type != C_END; i++) {
1007 * These two are treated identically, since both expect
1008 * a control on the left and another on the right.
1010 rect = [cfg_controls[k] frame];
1011 if (thish < rect.size.height + 1)
1012 thish = rect.size.height + 1;
1013 rect = [cfg_controls[k+1] frame];
1014 if (thish < rect.size.height + 1)
1015 thish = rect.size.height + 1;
1016 rect = [cfg_controls[k] frame];
1017 rect.origin.y = y - thish/2 - rect.size.height/2;
1018 rect.origin.x = SPACING;
1019 rect.size.width = leftw;
1020 [cfg_controls[k] setFrame:rect];
1021 rect = [cfg_controls[k+1] frame];
1022 rect.origin.y = y - thish/2 - rect.size.height/2;
1023 rect.origin.x = 2 * SPACING + leftw;
1024 rect.size.width = rightw;
1025 [cfg_controls[k+1] setFrame:rect];
1030 rect = [cfg_controls[k] frame];
1031 if (thish < rect.size.height + 1)
1032 thish = rect.size.height + 1;
1033 rect.origin.y = y - thish/2 - rect.size.height/2;
1034 rect.origin.x = SPACING;
1035 rect.size.width = totalw;
1036 [cfg_controls[k] setFrame:rect];
1043 assert(k == cfg_ncontrols);
1045 [cancel setFrame:NSMakeRect(SPACING+totalw/4-actw/2, SPACING, actw, acth)];
1046 [ok setFrame:NSMakeRect(SPACING+3*totalw/4-actw/2, SPACING, actw, acth)];
1048 sheet = [[NSWindow alloc]
1049 initWithContentRect:NSMakeRect(0,0,totalw + 2*SPACING,h)
1050 styleMask:NSTitledWindowMask | NSClosableWindowMask
1051 backing:NSBackingStoreBuffered
1054 [[sheet contentView] addSubview:cancel];
1055 [[sheet contentView] addSubview:ok];
1057 for (k = 0; k < cfg_ncontrols; k++)
1058 [[sheet contentView] addSubview:cfg_controls[k]];
1060 [NSApp beginSheet:sheet modalForWindow:self
1061 modalDelegate:nil didEndSelector:nil contextInfo:nil];
1064 - (void)specificGame:(id)sender
1066 [self startConfigureSheet:CFG_DESC];
1069 - (void)specificRandomGame:(id)sender
1071 [self startConfigureSheet:CFG_SEED];
1074 - (void)customGameType:(id)sender
1076 [self startConfigureSheet:CFG_SETTINGS];
1079 - (void)sheetEndWithStatus:(BOOL)update
1081 assert(sheet != NULL);
1082 [NSApp endSheet:sheet];
1083 [sheet orderOut:self];
1091 for (i = cfg; i->type != C_END; i++) {
1095 i->sval = dupstr([[[(id)cfg_controls[k+1] cell]
1100 i->ival = [(id)cfg_controls[k] state] == NSOnState;
1104 i->ival = [(id)cfg_controls[k+1] indexOfSelectedItem];
1110 error = midend_set_config(me, cfg_which, cfg);
1112 NSAlert *alert = [[[NSAlert alloc] init] autorelease];
1113 [alert addButtonWithTitle:@"Bah"];
1114 [alert setInformativeText:[NSString stringWithCString:error]];
1115 [alert beginSheetModalForWindow:self modalDelegate:nil
1116 didEndSelector:nil contextInfo:nil];
1118 midend_new_game(me);
1119 [self resizeForNewGameParams];
1122 sfree(cfg_controls);
1123 cfg_controls = NULL;
1125 - (void)sheetOKButton:(id)sender
1127 [self sheetEndWithStatus:YES];
1129 - (void)sheetCancelButton:(id)sender
1131 [self sheetEndWithStatus:NO];
1134 - (void)setStatusLine:(char *)text
1136 char *rewritten = midend_rewrite_statusbar(me, text);
1137 [[status cell] setTitle:[NSString stringWithCString:rewritten]];
1144 * Drawing routines called by the midend.
1146 void draw_polygon(frontend *fe, int *coords, int npoints,
1147 int fill, int colour)
1149 NSBezierPath *path = [NSBezierPath bezierPath];
1152 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1154 assert(colour >= 0 && colour < fe->ncolours);
1155 [fe->colours[colour] set];
1157 for (i = 0; i < npoints; i++) {
1158 NSPoint p = { coords[i*2] + 0.5, coords[i*2+1] + 0.5 };
1160 [path moveToPoint:p];
1162 [path lineToPoint:p];
1172 void draw_line(frontend *fe, int x1, int y1, int x2, int y2, int colour)
1174 NSBezierPath *path = [NSBezierPath bezierPath];
1175 NSPoint p1 = { x1 + 0.5, y1 + 0.5 }, p2 = { x2 + 0.5, y2 + 0.5 };
1177 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1179 assert(colour >= 0 && colour < fe->ncolours);
1180 [fe->colours[colour] set];
1182 [path moveToPoint:p1];
1183 [path lineToPoint:p2];
1186 void draw_rect(frontend *fe, int x, int y, int w, int h, int colour)
1188 NSRect r = { {x,y}, {w,h} };
1190 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1192 assert(colour >= 0 && colour < fe->ncolours);
1193 [fe->colours[colour] set];
1197 void draw_text(frontend *fe, int x, int y, int fonttype, int fontsize,
1198 int align, int colour, char *text)
1200 NSString *string = [NSString stringWithCString:text];
1206 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1208 assert(colour >= 0 && colour < fe->ncolours);
1210 if (fonttype == FONT_FIXED)
1211 font = [NSFont userFixedPitchFontOfSize:fontsize];
1213 font = [NSFont userFontOfSize:fontsize];
1215 attr = [NSDictionary dictionaryWithObjectsAndKeys:
1216 fe->colours[colour], NSForegroundColorAttributeName,
1217 font, NSFontAttributeName, nil];
1222 size = [string sizeWithAttributes:attr];
1223 if (align & ALIGN_HRIGHT)
1224 point.x -= size.width;
1225 else if (align & ALIGN_HCENTRE)
1226 point.x -= size.width / 2;
1227 if (align & ALIGN_VCENTRE)
1228 point.y -= size.height / 2;
1230 [string drawAtPoint:point withAttributes:attr];
1232 void draw_update(frontend *fe, int x, int y, int w, int h)
1234 [fe->view setNeedsDisplayInRect:NSMakeRect(x,y,w,h)];
1236 void clip(frontend *fe, int x, int y, int w, int h)
1238 NSRect r = { {x,y}, {w,h} };
1241 [[NSGraphicsContext currentContext] saveGraphicsState];
1242 [NSBezierPath clipRect:r];
1245 void unclip(frontend *fe)
1248 [[NSGraphicsContext currentContext] restoreGraphicsState];
1249 fe->clipped = FALSE;
1251 void start_draw(frontend *fe)
1253 [fe->image lockFocus];
1254 fe->clipped = FALSE;
1256 void end_draw(frontend *fe)
1258 [fe->image unlockFocus];
1261 void deactivate_timer(frontend *fe)
1263 [fe->window deactivateTimer];
1265 void activate_timer(frontend *fe)
1267 [fe->window activateTimer];
1270 void status_bar(frontend *fe, char *text)
1272 [fe->window setStatusLine:text];
1275 /* ----------------------------------------------------------------------
1276 * AppController: the object which receives the messages from all
1277 * menu selections that aren't standard OS X functions.
1279 @interface AppController : NSObject
1282 - (void)newGameWindow:(id)sender;
1283 - (void)about:(id)sender;
1286 @implementation AppController
1288 - (void)newGameWindow:(id)sender
1290 const game *g = [sender getPayload];
1293 win = [[GameWindow alloc] initWithGame:g];
1294 [win makeKeyAndOrderFront:self];
1297 - (void)about:(id)sender
1301 win = [[AboutBox alloc] init];
1302 [win makeKeyAndOrderFront:self];
1305 - (NSMenu *)applicationDockMenu:(NSApplication *)sender
1307 NSMenu *menu = newmenu("Dock Menu");
1311 for (i = 0; i < gamecount; i++) {
1313 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1314 menu, gamelist[i]->name, "", self,
1315 @selector(newGameWindow:));
1316 [item setPayload:(void *)gamelist[i]];
1324 /* ----------------------------------------------------------------------
1325 * Main program. Constructs the menus and runs the application.
1327 int main(int argc, char **argv)
1329 NSAutoreleasePool *pool;
1332 AppController *controller;
1335 pool = [[NSAutoreleasePool alloc] init];
1337 icon = [NSImage imageNamed:@"NSApplicationIcon"];
1338 [NSApplication sharedApplication];
1339 [NSApp setApplicationIconImage:icon];
1341 controller = [[[AppController alloc] init] autorelease];
1342 [NSApp setDelegate:controller];
1344 [NSApp setMainMenu: newmenu("Main Menu")];
1346 menu = newsubmenu([NSApp mainMenu], "Apple Menu");
1347 item = newitem(menu, "About Puzzles", "", NULL, @selector(about:));
1348 [menu addItem:[NSMenuItem separatorItem]];
1349 [NSApp setServicesMenu:newsubmenu(menu, "Services")];
1350 [menu addItem:[NSMenuItem separatorItem]];
1351 item = newitem(menu, "Hide Puzzles", "h", NSApp, @selector(hide:));
1352 item = newitem(menu, "Hide Others", "o-h", NSApp, @selector(hideOtherApplications:));
1353 item = newitem(menu, "Show All", "", NSApp, @selector(unhideAllApplications:));
1354 [menu addItem:[NSMenuItem separatorItem]];
1355 item = newitem(menu, "Quit", "q", NSApp, @selector(terminate:));
1356 [NSApp setAppleMenu: menu];
1358 menu = newsubmenu([NSApp mainMenu], "File");
1359 item = newitem(menu, "New Game", "n", NULL, @selector(newGame:));
1360 item = newitem(menu, "Restart Game", "r", NULL, @selector(restartGame:));
1361 item = newitem(menu, "Specific Game", "", NULL, @selector(specificGame:));
1362 item = newitem(menu, "Specific Random Seed", "", NULL,
1363 @selector(specificRandomGame:));
1364 [menu addItem:[NSMenuItem separatorItem]];
1366 NSMenu *submenu = newsubmenu(menu, "New Window");
1369 for (i = 0; i < gamecount; i++) {
1371 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1372 submenu, gamelist[i]->name, "", controller,
1373 @selector(newGameWindow:));
1374 [item setPayload:(void *)gamelist[i]];
1377 [menu addItem:[NSMenuItem separatorItem]];
1378 item = newitem(menu, "Close", "w", NULL, @selector(performClose:));
1380 menu = newsubmenu([NSApp mainMenu], "Edit");
1381 item = newitem(menu, "Undo", "z", NULL, @selector(undoMove:));
1382 item = newitem(menu, "Redo", "S-z", NULL, @selector(redoMove:));
1383 [menu addItem:[NSMenuItem separatorItem]];
1384 item = newitem(menu, "Cut", "x", NULL, @selector(cut:));
1385 item = newitem(menu, "Copy", "c", NULL, @selector(copy:));
1386 item = newitem(menu, "Paste", "v", NULL, @selector(paste:));
1387 [menu addItem:[NSMenuItem separatorItem]];
1388 item = newitem(menu, "Solve", "S-s", NULL, @selector(solveGame:));
1390 menu = newsubmenu([NSApp mainMenu], "Type");
1392 item = newitem(menu, "Custom", "", NULL, @selector(customGameType:));
1394 menu = newsubmenu([NSApp mainMenu], "Window");
1395 [NSApp setWindowsMenu: menu];
1396 item = newitem(menu, "Minimise Window", "m", NULL, @selector(performMiniaturize:));
1398 menu = newsubmenu([NSApp mainMenu], "Help");
1399 item = newitem(menu, "Puzzles Help", "?", NSApp, @selector(showHelp:));