2 * Mac OS X / Cocoa front end to puzzles.
6 * - status bar support.
8 * - preset selection. Should be reasonably simple: just a matter
9 * of dynamically frobbing the menu bar.
11 * - configurability. Will no doubt involve learning all about the
12 * dialog control side of Cocoa.
16 * - not sure what I should be doing about default window
17 * placement. Centring new windows is a bit feeble, but what's
18 * better? Is there a standard way to tell the OS "here's the
19 * _size_ of window I want, now use your best judgment about the
22 * - a brief frob of the Mac numeric keypad suggests that it
23 * generates numbers no matter what you do. I wonder if I should
24 * try to figure out a way of detecting keypad codes so I can
25 * implement UP_LEFT and friends. Alternatively, perhaps I
26 * should simply assign the number keys to UP_LEFT et al?
27 * They're not in use for anything else right now.
29 * - proper fatal errors.
31 * - is there a better approach to frontend_default_colour?
33 * - do we need any more options in the Window menu?
35 * - see if we can do anything to one-button-ise the multi-button
36 * dependent puzzle UIs:
37 * - Pattern is a _little_ unwieldy but not too bad (since
38 * generally you never need the middle button unless you've
39 * made a mistake, so it's just click versus command-click).
40 * - Net is utterly vile; having normal click be one rotate and
41 * command-click be the other introduces a horrid asymmetry,
42 * and yet requiring a shift key for _each_ click would be
43 * even worse because rotation feels as if it ought to be the
44 * default action. I fear this is why the Flash Net had the
47 * - Find out how to do help, and do some. We have a help file; at
48 * _worst_ this should involve a new Halibut back end, but I
49 * think help is HTML round here anyway so perhaps we can work
50 * with what we already have.
55 #import <Cocoa/Cocoa.h>
58 void fatal(char *fmt, ...)
60 /* FIXME: This will do for testing, but should be GUI-ish instead. */
63 fprintf(stderr, "fatal error: ");
66 vfprintf(stderr, fmt, ap);
69 fprintf(stderr, "\n");
73 void frontend_default_colour(frontend *fe, float *output)
76 output[0] = output[1] = output[2] = 0.8F;
78 void status_bar(frontend *fe, char *text)
83 void get_random_seed(void **randseed, int *randseedsize)
85 time_t *tp = snew(time_t);
87 *randseed = (void *)tp;
88 *randseedsize = sizeof(time_t);
91 /* ----------------------------------------------------------------------
92 * The front end presented to midend.c.
94 * This is mostly a subclass of NSWindow. The actual `frontend'
95 * structure passed to the midend contains a variety of pointers,
96 * including that window object but also including the image we
97 * draw on, an ImageView to display it in the window, and so on.
112 @interface MyImageView : NSImageView
116 - (void)setWindow:(GameWindow *)win;
118 - (void)mouseEvent:(NSEvent *)ev button:(int)b;
119 - (void)mouseDown:(NSEvent *)ev;
120 - (void)mouseDragged:(NSEvent *)ev;
121 - (void)mouseUp:(NSEvent *)ev;
122 - (void)rightMouseDown:(NSEvent *)ev;
123 - (void)rightMouseDragged:(NSEvent *)ev;
124 - (void)rightMouseUp:(NSEvent *)ev;
125 - (void)otherMouseDown:(NSEvent *)ev;
126 - (void)otherMouseDragged:(NSEvent *)ev;
127 - (void)otherMouseUp:(NSEvent *)ev;
130 @interface GameWindow : NSWindow
135 struct timeval last_time;
138 - (id)initWithGame:(const game *)g;
140 - (void)processButton:(int)b x:(int)x y:(int)y;
141 - (void)keyDown:(NSEvent *)ev;
142 - (void)activateTimer;
143 - (void)deactivateTimer;
146 @implementation MyImageView
148 - (void)setWindow:(GameWindow *)win
158 - (void)mouseEvent:(NSEvent *)ev button:(int)b
160 NSPoint point = [self convertPoint:[ev locationInWindow] fromView:nil];
161 [ourwin processButton:b x:point.x y:point.y];
164 - (void)mouseDown:(NSEvent *)ev
166 unsigned mod = [ev modifierFlags];
167 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_BUTTON :
168 (mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
171 - (void)mouseDragged:(NSEvent *)ev
173 unsigned mod = [ev modifierFlags];
174 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_DRAG :
175 (mod & NSShiftKeyMask) ? MIDDLE_DRAG :
178 - (void)mouseUp:(NSEvent *)ev
180 unsigned mod = [ev modifierFlags];
181 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_RELEASE :
182 (mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
185 - (void)rightMouseDown:(NSEvent *)ev
187 unsigned mod = [ev modifierFlags];
188 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
191 - (void)rightMouseDragged:(NSEvent *)ev
193 unsigned mod = [ev modifierFlags];
194 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_DRAG :
197 - (void)rightMouseUp:(NSEvent *)ev
199 unsigned mod = [ev modifierFlags];
200 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
203 - (void)otherMouseDown:(NSEvent *)ev
205 [self mouseEvent:ev button:MIDDLE_BUTTON];
207 - (void)otherMouseDragged:(NSEvent *)ev
209 [self mouseEvent:ev button:MIDDLE_DRAG];
211 - (void)otherMouseUp:(NSEvent *)ev
213 [self mouseEvent:ev button:MIDDLE_RELEASE];
217 @implementation GameWindow
218 - (id)initWithGame:(const game *)g
220 NSRect rect = { {0,0}, {0,0} };
227 me = midend_new(&fe, ourgame);
229 * If we ever need to open a fresh window using a provided game
230 * ID, I think the right thing is to move most of this method
231 * into a new initWithGame:gameID: method, and have
232 * initWithGame: simply call that one and pass it NULL.
235 midend_size(me, &w, &h);
237 rect.size.height = h;
239 self = [super initWithContentRect:rect
240 styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
241 NSClosableWindowMask)
242 backing:NSBackingStoreBuffered
244 [self setTitle:[NSString stringWithCString:ourgame->name]];
250 colours = midend_colours(me, &ncolours);
251 fe.ncolours = ncolours;
252 fe.colours = snewn(ncolours, NSColor *);
254 for (i = 0; i < ncolours; i++) {
255 fe.colours[i] = [[NSColor colorWithDeviceRed:colours[i*3]
256 green:colours[i*3+1] blue:colours[i*3+2]
261 fe.image = [[NSImage alloc] initWithSize:rect.size];
262 [fe.image setFlipped:YES];
263 fe.view = [[MyImageView alloc]
264 initWithFrame:[self contentRectForFrameRect:[self frame]]];
265 [fe.view setImage:fe.image];
266 [fe.view setWindow:self];
267 [self setContentView:fe.view];
268 [self setIgnoresMouseEvents:NO];
272 [self center]; /* :-) */
280 for (i = 0; i < fe.ncolours; i++) {
281 [fe.colours[i] release];
285 return [super dealloc];
288 - (void)processButton:(int)b x:(int)x y:(int)y
290 if (!midend_process_key(me, x, y, b))
294 - (void)keyDown:(NSEvent *)ev
296 NSString *s = [ev characters];
297 int i, n = [s length];
299 for (i = 0; i < n; i++) {
300 int c = [s characterAtIndex:i];
303 * ASCII gets passed straight to midend_process_key.
304 * Anything above that has to be translated to our own
305 * function key codes.
309 case NSUpArrowFunctionKey:
312 case NSDownArrowFunctionKey:
315 case NSLeftArrowFunctionKey:
318 case NSRightArrowFunctionKey:
326 [self processButton:c x:-1 y:-1];
330 - (void)activateTimer
335 timer = [NSTimer scheduledTimerWithTimeInterval:0.02
336 target:self selector:@selector(timerTick:)
337 userInfo:nil repeats:YES];
338 gettimeofday(&last_time, NULL);
341 - (void)deactivateTimer
350 - (void)timerTick:(id)sender
354 gettimeofday(&now, NULL);
355 elapsed = ((now.tv_usec - last_time.tv_usec) * 0.000001F +
356 (now.tv_sec - last_time.tv_sec));
357 midend_timer(me, elapsed);
361 - (void)newGame:(id)sender
363 [self processButton:'n' x:-1 y:-1];
365 - (void)restartGame:(id)sender
367 [self processButton:'r' x:-1 y:-1];
369 - (void)undoMove:(id)sender
371 [self processButton:'u' x:-1 y:-1];
373 - (void)redoMove:(id)sender
375 [self processButton:'r'&0x1F x:-1 y:-1];
381 * Drawing routines called by the midend.
383 void draw_polygon(frontend *fe, int *coords, int npoints,
384 int fill, int colour)
386 NSBezierPath *path = [NSBezierPath bezierPath];
389 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
391 assert(colour >= 0 && colour < fe->ncolours);
392 [fe->colours[colour] set];
394 for (i = 0; i < npoints; i++) {
395 NSPoint p = { coords[i*2] + 0.5, coords[i*2+1] + 0.5 };
397 [path moveToPoint:p];
399 [path lineToPoint:p];
409 void draw_line(frontend *fe, int x1, int y1, int x2, int y2, int colour)
411 NSBezierPath *path = [NSBezierPath bezierPath];
412 NSPoint p1 = { x1 + 0.5, y1 + 0.5 }, p2 = { x2 + 0.5, y2 + 0.5 };
414 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
416 assert(colour >= 0 && colour < fe->ncolours);
417 [fe->colours[colour] set];
419 [path moveToPoint:p1];
420 [path lineToPoint:p2];
423 void draw_rect(frontend *fe, int x, int y, int w, int h, int colour)
425 NSRect r = { {x,y}, {w,h} };
427 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
429 assert(colour >= 0 && colour < fe->ncolours);
430 [fe->colours[colour] set];
434 void draw_text(frontend *fe, int x, int y, int fonttype, int fontsize,
435 int align, int colour, char *text)
437 NSString *string = [NSString stringWithCString:text];
443 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
445 assert(colour >= 0 && colour < fe->ncolours);
447 if (fonttype == FONT_FIXED)
448 font = [NSFont userFixedPitchFontOfSize:fontsize];
450 font = [NSFont userFontOfSize:fontsize];
452 attr = [NSDictionary dictionaryWithObjectsAndKeys:
453 fe->colours[colour], NSForegroundColorAttributeName,
454 font, NSFontAttributeName, nil];
459 size = [string sizeWithAttributes:attr];
460 if (align & ALIGN_HRIGHT)
461 point.x -= size.width;
462 else if (align & ALIGN_HCENTRE)
463 point.x -= size.width / 2;
464 if (align & ALIGN_VCENTRE)
465 point.y -= size.height / 2;
467 [string drawAtPoint:point withAttributes:attr];
469 void draw_update(frontend *fe, int x, int y, int w, int h)
473 void clip(frontend *fe, int x, int y, int w, int h)
475 NSRect r = { {x,y}, {w,h} };
478 [[NSGraphicsContext currentContext] saveGraphicsState];
479 [NSBezierPath clipRect:r];
482 void unclip(frontend *fe)
485 [[NSGraphicsContext currentContext] restoreGraphicsState];
488 void start_draw(frontend *fe)
490 [fe->image lockFocus];
493 void end_draw(frontend *fe)
495 [fe->image unlockFocus];
496 [fe->view setNeedsDisplay];
499 void deactivate_timer(frontend *fe)
501 [fe->window deactivateTimer];
503 void activate_timer(frontend *fe)
505 [fe->window activateTimer];
508 /* ----------------------------------------------------------------------
509 * Utility routines for constructing OS X menus.
512 NSMenu *newmenu(const char *title)
514 return [[[NSMenu allocWithZone:[NSMenu menuZone]]
515 initWithTitle:[NSString stringWithCString:title]]
519 NSMenu *newsubmenu(NSMenu *parent, const char *title)
524 item = [[[NSMenuItem allocWithZone:[NSMenu menuZone]]
525 initWithTitle:[NSString stringWithCString:title]
529 child = newmenu(title);
530 [item setEnabled:YES];
531 [item setSubmenu:child];
532 [parent addItem:item];
536 id initnewitem(NSMenuItem *item, NSMenu *parent, const char *title,
537 const char *key, id target, SEL action)
539 unsigned mask = NSCommandKeyMask;
541 if (key[strcspn(key, "-")]) {
542 while (*key && *key != '-') {
543 int c = tolower((unsigned char)*key);
545 mask |= NSShiftKeyMask;
546 } else if (c == 'o' || c == 'a') {
547 mask |= NSAlternateKeyMask;
555 item = [[item initWithTitle:[NSString stringWithCString:title]
557 keyEquivalent:[NSString stringWithCString:key]]
561 [item setKeyEquivalentModifierMask: mask];
563 [item setEnabled:YES];
564 [item setTarget:target];
565 [item setAction:action];
567 [parent addItem:item];
572 NSMenuItem *newitem(NSMenu *parent, char *title, char *key,
573 id target, SEL action)
575 return initnewitem([NSMenuItem allocWithZone:[NSMenu menuZone]],
576 parent, title, key, target, action);
579 /* ----------------------------------------------------------------------
580 * Tiny extension to NSMenuItem which carries a payload of a `const
581 * game *', allowing our AppController to work out _which_ game
582 * needs to be launched when it receives a newGame message.
584 @interface GameMenuItem : NSMenuItem
588 - (void)setGame:(const game *)g;
589 - (const game *)getGame;
591 @implementation GameMenuItem
592 - (void)setGame:(const game *)g
596 - (const game *)getGame
602 /* ----------------------------------------------------------------------
603 * AppController: the object which receives the messages from all
604 * menu selections that aren't standard OS X functions.
606 @interface AppController : NSObject
609 - (IBAction)newGame:(id)sender;
612 @implementation AppController
614 - (IBAction)newGame:(id)sender
616 const game *g = [sender getGame];
619 win = [[GameWindow alloc] initWithGame:g];
620 [win makeKeyAndOrderFront:self];
625 /* ----------------------------------------------------------------------
626 * Main program. Constructs the menus and runs the application.
628 int main(int argc, char **argv)
630 NSAutoreleasePool *pool;
633 AppController *controller;
635 pool = [[NSAutoreleasePool alloc] init];
636 [NSApplication sharedApplication];
638 controller = [[[AppController alloc] init] autorelease];
640 [NSApp setMainMenu: newmenu("Main Menu")];
642 menu = newsubmenu([NSApp mainMenu], "Apple Menu");
643 [NSApp setServicesMenu:newsubmenu(menu, "Services")];
644 [menu addItem:[NSMenuItem separatorItem]];
645 item = newitem(menu, "Hide Puzzles", "h", NSApp, @selector(hide:));
646 item = newitem(menu, "Hide Others", "o-h", NSApp, @selector(hideOtherApplications:));
647 item = newitem(menu, "Show All", "", NSApp, @selector(unhideAllApplications:));
648 [menu addItem:[NSMenuItem separatorItem]];
649 item = newitem(menu, "Quit", "q", NSApp, @selector(terminate:));
650 [NSApp setAppleMenu: menu];
652 menu = newsubmenu([NSApp mainMenu], "Open");
656 for (i = 0; i < gamecount; i++) {
658 initnewitem([GameMenuItem allocWithZone:[NSMenu menuZone]],
659 menu, gamelist[i]->name, "", controller,
660 @selector(newGame:));
661 [item setGame:gamelist[i]];
665 menu = newsubmenu([NSApp mainMenu], "Game");
666 item = newitem(menu, "New", "n", NULL, @selector(newGame:));
667 item = newitem(menu, "Restart", "r", NULL, @selector(restartGame:));
668 item = newitem(menu, "Specific", "", NULL, @selector(specificGame:));
669 [menu addItem:[NSMenuItem separatorItem]];
670 item = newitem(menu, "Undo", "z", NULL, @selector(undoMove:));
671 item = newitem(menu, "Redo", "S-z", NULL, @selector(redoMove:));
672 [menu addItem:[NSMenuItem separatorItem]];
673 item = newitem(menu, "Close", "w", NULL, @selector(performClose:));
675 menu = newsubmenu([NSApp mainMenu], "Type");
676 item = newitem(menu, "Custom", "", NULL, @selector(customGameType:));
678 menu = newsubmenu([NSApp mainMenu], "Window");
679 [NSApp setWindowsMenu: menu];
680 item = newitem(menu, "Minimise Window", "m", NULL, @selector(performMiniaturize:));