2 * Mac OS X / Cocoa front end to puzzles.
6 * - status bar support.
8 * - configurability. Will no doubt involve learning all about the
9 * dialog control side of Cocoa.
11 * - not sure what I should be doing about default window
12 * placement. Centring new windows is a bit feeble, but what's
13 * better? Is there a standard way to tell the OS "here's the
14 * _size_ of window I want, now use your best judgment about the
17 * - a brief frob of the Mac numeric keypad suggests that it
18 * generates numbers no matter what you do. I wonder if I should
19 * try to figure out a way of detecting keypad codes so I can
20 * implement UP_LEFT and friends. Alternatively, perhaps I
21 * should simply assign the number keys to UP_LEFT et al?
22 * They're not in use for anything else right now.
24 * - proper fatal errors.
26 * - is there a better approach to frontend_default_colour?
28 * - do we need any more options in the Window menu?
30 * - see if we can do anything to one-button-ise the multi-button
31 * dependent puzzle UIs:
32 * - Pattern is a _little_ unwieldy but not too bad (since
33 * generally you never need the middle button unless you've
34 * made a mistake, so it's just click versus command-click).
35 * - Net is utterly vile; having normal click be one rotate and
36 * command-click be the other introduces a horrid asymmetry,
37 * and yet requiring a shift key for _each_ click would be
38 * even worse because rotation feels as if it ought to be the
39 * default action. I fear this is why the Flash Net had the
42 * - Find out how to do help, and do some. We have a help file; at
43 * _worst_ this should involve a new Halibut back end, but I
44 * think help is HTML round here anyway so perhaps we can work
45 * with what we already have.
47 * - Can we arrange for a pop-up menu from the Dock icon which
48 * launches specific games, perhaps?
50 * - Why are the right and bottom edges of the Pattern grid one
51 * pixel thinner than they should be?
53 * Grotty implementation details that could probably be improved:
55 * - I am _utterly_ unconvinced that NSImageView was the right way
56 * to go about having a window with a reliable backing store! It
57 * just doesn't feel right; NSImageView is a _control_. Is there
60 * - Resizing is currently very bad; rather than bother to work
61 * out how to resize the NSImageView, I just splatter and
67 #import <Cocoa/Cocoa.h>
70 void fatal(char *fmt, ...)
72 /* FIXME: This will do for testing, but should be GUI-ish instead. */
75 fprintf(stderr, "fatal error: ");
78 vfprintf(stderr, fmt, ap);
81 fprintf(stderr, "\n");
85 void frontend_default_colour(frontend *fe, float *output)
88 output[0] = output[1] = output[2] = 0.8F;
90 void status_bar(frontend *fe, char *text)
95 void get_random_seed(void **randseed, int *randseedsize)
97 time_t *tp = snew(time_t);
99 *randseed = (void *)tp;
100 *randseedsize = sizeof(time_t);
103 /* ----------------------------------------------------------------------
108 * The `Type' menu. We frob this dynamically to allow the user to
109 * choose a preset set of settings from the current game.
113 /* ----------------------------------------------------------------------
114 * Tiny extension to NSMenuItem which carries a payload of a `void
115 * *', allowing several menu items to invoke the same message but
116 * pass different data through it.
118 @interface DataMenuItem : NSMenuItem
122 - (void)setPayload:(void *)d;
123 - (void *)getPayload;
125 @implementation DataMenuItem
126 - (void)setPayload:(void *)d
136 /* ----------------------------------------------------------------------
137 * The front end presented to midend.c.
139 * This is mostly a subclass of NSWindow. The actual `frontend'
140 * structure passed to the midend contains a variety of pointers,
141 * including that window object but also including the image we
142 * draw on, an ImageView to display it in the window, and so on.
157 @interface MyImageView : NSImageView
161 - (void)setWindow:(GameWindow *)win;
163 - (void)mouseEvent:(NSEvent *)ev button:(int)b;
164 - (void)mouseDown:(NSEvent *)ev;
165 - (void)mouseDragged:(NSEvent *)ev;
166 - (void)mouseUp:(NSEvent *)ev;
167 - (void)rightMouseDown:(NSEvent *)ev;
168 - (void)rightMouseDragged:(NSEvent *)ev;
169 - (void)rightMouseUp:(NSEvent *)ev;
170 - (void)otherMouseDown:(NSEvent *)ev;
171 - (void)otherMouseDragged:(NSEvent *)ev;
172 - (void)otherMouseUp:(NSEvent *)ev;
175 @interface GameWindow : NSWindow
180 struct timeval last_time;
183 - (id)initWithGame:(const game *)g;
185 - (void)processButton:(int)b x:(int)x y:(int)y;
186 - (void)keyDown:(NSEvent *)ev;
187 - (void)activateTimer;
188 - (void)deactivateTimer;
191 @implementation MyImageView
193 - (void)setWindow:(GameWindow *)win
203 - (void)mouseEvent:(NSEvent *)ev button:(int)b
205 NSPoint point = [self convertPoint:[ev locationInWindow] fromView:nil];
206 [ourwin processButton:b x:point.x y:point.y];
209 - (void)mouseDown:(NSEvent *)ev
211 unsigned mod = [ev modifierFlags];
212 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_BUTTON :
213 (mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
216 - (void)mouseDragged:(NSEvent *)ev
218 unsigned mod = [ev modifierFlags];
219 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_DRAG :
220 (mod & NSShiftKeyMask) ? MIDDLE_DRAG :
223 - (void)mouseUp:(NSEvent *)ev
225 unsigned mod = [ev modifierFlags];
226 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_RELEASE :
227 (mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
230 - (void)rightMouseDown:(NSEvent *)ev
232 unsigned mod = [ev modifierFlags];
233 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
236 - (void)rightMouseDragged:(NSEvent *)ev
238 unsigned mod = [ev modifierFlags];
239 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_DRAG :
242 - (void)rightMouseUp:(NSEvent *)ev
244 unsigned mod = [ev modifierFlags];
245 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
248 - (void)otherMouseDown:(NSEvent *)ev
250 [self mouseEvent:ev button:MIDDLE_BUTTON];
252 - (void)otherMouseDragged:(NSEvent *)ev
254 [self mouseEvent:ev button:MIDDLE_DRAG];
256 - (void)otherMouseUp:(NSEvent *)ev
258 [self mouseEvent:ev button:MIDDLE_RELEASE];
262 @implementation GameWindow
263 - (void)setupContentView
268 midend_size(me, &w, &h);
272 fe.image = [[NSImage alloc] initWithSize:size];
273 [fe.image setFlipped:YES];
274 fe.view = [[MyImageView alloc]
275 initWithFrame:[self contentRectForFrameRect:[self frame]]];
276 [fe.view setImage:fe.image];
277 [fe.view setWindow:self];
281 [self setContentView:fe.view];
283 - (id)initWithGame:(const game *)g
285 NSRect rect = { {0,0}, {0,0} };
292 me = midend_new(&fe, ourgame);
294 * If we ever need to open a fresh window using a provided game
295 * ID, I think the right thing is to move most of this method
296 * into a new initWithGame:gameID: method, and have
297 * initWithGame: simply call that one and pass it NULL.
300 midend_size(me, &w, &h);
302 rect.size.height = h;
304 self = [super initWithContentRect:rect
305 styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
306 NSClosableWindowMask)
307 backing:NSBackingStoreBuffered
309 [self setTitle:[NSString stringWithCString:ourgame->name]];
315 colours = midend_colours(me, &ncolours);
316 fe.ncolours = ncolours;
317 fe.colours = snewn(ncolours, NSColor *);
319 for (i = 0; i < ncolours; i++) {
320 fe.colours[i] = [[NSColor colorWithDeviceRed:colours[i*3]
321 green:colours[i*3+1] blue:colours[i*3+2]
326 [self setupContentView];
327 [self setIgnoresMouseEvents:NO];
329 [self center]; /* :-) */
337 for (i = 0; i < fe.ncolours; i++) {
338 [fe.colours[i] release];
342 return [super dealloc];
345 - (void)processButton:(int)b x:(int)x y:(int)y
347 if (!midend_process_key(me, x, y, b))
351 - (void)keyDown:(NSEvent *)ev
353 NSString *s = [ev characters];
354 int i, n = [s length];
356 for (i = 0; i < n; i++) {
357 int c = [s characterAtIndex:i];
360 * ASCII gets passed straight to midend_process_key.
361 * Anything above that has to be translated to our own
362 * function key codes.
366 case NSUpArrowFunctionKey:
369 case NSDownArrowFunctionKey:
372 case NSLeftArrowFunctionKey:
375 case NSRightArrowFunctionKey:
383 [self processButton:c x:-1 y:-1];
387 - (void)activateTimer
392 timer = [NSTimer scheduledTimerWithTimeInterval:0.02
393 target:self selector:@selector(timerTick:)
394 userInfo:nil repeats:YES];
395 gettimeofday(&last_time, NULL);
398 - (void)deactivateTimer
407 - (void)timerTick:(id)sender
411 gettimeofday(&now, NULL);
412 elapsed = ((now.tv_usec - last_time.tv_usec) * 0.000001F +
413 (now.tv_sec - last_time.tv_sec));
414 midend_timer(me, elapsed);
418 - (void)newGame:(id)sender
420 [self processButton:'n' x:-1 y:-1];
422 - (void)restartGame:(id)sender
424 [self processButton:'r' x:-1 y:-1];
426 - (void)undoMove:(id)sender
428 [self processButton:'u' x:-1 y:-1];
430 - (void)redoMove:(id)sender
432 [self processButton:'r'&0x1F x:-1 y:-1];
435 - (void)clearTypeMenu
437 while ([typemenu numberOfItems] > 1)
438 [typemenu removeItemAtIndex:0];
441 - (void)becomeKeyWindow
445 [self clearTypeMenu];
447 [super becomeKeyWindow];
449 n = midend_num_presets(me);
452 [typemenu insertItem:[NSMenuItem separatorItem] atIndex:0];
458 midend_fetch_preset(me, n, &name, ¶ms);
460 item = [[[DataMenuItem alloc]
461 initWithTitle:[NSString stringWithCString:name]
462 action:NULL keyEquivalent:@""]
465 [item setEnabled:YES];
466 [item setTarget:self];
467 [item setAction:@selector(presetGame:)];
468 [item setPayload:params];
470 [typemenu insertItem:item atIndex:0];
475 - (void)resignKeyWindow
477 [self clearTypeMenu];
478 [super resignKeyWindow];
483 [self clearTypeMenu];
487 - (void)resizeForNewGameParams
492 midend_size(me, &w, &h);
496 NSDisableScreenUpdates();
497 [self setContentSize:size];
498 [self setupContentView];
499 NSEnableScreenUpdates();
502 - (void)presetGame:(id)sender
504 game_params *params = [sender getPayload];
506 midend_set_params(me, params);
509 [self resizeForNewGameParams];
515 * Drawing routines called by the midend.
517 void draw_polygon(frontend *fe, int *coords, int npoints,
518 int fill, int colour)
520 NSBezierPath *path = [NSBezierPath bezierPath];
523 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
525 assert(colour >= 0 && colour < fe->ncolours);
526 [fe->colours[colour] set];
528 for (i = 0; i < npoints; i++) {
529 NSPoint p = { coords[i*2] + 0.5, coords[i*2+1] + 0.5 };
531 [path moveToPoint:p];
533 [path lineToPoint:p];
543 void draw_line(frontend *fe, int x1, int y1, int x2, int y2, int colour)
545 NSBezierPath *path = [NSBezierPath bezierPath];
546 NSPoint p1 = { x1 + 0.5, y1 + 0.5 }, p2 = { x2 + 0.5, y2 + 0.5 };
548 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
550 assert(colour >= 0 && colour < fe->ncolours);
551 [fe->colours[colour] set];
553 [path moveToPoint:p1];
554 [path lineToPoint:p2];
557 void draw_rect(frontend *fe, int x, int y, int w, int h, int colour)
559 NSRect r = { {x,y}, {w,h} };
561 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
563 assert(colour >= 0 && colour < fe->ncolours);
564 [fe->colours[colour] set];
568 void draw_text(frontend *fe, int x, int y, int fonttype, int fontsize,
569 int align, int colour, char *text)
571 NSString *string = [NSString stringWithCString:text];
577 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
579 assert(colour >= 0 && colour < fe->ncolours);
581 if (fonttype == FONT_FIXED)
582 font = [NSFont userFixedPitchFontOfSize:fontsize];
584 font = [NSFont userFontOfSize:fontsize];
586 attr = [NSDictionary dictionaryWithObjectsAndKeys:
587 fe->colours[colour], NSForegroundColorAttributeName,
588 font, NSFontAttributeName, nil];
593 size = [string sizeWithAttributes:attr];
594 if (align & ALIGN_HRIGHT)
595 point.x -= size.width;
596 else if (align & ALIGN_HCENTRE)
597 point.x -= size.width / 2;
598 if (align & ALIGN_VCENTRE)
599 point.y -= size.height / 2;
601 [string drawAtPoint:point withAttributes:attr];
603 void draw_update(frontend *fe, int x, int y, int w, int h)
607 void clip(frontend *fe, int x, int y, int w, int h)
609 NSRect r = { {x,y}, {w,h} };
612 [[NSGraphicsContext currentContext] saveGraphicsState];
613 [NSBezierPath clipRect:r];
616 void unclip(frontend *fe)
619 [[NSGraphicsContext currentContext] restoreGraphicsState];
622 void start_draw(frontend *fe)
624 [fe->image lockFocus];
627 void end_draw(frontend *fe)
629 [fe->image unlockFocus];
630 [fe->view setNeedsDisplay];
633 void deactivate_timer(frontend *fe)
635 [fe->window deactivateTimer];
637 void activate_timer(frontend *fe)
639 [fe->window activateTimer];
642 /* ----------------------------------------------------------------------
643 * Utility routines for constructing OS X menus.
646 NSMenu *newmenu(const char *title)
648 return [[[NSMenu allocWithZone:[NSMenu menuZone]]
649 initWithTitle:[NSString stringWithCString:title]]
653 NSMenu *newsubmenu(NSMenu *parent, const char *title)
658 item = [[[NSMenuItem allocWithZone:[NSMenu menuZone]]
659 initWithTitle:[NSString stringWithCString:title]
663 child = newmenu(title);
664 [item setEnabled:YES];
665 [item setSubmenu:child];
666 [parent addItem:item];
670 id initnewitem(NSMenuItem *item, NSMenu *parent, const char *title,
671 const char *key, id target, SEL action)
673 unsigned mask = NSCommandKeyMask;
675 if (key[strcspn(key, "-")]) {
676 while (*key && *key != '-') {
677 int c = tolower((unsigned char)*key);
679 mask |= NSShiftKeyMask;
680 } else if (c == 'o' || c == 'a') {
681 mask |= NSAlternateKeyMask;
689 item = [[item initWithTitle:[NSString stringWithCString:title]
691 keyEquivalent:[NSString stringWithCString:key]]
695 [item setKeyEquivalentModifierMask: mask];
697 [item setEnabled:YES];
698 [item setTarget:target];
699 [item setAction:action];
701 [parent addItem:item];
706 NSMenuItem *newitem(NSMenu *parent, char *title, char *key,
707 id target, SEL action)
709 return initnewitem([NSMenuItem allocWithZone:[NSMenu menuZone]],
710 parent, title, key, target, action);
713 /* ----------------------------------------------------------------------
714 * AppController: the object which receives the messages from all
715 * menu selections that aren't standard OS X functions.
717 @interface AppController : NSObject
720 - (IBAction)newGame:(id)sender;
723 @implementation AppController
725 - (IBAction)newGame:(id)sender
727 const game *g = [sender getPayload];
730 win = [[GameWindow alloc] initWithGame:g];
731 [win makeKeyAndOrderFront:self];
736 /* ----------------------------------------------------------------------
737 * Main program. Constructs the menus and runs the application.
739 int main(int argc, char **argv)
741 NSAutoreleasePool *pool;
744 AppController *controller;
747 pool = [[NSAutoreleasePool alloc] init];
749 icon = [NSImage imageNamed:@"NSApplicationIcon"];
750 [NSApplication sharedApplication];
751 [NSApp setApplicationIconImage:icon];
753 controller = [[[AppController alloc] init] autorelease];
755 [NSApp setMainMenu: newmenu("Main Menu")];
757 menu = newsubmenu([NSApp mainMenu], "Apple Menu");
758 [NSApp setServicesMenu:newsubmenu(menu, "Services")];
759 [menu addItem:[NSMenuItem separatorItem]];
760 item = newitem(menu, "Hide Puzzles", "h", NSApp, @selector(hide:));
761 item = newitem(menu, "Hide Others", "o-h", NSApp, @selector(hideOtherApplications:));
762 item = newitem(menu, "Show All", "", NSApp, @selector(unhideAllApplications:));
763 [menu addItem:[NSMenuItem separatorItem]];
764 item = newitem(menu, "Quit", "q", NSApp, @selector(terminate:));
765 [NSApp setAppleMenu: menu];
767 menu = newsubmenu([NSApp mainMenu], "Open");
771 for (i = 0; i < gamecount; i++) {
773 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
774 menu, gamelist[i]->name, "", controller,
775 @selector(newGame:));
776 [item setPayload:(void *)gamelist[i]];
780 menu = newsubmenu([NSApp mainMenu], "Game");
781 item = newitem(menu, "New", "n", NULL, @selector(newGame:));
782 item = newitem(menu, "Restart", "r", NULL, @selector(restartGame:));
783 item = newitem(menu, "Specific", "", NULL, @selector(specificGame:));
784 [menu addItem:[NSMenuItem separatorItem]];
785 item = newitem(menu, "Undo", "z", NULL, @selector(undoMove:));
786 item = newitem(menu, "Redo", "S-z", NULL, @selector(redoMove:));
787 [menu addItem:[NSMenuItem separatorItem]];
788 item = newitem(menu, "Close", "w", NULL, @selector(performClose:));
790 menu = newsubmenu([NSApp mainMenu], "Type");
792 item = newitem(menu, "Custom", "", NULL, @selector(customGameType:));
794 menu = newsubmenu([NSApp mainMenu], "Window");
795 [NSApp setWindowsMenu: menu];
796 item = newitem(menu, "Minimise Window", "m", NULL, @selector(performMiniaturize:));