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)clearTypeMenu
576 while ([typemenu numberOfItems] > 1)
577 [typemenu removeItemAtIndex:0];
580 - (void)becomeKeyWindow
584 [self clearTypeMenu];
586 [super becomeKeyWindow];
588 n = midend_num_presets(me);
591 [typemenu insertItem:[NSMenuItem separatorItem] atIndex:0];
597 midend_fetch_preset(me, n, &name, ¶ms);
599 item = [[[DataMenuItem alloc]
600 initWithTitle:[NSString stringWithCString:name]
601 action:NULL keyEquivalent:@""]
604 [item setEnabled:YES];
605 [item setTarget:self];
606 [item setAction:@selector(presetGame:)];
607 [item setPayload:params];
609 [typemenu insertItem:item atIndex:0];
614 - (void)resignKeyWindow
616 [self clearTypeMenu];
617 [super resignKeyWindow];
622 [self clearTypeMenu];
626 - (void)resizeForNewGameParams
631 midend_size(me, &w, &h);
636 NSRect frame = [status frame];
637 size.height += frame.size.height;
638 frame.size.width = size.width;
639 [status setFrame:frame];
642 NSDisableScreenUpdates();
643 [self setContentSize:size];
644 [self setupContentView];
645 NSEnableScreenUpdates();
648 - (void)presetGame:(id)sender
650 game_params *params = [sender getPayload];
652 midend_set_params(me, params);
655 [self resizeForNewGameParams];
658 - (void)startConfigureSheet:(int)which
660 NSButton *ok, *cancel;
661 int actw, acth, leftw, rightw, totalw, h, thish, y;
663 NSRect rect, tmprect;
664 const int SPACING = 16;
672 assert(sheet == NULL);
675 * Every control we create here is going to have this size
676 * until we tell it to calculate a better one.
678 tmprect = NSMakeRect(0, 0, 100, 50);
681 * Set up OK and Cancel buttons. (Actually, MacOS doesn't seem
682 * to be fond of generic OK and Cancel wording, so I'm going to
683 * rename them to something nicer.)
687 cancel = [[NSButton alloc] initWithFrame:tmprect];
688 [cancel setBezelStyle:NSRoundedBezelStyle];
689 [cancel setTitle:@"Abandon"];
690 [cancel setTarget:self];
691 [cancel setKeyEquivalent:@"\033"];
692 [cancel setAction:@selector(sheetCancelButton:)];
694 rect = [cancel frame];
695 if (actw < rect.size.width) actw = rect.size.width;
696 if (acth < rect.size.height) acth = rect.size.height;
698 ok = [[NSButton alloc] initWithFrame:tmprect];
699 [ok setBezelStyle:NSRoundedBezelStyle];
700 [ok setTitle:@"Accept"];
702 [ok setKeyEquivalent:@"\r"];
703 [ok setAction:@selector(sheetOKButton:)];
706 if (actw < rect.size.width) actw = rect.size.width;
707 if (acth < rect.size.height) acth = rect.size.height;
709 totalw = SPACING + 2 * actw;
710 h = 2 * SPACING + acth;
713 * Now fetch the midend config data and go through it creating
716 cfg = midend_get_config(me, which, &title);
717 sfree(title); /* FIXME: should we use this somehow? */
720 cfg_ncontrols = cfg_controlsize = 0;
723 for (i = cfg; i->type != C_END; i++) {
724 if (cfg_controlsize < cfg_ncontrols + 5) {
725 cfg_controlsize = cfg_ncontrols + 32;
726 cfg_controls = sresize(cfg_controls, cfg_controlsize, NSView *);
734 * Two NSTextFields, one being a label and the other
738 tf = [[NSTextField alloc] initWithFrame:tmprect];
740 [tf setSelectable:NO];
742 [tf setDrawsBackground:NO];
743 [[tf cell] setTitle:[NSString stringWithCString:i->name]];
746 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
747 if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
748 cfg_controls[cfg_ncontrols++] = tf;
750 tf = [[NSTextField alloc] initWithFrame:tmprect];
751 [tf setEditable:YES];
752 [tf setSelectable:YES];
753 [tf setBordered:YES];
754 [[tf cell] setTitle:[NSString stringWithCString:i->sval]];
758 * We impose a minimum and maximum width on editable
759 * NSTextFields. If we allow them to size themselves to
760 * the contents of the text within them, then they will
761 * look very silly if that text is only one or two
762 * characters, and equally silly if it's an absolutely
763 * enormous Rectangles or Pattern game ID!
765 if (rect.size.width < 75) rect.size.width = 75;
766 if (rect.size.width > 400) rect.size.width = 400;
768 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
769 if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
770 cfg_controls[cfg_ncontrols++] = tf;
775 * A checkbox is an NSButton with a type of
778 b = [[NSButton alloc] initWithFrame:tmprect];
779 [b setBezelStyle:NSRoundedBezelStyle];
780 [b setButtonType:NSSwitchButton];
781 [b setTitle:[NSString stringWithCString:i->name]];
783 [b setState:(i->ival ? NSOnState : NSOffState)];
785 if (totalw < rect.size.width + 1) totalw = rect.size.width + 1;
786 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
787 cfg_controls[cfg_ncontrols++] = b;
792 * A pop-up menu control is an NSPopUpButton, which
793 * takes an embedded NSMenu. We also need an
794 * NSTextField to act as a label.
797 tf = [[NSTextField alloc] initWithFrame:tmprect];
799 [tf setSelectable:NO];
801 [tf setDrawsBackground:NO];
802 [[tf cell] setTitle:[NSString stringWithCString:i->name]];
805 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
806 if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
807 cfg_controls[cfg_ncontrols++] = tf;
809 pb = [[NSPopUpButton alloc] initWithFrame:tmprect pullsDown:NO];
810 [pb setBezelStyle:NSRoundedBezelStyle];
820 while (*p && *p != c) p++;
822 [pb addItemWithTitle:[NSString stringWithCString:q
828 [pb selectItemAtIndex:i->ival];
832 if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
833 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
834 cfg_controls[cfg_ncontrols++] = pb;
838 h += SPACING + thish;
841 if (totalw < leftw + SPACING + rightw)
842 totalw = leftw + SPACING + rightw;
843 if (totalw > leftw + SPACING + rightw) {
844 int excess = totalw - (leftw + SPACING + rightw);
845 int leftexcess = leftw * excess / (leftw + rightw);
846 int rightexcess = excess - leftexcess;
848 rightw += rightexcess;
852 * Now go through the list again, setting the final position
857 for (i = cfg; i->type != C_END; i++) {
864 * These two are treated identically, since both expect
865 * a control on the left and another on the right.
867 rect = [cfg_controls[k] frame];
868 if (thish < rect.size.height + 1)
869 thish = rect.size.height + 1;
870 rect = [cfg_controls[k+1] frame];
871 if (thish < rect.size.height + 1)
872 thish = rect.size.height + 1;
873 rect = [cfg_controls[k] frame];
874 rect.origin.y = y - thish/2 - rect.size.height/2;
875 rect.origin.x = SPACING;
876 rect.size.width = leftw;
877 [cfg_controls[k] setFrame:rect];
878 rect = [cfg_controls[k+1] frame];
879 rect.origin.y = y - thish/2 - rect.size.height/2;
880 rect.origin.x = 2 * SPACING + leftw;
881 rect.size.width = rightw;
882 [cfg_controls[k+1] setFrame:rect];
887 rect = [cfg_controls[k] frame];
888 if (thish < rect.size.height + 1)
889 thish = rect.size.height + 1;
890 rect.origin.y = y - thish/2 - rect.size.height/2;
891 rect.origin.x = SPACING;
892 rect.size.width = totalw;
893 [cfg_controls[k] setFrame:rect];
900 assert(k == cfg_ncontrols);
902 [cancel setFrame:NSMakeRect(SPACING+totalw/4-actw/2, SPACING, actw, acth)];
903 [ok setFrame:NSMakeRect(SPACING+3*totalw/4-actw/2, SPACING, actw, acth)];
905 sheet = [[NSWindow alloc]
906 initWithContentRect:NSMakeRect(0,0,totalw + 2*SPACING,h)
907 styleMask:NSTitledWindowMask | NSClosableWindowMask
908 backing:NSBackingStoreBuffered
911 [[sheet contentView] addSubview:cancel];
912 [[sheet contentView] addSubview:ok];
914 for (k = 0; k < cfg_ncontrols; k++)
915 [[sheet contentView] addSubview:cfg_controls[k]];
917 [NSApp beginSheet:sheet modalForWindow:self
918 modalDelegate:nil didEndSelector:nil contextInfo:nil];
921 - (void)specificGame:(id)sender
923 [self startConfigureSheet:CFG_SEED];
926 - (void)customGameType:(id)sender
928 [self startConfigureSheet:CFG_SETTINGS];
931 - (void)sheetEndWithStatus:(BOOL)update
933 assert(sheet != NULL);
934 [NSApp endSheet:sheet];
935 [sheet orderOut:self];
943 for (i = cfg; i->type != C_END; i++) {
947 i->sval = dupstr([[[(id)cfg_controls[k+1] cell]
952 i->ival = [(id)cfg_controls[k] state] == NSOnState;
956 i->ival = [(id)cfg_controls[k+1] indexOfSelectedItem];
962 error = midend_set_config(me, cfg_which, cfg);
964 NSAlert *alert = [[[NSAlert alloc] init] autorelease];
965 [alert addButtonWithTitle:@"Bah"];
966 [alert setInformativeText:[NSString stringWithCString:error]];
967 [alert beginSheetModalForWindow:self modalDelegate:nil
968 didEndSelector:nil contextInfo:nil];
971 [self resizeForNewGameParams];
977 - (void)sheetOKButton:(id)sender
979 [self sheetEndWithStatus:YES];
981 - (void)sheetCancelButton:(id)sender
983 [self sheetEndWithStatus:NO];
986 - (void)setStatusLine:(NSString *)text
988 [[status cell] setTitle:text];
994 * Drawing routines called by the midend.
996 void draw_polygon(frontend *fe, int *coords, int npoints,
997 int fill, int colour)
999 NSBezierPath *path = [NSBezierPath bezierPath];
1002 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1004 assert(colour >= 0 && colour < fe->ncolours);
1005 [fe->colours[colour] set];
1007 for (i = 0; i < npoints; i++) {
1008 NSPoint p = { coords[i*2] + 0.5, coords[i*2+1] + 0.5 };
1010 [path moveToPoint:p];
1012 [path lineToPoint:p];
1022 void draw_line(frontend *fe, int x1, int y1, int x2, int y2, int colour)
1024 NSBezierPath *path = [NSBezierPath bezierPath];
1025 NSPoint p1 = { x1 + 0.5, y1 + 0.5 }, p2 = { x2 + 0.5, y2 + 0.5 };
1027 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1029 assert(colour >= 0 && colour < fe->ncolours);
1030 [fe->colours[colour] set];
1032 [path moveToPoint:p1];
1033 [path lineToPoint:p2];
1036 void draw_rect(frontend *fe, int x, int y, int w, int h, int colour)
1038 NSRect r = { {x,y}, {w,h} };
1040 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1042 assert(colour >= 0 && colour < fe->ncolours);
1043 [fe->colours[colour] set];
1047 void draw_text(frontend *fe, int x, int y, int fonttype, int fontsize,
1048 int align, int colour, char *text)
1050 NSString *string = [NSString stringWithCString:text];
1056 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1058 assert(colour >= 0 && colour < fe->ncolours);
1060 if (fonttype == FONT_FIXED)
1061 font = [NSFont userFixedPitchFontOfSize:fontsize];
1063 font = [NSFont userFontOfSize:fontsize];
1065 attr = [NSDictionary dictionaryWithObjectsAndKeys:
1066 fe->colours[colour], NSForegroundColorAttributeName,
1067 font, NSFontAttributeName, nil];
1072 size = [string sizeWithAttributes:attr];
1073 if (align & ALIGN_HRIGHT)
1074 point.x -= size.width;
1075 else if (align & ALIGN_HCENTRE)
1076 point.x -= size.width / 2;
1077 if (align & ALIGN_VCENTRE)
1078 point.y -= size.height / 2;
1080 [string drawAtPoint:point withAttributes:attr];
1082 void draw_update(frontend *fe, int x, int y, int w, int h)
1084 [fe->view setNeedsDisplayInRect:NSMakeRect(x,y,w,h)];
1086 void clip(frontend *fe, int x, int y, int w, int h)
1088 NSRect r = { {x,y}, {w,h} };
1091 [[NSGraphicsContext currentContext] saveGraphicsState];
1092 [NSBezierPath clipRect:r];
1095 void unclip(frontend *fe)
1098 [[NSGraphicsContext currentContext] restoreGraphicsState];
1099 fe->clipped = FALSE;
1101 void start_draw(frontend *fe)
1103 [fe->image lockFocus];
1104 fe->clipped = FALSE;
1106 void end_draw(frontend *fe)
1108 [fe->image unlockFocus];
1111 void deactivate_timer(frontend *fe)
1113 [fe->window deactivateTimer];
1115 void activate_timer(frontend *fe)
1117 [fe->window activateTimer];
1120 void status_bar(frontend *fe, char *text)
1122 [fe->window setStatusLine:[NSString stringWithCString:text]];
1125 /* ----------------------------------------------------------------------
1126 * AppController: the object which receives the messages from all
1127 * menu selections that aren't standard OS X functions.
1129 @interface AppController : NSObject
1132 - (void)newGame:(id)sender;
1135 @implementation AppController
1137 - (void)newGame:(id)sender
1139 const game *g = [sender getPayload];
1142 win = [[GameWindow alloc] initWithGame:g];
1143 [win makeKeyAndOrderFront:self];
1146 - (NSMenu *)applicationDockMenu:(NSApplication *)sender
1148 NSMenu *menu = newmenu("Dock Menu");
1152 for (i = 0; i < gamecount; i++) {
1154 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1155 menu, gamelist[i]->name, "", self,
1156 @selector(newGame:));
1157 [item setPayload:(void *)gamelist[i]];
1165 /* ----------------------------------------------------------------------
1166 * Main program. Constructs the menus and runs the application.
1168 int main(int argc, char **argv)
1170 NSAutoreleasePool *pool;
1173 AppController *controller;
1176 pool = [[NSAutoreleasePool alloc] init];
1178 icon = [NSImage imageNamed:@"NSApplicationIcon"];
1179 [NSApplication sharedApplication];
1180 [NSApp setApplicationIconImage:icon];
1182 controller = [[[AppController alloc] init] autorelease];
1183 [NSApp setDelegate:controller];
1185 [NSApp setMainMenu: newmenu("Main Menu")];
1187 menu = newsubmenu([NSApp mainMenu], "Apple Menu");
1188 [NSApp setServicesMenu:newsubmenu(menu, "Services")];
1189 [menu addItem:[NSMenuItem separatorItem]];
1190 item = newitem(menu, "Hide Puzzles", "h", NSApp, @selector(hide:));
1191 item = newitem(menu, "Hide Others", "o-h", NSApp, @selector(hideOtherApplications:));
1192 item = newitem(menu, "Show All", "", NSApp, @selector(unhideAllApplications:));
1193 [menu addItem:[NSMenuItem separatorItem]];
1194 item = newitem(menu, "Quit", "q", NSApp, @selector(terminate:));
1195 [NSApp setAppleMenu: menu];
1197 menu = newsubmenu([NSApp mainMenu], "Open");
1201 for (i = 0; i < gamecount; i++) {
1203 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1204 menu, gamelist[i]->name, "", controller,
1205 @selector(newGame:));
1206 [item setPayload:(void *)gamelist[i]];
1210 menu = newsubmenu([NSApp mainMenu], "Game");
1211 item = newitem(menu, "New", "n", NULL, @selector(newGame:));
1212 item = newitem(menu, "Restart", "r", NULL, @selector(restartGame:));
1213 item = newitem(menu, "Specific", "", NULL, @selector(specificGame:));
1214 [menu addItem:[NSMenuItem separatorItem]];
1215 item = newitem(menu, "Undo", "z", NULL, @selector(undoMove:));
1216 item = newitem(menu, "Redo", "S-z", NULL, @selector(redoMove:));
1217 [menu addItem:[NSMenuItem separatorItem]];
1218 item = newitem(menu, "Close", "w", NULL, @selector(performClose:));
1220 menu = newsubmenu([NSApp mainMenu], "Type");
1222 item = newitem(menu, "Custom", "", NULL, @selector(customGameType:));
1224 menu = newsubmenu([NSApp mainMenu], "Window");
1225 [NSApp setWindowsMenu: menu];
1226 item = newitem(menu, "Minimise Window", "m", NULL, @selector(performMiniaturize:));
1228 menu = newsubmenu([NSApp mainMenu], "Help");
1229 item = newitem(menu, "Puzzles Help", "?", NSApp, @selector(showHelp:));