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 suggests we should have `File' and `Edit' menus
64 * like everyone else, so some menu reorg is probably required,
65 * along with some documentation rewording.
67 * - User feedback also dislikes nothing happening when you start
68 * the app; they suggest a finder-like window containing an icon
69 * for each puzzle type, enabling you to start one easily. Needs
72 * Grotty implementation details that could probably be improved:
74 * - I am _utterly_ unconvinced that NSImageView was the right way
75 * to go about having a window with a reliable backing store! It
76 * just doesn't feel right; NSImageView is a _control_. Is there
79 * - Resizing is currently very bad; rather than bother to work
80 * out how to resize the NSImageView, I just splatter and
86 #import <Cocoa/Cocoa.h>
89 /* ----------------------------------------------------------------------
94 * The `Type' menu. We frob this dynamically to allow the user to
95 * choose a preset set of settings from the current game.
99 /* ----------------------------------------------------------------------
100 * Miscellaneous support routines that aren't part of any object or
101 * clearly defined subsystem.
104 void fatal(char *fmt, ...)
111 vsnprintf(errorbuf, lenof(errorbuf), fmt, ap);
114 alert = [NSAlert alloc];
116 * We may have come here because we ran out of memory, in which
117 * case it's entirely likely that that alloc will fail, so we
118 * should have a fallback of some sort.
121 fprintf(stderr, "fatal error (and NSAlert failed): %s\n", errorbuf);
123 alert = [[alert init] autorelease];
124 [alert addButtonWithTitle:@"Oh dear"];
125 [alert setInformativeText:[NSString stringWithCString:errorbuf]];
131 void frontend_default_colour(frontend *fe, float *output)
133 /* FIXME: Is there a system default we can tap into for this? */
134 output[0] = output[1] = output[2] = 0.8F;
137 void get_random_seed(void **randseed, int *randseedsize)
139 time_t *tp = snew(time_t);
141 *randseed = (void *)tp;
142 *randseedsize = sizeof(time_t);
145 /* ----------------------------------------------------------------------
146 * Tiny extension to NSMenuItem which carries a payload of a `void
147 * *', allowing several menu items to invoke the same message but
148 * pass different data through it.
150 @interface DataMenuItem : NSMenuItem
154 - (void)setPayload:(void *)d;
155 - (void *)getPayload;
157 @implementation DataMenuItem
158 - (void)setPayload:(void *)d
168 /* ----------------------------------------------------------------------
169 * Utility routines for constructing OS X menus.
172 NSMenu *newmenu(const char *title)
174 return [[[NSMenu allocWithZone:[NSMenu menuZone]]
175 initWithTitle:[NSString stringWithCString:title]]
179 NSMenu *newsubmenu(NSMenu *parent, const char *title)
184 item = [[[NSMenuItem allocWithZone:[NSMenu menuZone]]
185 initWithTitle:[NSString stringWithCString:title]
189 child = newmenu(title);
190 [item setEnabled:YES];
191 [item setSubmenu:child];
192 [parent addItem:item];
196 id initnewitem(NSMenuItem *item, NSMenu *parent, const char *title,
197 const char *key, id target, SEL action)
199 unsigned mask = NSCommandKeyMask;
201 if (key[strcspn(key, "-")]) {
202 while (*key && *key != '-') {
203 int c = tolower((unsigned char)*key);
205 mask |= NSShiftKeyMask;
206 } else if (c == 'o' || c == 'a') {
207 mask |= NSAlternateKeyMask;
215 item = [[item initWithTitle:[NSString stringWithCString:title]
217 keyEquivalent:[NSString stringWithCString:key]]
221 [item setKeyEquivalentModifierMask: mask];
223 [item setEnabled:YES];
224 [item setTarget:target];
225 [item setAction:action];
227 [parent addItem:item];
232 NSMenuItem *newitem(NSMenu *parent, char *title, char *key,
233 id target, SEL action)
235 return initnewitem([NSMenuItem allocWithZone:[NSMenu menuZone]],
236 parent, title, key, target, action);
239 /* ----------------------------------------------------------------------
240 * The front end presented to midend.c.
242 * This is mostly a subclass of NSWindow. The actual `frontend'
243 * structure passed to the midend contains a variety of pointers,
244 * including that window object but also including the image we
245 * draw on, an ImageView to display it in the window, and so on.
260 @interface MyImageView : NSImageView
264 - (void)setWindow:(GameWindow *)win;
266 - (void)mouseEvent:(NSEvent *)ev button:(int)b;
267 - (void)mouseDown:(NSEvent *)ev;
268 - (void)mouseDragged:(NSEvent *)ev;
269 - (void)mouseUp:(NSEvent *)ev;
270 - (void)rightMouseDown:(NSEvent *)ev;
271 - (void)rightMouseDragged:(NSEvent *)ev;
272 - (void)rightMouseUp:(NSEvent *)ev;
273 - (void)otherMouseDown:(NSEvent *)ev;
274 - (void)otherMouseDragged:(NSEvent *)ev;
275 - (void)otherMouseUp:(NSEvent *)ev;
278 @interface GameWindow : NSWindow
283 struct timeval last_time;
288 NSView **cfg_controls;
292 - (id)initWithGame:(const game *)g;
294 - (void)processButton:(int)b x:(int)x y:(int)y;
295 - (void)keyDown:(NSEvent *)ev;
296 - (void)activateTimer;
297 - (void)deactivateTimer;
298 - (void)setStatusLine:(NSString *)text;
301 @implementation MyImageView
303 - (void)setWindow:(GameWindow *)win
313 - (void)mouseEvent:(NSEvent *)ev button:(int)b
315 NSPoint point = [self convertPoint:[ev locationInWindow] fromView:nil];
316 [ourwin processButton:b x:point.x y:point.y];
319 - (void)mouseDown:(NSEvent *)ev
321 unsigned mod = [ev modifierFlags];
322 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_BUTTON :
323 (mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
326 - (void)mouseDragged:(NSEvent *)ev
328 unsigned mod = [ev modifierFlags];
329 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_DRAG :
330 (mod & NSShiftKeyMask) ? MIDDLE_DRAG :
333 - (void)mouseUp:(NSEvent *)ev
335 unsigned mod = [ev modifierFlags];
336 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_RELEASE :
337 (mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
340 - (void)rightMouseDown:(NSEvent *)ev
342 unsigned mod = [ev modifierFlags];
343 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
346 - (void)rightMouseDragged:(NSEvent *)ev
348 unsigned mod = [ev modifierFlags];
349 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_DRAG :
352 - (void)rightMouseUp:(NSEvent *)ev
354 unsigned mod = [ev modifierFlags];
355 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
358 - (void)otherMouseDown:(NSEvent *)ev
360 [self mouseEvent:ev button:MIDDLE_BUTTON];
362 - (void)otherMouseDragged:(NSEvent *)ev
364 [self mouseEvent:ev button:MIDDLE_DRAG];
366 - (void)otherMouseUp:(NSEvent *)ev
368 [self mouseEvent:ev button:MIDDLE_RELEASE];
372 @implementation GameWindow
373 - (void)setupContentView
379 frame = [status frame];
380 frame.origin.y = frame.size.height;
385 midend_size(me, &w, &h);
386 frame.size.width = w;
387 frame.size.height = h;
389 fe.image = [[NSImage alloc] initWithSize:frame.size];
390 [fe.image setFlipped:YES];
391 fe.view = [[MyImageView alloc] initWithFrame:frame];
392 [fe.view setImage:fe.image];
393 [fe.view setWindow:self];
397 [[self contentView] addSubview:fe.view];
399 - (id)initWithGame:(const game *)g
401 NSRect rect = { {0,0}, {0,0} }, rect2;
408 me = midend_new(&fe, ourgame);
410 * If we ever need to open a fresh window using a provided game
411 * ID, I think the right thing is to move most of this method
412 * into a new initWithGame:gameID: method, and have
413 * initWithGame: simply call that one and pass it NULL.
416 midend_size(me, &w, &h);
418 rect.size.height = h;
421 * Create the status bar, which will just be an NSTextField.
423 if (ourgame->wants_statusbar()) {
424 status = [[NSTextField alloc] initWithFrame:NSMakeRect(0,0,100,50)];
425 [status setEditable:NO];
426 [status setSelectable:NO];
427 [status setBordered:YES];
428 [status setBezeled:YES];
429 [status setBezelStyle:NSTextFieldSquareBezel];
430 [status setDrawsBackground:YES];
431 [[status cell] setTitle:@""];
433 rect2 = [status frame];
434 rect.size.height += rect2.size.height;
435 rect2.size.width = rect.size.width;
436 rect2.origin.x = rect2.origin.y = 0;
437 [status setFrame:rect2];
441 self = [super initWithContentRect:rect
442 styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
443 NSClosableWindowMask)
444 backing:NSBackingStoreBuffered
446 [self setTitle:[NSString stringWithCString:ourgame->name]];
452 colours = midend_colours(me, &ncolours);
453 fe.ncolours = ncolours;
454 fe.colours = snewn(ncolours, NSColor *);
456 for (i = 0; i < ncolours; i++) {
457 fe.colours[i] = [[NSColor colorWithDeviceRed:colours[i*3]
458 green:colours[i*3+1] blue:colours[i*3+2]
463 [self setupContentView];
465 [[self contentView] addSubview:status];
466 [self setIgnoresMouseEvents:NO];
468 [self center]; /* :-) */
476 for (i = 0; i < fe.ncolours; i++) {
477 [fe.colours[i] release];
481 return [super dealloc];
484 - (void)processButton:(int)b x:(int)x y:(int)y
486 if (!midend_process_key(me, x, y, b))
490 - (void)keyDown:(NSEvent *)ev
492 NSString *s = [ev characters];
493 int i, n = [s length];
495 for (i = 0; i < n; i++) {
496 int c = [s characterAtIndex:i];
499 * ASCII gets passed straight to midend_process_key.
500 * Anything above that has to be translated to our own
501 * function key codes.
505 case NSUpArrowFunctionKey:
508 case NSDownArrowFunctionKey:
511 case NSLeftArrowFunctionKey:
514 case NSRightArrowFunctionKey:
522 [self processButton:c x:-1 y:-1];
526 - (void)activateTimer
531 timer = [NSTimer scheduledTimerWithTimeInterval:0.02
532 target:self selector:@selector(timerTick:)
533 userInfo:nil repeats:YES];
534 gettimeofday(&last_time, NULL);
537 - (void)deactivateTimer
546 - (void)timerTick:(id)sender
550 gettimeofday(&now, NULL);
551 elapsed = ((now.tv_usec - last_time.tv_usec) * 0.000001F +
552 (now.tv_sec - last_time.tv_sec));
553 midend_timer(me, elapsed);
557 - (void)newGame:(id)sender
559 [self processButton:'n' x:-1 y:-1];
561 - (void)restartGame:(id)sender
563 [self processButton:'r' x:-1 y:-1];
565 - (void)undoMove:(id)sender
567 [self processButton:'u' x:-1 y:-1];
569 - (void)redoMove:(id)sender
571 [self processButton:'r'&0x1F x:-1 y:-1];
574 - (void)copy:(id)sender
578 if ((text = midend_text_format(me)) != NULL) {
579 NSPasteboard *pb = [NSPasteboard generalPasteboard];
580 NSArray *a = [NSArray arrayWithObject:NSStringPboardType];
581 [pb declareTypes:a owner:nil];
582 [pb setString:[NSString stringWithCString:text]
583 forType:NSStringPboardType];
588 - (BOOL)validateMenuItem:(NSMenuItem *)item
590 if ([item action] == @selector(copy:))
591 return (ourgame->can_format_as_text ? YES : NO);
593 return [super validateMenuItem:item];
596 - (void)clearTypeMenu
598 while ([typemenu numberOfItems] > 1)
599 [typemenu removeItemAtIndex:0];
602 - (void)becomeKeyWindow
606 [self clearTypeMenu];
608 [super becomeKeyWindow];
610 n = midend_num_presets(me);
613 [typemenu insertItem:[NSMenuItem separatorItem] atIndex:0];
619 midend_fetch_preset(me, n, &name, ¶ms);
621 item = [[[DataMenuItem alloc]
622 initWithTitle:[NSString stringWithCString:name]
623 action:NULL keyEquivalent:@""]
626 [item setEnabled:YES];
627 [item setTarget:self];
628 [item setAction:@selector(presetGame:)];
629 [item setPayload:params];
631 [typemenu insertItem:item atIndex:0];
636 - (void)resignKeyWindow
638 [self clearTypeMenu];
639 [super resignKeyWindow];
644 [self clearTypeMenu];
648 - (void)resizeForNewGameParams
653 midend_size(me, &w, &h);
658 NSRect frame = [status frame];
659 size.height += frame.size.height;
660 frame.size.width = size.width;
661 [status setFrame:frame];
664 NSDisableScreenUpdates();
665 [self setContentSize:size];
666 [self setupContentView];
667 NSEnableScreenUpdates();
670 - (void)presetGame:(id)sender
672 game_params *params = [sender getPayload];
674 midend_set_params(me, params);
677 [self resizeForNewGameParams];
680 - (void)startConfigureSheet:(int)which
682 NSButton *ok, *cancel;
683 int actw, acth, leftw, rightw, totalw, h, thish, y;
685 NSRect rect, tmprect;
686 const int SPACING = 16;
694 assert(sheet == NULL);
697 * Every control we create here is going to have this size
698 * until we tell it to calculate a better one.
700 tmprect = NSMakeRect(0, 0, 100, 50);
703 * Set up OK and Cancel buttons. (Actually, MacOS doesn't seem
704 * to be fond of generic OK and Cancel wording, so I'm going to
705 * rename them to something nicer.)
709 cancel = [[NSButton alloc] initWithFrame:tmprect];
710 [cancel setBezelStyle:NSRoundedBezelStyle];
711 [cancel setTitle:@"Abandon"];
712 [cancel setTarget:self];
713 [cancel setKeyEquivalent:@"\033"];
714 [cancel setAction:@selector(sheetCancelButton:)];
716 rect = [cancel frame];
717 if (actw < rect.size.width) actw = rect.size.width;
718 if (acth < rect.size.height) acth = rect.size.height;
720 ok = [[NSButton alloc] initWithFrame:tmprect];
721 [ok setBezelStyle:NSRoundedBezelStyle];
722 [ok setTitle:@"Accept"];
724 [ok setKeyEquivalent:@"\r"];
725 [ok setAction:@selector(sheetOKButton:)];
728 if (actw < rect.size.width) actw = rect.size.width;
729 if (acth < rect.size.height) acth = rect.size.height;
731 totalw = SPACING + 2 * actw;
732 h = 2 * SPACING + acth;
735 * Now fetch the midend config data and go through it creating
738 cfg = midend_get_config(me, which, &title);
739 sfree(title); /* FIXME: should we use this somehow? */
742 cfg_ncontrols = cfg_controlsize = 0;
745 for (i = cfg; i->type != C_END; i++) {
746 if (cfg_controlsize < cfg_ncontrols + 5) {
747 cfg_controlsize = cfg_ncontrols + 32;
748 cfg_controls = sresize(cfg_controls, cfg_controlsize, NSView *);
756 * Two NSTextFields, one being a label and the other
760 tf = [[NSTextField alloc] initWithFrame:tmprect];
762 [tf setSelectable:NO];
764 [tf setDrawsBackground:NO];
765 [[tf cell] setTitle:[NSString stringWithCString:i->name]];
768 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
769 if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
770 cfg_controls[cfg_ncontrols++] = tf;
772 tf = [[NSTextField alloc] initWithFrame:tmprect];
773 [tf setEditable:YES];
774 [tf setSelectable:YES];
775 [tf setBordered:YES];
776 [[tf cell] setTitle:[NSString stringWithCString:i->sval]];
780 * We impose a minimum and maximum width on editable
781 * NSTextFields. If we allow them to size themselves to
782 * the contents of the text within them, then they will
783 * look very silly if that text is only one or two
784 * characters, and equally silly if it's an absolutely
785 * enormous Rectangles or Pattern game ID!
787 if (rect.size.width < 75) rect.size.width = 75;
788 if (rect.size.width > 400) rect.size.width = 400;
790 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
791 if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
792 cfg_controls[cfg_ncontrols++] = tf;
797 * A checkbox is an NSButton with a type of
800 b = [[NSButton alloc] initWithFrame:tmprect];
801 [b setBezelStyle:NSRoundedBezelStyle];
802 [b setButtonType:NSSwitchButton];
803 [b setTitle:[NSString stringWithCString:i->name]];
805 [b setState:(i->ival ? NSOnState : NSOffState)];
807 if (totalw < rect.size.width + 1) totalw = rect.size.width + 1;
808 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
809 cfg_controls[cfg_ncontrols++] = b;
814 * A pop-up menu control is an NSPopUpButton, which
815 * takes an embedded NSMenu. We also need an
816 * NSTextField to act as a label.
819 tf = [[NSTextField alloc] initWithFrame:tmprect];
821 [tf setSelectable:NO];
823 [tf setDrawsBackground:NO];
824 [[tf cell] setTitle:[NSString stringWithCString:i->name]];
827 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
828 if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
829 cfg_controls[cfg_ncontrols++] = tf;
831 pb = [[NSPopUpButton alloc] initWithFrame:tmprect pullsDown:NO];
832 [pb setBezelStyle:NSRoundedBezelStyle];
842 while (*p && *p != c) p++;
844 [pb addItemWithTitle:[NSString stringWithCString:q
850 [pb selectItemAtIndex:i->ival];
854 if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
855 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
856 cfg_controls[cfg_ncontrols++] = pb;
860 h += SPACING + thish;
863 if (totalw < leftw + SPACING + rightw)
864 totalw = leftw + SPACING + rightw;
865 if (totalw > leftw + SPACING + rightw) {
866 int excess = totalw - (leftw + SPACING + rightw);
867 int leftexcess = leftw * excess / (leftw + rightw);
868 int rightexcess = excess - leftexcess;
870 rightw += rightexcess;
874 * Now go through the list again, setting the final position
879 for (i = cfg; i->type != C_END; i++) {
886 * These two are treated identically, since both expect
887 * a control on the left and another on the right.
889 rect = [cfg_controls[k] frame];
890 if (thish < rect.size.height + 1)
891 thish = rect.size.height + 1;
892 rect = [cfg_controls[k+1] frame];
893 if (thish < rect.size.height + 1)
894 thish = rect.size.height + 1;
895 rect = [cfg_controls[k] frame];
896 rect.origin.y = y - thish/2 - rect.size.height/2;
897 rect.origin.x = SPACING;
898 rect.size.width = leftw;
899 [cfg_controls[k] setFrame:rect];
900 rect = [cfg_controls[k+1] frame];
901 rect.origin.y = y - thish/2 - rect.size.height/2;
902 rect.origin.x = 2 * SPACING + leftw;
903 rect.size.width = rightw;
904 [cfg_controls[k+1] setFrame:rect];
909 rect = [cfg_controls[k] frame];
910 if (thish < rect.size.height + 1)
911 thish = rect.size.height + 1;
912 rect.origin.y = y - thish/2 - rect.size.height/2;
913 rect.origin.x = SPACING;
914 rect.size.width = totalw;
915 [cfg_controls[k] setFrame:rect];
922 assert(k == cfg_ncontrols);
924 [cancel setFrame:NSMakeRect(SPACING+totalw/4-actw/2, SPACING, actw, acth)];
925 [ok setFrame:NSMakeRect(SPACING+3*totalw/4-actw/2, SPACING, actw, acth)];
927 sheet = [[NSWindow alloc]
928 initWithContentRect:NSMakeRect(0,0,totalw + 2*SPACING,h)
929 styleMask:NSTitledWindowMask | NSClosableWindowMask
930 backing:NSBackingStoreBuffered
933 [[sheet contentView] addSubview:cancel];
934 [[sheet contentView] addSubview:ok];
936 for (k = 0; k < cfg_ncontrols; k++)
937 [[sheet contentView] addSubview:cfg_controls[k]];
939 [NSApp beginSheet:sheet modalForWindow:self
940 modalDelegate:nil didEndSelector:nil contextInfo:nil];
943 - (void)specificGame:(id)sender
945 [self startConfigureSheet:CFG_SEED];
948 - (void)customGameType:(id)sender
950 [self startConfigureSheet:CFG_SETTINGS];
953 - (void)sheetEndWithStatus:(BOOL)update
955 assert(sheet != NULL);
956 [NSApp endSheet:sheet];
957 [sheet orderOut:self];
965 for (i = cfg; i->type != C_END; i++) {
969 i->sval = dupstr([[[(id)cfg_controls[k+1] cell]
974 i->ival = [(id)cfg_controls[k] state] == NSOnState;
978 i->ival = [(id)cfg_controls[k+1] indexOfSelectedItem];
984 error = midend_set_config(me, cfg_which, cfg);
986 NSAlert *alert = [[[NSAlert alloc] init] autorelease];
987 [alert addButtonWithTitle:@"Bah"];
988 [alert setInformativeText:[NSString stringWithCString:error]];
989 [alert beginSheetModalForWindow:self modalDelegate:nil
990 didEndSelector:nil contextInfo:nil];
993 [self resizeForNewGameParams];
999 - (void)sheetOKButton:(id)sender
1001 [self sheetEndWithStatus:YES];
1003 - (void)sheetCancelButton:(id)sender
1005 [self sheetEndWithStatus:NO];
1008 - (void)setStatusLine:(NSString *)text
1010 [[status cell] setTitle:text];
1016 * Drawing routines called by the midend.
1018 void draw_polygon(frontend *fe, int *coords, int npoints,
1019 int fill, int colour)
1021 NSBezierPath *path = [NSBezierPath bezierPath];
1024 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1026 assert(colour >= 0 && colour < fe->ncolours);
1027 [fe->colours[colour] set];
1029 for (i = 0; i < npoints; i++) {
1030 NSPoint p = { coords[i*2] + 0.5, coords[i*2+1] + 0.5 };
1032 [path moveToPoint:p];
1034 [path lineToPoint:p];
1044 void draw_line(frontend *fe, int x1, int y1, int x2, int y2, int colour)
1046 NSBezierPath *path = [NSBezierPath bezierPath];
1047 NSPoint p1 = { x1 + 0.5, y1 + 0.5 }, p2 = { x2 + 0.5, y2 + 0.5 };
1049 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1051 assert(colour >= 0 && colour < fe->ncolours);
1052 [fe->colours[colour] set];
1054 [path moveToPoint:p1];
1055 [path lineToPoint:p2];
1058 void draw_rect(frontend *fe, int x, int y, int w, int h, int colour)
1060 NSRect r = { {x,y}, {w,h} };
1062 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1064 assert(colour >= 0 && colour < fe->ncolours);
1065 [fe->colours[colour] set];
1069 void draw_text(frontend *fe, int x, int y, int fonttype, int fontsize,
1070 int align, int colour, char *text)
1072 NSString *string = [NSString stringWithCString:text];
1078 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1080 assert(colour >= 0 && colour < fe->ncolours);
1082 if (fonttype == FONT_FIXED)
1083 font = [NSFont userFixedPitchFontOfSize:fontsize];
1085 font = [NSFont userFontOfSize:fontsize];
1087 attr = [NSDictionary dictionaryWithObjectsAndKeys:
1088 fe->colours[colour], NSForegroundColorAttributeName,
1089 font, NSFontAttributeName, nil];
1094 size = [string sizeWithAttributes:attr];
1095 if (align & ALIGN_HRIGHT)
1096 point.x -= size.width;
1097 else if (align & ALIGN_HCENTRE)
1098 point.x -= size.width / 2;
1099 if (align & ALIGN_VCENTRE)
1100 point.y -= size.height / 2;
1102 [string drawAtPoint:point withAttributes:attr];
1104 void draw_update(frontend *fe, int x, int y, int w, int h)
1106 [fe->view setNeedsDisplayInRect:NSMakeRect(x,y,w,h)];
1108 void clip(frontend *fe, int x, int y, int w, int h)
1110 NSRect r = { {x,y}, {w,h} };
1113 [[NSGraphicsContext currentContext] saveGraphicsState];
1114 [NSBezierPath clipRect:r];
1117 void unclip(frontend *fe)
1120 [[NSGraphicsContext currentContext] restoreGraphicsState];
1121 fe->clipped = FALSE;
1123 void start_draw(frontend *fe)
1125 [fe->image lockFocus];
1126 fe->clipped = FALSE;
1128 void end_draw(frontend *fe)
1130 [fe->image unlockFocus];
1133 void deactivate_timer(frontend *fe)
1135 [fe->window deactivateTimer];
1137 void activate_timer(frontend *fe)
1139 [fe->window activateTimer];
1142 void status_bar(frontend *fe, char *text)
1144 [fe->window setStatusLine:[NSString stringWithCString:text]];
1147 /* ----------------------------------------------------------------------
1148 * AppController: the object which receives the messages from all
1149 * menu selections that aren't standard OS X functions.
1151 @interface AppController : NSObject
1154 - (void)newGame:(id)sender;
1157 @implementation AppController
1159 - (void)newGame:(id)sender
1161 const game *g = [sender getPayload];
1164 win = [[GameWindow alloc] initWithGame:g];
1165 [win makeKeyAndOrderFront:self];
1168 - (NSMenu *)applicationDockMenu:(NSApplication *)sender
1170 NSMenu *menu = newmenu("Dock Menu");
1174 for (i = 0; i < gamecount; i++) {
1176 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1177 menu, gamelist[i]->name, "", self,
1178 @selector(newGame:));
1179 [item setPayload:(void *)gamelist[i]];
1187 /* ----------------------------------------------------------------------
1188 * Main program. Constructs the menus and runs the application.
1190 int main(int argc, char **argv)
1192 NSAutoreleasePool *pool;
1195 AppController *controller;
1198 pool = [[NSAutoreleasePool alloc] init];
1200 icon = [NSImage imageNamed:@"NSApplicationIcon"];
1201 [NSApplication sharedApplication];
1202 [NSApp setApplicationIconImage:icon];
1204 controller = [[[AppController alloc] init] autorelease];
1205 [NSApp setDelegate:controller];
1207 [NSApp setMainMenu: newmenu("Main Menu")];
1209 menu = newsubmenu([NSApp mainMenu], "Apple Menu");
1210 [NSApp setServicesMenu:newsubmenu(menu, "Services")];
1211 [menu addItem:[NSMenuItem separatorItem]];
1212 item = newitem(menu, "Hide Puzzles", "h", NSApp, @selector(hide:));
1213 item = newitem(menu, "Hide Others", "o-h", NSApp, @selector(hideOtherApplications:));
1214 item = newitem(menu, "Show All", "", NSApp, @selector(unhideAllApplications:));
1215 [menu addItem:[NSMenuItem separatorItem]];
1216 item = newitem(menu, "Quit", "q", NSApp, @selector(terminate:));
1217 [NSApp setAppleMenu: menu];
1219 menu = newsubmenu([NSApp mainMenu], "Open");
1223 for (i = 0; i < gamecount; i++) {
1225 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1226 menu, gamelist[i]->name, "", controller,
1227 @selector(newGame:));
1228 [item setPayload:(void *)gamelist[i]];
1232 menu = newsubmenu([NSApp mainMenu], "Game");
1233 item = newitem(menu, "New", "n", NULL, @selector(newGame:));
1234 item = newitem(menu, "Restart", "r", NULL, @selector(restartGame:));
1235 item = newitem(menu, "Specific", "", NULL, @selector(specificGame:));
1236 [menu addItem:[NSMenuItem separatorItem]];
1237 item = newitem(menu, "Undo", "z", NULL, @selector(undoMove:));
1238 item = newitem(menu, "Redo", "S-z", NULL, @selector(redoMove:));
1239 [menu addItem:[NSMenuItem separatorItem]];
1240 item = newitem(menu, "Copy", "c", NULL, @selector(copy:));
1241 [menu addItem:[NSMenuItem separatorItem]];
1242 item = newitem(menu, "Close", "w", NULL, @selector(performClose:));
1244 menu = newsubmenu([NSApp mainMenu], "Type");
1246 item = newitem(menu, "Custom", "", NULL, @selector(customGameType:));
1248 menu = newsubmenu([NSApp mainMenu], "Window");
1249 [NSApp setWindowsMenu: menu];
1250 item = newitem(menu, "Minimise Window", "m", NULL, @selector(performMiniaturize:));
1252 menu = newsubmenu([NSApp mainMenu], "Help");
1253 item = newitem(menu, "Puzzles Help", "?", NSApp, @selector(showHelp:));