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.
13 * - not sure what I should be doing about default window
14 * placement. Centring new windows is a bit feeble, but what's
15 * better? Is there a standard way to tell the OS "here's the
16 * _size_ of window I want, now use your best judgment about the
19 * - a brief frob of the Mac numeric keypad suggests that it
20 * generates numbers no matter what you do. I wonder if I should
21 * try to figure out a way of detecting keypad codes so I can
22 * implement UP_LEFT and friends. Alternatively, perhaps I
23 * should simply assign the number keys to UP_LEFT et al?
24 * They're not in use for anything else right now.
26 * - proper fatal errors.
28 * - is there a better approach to frontend_default_colour?
30 * - do we need any more options in the Window menu?
32 * - see if we can do anything to one-button-ise the multi-button
33 * dependent puzzle UIs:
34 * - Pattern is a _little_ unwieldy but not too bad (since
35 * generally you never need the middle button unless you've
36 * made a mistake, so it's just click versus command-click).
37 * - Net is utterly vile; having normal click be one rotate and
38 * command-click be the other introduces a horrid asymmetry,
39 * and yet requiring a shift key for _each_ click would be
40 * even worse because rotation feels as if it ought to be the
41 * default action. I fear this is why the Flash Net had the
44 * - Find out how to do help, and do some. We have a help file; at
45 * _worst_ this should involve a new Halibut back end, but I
46 * think help is HTML round here anyway so perhaps we can work
47 * with what we already have.
49 * - Can we arrange for a pop-up menu from the Dock icon which
50 * launches specific games, perhaps?
52 * - Why are the right and bottom edges of the Pattern grid one
53 * pixel thinner than they should be?
55 * Grotty implementation details that could probably be improved:
57 * - I am _utterly_ unconvinced that NSImageView was the right way
58 * to go about having a window with a reliable backing store! It
59 * just doesn't feel right; NSImageView is a _control_. Is there
62 * - Resizing is currently very bad; rather than bother to work
63 * out how to resize the NSImageView, I just splatter and
69 #import <Cocoa/Cocoa.h>
72 void fatal(char *fmt, ...)
74 /* FIXME: This will do for testing, but should be GUI-ish instead. */
77 fprintf(stderr, "fatal error: ");
80 vfprintf(stderr, fmt, ap);
83 fprintf(stderr, "\n");
87 void frontend_default_colour(frontend *fe, float *output)
90 output[0] = output[1] = output[2] = 0.8F;
92 void status_bar(frontend *fe, char *text)
97 void get_random_seed(void **randseed, int *randseedsize)
99 time_t *tp = snew(time_t);
101 *randseed = (void *)tp;
102 *randseedsize = sizeof(time_t);
105 /* ----------------------------------------------------------------------
110 * The `Type' menu. We frob this dynamically to allow the user to
111 * choose a preset set of settings from the current game.
115 /* ----------------------------------------------------------------------
116 * Tiny extension to NSMenuItem which carries a payload of a `void
117 * *', allowing several menu items to invoke the same message but
118 * pass different data through it.
120 @interface DataMenuItem : NSMenuItem
125 - (void)setPayload:(void *)d;
126 - (void)setPayloadFree:(BOOL)yesno;
127 - (void *)getPayload;
129 @implementation DataMenuItem
130 - (id)initWithTitle:(NSString *)title
132 keyEquivalent:(NSString *)key
134 id ret = [super initWithTitle:title action:act keyEquivalent:key];
139 - (void)setPayload:(void *)d
143 - (void)setPayloadFree:(BOOL)yesno
145 payload_free = yesno;
159 /* ----------------------------------------------------------------------
160 * The front end presented to midend.c.
162 * This is mostly a subclass of NSWindow. The actual `frontend'
163 * structure passed to the midend contains a variety of pointers,
164 * including that window object but also including the image we
165 * draw on, an ImageView to display it in the window, and so on.
180 @interface MyImageView : NSImageView
184 - (void)setWindow:(GameWindow *)win;
186 - (void)mouseEvent:(NSEvent *)ev button:(int)b;
187 - (void)mouseDown:(NSEvent *)ev;
188 - (void)mouseDragged:(NSEvent *)ev;
189 - (void)mouseUp:(NSEvent *)ev;
190 - (void)rightMouseDown:(NSEvent *)ev;
191 - (void)rightMouseDragged:(NSEvent *)ev;
192 - (void)rightMouseUp:(NSEvent *)ev;
193 - (void)otherMouseDown:(NSEvent *)ev;
194 - (void)otherMouseDragged:(NSEvent *)ev;
195 - (void)otherMouseUp:(NSEvent *)ev;
198 @interface GameWindow : NSWindow
203 struct timeval last_time;
206 - (id)initWithGame:(const game *)g;
208 - (void)processButton:(int)b x:(int)x y:(int)y;
209 - (void)keyDown:(NSEvent *)ev;
210 - (void)activateTimer;
211 - (void)deactivateTimer;
214 @implementation MyImageView
216 - (void)setWindow:(GameWindow *)win
226 - (void)mouseEvent:(NSEvent *)ev button:(int)b
228 NSPoint point = [self convertPoint:[ev locationInWindow] fromView:nil];
229 [ourwin processButton:b x:point.x y:point.y];
232 - (void)mouseDown:(NSEvent *)ev
234 unsigned mod = [ev modifierFlags];
235 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_BUTTON :
236 (mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
239 - (void)mouseDragged:(NSEvent *)ev
241 unsigned mod = [ev modifierFlags];
242 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_DRAG :
243 (mod & NSShiftKeyMask) ? MIDDLE_DRAG :
246 - (void)mouseUp:(NSEvent *)ev
248 unsigned mod = [ev modifierFlags];
249 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_RELEASE :
250 (mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
253 - (void)rightMouseDown:(NSEvent *)ev
255 unsigned mod = [ev modifierFlags];
256 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
259 - (void)rightMouseDragged:(NSEvent *)ev
261 unsigned mod = [ev modifierFlags];
262 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_DRAG :
265 - (void)rightMouseUp:(NSEvent *)ev
267 unsigned mod = [ev modifierFlags];
268 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
271 - (void)otherMouseDown:(NSEvent *)ev
273 [self mouseEvent:ev button:MIDDLE_BUTTON];
275 - (void)otherMouseDragged:(NSEvent *)ev
277 [self mouseEvent:ev button:MIDDLE_DRAG];
279 - (void)otherMouseUp:(NSEvent *)ev
281 [self mouseEvent:ev button:MIDDLE_RELEASE];
285 @implementation GameWindow
286 - (void)setupContentView
291 midend_size(me, &w, &h);
295 fe.image = [[NSImage alloc] initWithSize:size];
296 [fe.image setFlipped:YES];
297 fe.view = [[MyImageView alloc]
298 initWithFrame:[self contentRectForFrameRect:[self frame]]];
299 [fe.view setImage:fe.image];
300 [fe.view setWindow:self];
304 [self setContentView:fe.view];
306 - (id)initWithGame:(const game *)g
308 NSRect rect = { {0,0}, {0,0} };
315 me = midend_new(&fe, ourgame);
317 * If we ever need to open a fresh window using a provided game
318 * ID, I think the right thing is to move most of this method
319 * into a new initWithGame:gameID: method, and have
320 * initWithGame: simply call that one and pass it NULL.
323 midend_size(me, &w, &h);
325 rect.size.height = h;
327 self = [super initWithContentRect:rect
328 styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
329 NSClosableWindowMask)
330 backing:NSBackingStoreBuffered
332 [self setTitle:[NSString stringWithCString:ourgame->name]];
338 colours = midend_colours(me, &ncolours);
339 fe.ncolours = ncolours;
340 fe.colours = snewn(ncolours, NSColor *);
342 for (i = 0; i < ncolours; i++) {
343 fe.colours[i] = [[NSColor colorWithDeviceRed:colours[i*3]
344 green:colours[i*3+1] blue:colours[i*3+2]
349 [self setupContentView];
350 [self setIgnoresMouseEvents:NO];
352 [self center]; /* :-) */
360 for (i = 0; i < fe.ncolours; i++) {
361 [fe.colours[i] release];
365 return [super dealloc];
368 - (void)processButton:(int)b x:(int)x y:(int)y
370 if (!midend_process_key(me, x, y, b))
374 - (void)keyDown:(NSEvent *)ev
376 NSString *s = [ev characters];
377 int i, n = [s length];
379 for (i = 0; i < n; i++) {
380 int c = [s characterAtIndex:i];
383 * ASCII gets passed straight to midend_process_key.
384 * Anything above that has to be translated to our own
385 * function key codes.
389 case NSUpArrowFunctionKey:
392 case NSDownArrowFunctionKey:
395 case NSLeftArrowFunctionKey:
398 case NSRightArrowFunctionKey:
406 [self processButton:c x:-1 y:-1];
410 - (void)activateTimer
415 timer = [NSTimer scheduledTimerWithTimeInterval:0.02
416 target:self selector:@selector(timerTick:)
417 userInfo:nil repeats:YES];
418 gettimeofday(&last_time, NULL);
421 - (void)deactivateTimer
430 - (void)timerTick:(id)sender
434 gettimeofday(&now, NULL);
435 elapsed = ((now.tv_usec - last_time.tv_usec) * 0.000001F +
436 (now.tv_sec - last_time.tv_sec));
437 midend_timer(me, elapsed);
441 - (void)newGame:(id)sender
443 [self processButton:'n' x:-1 y:-1];
445 - (void)restartGame:(id)sender
447 [self processButton:'r' x:-1 y:-1];
449 - (void)undoMove:(id)sender
451 [self processButton:'u' x:-1 y:-1];
453 - (void)redoMove:(id)sender
455 [self processButton:'r'&0x1F x:-1 y:-1];
458 - (void)clearTypeMenu
460 while ([typemenu numberOfItems] > 1)
461 [typemenu removeItemAtIndex:0];
464 - (void)becomeKeyWindow
468 [self clearTypeMenu];
470 [super becomeKeyWindow];
472 n = midend_num_presets(me);
475 [typemenu insertItem:[NSMenuItem separatorItem] atIndex:0];
481 midend_fetch_preset(me, n, &name, ¶ms);
483 item = [[[DataMenuItem alloc]
484 initWithTitle:[NSString stringWithCString:name]
485 action:NULL keyEquivalent:@""]
488 [item setEnabled:YES];
489 [item setTarget:self];
490 [item setAction:@selector(presetGame:)];
491 [item setPayload:params];
492 [item setPayloadFree:YES];
494 [typemenu insertItem:item atIndex:0];
499 - (void)resignKeyWindow
501 [self clearTypeMenu];
502 [super resignKeyWindow];
507 [self clearTypeMenu];
511 - (void)resizeForNewGameParams
516 midend_size(me, &w, &h);
520 NSDisableScreenUpdates();
521 [self setContentSize:size];
522 [self setupContentView];
523 NSEnableScreenUpdates();
526 - (void)presetGame:(id)sender
528 game_params *params = [sender getPayload];
530 midend_set_params(me, params);
533 [self resizeForNewGameParams];
539 * Drawing routines called by the midend.
541 void draw_polygon(frontend *fe, int *coords, int npoints,
542 int fill, int colour)
544 NSBezierPath *path = [NSBezierPath bezierPath];
547 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
549 assert(colour >= 0 && colour < fe->ncolours);
550 [fe->colours[colour] set];
552 for (i = 0; i < npoints; i++) {
553 NSPoint p = { coords[i*2] + 0.5, coords[i*2+1] + 0.5 };
555 [path moveToPoint:p];
557 [path lineToPoint:p];
567 void draw_line(frontend *fe, int x1, int y1, int x2, int y2, int colour)
569 NSBezierPath *path = [NSBezierPath bezierPath];
570 NSPoint p1 = { x1 + 0.5, y1 + 0.5 }, p2 = { x2 + 0.5, y2 + 0.5 };
572 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
574 assert(colour >= 0 && colour < fe->ncolours);
575 [fe->colours[colour] set];
577 [path moveToPoint:p1];
578 [path lineToPoint:p2];
581 void draw_rect(frontend *fe, int x, int y, int w, int h, int colour)
583 NSRect r = { {x,y}, {w,h} };
585 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
587 assert(colour >= 0 && colour < fe->ncolours);
588 [fe->colours[colour] set];
592 void draw_text(frontend *fe, int x, int y, int fonttype, int fontsize,
593 int align, int colour, char *text)
595 NSString *string = [NSString stringWithCString:text];
601 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
603 assert(colour >= 0 && colour < fe->ncolours);
605 if (fonttype == FONT_FIXED)
606 font = [NSFont userFixedPitchFontOfSize:fontsize];
608 font = [NSFont userFontOfSize:fontsize];
610 attr = [NSDictionary dictionaryWithObjectsAndKeys:
611 fe->colours[colour], NSForegroundColorAttributeName,
612 font, NSFontAttributeName, nil];
617 size = [string sizeWithAttributes:attr];
618 if (align & ALIGN_HRIGHT)
619 point.x -= size.width;
620 else if (align & ALIGN_HCENTRE)
621 point.x -= size.width / 2;
622 if (align & ALIGN_VCENTRE)
623 point.y -= size.height / 2;
625 [string drawAtPoint:point withAttributes:attr];
627 void draw_update(frontend *fe, int x, int y, int w, int h)
631 void clip(frontend *fe, int x, int y, int w, int h)
633 NSRect r = { {x,y}, {w,h} };
636 [[NSGraphicsContext currentContext] saveGraphicsState];
637 [NSBezierPath clipRect:r];
640 void unclip(frontend *fe)
643 [[NSGraphicsContext currentContext] restoreGraphicsState];
646 void start_draw(frontend *fe)
648 [fe->image lockFocus];
651 void end_draw(frontend *fe)
653 [fe->image unlockFocus];
654 [fe->view setNeedsDisplay];
657 void deactivate_timer(frontend *fe)
659 [fe->window deactivateTimer];
661 void activate_timer(frontend *fe)
663 [fe->window activateTimer];
666 /* ----------------------------------------------------------------------
667 * Utility routines for constructing OS X menus.
670 NSMenu *newmenu(const char *title)
672 return [[[NSMenu allocWithZone:[NSMenu menuZone]]
673 initWithTitle:[NSString stringWithCString:title]]
677 NSMenu *newsubmenu(NSMenu *parent, const char *title)
682 item = [[[NSMenuItem allocWithZone:[NSMenu menuZone]]
683 initWithTitle:[NSString stringWithCString:title]
687 child = newmenu(title);
688 [item setEnabled:YES];
689 [item setSubmenu:child];
690 [parent addItem:item];
694 id initnewitem(NSMenuItem *item, NSMenu *parent, const char *title,
695 const char *key, id target, SEL action)
697 unsigned mask = NSCommandKeyMask;
699 if (key[strcspn(key, "-")]) {
700 while (*key && *key != '-') {
701 int c = tolower((unsigned char)*key);
703 mask |= NSShiftKeyMask;
704 } else if (c == 'o' || c == 'a') {
705 mask |= NSAlternateKeyMask;
713 item = [[item initWithTitle:[NSString stringWithCString:title]
715 keyEquivalent:[NSString stringWithCString:key]]
719 [item setKeyEquivalentModifierMask: mask];
721 [item setEnabled:YES];
722 [item setTarget:target];
723 [item setAction:action];
725 [parent addItem:item];
730 NSMenuItem *newitem(NSMenu *parent, char *title, char *key,
731 id target, SEL action)
733 return initnewitem([NSMenuItem allocWithZone:[NSMenu menuZone]],
734 parent, title, key, target, action);
737 /* ----------------------------------------------------------------------
738 * AppController: the object which receives the messages from all
739 * menu selections that aren't standard OS X functions.
741 @interface AppController : NSObject
744 - (IBAction)newGame:(id)sender;
747 @implementation AppController
749 - (IBAction)newGame:(id)sender
751 const game *g = [sender getPayload];
754 win = [[GameWindow alloc] initWithGame:g];
755 [win makeKeyAndOrderFront:self];
760 /* ----------------------------------------------------------------------
761 * Main program. Constructs the menus and runs the application.
763 int main(int argc, char **argv)
765 NSAutoreleasePool *pool;
768 AppController *controller;
770 pool = [[NSAutoreleasePool alloc] init];
771 [NSApplication sharedApplication];
773 controller = [[[AppController alloc] init] autorelease];
775 [NSApp setMainMenu: newmenu("Main Menu")];
777 menu = newsubmenu([NSApp mainMenu], "Apple Menu");
778 [NSApp setServicesMenu:newsubmenu(menu, "Services")];
779 [menu addItem:[NSMenuItem separatorItem]];
780 item = newitem(menu, "Hide Puzzles", "h", NSApp, @selector(hide:));
781 item = newitem(menu, "Hide Others", "o-h", NSApp, @selector(hideOtherApplications:));
782 item = newitem(menu, "Show All", "", NSApp, @selector(unhideAllApplications:));
783 [menu addItem:[NSMenuItem separatorItem]];
784 item = newitem(menu, "Quit", "q", NSApp, @selector(terminate:));
785 [NSApp setAppleMenu: menu];
787 menu = newsubmenu([NSApp mainMenu], "Open");
791 for (i = 0; i < gamecount; i++) {
793 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
794 menu, gamelist[i]->name, "", controller,
795 @selector(newGame:));
796 [item setPayload:(void *)gamelist[i]];
800 menu = newsubmenu([NSApp mainMenu], "Game");
801 item = newitem(menu, "New", "n", NULL, @selector(newGame:));
802 item = newitem(menu, "Restart", "r", NULL, @selector(restartGame:));
803 item = newitem(menu, "Specific", "", NULL, @selector(specificGame:));
804 [menu addItem:[NSMenuItem separatorItem]];
805 item = newitem(menu, "Undo", "z", NULL, @selector(undoMove:));
806 item = newitem(menu, "Redo", "S-z", NULL, @selector(redoMove:));
807 [menu addItem:[NSMenuItem separatorItem]];
808 item = newitem(menu, "Close", "w", NULL, @selector(performClose:));
810 menu = newsubmenu([NSApp mainMenu], "Type");
812 item = newitem(menu, "Custom", "", NULL, @selector(customGameType:));
814 menu = newsubmenu([NSApp mainMenu], "Window");
815 [NSApp setWindowsMenu: menu];
816 item = newitem(menu, "Minimise Window", "m", NULL, @selector(performMiniaturize:));