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 * Grotty implementation details that could probably be improved:
54 * - I am _utterly_ unconvinced that NSImageView was the right way
55 * to go about having a window with a reliable backing store! It
56 * just doesn't feel right; NSImageView is a _control_. Is there
59 * - Resizing is currently very bad; rather than bother to work
60 * out how to resize the NSImageView, I just splatter and
66 #import <Cocoa/Cocoa.h>
69 void fatal(char *fmt, ...)
71 /* FIXME: This will do for testing, but should be GUI-ish instead. */
74 fprintf(stderr, "fatal error: ");
77 vfprintf(stderr, fmt, ap);
80 fprintf(stderr, "\n");
84 void frontend_default_colour(frontend *fe, float *output)
87 output[0] = output[1] = output[2] = 0.8F;
89 void status_bar(frontend *fe, char *text)
94 void get_random_seed(void **randseed, int *randseedsize)
96 time_t *tp = snew(time_t);
98 *randseed = (void *)tp;
99 *randseedsize = sizeof(time_t);
102 /* ----------------------------------------------------------------------
107 * The `Type' menu. We frob this dynamically to allow the user to
108 * choose a preset set of settings from the current game.
112 /* ----------------------------------------------------------------------
113 * Tiny extension to NSMenuItem which carries a payload of a `void
114 * *', allowing several menu items to invoke the same message but
115 * pass different data through it.
117 @interface DataMenuItem : NSMenuItem
122 - (void)setPayload:(void *)d;
123 - (void)setPayloadFree:(BOOL)yesno;
124 - (void *)getPayload;
126 @implementation DataMenuItem
127 - (id)initWithTitle:(NSString *)title
129 keyEquivalent:(NSString *)key
133 return [super initWithTitle:title action:act keyEquivalent:key];
135 - (void)setPayload:(void *)d
139 - (void)setPayloadFree:(BOOL)yesno
141 payload_free = yesno;
155 /* ----------------------------------------------------------------------
156 * The front end presented to midend.c.
158 * This is mostly a subclass of NSWindow. The actual `frontend'
159 * structure passed to the midend contains a variety of pointers,
160 * including that window object but also including the image we
161 * draw on, an ImageView to display it in the window, and so on.
176 @interface MyImageView : NSImageView
180 - (void)setWindow:(GameWindow *)win;
182 - (void)mouseEvent:(NSEvent *)ev button:(int)b;
183 - (void)mouseDown:(NSEvent *)ev;
184 - (void)mouseDragged:(NSEvent *)ev;
185 - (void)mouseUp:(NSEvent *)ev;
186 - (void)rightMouseDown:(NSEvent *)ev;
187 - (void)rightMouseDragged:(NSEvent *)ev;
188 - (void)rightMouseUp:(NSEvent *)ev;
189 - (void)otherMouseDown:(NSEvent *)ev;
190 - (void)otherMouseDragged:(NSEvent *)ev;
191 - (void)otherMouseUp:(NSEvent *)ev;
194 @interface GameWindow : NSWindow
199 struct timeval last_time;
202 - (id)initWithGame:(const game *)g;
204 - (void)processButton:(int)b x:(int)x y:(int)y;
205 - (void)keyDown:(NSEvent *)ev;
206 - (void)activateTimer;
207 - (void)deactivateTimer;
210 @implementation MyImageView
212 - (void)setWindow:(GameWindow *)win
222 - (void)mouseEvent:(NSEvent *)ev button:(int)b
224 NSPoint point = [self convertPoint:[ev locationInWindow] fromView:nil];
225 [ourwin processButton:b x:point.x y:point.y];
228 - (void)mouseDown:(NSEvent *)ev
230 unsigned mod = [ev modifierFlags];
231 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_BUTTON :
232 (mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
235 - (void)mouseDragged:(NSEvent *)ev
237 unsigned mod = [ev modifierFlags];
238 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_DRAG :
239 (mod & NSShiftKeyMask) ? MIDDLE_DRAG :
242 - (void)mouseUp:(NSEvent *)ev
244 unsigned mod = [ev modifierFlags];
245 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_RELEASE :
246 (mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
249 - (void)rightMouseDown:(NSEvent *)ev
251 unsigned mod = [ev modifierFlags];
252 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
255 - (void)rightMouseDragged:(NSEvent *)ev
257 unsigned mod = [ev modifierFlags];
258 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_DRAG :
261 - (void)rightMouseUp:(NSEvent *)ev
263 unsigned mod = [ev modifierFlags];
264 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
267 - (void)otherMouseDown:(NSEvent *)ev
269 [self mouseEvent:ev button:MIDDLE_BUTTON];
271 - (void)otherMouseDragged:(NSEvent *)ev
273 [self mouseEvent:ev button:MIDDLE_DRAG];
275 - (void)otherMouseUp:(NSEvent *)ev
277 [self mouseEvent:ev button:MIDDLE_RELEASE];
281 @implementation GameWindow
282 - (void)setupContentView
287 midend_size(me, &w, &h);
291 fe.image = [[NSImage alloc] initWithSize:size];
292 [fe.image setFlipped:YES];
293 fe.view = [[MyImageView alloc]
294 initWithFrame:[self contentRectForFrameRect:[self frame]]];
295 [fe.view setImage:fe.image];
296 [fe.view setWindow:self];
300 [self setContentView:fe.view];
302 - (id)initWithGame:(const game *)g
304 NSRect rect = { {0,0}, {0,0} };
311 me = midend_new(&fe, ourgame);
313 * If we ever need to open a fresh window using a provided game
314 * ID, I think the right thing is to move most of this method
315 * into a new initWithGame:gameID: method, and have
316 * initWithGame: simply call that one and pass it NULL.
319 midend_size(me, &w, &h);
321 rect.size.height = h;
323 self = [super initWithContentRect:rect
324 styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
325 NSClosableWindowMask)
326 backing:NSBackingStoreBuffered
328 [self setTitle:[NSString stringWithCString:ourgame->name]];
334 colours = midend_colours(me, &ncolours);
335 fe.ncolours = ncolours;
336 fe.colours = snewn(ncolours, NSColor *);
338 for (i = 0; i < ncolours; i++) {
339 fe.colours[i] = [[NSColor colorWithDeviceRed:colours[i*3]
340 green:colours[i*3+1] blue:colours[i*3+2]
345 [self setupContentView];
346 [self setIgnoresMouseEvents:NO];
348 [self center]; /* :-) */
356 for (i = 0; i < fe.ncolours; i++) {
357 [fe.colours[i] release];
361 return [super dealloc];
364 - (void)processButton:(int)b x:(int)x y:(int)y
366 if (!midend_process_key(me, x, y, b))
370 - (void)keyDown:(NSEvent *)ev
372 NSString *s = [ev characters];
373 int i, n = [s length];
375 for (i = 0; i < n; i++) {
376 int c = [s characterAtIndex:i];
379 * ASCII gets passed straight to midend_process_key.
380 * Anything above that has to be translated to our own
381 * function key codes.
385 case NSUpArrowFunctionKey:
388 case NSDownArrowFunctionKey:
391 case NSLeftArrowFunctionKey:
394 case NSRightArrowFunctionKey:
402 [self processButton:c x:-1 y:-1];
406 - (void)activateTimer
411 timer = [NSTimer scheduledTimerWithTimeInterval:0.02
412 target:self selector:@selector(timerTick:)
413 userInfo:nil repeats:YES];
414 gettimeofday(&last_time, NULL);
417 - (void)deactivateTimer
426 - (void)timerTick:(id)sender
430 gettimeofday(&now, NULL);
431 elapsed = ((now.tv_usec - last_time.tv_usec) * 0.000001F +
432 (now.tv_sec - last_time.tv_sec));
433 midend_timer(me, elapsed);
437 - (void)newGame:(id)sender
439 [self processButton:'n' x:-1 y:-1];
441 - (void)restartGame:(id)sender
443 [self processButton:'r' x:-1 y:-1];
445 - (void)undoMove:(id)sender
447 [self processButton:'u' x:-1 y:-1];
449 - (void)redoMove:(id)sender
451 [self processButton:'r'&0x1F x:-1 y:-1];
454 - (void)clearTypeMenu
456 while ([typemenu numberOfItems] > 1)
457 [typemenu removeItemAtIndex:0];
460 - (void)becomeKeyWindow
464 [self clearTypeMenu];
466 [super becomeKeyWindow];
468 n = midend_num_presets(me);
471 [typemenu insertItem:[NSMenuItem separatorItem] atIndex:0];
477 midend_fetch_preset(me, n, &name, ¶ms);
479 item = [[[DataMenuItem alloc]
480 initWithTitle:[NSString stringWithCString:name]
481 action:NULL keyEquivalent:@""]
484 [item setEnabled:YES];
485 [item setTarget:self];
486 [item setAction:@selector(presetGame:)];
487 [item setPayload:params];
488 [item setPayloadFree:YES];
490 [typemenu insertItem:item atIndex:0];
495 - (void)resignKeyWindow
497 [self clearTypeMenu];
498 [super resignKeyWindow];
503 [self clearTypeMenu];
507 - (void)resizeForNewGameParams
512 midend_size(me, &w, &h);
516 NSDisableScreenUpdates();
517 [self setContentSize:size];
518 [self setupContentView];
519 NSEnableScreenUpdates();
522 - (void)presetGame:(id)sender
524 game_params *params = [sender getPayload];
526 midend_set_params(me, params);
529 [self resizeForNewGameParams];
535 * Drawing routines called by the midend.
537 void draw_polygon(frontend *fe, int *coords, int npoints,
538 int fill, int colour)
540 NSBezierPath *path = [NSBezierPath bezierPath];
543 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
545 assert(colour >= 0 && colour < fe->ncolours);
546 [fe->colours[colour] set];
548 for (i = 0; i < npoints; i++) {
549 NSPoint p = { coords[i*2] + 0.5, coords[i*2+1] + 0.5 };
551 [path moveToPoint:p];
553 [path lineToPoint:p];
563 void draw_line(frontend *fe, int x1, int y1, int x2, int y2, int colour)
565 NSBezierPath *path = [NSBezierPath bezierPath];
566 NSPoint p1 = { x1 + 0.5, y1 + 0.5 }, p2 = { x2 + 0.5, y2 + 0.5 };
568 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
570 assert(colour >= 0 && colour < fe->ncolours);
571 [fe->colours[colour] set];
573 [path moveToPoint:p1];
574 [path lineToPoint:p2];
577 void draw_rect(frontend *fe, int x, int y, int w, int h, int colour)
579 NSRect r = { {x,y}, {w,h} };
581 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
583 assert(colour >= 0 && colour < fe->ncolours);
584 [fe->colours[colour] set];
588 void draw_text(frontend *fe, int x, int y, int fonttype, int fontsize,
589 int align, int colour, char *text)
591 NSString *string = [NSString stringWithCString:text];
597 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
599 assert(colour >= 0 && colour < fe->ncolours);
601 if (fonttype == FONT_FIXED)
602 font = [NSFont userFixedPitchFontOfSize:fontsize];
604 font = [NSFont userFontOfSize:fontsize];
606 attr = [NSDictionary dictionaryWithObjectsAndKeys:
607 fe->colours[colour], NSForegroundColorAttributeName,
608 font, NSFontAttributeName, nil];
613 size = [string sizeWithAttributes:attr];
614 if (align & ALIGN_HRIGHT)
615 point.x -= size.width;
616 else if (align & ALIGN_HCENTRE)
617 point.x -= size.width / 2;
618 if (align & ALIGN_VCENTRE)
619 point.y -= size.height / 2;
621 [string drawAtPoint:point withAttributes:attr];
623 void draw_update(frontend *fe, int x, int y, int w, int h)
627 void clip(frontend *fe, int x, int y, int w, int h)
629 NSRect r = { {x,y}, {w,h} };
632 [[NSGraphicsContext currentContext] saveGraphicsState];
633 [NSBezierPath clipRect:r];
636 void unclip(frontend *fe)
639 [[NSGraphicsContext currentContext] restoreGraphicsState];
642 void start_draw(frontend *fe)
644 [fe->image lockFocus];
647 void end_draw(frontend *fe)
649 [fe->image unlockFocus];
650 [fe->view setNeedsDisplay];
653 void deactivate_timer(frontend *fe)
655 [fe->window deactivateTimer];
657 void activate_timer(frontend *fe)
659 [fe->window activateTimer];
662 /* ----------------------------------------------------------------------
663 * Utility routines for constructing OS X menus.
666 NSMenu *newmenu(const char *title)
668 return [[[NSMenu allocWithZone:[NSMenu menuZone]]
669 initWithTitle:[NSString stringWithCString:title]]
673 NSMenu *newsubmenu(NSMenu *parent, const char *title)
678 item = [[[NSMenuItem allocWithZone:[NSMenu menuZone]]
679 initWithTitle:[NSString stringWithCString:title]
683 child = newmenu(title);
684 [item setEnabled:YES];
685 [item setSubmenu:child];
686 [parent addItem:item];
690 id initnewitem(NSMenuItem *item, NSMenu *parent, const char *title,
691 const char *key, id target, SEL action)
693 unsigned mask = NSCommandKeyMask;
695 if (key[strcspn(key, "-")]) {
696 while (*key && *key != '-') {
697 int c = tolower((unsigned char)*key);
699 mask |= NSShiftKeyMask;
700 } else if (c == 'o' || c == 'a') {
701 mask |= NSAlternateKeyMask;
709 item = [[item initWithTitle:[NSString stringWithCString:title]
711 keyEquivalent:[NSString stringWithCString:key]]
715 [item setKeyEquivalentModifierMask: mask];
717 [item setEnabled:YES];
718 [item setTarget:target];
719 [item setAction:action];
721 [parent addItem:item];
726 NSMenuItem *newitem(NSMenu *parent, char *title, char *key,
727 id target, SEL action)
729 return initnewitem([NSMenuItem allocWithZone:[NSMenu menuZone]],
730 parent, title, key, target, action);
733 /* ----------------------------------------------------------------------
734 * AppController: the object which receives the messages from all
735 * menu selections that aren't standard OS X functions.
737 @interface AppController : NSObject
740 - (IBAction)newGame:(id)sender;
743 @implementation AppController
745 - (IBAction)newGame:(id)sender
747 const game *g = [sender getPayload];
750 win = [[GameWindow alloc] initWithGame:g];
751 [win makeKeyAndOrderFront:self];
756 /* ----------------------------------------------------------------------
757 * Main program. Constructs the menus and runs the application.
759 int main(int argc, char **argv)
761 NSAutoreleasePool *pool;
764 AppController *controller;
766 pool = [[NSAutoreleasePool alloc] init];
767 [NSApplication sharedApplication];
769 controller = [[[AppController alloc] init] autorelease];
771 [NSApp setMainMenu: newmenu("Main Menu")];
773 menu = newsubmenu([NSApp mainMenu], "Apple Menu");
774 [NSApp setServicesMenu:newsubmenu(menu, "Services")];
775 [menu addItem:[NSMenuItem separatorItem]];
776 item = newitem(menu, "Hide Puzzles", "h", NSApp, @selector(hide:));
777 item = newitem(menu, "Hide Others", "o-h", NSApp, @selector(hideOtherApplications:));
778 item = newitem(menu, "Show All", "", NSApp, @selector(unhideAllApplications:));
779 [menu addItem:[NSMenuItem separatorItem]];
780 item = newitem(menu, "Quit", "q", NSApp, @selector(terminate:));
781 [NSApp setAppleMenu: menu];
783 menu = newsubmenu([NSApp mainMenu], "Open");
787 for (i = 0; i < gamecount; i++) {
789 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
790 menu, gamelist[i]->name, "", controller,
791 @selector(newGame:));
792 [item setPayload:(void *)gamelist[i]];
796 menu = newsubmenu([NSApp mainMenu], "Game");
797 item = newitem(menu, "New", "n", NULL, @selector(newGame:));
798 item = newitem(menu, "Restart", "r", NULL, @selector(restartGame:));
799 item = newitem(menu, "Specific", "", NULL, @selector(specificGame:));
800 [menu addItem:[NSMenuItem separatorItem]];
801 item = newitem(menu, "Undo", "z", NULL, @selector(undoMove:));
802 item = newitem(menu, "Redo", "S-z", NULL, @selector(redoMove:));
803 [menu addItem:[NSMenuItem separatorItem]];
804 item = newitem(menu, "Close", "w", NULL, @selector(performClose:));
806 menu = newsubmenu([NSApp mainMenu], "Type");
808 item = newitem(menu, "Custom", "", NULL, @selector(customGameType:));
810 menu = newsubmenu([NSApp mainMenu], "Window");
811 [NSApp setWindowsMenu: menu];
812 item = newitem(menu, "Minimise Window", "m", NULL, @selector(performMiniaturize:));