Flesh out the menus a bit.
[sgt/puzzles] / macosx.m
CommitLineData
9494d866 1/*
2 * Mac OS X / Cocoa front end to puzzles.
00461804 3 *
9494d866 4 * TODO:
00461804 5 *
9494d866 6 * - status bar support.
00461804 7 *
9494d866 8 * - preset selection. Should be reasonably simple: just a matter
9 * of dynamically frobbing the menu bar.
00461804 10 *
9494d866 11 * - configurability. Will no doubt involve learning all about the
12 * dialog control side of Cocoa.
00461804 13 *
9494d866 14 * - needs an icon.
00461804 15 *
9494d866 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
20 * initial position"?
00461804 21 *
9494d866 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
6d634196 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.
00461804 28 *
9494d866 29 * - proper fatal errors.
00461804 30 *
9494d866 31 * - is there a better approach to frontend_default_colour?
00461804 32 *
33 * - do we need any more options in the Window menu?
34 *
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
45 * UI it did...
46 *
6d634196 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.
9494d866 51 */
52
53#include <ctype.h>
54#include <sys/time.h>
55#import <Cocoa/Cocoa.h>
56#include "puzzles.h"
57
58void fatal(char *fmt, ...)
59{
60 /* FIXME: This will do for testing, but should be GUI-ish instead. */
61 va_list ap;
62
63 fprintf(stderr, "fatal error: ");
64
65 va_start(ap, fmt);
66 vfprintf(stderr, fmt, ap);
67 va_end(ap);
68
69 fprintf(stderr, "\n");
70 exit(1);
71}
72
73void frontend_default_colour(frontend *fe, float *output)
74{
75 /* FIXME */
76 output[0] = output[1] = output[2] = 0.8F;
77}
78void status_bar(frontend *fe, char *text)
79{
80 /* FIXME */
81}
82
83void get_random_seed(void **randseed, int *randseedsize)
84{
85 time_t *tp = snew(time_t);
86 time(tp);
87 *randseed = (void *)tp;
88 *randseedsize = sizeof(time_t);
89}
90
91/* ----------------------------------------------------------------------
92 * The front end presented to midend.c.
93 *
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.
98 */
99
100@class GameWindow;
101@class MyImageView;
102
103struct frontend {
104 GameWindow *window;
105 NSImage *image;
106 MyImageView *view;
107 NSColor **colours;
108 int ncolours;
109 int clipped;
110};
111
112@interface MyImageView : NSImageView
113{
114 GameWindow *ourwin;
115}
116- (void)setWindow:(GameWindow *)win;
117- (BOOL)isFlipped;
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;
128@end
129
130@interface GameWindow : NSWindow
131{
132 const game *ourgame;
133 midend_data *me;
134 struct frontend fe;
135 struct timeval last_time;
136 NSTimer *timer;
137}
138- (id)initWithGame:(const game *)g;
139- dealloc;
140- (void)processButton:(int)b x:(int)x y:(int)y;
141- (void)keyDown:(NSEvent *)ev;
142- (void)activateTimer;
143- (void)deactivateTimer;
144@end
145
146@implementation MyImageView
147
148- (void)setWindow:(GameWindow *)win
149{
150 ourwin = win;
151}
152
153- (BOOL)isFlipped
154{
155 return YES;
156}
157
158- (void)mouseEvent:(NSEvent *)ev button:(int)b
159{
160 NSPoint point = [self convertPoint:[ev locationInWindow] fromView:nil];
161 [ourwin processButton:b x:point.x y:point.y];
162}
163
164- (void)mouseDown:(NSEvent *)ev
165{
166 unsigned mod = [ev modifierFlags];
167 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_BUTTON :
168 (mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
169 LEFT_BUTTON)];
170}
171- (void)mouseDragged:(NSEvent *)ev
172{
173 unsigned mod = [ev modifierFlags];
174 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_DRAG :
175 (mod & NSShiftKeyMask) ? MIDDLE_DRAG :
176 LEFT_DRAG)];
177}
178- (void)mouseUp:(NSEvent *)ev
179{
180 unsigned mod = [ev modifierFlags];
181 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_RELEASE :
182 (mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
183 LEFT_RELEASE)];
184}
185- (void)rightMouseDown:(NSEvent *)ev
186{
187 unsigned mod = [ev modifierFlags];
188 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
189 RIGHT_BUTTON)];
190}
191- (void)rightMouseDragged:(NSEvent *)ev
192{
193 unsigned mod = [ev modifierFlags];
194 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_DRAG :
195 RIGHT_DRAG)];
196}
197- (void)rightMouseUp:(NSEvent *)ev
198{
199 unsigned mod = [ev modifierFlags];
200 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
201 RIGHT_RELEASE)];
202}
203- (void)otherMouseDown:(NSEvent *)ev
204{
205 [self mouseEvent:ev button:MIDDLE_BUTTON];
206}
207- (void)otherMouseDragged:(NSEvent *)ev
208{
209 [self mouseEvent:ev button:MIDDLE_DRAG];
210}
211- (void)otherMouseUp:(NSEvent *)ev
212{
213 [self mouseEvent:ev button:MIDDLE_RELEASE];
214}
215@end
216
217@implementation GameWindow
218- (id)initWithGame:(const game *)g
219{
220 NSRect rect = { {0,0}, {0,0} };
221 int w, h;
222
223 ourgame = g;
224
225 fe.window = self;
226
227 me = midend_new(&fe, ourgame);
228 /*
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.
233 */
234 midend_new_game(me);
235 midend_size(me, &w, &h);
236 rect.size.width = w;
237 rect.size.height = h;
238
239 self = [super initWithContentRect:rect
240 styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
241 NSClosableWindowMask)
242 backing:NSBackingStoreBuffered
243 defer:true];
244 [self setTitle:[NSString stringWithCString:ourgame->name]];
245
246 {
247 float *colours;
248 int i, ncolours;
249
250 colours = midend_colours(me, &ncolours);
251 fe.ncolours = ncolours;
252 fe.colours = snewn(ncolours, NSColor *);
253
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]
257 alpha:1.0] retain];
258 }
259 }
260
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];
269
270 midend_redraw(me);
271
272 [self center]; /* :-) */
273
274 return self;
275}
276
277- dealloc
278{
279 int i;
280 for (i = 0; i < fe.ncolours; i++) {
281 [fe.colours[i] release];
282 }
283 sfree(fe.colours);
284 midend_free(me);
285 return [super dealloc];
286}
287
288- (void)processButton:(int)b x:(int)x y:(int)y
289{
290 if (!midend_process_key(me, x, y, b))
291 [self close];
292}
293
294- (void)keyDown:(NSEvent *)ev
295{
296 NSString *s = [ev characters];
297 int i, n = [s length];
298
299 for (i = 0; i < n; i++) {
300 int c = [s characterAtIndex:i];
301
302 /*
303 * ASCII gets passed straight to midend_process_key.
304 * Anything above that has to be translated to our own
305 * function key codes.
306 */
307 if (c >= 0x80) {
308 switch (c) {
309 case NSUpArrowFunctionKey:
310 c = CURSOR_UP;
311 break;
312 case NSDownArrowFunctionKey:
313 c = CURSOR_DOWN;
314 break;
315 case NSLeftArrowFunctionKey:
316 c = CURSOR_LEFT;
317 break;
318 case NSRightArrowFunctionKey:
319 c = CURSOR_RIGHT;
320 break;
321 default:
322 continue;
323 }
324 }
325
326 [self processButton:c x:-1 y:-1];
327 }
328}
329
330- (void)activateTimer
331{
332 if (timer != nil)
333 return;
334
335 timer = [NSTimer scheduledTimerWithTimeInterval:0.02
336 target:self selector:@selector(timerTick:)
337 userInfo:nil repeats:YES];
338 gettimeofday(&last_time, NULL);
339}
340
341- (void)deactivateTimer
342{
343 if (timer == nil)
344 return;
345
346 [timer invalidate];
347 timer = nil;
348}
349
350- (void)timerTick:(id)sender
351{
352 struct timeval now;
353 float elapsed;
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);
358 last_time = now;
359}
360
00461804 361- (void)newGame:(id)sender
362{
363 [self processButton:'n' x:-1 y:-1];
364}
365- (void)restartGame:(id)sender
366{
367 [self processButton:'r' x:-1 y:-1];
368}
369- (void)undoMove:(id)sender
370{
371 [self processButton:'u' x:-1 y:-1];
372}
373- (void)redoMove:(id)sender
374{
375 [self processButton:'r'&0x1F x:-1 y:-1];
376}
377
9494d866 378@end
379
380/*
381 * Drawing routines called by the midend.
382 */
383void draw_polygon(frontend *fe, int *coords, int npoints,
384 int fill, int colour)
385{
386 NSBezierPath *path = [NSBezierPath bezierPath];
387 int i;
388
389 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
390
391 assert(colour >= 0 && colour < fe->ncolours);
392 [fe->colours[colour] set];
393
394 for (i = 0; i < npoints; i++) {
395 NSPoint p = { coords[i*2] + 0.5, coords[i*2+1] + 0.5 };
396 if (i == 0)
397 [path moveToPoint:p];
398 else
399 [path lineToPoint:p];
400 }
401
402 [path closePath];
403
404 if (fill)
405 [path fill];
406 else
407 [path stroke];
408}
409void draw_line(frontend *fe, int x1, int y1, int x2, int y2, int colour)
410{
411 NSBezierPath *path = [NSBezierPath bezierPath];
412 NSPoint p1 = { x1 + 0.5, y1 + 0.5 }, p2 = { x2 + 0.5, y2 + 0.5 };
413
414 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
415
416 assert(colour >= 0 && colour < fe->ncolours);
417 [fe->colours[colour] set];
418
419 [path moveToPoint:p1];
420 [path lineToPoint:p2];
421 [path stroke];
422}
423void draw_rect(frontend *fe, int x, int y, int w, int h, int colour)
424{
425 NSRect r = { {x,y}, {w,h} };
426
427 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
428
429 assert(colour >= 0 && colour < fe->ncolours);
430 [fe->colours[colour] set];
431
432 NSRectFill(r);
433}
434void draw_text(frontend *fe, int x, int y, int fonttype, int fontsize,
435 int align, int colour, char *text)
436{
437 NSString *string = [NSString stringWithCString:text];
438 NSDictionary *attr;
439 NSFont *font;
440 NSSize size;
441 NSPoint point;
442
443 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
444
445 assert(colour >= 0 && colour < fe->ncolours);
446
447 if (fonttype == FONT_FIXED)
448 font = [NSFont userFixedPitchFontOfSize:fontsize];
449 else
450 font = [NSFont userFontOfSize:fontsize];
451
452 attr = [NSDictionary dictionaryWithObjectsAndKeys:
453 fe->colours[colour], NSForegroundColorAttributeName,
454 font, NSFontAttributeName, nil];
455
456 point.x = x;
457 point.y = y;
458
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;
466
467 [string drawAtPoint:point withAttributes:attr];
468}
469void draw_update(frontend *fe, int x, int y, int w, int h)
470{
471 /* FIXME */
472}
473void clip(frontend *fe, int x, int y, int w, int h)
474{
475 NSRect r = { {x,y}, {w,h} };
476
477 if (!fe->clipped)
478 [[NSGraphicsContext currentContext] saveGraphicsState];
479 [NSBezierPath clipRect:r];
480 fe->clipped = TRUE;
481}
482void unclip(frontend *fe)
483{
484 if (fe->clipped)
485 [[NSGraphicsContext currentContext] restoreGraphicsState];
486 fe->clipped = FALSE;
487}
488void start_draw(frontend *fe)
489{
490 [fe->image lockFocus];
491 fe->clipped = FALSE;
492}
493void end_draw(frontend *fe)
494{
495 [fe->image unlockFocus];
496 [fe->view setNeedsDisplay];
497}
498
499void deactivate_timer(frontend *fe)
500{
501 [fe->window deactivateTimer];
502}
503void activate_timer(frontend *fe)
504{
505 [fe->window activateTimer];
506}
507
508/* ----------------------------------------------------------------------
509 * Utility routines for constructing OS X menus.
00461804 510 */
9494d866 511
512NSMenu *newmenu(const char *title)
513{
514 return [[[NSMenu allocWithZone:[NSMenu menuZone]]
515 initWithTitle:[NSString stringWithCString:title]]
516 autorelease];
517}
518
519NSMenu *newsubmenu(NSMenu *parent, const char *title)
520{
521 NSMenuItem *item;
522 NSMenu *child;
523
524 item = [[[NSMenuItem allocWithZone:[NSMenu menuZone]]
525 initWithTitle:[NSString stringWithCString:title]
526 action:NULL
527 keyEquivalent:@""]
528 autorelease];
529 child = newmenu(title);
530 [item setEnabled:YES];
531 [item setSubmenu:child];
532 [parent addItem:item];
533 return child;
534}
535
536id initnewitem(NSMenuItem *item, NSMenu *parent, const char *title,
537 const char *key, id target, SEL action)
538{
539 unsigned mask = NSCommandKeyMask;
540
541 if (key[strcspn(key, "-")]) {
542 while (*key && *key != '-') {
543 int c = tolower((unsigned char)*key);
544 if (c == 's') {
545 mask |= NSShiftKeyMask;
546 } else if (c == 'o' || c == 'a') {
547 mask |= NSAlternateKeyMask;
548 }
549 key++;
550 }
551 if (*key)
552 key++;
553 }
554
555 item = [[item initWithTitle:[NSString stringWithCString:title]
556 action:NULL
557 keyEquivalent:[NSString stringWithCString:key]]
558 autorelease];
559
560 if (*key)
561 [item setKeyEquivalentModifierMask: mask];
562
563 [item setEnabled:YES];
564 [item setTarget:target];
565 [item setAction:action];
566
567 [parent addItem:item];
568
569 return item;
570}
571
572NSMenuItem *newitem(NSMenu *parent, char *title, char *key,
573 id target, SEL action)
574{
575 return initnewitem([NSMenuItem allocWithZone:[NSMenu menuZone]],
576 parent, title, key, target, action);
577}
578
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.
583 */
584@interface GameMenuItem : NSMenuItem
585{
586 const game *ourgame;
587}
588- (void)setGame:(const game *)g;
589- (const game *)getGame;
590@end
591@implementation GameMenuItem
592- (void)setGame:(const game *)g
593{
594 ourgame = g;
595}
596- (const game *)getGame
597{
598 return ourgame;
599}
600@end
601
602/* ----------------------------------------------------------------------
603 * AppController: the object which receives the messages from all
604 * menu selections that aren't standard OS X functions.
605 */
606@interface AppController : NSObject
607{
608}
609- (IBAction)newGame:(id)sender;
610@end
611
612@implementation AppController
613
614- (IBAction)newGame:(id)sender
615{
616 const game *g = [sender getGame];
617 id win;
618
619 win = [[GameWindow alloc] initWithGame:g];
620 [win makeKeyAndOrderFront:self];
621}
622
623@end
624
625/* ----------------------------------------------------------------------
626 * Main program. Constructs the menus and runs the application.
627 */
628int main(int argc, char **argv)
629{
630 NSAutoreleasePool *pool;
631 NSMenu *menu;
632 NSMenuItem *item;
633 AppController *controller;
634
635 pool = [[NSAutoreleasePool alloc] init];
636 [NSApplication sharedApplication];
637
638 controller = [[[AppController alloc] init] autorelease];
639
640 [NSApp setMainMenu: newmenu("Main Menu")];
641
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];
651
00461804 652 menu = newsubmenu([NSApp mainMenu], "Open");
9494d866 653 {
654 int i;
655
656 for (i = 0; i < gamecount; i++) {
657 id item =
658 initnewitem([GameMenuItem allocWithZone:[NSMenu menuZone]],
659 menu, gamelist[i]->name, "", controller,
660 @selector(newGame:));
661 [item setGame:gamelist[i]];
662 }
663 }
664
00461804 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:));
674
675 menu = newsubmenu([NSApp mainMenu], "Type");
676 item = newitem(menu, "Custom", "", NULL, @selector(customGameType:));
677
678 menu = newsubmenu([NSApp mainMenu], "Window");
9494d866 679 [NSApp setWindowsMenu: menu];
00461804 680 item = newitem(menu, "Minimise Window", "m", NULL, @selector(performMiniaturize:));
9494d866 681
682 [NSApp run];
683 [pool release];
684}