2 * Mac OS X / Cocoa front end to puzzles.
6 * - I'd like to be able to call up context help for a specific
9 * Mac interface issues that possibly could be done better:
11 * - is there a better approach to frontend_default_colour?
13 * - do we need any more options in the Window menu?
15 * - can / should we be doing anything with the titles of the
16 * configuration boxes?
18 * - not sure what I should be doing about default window
19 * placement. Centring new windows is a bit feeble, but what's
20 * better? Is there a standard way to tell the OS "here's the
21 * _size_ of window I want, now use your best judgment about the
23 * + there's a standard _policy_ on window placement, given in
24 * the HI guidelines. Have to implement it ourselves though,
27 * - a brief frob of the Mac numeric keypad suggests that it
28 * generates numbers no matter what you do. I wonder if I should
29 * try to figure out a way of detecting keypad codes so I can
30 * implement UP_LEFT and friends. Alternatively, perhaps I
31 * should simply assign the number keys to UP_LEFT et al?
32 * They're not in use for anything else right now.
34 * - see if we can do anything to one-button-ise the multi-button
35 * dependent puzzle UIs:
36 * - Pattern is a _little_ unwieldy but not too bad (since
37 * generally you never need the middle button unless you've
38 * made a mistake, so it's just click versus command-click).
39 * - Net is utterly vile; having normal click be one rotate and
40 * command-click be the other introduces a horrid asymmetry,
41 * and yet requiring a shift key for _each_ click would be
42 * even worse because rotation feels as if it ought to be the
43 * default action. I fear this is why the Flash Net had the
45 * + I've tried out an alternative dragging interface for
46 * Net; it might work nicely for stylus-based platforms
47 * where you have better hand/eye feedback for the thing
48 * you're clicking on, but it's rather unwieldy on the
49 * Mac. I fear even shift-clicking is better than that.
51 * - Should we _return_ to a game configuration sheet once an
52 * error is reported by midend_set_config, to allow the user to
53 * correct the one faulty input and keep the other five OK ones?
54 * The Apple `one sheet at a time' restriction would require me
55 * to do this by closing the config sheet, opening the alert
56 * sheet, and then reopening the config sheet when the alert is
57 * closed; and the human interface types, who presumably
58 * invented the one-sheet-at-a-time rule for good reasons, might
59 * look with disfavour on me trying to get round them to fake a
60 * nested sheet. On the other hand I think there are good
61 * practical reasons for wanting it that way. Uncertain.
63 * - User feedback dislikes nothing happening when you start the
64 * app; they suggest a finder-like window containing an icon for
65 * each puzzle type, enabling you to start one easily. Needs
68 * Grotty implementation details that could probably be improved:
70 * - I am _utterly_ unconvinced that NSImageView was the right way
71 * to go about having a window with a reliable backing store! It
72 * just doesn't feel right; NSImageView is a _control_. Is there
75 * - Resizing is currently very bad; rather than bother to work
76 * out how to resize the NSImageView, I just splatter and
82 #import <Cocoa/Cocoa.h>
85 /* ----------------------------------------------------------------------
90 * The `Type' menu. We frob this dynamically to allow the user to
91 * choose a preset set of settings from the current game.
98 extern const struct drawing_api osx_drawing;
100 /* ----------------------------------------------------------------------
101 * Miscellaneous support routines that aren't part of any object or
102 * clearly defined subsystem.
105 void fatal(char *fmt, ...)
112 vsnprintf(errorbuf, lenof(errorbuf), fmt, ap);
115 alert = [NSAlert alloc];
117 * We may have come here because we ran out of memory, in which
118 * case it's entirely likely that that alloc will fail, so we
119 * should have a fallback of some sort.
122 fprintf(stderr, "fatal error (and NSAlert failed): %s\n", errorbuf);
124 alert = [[alert init] autorelease];
125 [alert addButtonWithTitle:@"Oh dear"];
126 [alert setInformativeText:[NSString stringWithCString:errorbuf]];
132 void frontend_default_colour(frontend *fe, float *output)
134 /* FIXME: Is there a system default we can tap into for this? */
135 output[0] = output[1] = output[2] = 0.8F;
138 void get_random_seed(void **randseed, int *randseedsize)
140 time_t *tp = snew(time_t);
142 *randseed = (void *)tp;
143 *randseedsize = sizeof(time_t);
146 static void savefile_write(void *wctx, void *buf, int len)
148 FILE *fp = (FILE *)wctx;
149 fwrite(buf, 1, len, fp);
152 static int savefile_read(void *wctx, void *buf, int len)
154 FILE *fp = (FILE *)wctx;
157 ret = fread(buf, 1, len, fp);
162 * Since this front end does not support printing (yet), we need
163 * this stub to satisfy the reference in midend_print_puzzle().
165 void document_add_puzzle(document *doc, const game *game, game_params *par,
166 game_state *st, game_state *st2)
170 /* ----------------------------------------------------------------------
171 * Tiny extension to NSMenuItem which carries a payload of a `void
172 * *', allowing several menu items to invoke the same message but
173 * pass different data through it.
175 @interface DataMenuItem : NSMenuItem
179 - (void)setPayload:(void *)d;
180 - (void *)getPayload;
182 @implementation DataMenuItem
183 - (void)setPayload:(void *)d
193 /* ----------------------------------------------------------------------
194 * Utility routines for constructing OS X menus.
197 NSMenu *newmenu(const char *title)
199 return [[[NSMenu allocWithZone:[NSMenu menuZone]]
200 initWithTitle:[NSString stringWithCString:title]]
204 NSMenu *newsubmenu(NSMenu *parent, const char *title)
209 item = [[[NSMenuItem allocWithZone:[NSMenu menuZone]]
210 initWithTitle:[NSString stringWithCString:title]
214 child = newmenu(title);
215 [item setEnabled:YES];
216 [item setSubmenu:child];
217 [parent addItem:item];
221 id initnewitem(NSMenuItem *item, NSMenu *parent, const char *title,
222 const char *key, id target, SEL action)
224 unsigned mask = NSCommandKeyMask;
226 if (key[strcspn(key, "-")]) {
227 while (*key && *key != '-') {
228 int c = tolower((unsigned char)*key);
230 mask |= NSShiftKeyMask;
231 } else if (c == 'o' || c == 'a') {
232 mask |= NSAlternateKeyMask;
240 item = [[item initWithTitle:[NSString stringWithCString:title]
242 keyEquivalent:[NSString stringWithCString:key]]
246 [item setKeyEquivalentModifierMask: mask];
248 [item setEnabled:YES];
249 [item setTarget:target];
250 [item setAction:action];
252 [parent addItem:item];
257 NSMenuItem *newitem(NSMenu *parent, char *title, char *key,
258 id target, SEL action)
260 return initnewitem([NSMenuItem allocWithZone:[NSMenu menuZone]],
261 parent, title, key, target, action);
264 /* ----------------------------------------------------------------------
270 @interface AboutBox : NSWindow
276 @implementation AboutBox
284 NSFont *font1 = [NSFont systemFontOfSize:0];
285 NSFont *font2 = [NSFont boldSystemFontOfSize:[font1 pointSize] * 1.1];
286 const int border = 24;
291 * Construct the controls that go in the About box.
294 iv = [[NSImageView alloc] initWithFrame:NSMakeRect(0,0,64,64)];
295 [iv setImage:[NSImage imageNamed:@"NSApplicationIcon"]];
296 views[nviews++] = iv;
298 tf = [[NSTextField alloc]
299 initWithFrame:NSMakeRect(0,0,400,1)];
301 [tf setSelectable:NO];
303 [tf setDrawsBackground:NO];
305 [tf setStringValue:@"Simon Tatham's Portable Puzzle Collection"];
307 views[nviews++] = tf;
309 tf = [[NSTextField alloc]
310 initWithFrame:NSMakeRect(0,0,400,1)];
312 [tf setSelectable:NO];
314 [tf setDrawsBackground:NO];
316 [tf setStringValue:[NSString stringWithCString:ver]];
318 views[nviews++] = tf;
321 * Lay the controls out.
323 totalrect = NSMakeRect(0,0,0,0);
324 for (i = 0; i < nviews; i++) {
325 NSRect r = [views[i] frame];
326 if (totalrect.size.width < r.size.width)
327 totalrect.size.width = r.size.width;
328 totalrect.size.height += border + r.size.height;
330 totalrect.size.width += 2 * border;
331 totalrect.size.height += border;
332 y = totalrect.size.height;
333 for (i = 0; i < nviews; i++) {
334 NSRect r = [views[i] frame];
335 r.origin.x = (totalrect.size.width - r.size.width) / 2;
336 y -= border + r.size.height;
338 [views[i] setFrame:r];
341 self = [super initWithContentRect:totalrect
342 styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
343 NSClosableWindowMask)
344 backing:NSBackingStoreBuffered
347 for (i = 0; i < nviews; i++)
348 [[self contentView] addSubview:views[i]];
350 [self center]; /* :-) */
356 /* ----------------------------------------------------------------------
357 * The front end presented to midend.c.
359 * This is mostly a subclass of NSWindow. The actual `frontend'
360 * structure passed to the midend contains a variety of pointers,
361 * including that window object but also including the image we
362 * draw on, an ImageView to display it in the window, and so on.
377 @interface MyImageView : NSImageView
381 - (void)setWindow:(GameWindow *)win;
383 - (void)mouseEvent:(NSEvent *)ev button:(int)b;
384 - (void)mouseDown:(NSEvent *)ev;
385 - (void)mouseDragged:(NSEvent *)ev;
386 - (void)mouseUp:(NSEvent *)ev;
387 - (void)rightMouseDown:(NSEvent *)ev;
388 - (void)rightMouseDragged:(NSEvent *)ev;
389 - (void)rightMouseUp:(NSEvent *)ev;
390 - (void)otherMouseDown:(NSEvent *)ev;
391 - (void)otherMouseDragged:(NSEvent *)ev;
392 - (void)otherMouseUp:(NSEvent *)ev;
395 @interface GameWindow : NSWindow
400 struct timeval last_time;
405 NSView **cfg_controls;
409 - (id)initWithGame:(const game *)g;
411 - (void)processButton:(int)b x:(int)x y:(int)y;
412 - (void)keyDown:(NSEvent *)ev;
413 - (void)activateTimer;
414 - (void)deactivateTimer;
415 - (void)setStatusLine:(char *)text;
416 - (void)resizeForNewGameParams;
419 @implementation MyImageView
421 - (void)setWindow:(GameWindow *)win
431 - (void)mouseEvent:(NSEvent *)ev button:(int)b
433 NSPoint point = [self convertPoint:[ev locationInWindow] fromView:nil];
434 [ourwin processButton:b x:point.x y:point.y];
437 - (void)mouseDown:(NSEvent *)ev
439 unsigned mod = [ev modifierFlags];
440 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_BUTTON :
441 (mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
444 - (void)mouseDragged:(NSEvent *)ev
446 unsigned mod = [ev modifierFlags];
447 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_DRAG :
448 (mod & NSShiftKeyMask) ? MIDDLE_DRAG :
451 - (void)mouseUp:(NSEvent *)ev
453 unsigned mod = [ev modifierFlags];
454 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_RELEASE :
455 (mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
458 - (void)rightMouseDown:(NSEvent *)ev
460 unsigned mod = [ev modifierFlags];
461 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
464 - (void)rightMouseDragged:(NSEvent *)ev
466 unsigned mod = [ev modifierFlags];
467 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_DRAG :
470 - (void)rightMouseUp:(NSEvent *)ev
472 unsigned mod = [ev modifierFlags];
473 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
476 - (void)otherMouseDown:(NSEvent *)ev
478 [self mouseEvent:ev button:MIDDLE_BUTTON];
480 - (void)otherMouseDragged:(NSEvent *)ev
482 [self mouseEvent:ev button:MIDDLE_DRAG];
484 - (void)otherMouseUp:(NSEvent *)ev
486 [self mouseEvent:ev button:MIDDLE_RELEASE];
490 @implementation GameWindow
491 - (void)setupContentView
497 frame = [status frame];
498 frame.origin.y = frame.size.height;
504 midend_size(me, &w, &h, FALSE);
505 frame.size.width = w;
506 frame.size.height = h;
508 fe.image = [[NSImage alloc] initWithSize:frame.size];
509 [fe.image setFlipped:YES];
510 fe.view = [[MyImageView alloc] initWithFrame:frame];
511 [fe.view setImage:fe.image];
512 [fe.view setWindow:self];
516 [[self contentView] addSubview:fe.view];
518 - (id)initWithGame:(const game *)g
520 NSRect rect = { {0,0}, {0,0} }, rect2;
527 me = midend_new(&fe, ourgame, &osx_drawing, &fe);
529 * If we ever need to open a fresh window using a provided game
530 * ID, I think the right thing is to move most of this method
531 * into a new initWithGame:gameID: method, and have
532 * initWithGame: simply call that one and pass it NULL.
536 midend_size(me, &w, &h, FALSE);
538 rect.size.height = h;
541 * Create the status bar, which will just be an NSTextField.
543 if (midend_wants_statusbar(me)) {
544 status = [[NSTextField alloc] initWithFrame:NSMakeRect(0,0,100,50)];
545 [status setEditable:NO];
546 [status setSelectable:NO];
547 [status setBordered:YES];
548 [status setBezeled:YES];
549 [status setBezelStyle:NSTextFieldSquareBezel];
550 [status setDrawsBackground:YES];
551 [[status cell] setTitle:@""];
553 rect2 = [status frame];
554 rect.size.height += rect2.size.height;
555 rect2.size.width = rect.size.width;
556 rect2.origin.x = rect2.origin.y = 0;
557 [status setFrame:rect2];
561 self = [super initWithContentRect:rect
562 styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
563 NSClosableWindowMask)
564 backing:NSBackingStoreBuffered
566 [self setTitle:[NSString stringWithCString:ourgame->name]];
572 colours = midend_colours(me, &ncolours);
573 fe.ncolours = ncolours;
574 fe.colours = snewn(ncolours, NSColor *);
576 for (i = 0; i < ncolours; i++) {
577 fe.colours[i] = [[NSColor colorWithDeviceRed:colours[i*3]
578 green:colours[i*3+1] blue:colours[i*3+2]
583 [self setupContentView];
585 [[self contentView] addSubview:status];
586 [self setIgnoresMouseEvents:NO];
588 [self center]; /* :-) */
596 for (i = 0; i < fe.ncolours; i++) {
597 [fe.colours[i] release];
601 return [super dealloc];
604 - (void)processButton:(int)b x:(int)x y:(int)y
606 if (!midend_process_key(me, x, y, b))
610 - (void)keyDown:(NSEvent *)ev
612 NSString *s = [ev characters];
613 int i, n = [s length];
615 for (i = 0; i < n; i++) {
616 int c = [s characterAtIndex:i];
619 * ASCII gets passed straight to midend_process_key.
620 * Anything above that has to be translated to our own
621 * function key codes.
626 case NSUpArrowFunctionKey:
630 case NSDownArrowFunctionKey:
634 case NSLeftArrowFunctionKey:
638 case NSRightArrowFunctionKey:
647 if ([ev modifierFlags] & NSShiftKeyMask)
649 if ([ev modifierFlags] & NSControlKeyMask)
654 if (c >= '0' && c <= '9' && ([ev modifierFlags] & NSNumericPadKeyMask))
657 [self processButton:c x:-1 y:-1];
661 - (void)activateTimer
666 timer = [NSTimer scheduledTimerWithTimeInterval:0.02
667 target:self selector:@selector(timerTick:)
668 userInfo:nil repeats:YES];
669 gettimeofday(&last_time, NULL);
672 - (void)deactivateTimer
681 - (void)timerTick:(id)sender
685 gettimeofday(&now, NULL);
686 elapsed = ((now.tv_usec - last_time.tv_usec) * 0.000001F +
687 (now.tv_sec - last_time.tv_sec));
688 midend_timer(me, elapsed);
692 - (void)showError:(char *)message
696 alert = [[[NSAlert alloc] init] autorelease];
697 [alert addButtonWithTitle:@"Bah"];
698 [alert setInformativeText:[NSString stringWithCString:message]];
699 [alert beginSheetModalForWindow:self modalDelegate:nil
700 didEndSelector:nil contextInfo:nil];
703 - (void)newGame:(id)sender
705 [self processButton:'n' x:-1 y:-1];
707 - (void)restartGame:(id)sender
709 midend_restart_game(me);
711 - (void)saveGame:(id)sender
713 NSSavePanel *sp = [NSSavePanel savePanel];
715 if ([sp runModal] == NSFileHandlingPanelOKButton) {
716 const char *name = [[sp filename] cString];
718 FILE *fp = fopen(name, "w");
721 [self showError:"Unable to open save file"];
725 midend_serialise(me, savefile_write, fp);
730 - (void)loadSavedGame:(id)sender
732 NSOpenPanel *op = [NSOpenPanel openPanel];
734 [op setAllowsMultipleSelection:NO];
736 if ([op runModalForTypes:nil] == NSOKButton) {
737 const char *name = [[[op filenames] objectAtIndex:0] cString];
740 FILE *fp = fopen(name, "r");
743 [self showError:"Unable to open saved game file"];
747 err = midend_deserialise(me, savefile_read, fp);
752 [self showError:err];
756 [self resizeForNewGameParams];
759 - (void)undoMove:(id)sender
761 [self processButton:'u' x:-1 y:-1];
763 - (void)redoMove:(id)sender
765 [self processButton:'r'&0x1F x:-1 y:-1];
768 - (void)copy:(id)sender
772 if ((text = midend_text_format(me)) != NULL) {
773 NSPasteboard *pb = [NSPasteboard generalPasteboard];
774 NSArray *a = [NSArray arrayWithObject:NSStringPboardType];
775 [pb declareTypes:a owner:nil];
776 [pb setString:[NSString stringWithCString:text]
777 forType:NSStringPboardType];
782 - (void)solveGame:(id)sender
786 msg = midend_solve(me);
789 [self showError:msg];
792 - (BOOL)validateMenuItem:(NSMenuItem *)item
794 if ([item action] == @selector(copy:))
795 return (ourgame->can_format_as_text ? YES : NO);
796 else if ([item action] == @selector(solveGame:))
797 return (ourgame->can_solve ? YES : NO);
799 return [super validateMenuItem:item];
802 - (void)clearTypeMenu
804 while ([typemenu numberOfItems] > 1)
805 [typemenu removeItemAtIndex:0];
808 - (void)becomeKeyWindow
812 [self clearTypeMenu];
814 [super becomeKeyWindow];
816 n = midend_num_presets(me);
819 [typemenu insertItem:[NSMenuItem separatorItem] atIndex:0];
825 midend_fetch_preset(me, n, &name, ¶ms);
827 item = [[[DataMenuItem alloc]
828 initWithTitle:[NSString stringWithCString:name]
829 action:NULL keyEquivalent:@""]
832 [item setEnabled:YES];
833 [item setTarget:self];
834 [item setAction:@selector(presetGame:)];
835 [item setPayload:params];
837 [typemenu insertItem:item atIndex:0];
842 - (void)resignKeyWindow
844 [self clearTypeMenu];
845 [super resignKeyWindow];
850 [self clearTypeMenu];
854 - (void)resizeForNewGameParams
860 midend_size(me, &w, &h, FALSE);
865 NSRect frame = [status frame];
866 size.height += frame.size.height;
867 frame.size.width = size.width;
868 [status setFrame:frame];
871 NSDisableScreenUpdates();
872 [self setContentSize:size];
873 [self setupContentView];
874 NSEnableScreenUpdates();
877 - (void)presetGame:(id)sender
879 game_params *params = [sender getPayload];
881 midend_set_params(me, params);
884 [self resizeForNewGameParams];
887 - (void)startConfigureSheet:(int)which
889 NSButton *ok, *cancel;
890 int actw, acth, leftw, rightw, totalw, h, thish, y;
892 NSRect rect, tmprect;
893 const int SPACING = 16;
901 assert(sheet == NULL);
904 * Every control we create here is going to have this size
905 * until we tell it to calculate a better one.
907 tmprect = NSMakeRect(0, 0, 100, 50);
910 * Set up OK and Cancel buttons. (Actually, MacOS doesn't seem
911 * to be fond of generic OK and Cancel wording, so I'm going to
912 * rename them to something nicer.)
916 cancel = [[NSButton alloc] initWithFrame:tmprect];
917 [cancel setBezelStyle:NSRoundedBezelStyle];
918 [cancel setTitle:@"Abandon"];
919 [cancel setTarget:self];
920 [cancel setKeyEquivalent:@"\033"];
921 [cancel setAction:@selector(sheetCancelButton:)];
923 rect = [cancel frame];
924 if (actw < rect.size.width) actw = rect.size.width;
925 if (acth < rect.size.height) acth = rect.size.height;
927 ok = [[NSButton alloc] initWithFrame:tmprect];
928 [ok setBezelStyle:NSRoundedBezelStyle];
929 [ok setTitle:@"Accept"];
931 [ok setKeyEquivalent:@"\r"];
932 [ok setAction:@selector(sheetOKButton:)];
935 if (actw < rect.size.width) actw = rect.size.width;
936 if (acth < rect.size.height) acth = rect.size.height;
938 totalw = SPACING + 2 * actw;
939 h = 2 * SPACING + acth;
942 * Now fetch the midend config data and go through it creating
945 cfg = midend_get_config(me, which, &title);
946 sfree(title); /* FIXME: should we use this somehow? */
949 cfg_ncontrols = cfg_controlsize = 0;
952 for (i = cfg; i->type != C_END; i++) {
953 if (cfg_controlsize < cfg_ncontrols + 5) {
954 cfg_controlsize = cfg_ncontrols + 32;
955 cfg_controls = sresize(cfg_controls, cfg_controlsize, NSView *);
963 * Two NSTextFields, one being a label and the other
967 tf = [[NSTextField alloc] initWithFrame:tmprect];
969 [tf setSelectable:NO];
971 [tf setDrawsBackground:NO];
972 [[tf cell] setTitle:[NSString stringWithCString:i->name]];
975 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
976 if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
977 cfg_controls[cfg_ncontrols++] = tf;
979 tf = [[NSTextField alloc] initWithFrame:tmprect];
980 [tf setEditable:YES];
981 [tf setSelectable:YES];
982 [tf setBordered:YES];
983 [[tf cell] setTitle:[NSString stringWithCString:i->sval]];
987 * We impose a minimum and maximum width on editable
988 * NSTextFields. If we allow them to size themselves to
989 * the contents of the text within them, then they will
990 * look very silly if that text is only one or two
991 * characters, and equally silly if it's an absolutely
992 * enormous Rectangles or Pattern game ID!
994 if (rect.size.width < 75) rect.size.width = 75;
995 if (rect.size.width > 400) rect.size.width = 400;
997 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
998 if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
999 cfg_controls[cfg_ncontrols++] = tf;
1004 * A checkbox is an NSButton with a type of
1007 b = [[NSButton alloc] initWithFrame:tmprect];
1008 [b setBezelStyle:NSRoundedBezelStyle];
1009 [b setButtonType:NSSwitchButton];
1010 [b setTitle:[NSString stringWithCString:i->name]];
1012 [b setState:(i->ival ? NSOnState : NSOffState)];
1014 if (totalw < rect.size.width + 1) totalw = rect.size.width + 1;
1015 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1016 cfg_controls[cfg_ncontrols++] = b;
1021 * A pop-up menu control is an NSPopUpButton, which
1022 * takes an embedded NSMenu. We also need an
1023 * NSTextField to act as a label.
1026 tf = [[NSTextField alloc] initWithFrame:tmprect];
1027 [tf setEditable:NO];
1028 [tf setSelectable:NO];
1029 [tf setBordered:NO];
1030 [tf setDrawsBackground:NO];
1031 [[tf cell] setTitle:[NSString stringWithCString:i->name]];
1034 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1035 if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
1036 cfg_controls[cfg_ncontrols++] = tf;
1038 pb = [[NSPopUpButton alloc] initWithFrame:tmprect pullsDown:NO];
1039 [pb setBezelStyle:NSRoundedBezelStyle];
1049 while (*p && *p != c) p++;
1051 [pb addItemWithTitle:[NSString stringWithCString:q
1057 [pb selectItemAtIndex:i->ival];
1061 if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
1062 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1063 cfg_controls[cfg_ncontrols++] = pb;
1067 h += SPACING + thish;
1070 if (totalw < leftw + SPACING + rightw)
1071 totalw = leftw + SPACING + rightw;
1072 if (totalw > leftw + SPACING + rightw) {
1073 int excess = totalw - (leftw + SPACING + rightw);
1074 int leftexcess = leftw * excess / (leftw + rightw);
1075 int rightexcess = excess - leftexcess;
1076 leftw += leftexcess;
1077 rightw += rightexcess;
1081 * Now go through the list again, setting the final position
1086 for (i = cfg; i->type != C_END; i++) {
1093 * These two are treated identically, since both expect
1094 * a control on the left and another on the right.
1096 rect = [cfg_controls[k] frame];
1097 if (thish < rect.size.height + 1)
1098 thish = rect.size.height + 1;
1099 rect = [cfg_controls[k+1] frame];
1100 if (thish < rect.size.height + 1)
1101 thish = rect.size.height + 1;
1102 rect = [cfg_controls[k] frame];
1103 rect.origin.y = y - thish/2 - rect.size.height/2;
1104 rect.origin.x = SPACING;
1105 rect.size.width = leftw;
1106 [cfg_controls[k] setFrame:rect];
1107 rect = [cfg_controls[k+1] frame];
1108 rect.origin.y = y - thish/2 - rect.size.height/2;
1109 rect.origin.x = 2 * SPACING + leftw;
1110 rect.size.width = rightw;
1111 [cfg_controls[k+1] setFrame:rect];
1116 rect = [cfg_controls[k] frame];
1117 if (thish < rect.size.height + 1)
1118 thish = rect.size.height + 1;
1119 rect.origin.y = y - thish/2 - rect.size.height/2;
1120 rect.origin.x = SPACING;
1121 rect.size.width = totalw;
1122 [cfg_controls[k] setFrame:rect];
1129 assert(k == cfg_ncontrols);
1131 [cancel setFrame:NSMakeRect(SPACING+totalw/4-actw/2, SPACING, actw, acth)];
1132 [ok setFrame:NSMakeRect(SPACING+3*totalw/4-actw/2, SPACING, actw, acth)];
1134 sheet = [[NSWindow alloc]
1135 initWithContentRect:NSMakeRect(0,0,totalw + 2*SPACING,h)
1136 styleMask:NSTitledWindowMask | NSClosableWindowMask
1137 backing:NSBackingStoreBuffered
1140 [[sheet contentView] addSubview:cancel];
1141 [[sheet contentView] addSubview:ok];
1143 for (k = 0; k < cfg_ncontrols; k++)
1144 [[sheet contentView] addSubview:cfg_controls[k]];
1146 [NSApp beginSheet:sheet modalForWindow:self
1147 modalDelegate:nil didEndSelector:nil contextInfo:nil];
1150 - (void)specificGame:(id)sender
1152 [self startConfigureSheet:CFG_DESC];
1155 - (void)specificRandomGame:(id)sender
1157 [self startConfigureSheet:CFG_SEED];
1160 - (void)customGameType:(id)sender
1162 [self startConfigureSheet:CFG_SETTINGS];
1165 - (void)sheetEndWithStatus:(BOOL)update
1167 assert(sheet != NULL);
1168 [NSApp endSheet:sheet];
1169 [sheet orderOut:self];
1177 for (i = cfg; i->type != C_END; i++) {
1181 i->sval = dupstr([[[(id)cfg_controls[k+1] cell]
1186 i->ival = [(id)cfg_controls[k] state] == NSOnState;
1190 i->ival = [(id)cfg_controls[k+1] indexOfSelectedItem];
1196 error = midend_set_config(me, cfg_which, cfg);
1198 NSAlert *alert = [[[NSAlert alloc] init] autorelease];
1199 [alert addButtonWithTitle:@"Bah"];
1200 [alert setInformativeText:[NSString stringWithCString:error]];
1201 [alert beginSheetModalForWindow:self modalDelegate:nil
1202 didEndSelector:nil contextInfo:nil];
1204 midend_new_game(me);
1205 [self resizeForNewGameParams];
1208 sfree(cfg_controls);
1209 cfg_controls = NULL;
1211 - (void)sheetOKButton:(id)sender
1213 [self sheetEndWithStatus:YES];
1215 - (void)sheetCancelButton:(id)sender
1217 [self sheetEndWithStatus:NO];
1220 - (void)setStatusLine:(char *)text
1222 [[status cell] setTitle:[NSString stringWithCString:text]];
1228 * Drawing routines called by the midend.
1230 static void osx_draw_polygon(void *handle, int *coords, int npoints,
1231 int fillcolour, int outlinecolour)
1233 frontend *fe = (frontend *)handle;
1234 NSBezierPath *path = [NSBezierPath bezierPath];
1237 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1239 for (i = 0; i < npoints; i++) {
1240 NSPoint p = { coords[i*2] + 0.5, coords[i*2+1] + 0.5 };
1242 [path moveToPoint:p];
1244 [path lineToPoint:p];
1249 if (fillcolour >= 0) {
1250 assert(fillcolour >= 0 && fillcolour < fe->ncolours);
1251 [fe->colours[fillcolour] set];
1255 assert(outlinecolour >= 0 && outlinecolour < fe->ncolours);
1256 [fe->colours[outlinecolour] set];
1259 static void osx_draw_circle(void *handle, int cx, int cy, int radius,
1260 int fillcolour, int outlinecolour)
1262 frontend *fe = (frontend *)handle;
1263 NSBezierPath *path = [NSBezierPath bezierPath];
1265 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1267 [path appendBezierPathWithArcWithCenter:NSMakePoint(cx + 0.5, cy + 0.5)
1268 radius:radius startAngle:0.0 endAngle:360.0];
1272 if (fillcolour >= 0) {
1273 assert(fillcolour >= 0 && fillcolour < fe->ncolours);
1274 [fe->colours[fillcolour] set];
1278 assert(outlinecolour >= 0 && outlinecolour < fe->ncolours);
1279 [fe->colours[outlinecolour] set];
1282 static void osx_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
1284 frontend *fe = (frontend *)handle;
1285 NSBezierPath *path = [NSBezierPath bezierPath];
1286 NSPoint p1 = { x1 + 0.5, y1 + 0.5 }, p2 = { x2 + 0.5, y2 + 0.5 };
1288 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1290 assert(colour >= 0 && colour < fe->ncolours);
1291 [fe->colours[colour] set];
1293 [path moveToPoint:p1];
1294 [path lineToPoint:p2];
1297 static void osx_draw_rect(void *handle, int x, int y, int w, int h, int colour)
1299 frontend *fe = (frontend *)handle;
1300 NSRect r = { {x,y}, {w,h} };
1302 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1304 assert(colour >= 0 && colour < fe->ncolours);
1305 [fe->colours[colour] set];
1309 static void osx_draw_text(void *handle, int x, int y, int fonttype,
1310 int fontsize, int align, int colour, char *text)
1312 frontend *fe = (frontend *)handle;
1313 NSString *string = [NSString stringWithCString:text];
1319 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1321 assert(colour >= 0 && colour < fe->ncolours);
1323 if (fonttype == FONT_FIXED)
1324 font = [NSFont userFixedPitchFontOfSize:fontsize];
1326 font = [NSFont userFontOfSize:fontsize];
1328 attr = [NSDictionary dictionaryWithObjectsAndKeys:
1329 fe->colours[colour], NSForegroundColorAttributeName,
1330 font, NSFontAttributeName, nil];
1335 size = [string sizeWithAttributes:attr];
1336 if (align & ALIGN_HRIGHT)
1337 point.x -= size.width;
1338 else if (align & ALIGN_HCENTRE)
1339 point.x -= size.width / 2;
1340 if (align & ALIGN_VCENTRE)
1341 point.y -= size.height / 2;
1343 point.y -= size.height;
1345 [string drawAtPoint:point withAttributes:attr];
1352 static blitter *osx_blitter_new(void *handle, int w, int h)
1354 blitter *bl = snew(blitter);
1358 bl->img = [[NSImage alloc] initWithSize:NSMakeSize(w, h)];
1359 [bl->img setFlipped:YES];
1362 static void osx_blitter_free(void *handle, blitter *bl)
1367 static void osx_blitter_save(void *handle, blitter *bl, int x, int y)
1369 frontend *fe = (frontend *)handle;
1370 [fe->image unlockFocus];
1371 [bl->img lockFocus];
1372 [fe->image drawInRect:NSMakeRect(0, 0, bl->w, bl->h)
1373 fromRect:NSMakeRect(x, y, bl->w, bl->h)
1374 operation:NSCompositeCopy fraction:1.0];
1375 [bl->img unlockFocus];
1376 [fe->image lockFocus];
1380 static void osx_blitter_load(void *handle, blitter *bl, int x, int y)
1382 /* frontend *fe = (frontend *)handle; */
1383 if (x == BLITTER_FROMSAVED && y == BLITTER_FROMSAVED) {
1387 [bl->img drawInRect:NSMakeRect(x, y, bl->w, bl->h)
1388 fromRect:NSMakeRect(0, 0, bl->w, bl->h)
1389 operation:NSCompositeCopy fraction:1.0];
1391 static void osx_draw_update(void *handle, int x, int y, int w, int h)
1393 frontend *fe = (frontend *)handle;
1394 [fe->view setNeedsDisplayInRect:NSMakeRect(x,y,w,h)];
1396 static void osx_clip(void *handle, int x, int y, int w, int h)
1398 frontend *fe = (frontend *)handle;
1399 NSRect r = { {x,y}, {w,h} };
1402 [[NSGraphicsContext currentContext] saveGraphicsState];
1403 [NSBezierPath clipRect:r];
1406 static void osx_unclip(void *handle)
1408 frontend *fe = (frontend *)handle;
1410 [[NSGraphicsContext currentContext] restoreGraphicsState];
1411 fe->clipped = FALSE;
1413 static void osx_start_draw(void *handle)
1415 frontend *fe = (frontend *)handle;
1416 [fe->image lockFocus];
1417 fe->clipped = FALSE;
1419 static void osx_end_draw(void *handle)
1421 frontend *fe = (frontend *)handle;
1422 [fe->image unlockFocus];
1424 static void osx_status_bar(void *handle, char *text)
1426 frontend *fe = (frontend *)handle;
1427 [fe->window setStatusLine:text];
1430 const struct drawing_api osx_drawing = {
1446 NULL, NULL, NULL, NULL, NULL, NULL, /* {begin,end}_{doc,page,puzzle} */
1447 NULL, /* line_width */
1450 void deactivate_timer(frontend *fe)
1452 [fe->window deactivateTimer];
1454 void activate_timer(frontend *fe)
1456 [fe->window activateTimer];
1459 /* ----------------------------------------------------------------------
1460 * AppController: the object which receives the messages from all
1461 * menu selections that aren't standard OS X functions.
1463 @interface AppController : NSObject
1466 - (void)newGameWindow:(id)sender;
1467 - (void)about:(id)sender;
1470 @implementation AppController
1472 - (void)newGameWindow:(id)sender
1474 const game *g = [sender getPayload];
1477 win = [[GameWindow alloc] initWithGame:g];
1478 [win makeKeyAndOrderFront:self];
1481 - (void)about:(id)sender
1485 win = [[AboutBox alloc] init];
1486 [win makeKeyAndOrderFront:self];
1489 - (NSMenu *)applicationDockMenu:(NSApplication *)sender
1491 NSMenu *menu = newmenu("Dock Menu");
1495 for (i = 0; i < gamecount; i++) {
1497 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1498 menu, gamelist[i]->name, "", self,
1499 @selector(newGameWindow:));
1500 [item setPayload:(void *)gamelist[i]];
1508 /* ----------------------------------------------------------------------
1509 * Main program. Constructs the menus and runs the application.
1511 int main(int argc, char **argv)
1513 NSAutoreleasePool *pool;
1516 AppController *controller;
1519 pool = [[NSAutoreleasePool alloc] init];
1521 icon = [NSImage imageNamed:@"NSApplicationIcon"];
1522 [NSApplication sharedApplication];
1523 [NSApp setApplicationIconImage:icon];
1525 controller = [[[AppController alloc] init] autorelease];
1526 [NSApp setDelegate:controller];
1528 [NSApp setMainMenu: newmenu("Main Menu")];
1530 menu = newsubmenu([NSApp mainMenu], "Apple Menu");
1531 item = newitem(menu, "About Puzzles", "", NULL, @selector(about:));
1532 [menu addItem:[NSMenuItem separatorItem]];
1533 [NSApp setServicesMenu:newsubmenu(menu, "Services")];
1534 [menu addItem:[NSMenuItem separatorItem]];
1535 item = newitem(menu, "Hide Puzzles", "h", NSApp, @selector(hide:));
1536 item = newitem(menu, "Hide Others", "o-h", NSApp, @selector(hideOtherApplications:));
1537 item = newitem(menu, "Show All", "", NSApp, @selector(unhideAllApplications:));
1538 [menu addItem:[NSMenuItem separatorItem]];
1539 item = newitem(menu, "Quit", "q", NSApp, @selector(terminate:));
1540 [NSApp setAppleMenu: menu];
1542 menu = newsubmenu([NSApp mainMenu], "File");
1543 item = newitem(menu, "Open", "o", NULL, @selector(loadSavedGame:));
1544 item = newitem(menu, "Save As", "s", NULL, @selector(saveGame:));
1545 item = newitem(menu, "New Game", "n", NULL, @selector(newGame:));
1546 item = newitem(menu, "Restart Game", "r", NULL, @selector(restartGame:));
1547 item = newitem(menu, "Specific Game", "", NULL, @selector(specificGame:));
1548 item = newitem(menu, "Specific Random Seed", "", NULL,
1549 @selector(specificRandomGame:));
1550 [menu addItem:[NSMenuItem separatorItem]];
1552 NSMenu *submenu = newsubmenu(menu, "New Window");
1555 for (i = 0; i < gamecount; i++) {
1557 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1558 submenu, gamelist[i]->name, "", controller,
1559 @selector(newGameWindow:));
1560 [item setPayload:(void *)gamelist[i]];
1563 [menu addItem:[NSMenuItem separatorItem]];
1564 item = newitem(menu, "Close", "w", NULL, @selector(performClose:));
1566 menu = newsubmenu([NSApp mainMenu], "Edit");
1567 item = newitem(menu, "Undo", "z", NULL, @selector(undoMove:));
1568 item = newitem(menu, "Redo", "S-z", NULL, @selector(redoMove:));
1569 [menu addItem:[NSMenuItem separatorItem]];
1570 item = newitem(menu, "Cut", "x", NULL, @selector(cut:));
1571 item = newitem(menu, "Copy", "c", NULL, @selector(copy:));
1572 item = newitem(menu, "Paste", "v", NULL, @selector(paste:));
1573 [menu addItem:[NSMenuItem separatorItem]];
1574 item = newitem(menu, "Solve", "S-s", NULL, @selector(solveGame:));
1576 menu = newsubmenu([NSApp mainMenu], "Type");
1578 item = newitem(menu, "Custom", "", NULL, @selector(customGameType:));
1580 menu = newsubmenu([NSApp mainMenu], "Window");
1581 [NSApp setWindowsMenu: menu];
1582 item = newitem(menu, "Minimise Window", "m", NULL, @selector(performMiniaturize:));
1584 menu = newsubmenu([NSApp mainMenu], "Help");
1585 item = newitem(menu, "Puzzles Help", "?", NSApp, @selector(showHelp:));