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.
95 /* ----------------------------------------------------------------------
96 * Miscellaneous support routines that aren't part of any object or
97 * clearly defined subsystem.
100 void fatal(char *fmt, ...)
107 vsnprintf(errorbuf, lenof(errorbuf), fmt, ap);
110 alert = [NSAlert alloc];
112 * We may have come here because we ran out of memory, in which
113 * case it's entirely likely that that alloc will fail, so we
114 * should have a fallback of some sort.
117 fprintf(stderr, "fatal error (and NSAlert failed): %s\n", errorbuf);
119 alert = [[alert init] autorelease];
120 [alert addButtonWithTitle:@"Oh dear"];
121 [alert setInformativeText:[NSString stringWithCString:errorbuf]];
127 void frontend_default_colour(frontend *fe, float *output)
129 /* FIXME: Is there a system default we can tap into for this? */
130 output[0] = output[1] = output[2] = 0.8F;
133 void get_random_seed(void **randseed, int *randseedsize)
135 time_t *tp = snew(time_t);
137 *randseed = (void *)tp;
138 *randseedsize = sizeof(time_t);
141 static void savefile_write(void *wctx, void *buf, int len)
143 FILE *fp = (FILE *)wctx;
144 fwrite(buf, 1, len, fp);
147 static int savefile_read(void *wctx, void *buf, int len)
149 FILE *fp = (FILE *)wctx;
152 ret = fread(buf, 1, len, fp);
156 /* ----------------------------------------------------------------------
157 * Tiny extension to NSMenuItem which carries a payload of a `void
158 * *', allowing several menu items to invoke the same message but
159 * pass different data through it.
161 @interface DataMenuItem : NSMenuItem
165 - (void)setPayload:(void *)d;
166 - (void *)getPayload;
168 @implementation DataMenuItem
169 - (void)setPayload:(void *)d
179 /* ----------------------------------------------------------------------
180 * Utility routines for constructing OS X menus.
183 NSMenu *newmenu(const char *title)
185 return [[[NSMenu allocWithZone:[NSMenu menuZone]]
186 initWithTitle:[NSString stringWithCString:title]]
190 NSMenu *newsubmenu(NSMenu *parent, const char *title)
195 item = [[[NSMenuItem allocWithZone:[NSMenu menuZone]]
196 initWithTitle:[NSString stringWithCString:title]
200 child = newmenu(title);
201 [item setEnabled:YES];
202 [item setSubmenu:child];
203 [parent addItem:item];
207 id initnewitem(NSMenuItem *item, NSMenu *parent, const char *title,
208 const char *key, id target, SEL action)
210 unsigned mask = NSCommandKeyMask;
212 if (key[strcspn(key, "-")]) {
213 while (*key && *key != '-') {
214 int c = tolower((unsigned char)*key);
216 mask |= NSShiftKeyMask;
217 } else if (c == 'o' || c == 'a') {
218 mask |= NSAlternateKeyMask;
226 item = [[item initWithTitle:[NSString stringWithCString:title]
228 keyEquivalent:[NSString stringWithCString:key]]
232 [item setKeyEquivalentModifierMask: mask];
234 [item setEnabled:YES];
235 [item setTarget:target];
236 [item setAction:action];
238 [parent addItem:item];
243 NSMenuItem *newitem(NSMenu *parent, char *title, char *key,
244 id target, SEL action)
246 return initnewitem([NSMenuItem allocWithZone:[NSMenu menuZone]],
247 parent, title, key, target, action);
250 /* ----------------------------------------------------------------------
256 @interface AboutBox : NSWindow
262 @implementation AboutBox
270 NSFont *font1 = [NSFont systemFontOfSize:0];
271 NSFont *font2 = [NSFont boldSystemFontOfSize:[font1 pointSize] * 1.1];
272 const int border = 24;
277 * Construct the controls that go in the About box.
280 iv = [[NSImageView alloc] initWithFrame:NSMakeRect(0,0,64,64)];
281 [iv setImage:[NSImage imageNamed:@"NSApplicationIcon"]];
282 views[nviews++] = iv;
284 tf = [[NSTextField alloc]
285 initWithFrame:NSMakeRect(0,0,400,1)];
287 [tf setSelectable:NO];
289 [tf setDrawsBackground:NO];
291 [tf setStringValue:@"Simon Tatham's Portable Puzzle Collection"];
293 views[nviews++] = tf;
295 tf = [[NSTextField alloc]
296 initWithFrame:NSMakeRect(0,0,400,1)];
298 [tf setSelectable:NO];
300 [tf setDrawsBackground:NO];
302 [tf setStringValue:[NSString stringWithCString:ver]];
304 views[nviews++] = tf;
307 * Lay the controls out.
309 totalrect = NSMakeRect(0,0,0,0);
310 for (i = 0; i < nviews; i++) {
311 NSRect r = [views[i] frame];
312 if (totalrect.size.width < r.size.width)
313 totalrect.size.width = r.size.width;
314 totalrect.size.height += border + r.size.height;
316 totalrect.size.width += 2 * border;
317 totalrect.size.height += border;
318 y = totalrect.size.height;
319 for (i = 0; i < nviews; i++) {
320 NSRect r = [views[i] frame];
321 r.origin.x = (totalrect.size.width - r.size.width) / 2;
322 y -= border + r.size.height;
324 [views[i] setFrame:r];
327 self = [super initWithContentRect:totalrect
328 styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
329 NSClosableWindowMask)
330 backing:NSBackingStoreBuffered
333 for (i = 0; i < nviews; i++)
334 [[self contentView] addSubview:views[i]];
336 [self center]; /* :-) */
342 /* ----------------------------------------------------------------------
343 * The front end presented to midend.c.
345 * This is mostly a subclass of NSWindow. The actual `frontend'
346 * structure passed to the midend contains a variety of pointers,
347 * including that window object but also including the image we
348 * draw on, an ImageView to display it in the window, and so on.
363 @interface MyImageView : NSImageView
367 - (void)setWindow:(GameWindow *)win;
369 - (void)mouseEvent:(NSEvent *)ev button:(int)b;
370 - (void)mouseDown:(NSEvent *)ev;
371 - (void)mouseDragged:(NSEvent *)ev;
372 - (void)mouseUp:(NSEvent *)ev;
373 - (void)rightMouseDown:(NSEvent *)ev;
374 - (void)rightMouseDragged:(NSEvent *)ev;
375 - (void)rightMouseUp:(NSEvent *)ev;
376 - (void)otherMouseDown:(NSEvent *)ev;
377 - (void)otherMouseDragged:(NSEvent *)ev;
378 - (void)otherMouseUp:(NSEvent *)ev;
381 @interface GameWindow : NSWindow
386 struct timeval last_time;
391 NSView **cfg_controls;
395 - (id)initWithGame:(const game *)g;
397 - (void)processButton:(int)b x:(int)x y:(int)y;
398 - (void)keyDown:(NSEvent *)ev;
399 - (void)activateTimer;
400 - (void)deactivateTimer;
401 - (void)setStatusLine:(char *)text;
402 - (void)resizeForNewGameParams;
405 @implementation MyImageView
407 - (void)setWindow:(GameWindow *)win
417 - (void)mouseEvent:(NSEvent *)ev button:(int)b
419 NSPoint point = [self convertPoint:[ev locationInWindow] fromView:nil];
420 [ourwin processButton:b x:point.x y:point.y];
423 - (void)mouseDown:(NSEvent *)ev
425 unsigned mod = [ev modifierFlags];
426 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_BUTTON :
427 (mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
430 - (void)mouseDragged:(NSEvent *)ev
432 unsigned mod = [ev modifierFlags];
433 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_DRAG :
434 (mod & NSShiftKeyMask) ? MIDDLE_DRAG :
437 - (void)mouseUp:(NSEvent *)ev
439 unsigned mod = [ev modifierFlags];
440 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_RELEASE :
441 (mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
444 - (void)rightMouseDown:(NSEvent *)ev
446 unsigned mod = [ev modifierFlags];
447 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
450 - (void)rightMouseDragged:(NSEvent *)ev
452 unsigned mod = [ev modifierFlags];
453 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_DRAG :
456 - (void)rightMouseUp:(NSEvent *)ev
458 unsigned mod = [ev modifierFlags];
459 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
462 - (void)otherMouseDown:(NSEvent *)ev
464 [self mouseEvent:ev button:MIDDLE_BUTTON];
466 - (void)otherMouseDragged:(NSEvent *)ev
468 [self mouseEvent:ev button:MIDDLE_DRAG];
470 - (void)otherMouseUp:(NSEvent *)ev
472 [self mouseEvent:ev button:MIDDLE_RELEASE];
476 @implementation GameWindow
477 - (void)setupContentView
483 frame = [status frame];
484 frame.origin.y = frame.size.height;
490 midend_size(me, &w, &h, FALSE);
491 frame.size.width = w;
492 frame.size.height = h;
494 fe.image = [[NSImage alloc] initWithSize:frame.size];
495 [fe.image setFlipped:YES];
496 fe.view = [[MyImageView alloc] initWithFrame:frame];
497 [fe.view setImage:fe.image];
498 [fe.view setWindow:self];
502 [[self contentView] addSubview:fe.view];
504 - (id)initWithGame:(const game *)g
506 NSRect rect = { {0,0}, {0,0} }, rect2;
513 me = midend_new(&fe, ourgame);
515 * If we ever need to open a fresh window using a provided game
516 * ID, I think the right thing is to move most of this method
517 * into a new initWithGame:gameID: method, and have
518 * initWithGame: simply call that one and pass it NULL.
522 midend_size(me, &w, &h, FALSE);
524 rect.size.height = h;
527 * Create the status bar, which will just be an NSTextField.
529 if (ourgame->wants_statusbar()) {
530 status = [[NSTextField alloc] initWithFrame:NSMakeRect(0,0,100,50)];
531 [status setEditable:NO];
532 [status setSelectable:NO];
533 [status setBordered:YES];
534 [status setBezeled:YES];
535 [status setBezelStyle:NSTextFieldSquareBezel];
536 [status setDrawsBackground:YES];
537 [[status cell] setTitle:@""];
539 rect2 = [status frame];
540 rect.size.height += rect2.size.height;
541 rect2.size.width = rect.size.width;
542 rect2.origin.x = rect2.origin.y = 0;
543 [status setFrame:rect2];
547 self = [super initWithContentRect:rect
548 styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
549 NSClosableWindowMask)
550 backing:NSBackingStoreBuffered
552 [self setTitle:[NSString stringWithCString:ourgame->name]];
558 colours = midend_colours(me, &ncolours);
559 fe.ncolours = ncolours;
560 fe.colours = snewn(ncolours, NSColor *);
562 for (i = 0; i < ncolours; i++) {
563 fe.colours[i] = [[NSColor colorWithDeviceRed:colours[i*3]
564 green:colours[i*3+1] blue:colours[i*3+2]
569 [self setupContentView];
571 [[self contentView] addSubview:status];
572 [self setIgnoresMouseEvents:NO];
574 [self center]; /* :-) */
582 for (i = 0; i < fe.ncolours; i++) {
583 [fe.colours[i] release];
587 return [super dealloc];
590 - (void)processButton:(int)b x:(int)x y:(int)y
592 if (!midend_process_key(me, x, y, b))
596 - (void)keyDown:(NSEvent *)ev
598 NSString *s = [ev characters];
599 int i, n = [s length];
601 for (i = 0; i < n; i++) {
602 int c = [s characterAtIndex:i];
605 * ASCII gets passed straight to midend_process_key.
606 * Anything above that has to be translated to our own
607 * function key codes.
612 case NSUpArrowFunctionKey:
616 case NSDownArrowFunctionKey:
620 case NSLeftArrowFunctionKey:
624 case NSRightArrowFunctionKey:
633 if ([ev modifierFlags] & NSShiftKeyMask)
635 if ([ev modifierFlags] & NSControlKeyMask)
640 if (c >= '0' && c <= '9' && ([ev modifierFlags] & NSNumericPadKeyMask))
643 [self processButton:c x:-1 y:-1];
647 - (void)activateTimer
652 timer = [NSTimer scheduledTimerWithTimeInterval:0.02
653 target:self selector:@selector(timerTick:)
654 userInfo:nil repeats:YES];
655 gettimeofday(&last_time, NULL);
658 - (void)deactivateTimer
667 - (void)timerTick:(id)sender
671 gettimeofday(&now, NULL);
672 elapsed = ((now.tv_usec - last_time.tv_usec) * 0.000001F +
673 (now.tv_sec - last_time.tv_sec));
674 midend_timer(me, elapsed);
678 - (void)showError:(char *)message
682 alert = [[[NSAlert alloc] init] autorelease];
683 [alert addButtonWithTitle:@"Bah"];
684 [alert setInformativeText:[NSString stringWithCString:message]];
685 [alert beginSheetModalForWindow:self modalDelegate:nil
686 didEndSelector:nil contextInfo:nil];
689 - (void)newGame:(id)sender
691 [self processButton:'n' x:-1 y:-1];
693 - (void)restartGame:(id)sender
695 midend_restart_game(me);
697 - (void)saveGame:(id)sender
699 NSSavePanel *sp = [NSSavePanel savePanel];
701 if ([sp runModal] == NSFileHandlingPanelOKButton) {
702 const char *name = [[sp filename] cString];
704 FILE *fp = fopen(name, "w");
707 [self showError:"Unable to open save file"];
711 midend_serialise(me, savefile_write, fp);
716 - (void)loadSavedGame:(id)sender
718 NSOpenPanel *op = [NSOpenPanel openPanel];
720 [op setAllowsMultipleSelection:NO];
722 if ([op runModalForTypes:nil] == NSOKButton) {
723 const char *name = [[[op filenames] objectAtIndex:0] cString];
726 FILE *fp = fopen(name, "r");
729 [self showError:"Unable to open saved game file"];
733 err = midend_deserialise(me, savefile_read, fp);
738 [self showError:err];
742 [self resizeForNewGameParams];
745 - (void)undoMove:(id)sender
747 [self processButton:'u' x:-1 y:-1];
749 - (void)redoMove:(id)sender
751 [self processButton:'r'&0x1F x:-1 y:-1];
754 - (void)copy:(id)sender
758 if ((text = midend_text_format(me)) != NULL) {
759 NSPasteboard *pb = [NSPasteboard generalPasteboard];
760 NSArray *a = [NSArray arrayWithObject:NSStringPboardType];
761 [pb declareTypes:a owner:nil];
762 [pb setString:[NSString stringWithCString:text]
763 forType:NSStringPboardType];
768 - (void)solveGame:(id)sender
772 msg = midend_solve(me);
775 [self showError:msg];
778 - (BOOL)validateMenuItem:(NSMenuItem *)item
780 if ([item action] == @selector(copy:))
781 return (ourgame->can_format_as_text ? YES : NO);
782 else if ([item action] == @selector(solveGame:))
783 return (ourgame->can_solve ? YES : NO);
785 return [super validateMenuItem:item];
788 - (void)clearTypeMenu
790 while ([typemenu numberOfItems] > 1)
791 [typemenu removeItemAtIndex:0];
794 - (void)becomeKeyWindow
798 [self clearTypeMenu];
800 [super becomeKeyWindow];
802 n = midend_num_presets(me);
805 [typemenu insertItem:[NSMenuItem separatorItem] atIndex:0];
811 midend_fetch_preset(me, n, &name, ¶ms);
813 item = [[[DataMenuItem alloc]
814 initWithTitle:[NSString stringWithCString:name]
815 action:NULL keyEquivalent:@""]
818 [item setEnabled:YES];
819 [item setTarget:self];
820 [item setAction:@selector(presetGame:)];
821 [item setPayload:params];
823 [typemenu insertItem:item atIndex:0];
828 - (void)resignKeyWindow
830 [self clearTypeMenu];
831 [super resignKeyWindow];
836 [self clearTypeMenu];
840 - (void)resizeForNewGameParams
846 midend_size(me, &w, &h, FALSE);
851 NSRect frame = [status frame];
852 size.height += frame.size.height;
853 frame.size.width = size.width;
854 [status setFrame:frame];
857 NSDisableScreenUpdates();
858 [self setContentSize:size];
859 [self setupContentView];
860 NSEnableScreenUpdates();
863 - (void)presetGame:(id)sender
865 game_params *params = [sender getPayload];
867 midend_set_params(me, params);
870 [self resizeForNewGameParams];
873 - (void)startConfigureSheet:(int)which
875 NSButton *ok, *cancel;
876 int actw, acth, leftw, rightw, totalw, h, thish, y;
878 NSRect rect, tmprect;
879 const int SPACING = 16;
887 assert(sheet == NULL);
890 * Every control we create here is going to have this size
891 * until we tell it to calculate a better one.
893 tmprect = NSMakeRect(0, 0, 100, 50);
896 * Set up OK and Cancel buttons. (Actually, MacOS doesn't seem
897 * to be fond of generic OK and Cancel wording, so I'm going to
898 * rename them to something nicer.)
902 cancel = [[NSButton alloc] initWithFrame:tmprect];
903 [cancel setBezelStyle:NSRoundedBezelStyle];
904 [cancel setTitle:@"Abandon"];
905 [cancel setTarget:self];
906 [cancel setKeyEquivalent:@"\033"];
907 [cancel setAction:@selector(sheetCancelButton:)];
909 rect = [cancel frame];
910 if (actw < rect.size.width) actw = rect.size.width;
911 if (acth < rect.size.height) acth = rect.size.height;
913 ok = [[NSButton alloc] initWithFrame:tmprect];
914 [ok setBezelStyle:NSRoundedBezelStyle];
915 [ok setTitle:@"Accept"];
917 [ok setKeyEquivalent:@"\r"];
918 [ok setAction:@selector(sheetOKButton:)];
921 if (actw < rect.size.width) actw = rect.size.width;
922 if (acth < rect.size.height) acth = rect.size.height;
924 totalw = SPACING + 2 * actw;
925 h = 2 * SPACING + acth;
928 * Now fetch the midend config data and go through it creating
931 cfg = midend_get_config(me, which, &title);
932 sfree(title); /* FIXME: should we use this somehow? */
935 cfg_ncontrols = cfg_controlsize = 0;
938 for (i = cfg; i->type != C_END; i++) {
939 if (cfg_controlsize < cfg_ncontrols + 5) {
940 cfg_controlsize = cfg_ncontrols + 32;
941 cfg_controls = sresize(cfg_controls, cfg_controlsize, NSView *);
949 * Two NSTextFields, one being a label and the other
953 tf = [[NSTextField alloc] initWithFrame:tmprect];
955 [tf setSelectable:NO];
957 [tf setDrawsBackground:NO];
958 [[tf cell] setTitle:[NSString stringWithCString:i->name]];
961 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
962 if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
963 cfg_controls[cfg_ncontrols++] = tf;
965 tf = [[NSTextField alloc] initWithFrame:tmprect];
966 [tf setEditable:YES];
967 [tf setSelectable:YES];
968 [tf setBordered:YES];
969 [[tf cell] setTitle:[NSString stringWithCString:i->sval]];
973 * We impose a minimum and maximum width on editable
974 * NSTextFields. If we allow them to size themselves to
975 * the contents of the text within them, then they will
976 * look very silly if that text is only one or two
977 * characters, and equally silly if it's an absolutely
978 * enormous Rectangles or Pattern game ID!
980 if (rect.size.width < 75) rect.size.width = 75;
981 if (rect.size.width > 400) rect.size.width = 400;
983 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
984 if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
985 cfg_controls[cfg_ncontrols++] = tf;
990 * A checkbox is an NSButton with a type of
993 b = [[NSButton alloc] initWithFrame:tmprect];
994 [b setBezelStyle:NSRoundedBezelStyle];
995 [b setButtonType:NSSwitchButton];
996 [b setTitle:[NSString stringWithCString:i->name]];
998 [b setState:(i->ival ? NSOnState : NSOffState)];
1000 if (totalw < rect.size.width + 1) totalw = rect.size.width + 1;
1001 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1002 cfg_controls[cfg_ncontrols++] = b;
1007 * A pop-up menu control is an NSPopUpButton, which
1008 * takes an embedded NSMenu. We also need an
1009 * NSTextField to act as a label.
1012 tf = [[NSTextField alloc] initWithFrame:tmprect];
1013 [tf setEditable:NO];
1014 [tf setSelectable:NO];
1015 [tf setBordered:NO];
1016 [tf setDrawsBackground:NO];
1017 [[tf cell] setTitle:[NSString stringWithCString:i->name]];
1020 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1021 if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
1022 cfg_controls[cfg_ncontrols++] = tf;
1024 pb = [[NSPopUpButton alloc] initWithFrame:tmprect pullsDown:NO];
1025 [pb setBezelStyle:NSRoundedBezelStyle];
1035 while (*p && *p != c) p++;
1037 [pb addItemWithTitle:[NSString stringWithCString:q
1043 [pb selectItemAtIndex:i->ival];
1047 if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
1048 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1049 cfg_controls[cfg_ncontrols++] = pb;
1053 h += SPACING + thish;
1056 if (totalw < leftw + SPACING + rightw)
1057 totalw = leftw + SPACING + rightw;
1058 if (totalw > leftw + SPACING + rightw) {
1059 int excess = totalw - (leftw + SPACING + rightw);
1060 int leftexcess = leftw * excess / (leftw + rightw);
1061 int rightexcess = excess - leftexcess;
1062 leftw += leftexcess;
1063 rightw += rightexcess;
1067 * Now go through the list again, setting the final position
1072 for (i = cfg; i->type != C_END; i++) {
1079 * These two are treated identically, since both expect
1080 * a control on the left and another on the right.
1082 rect = [cfg_controls[k] frame];
1083 if (thish < rect.size.height + 1)
1084 thish = rect.size.height + 1;
1085 rect = [cfg_controls[k+1] frame];
1086 if (thish < rect.size.height + 1)
1087 thish = rect.size.height + 1;
1088 rect = [cfg_controls[k] frame];
1089 rect.origin.y = y - thish/2 - rect.size.height/2;
1090 rect.origin.x = SPACING;
1091 rect.size.width = leftw;
1092 [cfg_controls[k] setFrame:rect];
1093 rect = [cfg_controls[k+1] frame];
1094 rect.origin.y = y - thish/2 - rect.size.height/2;
1095 rect.origin.x = 2 * SPACING + leftw;
1096 rect.size.width = rightw;
1097 [cfg_controls[k+1] setFrame:rect];
1102 rect = [cfg_controls[k] frame];
1103 if (thish < rect.size.height + 1)
1104 thish = rect.size.height + 1;
1105 rect.origin.y = y - thish/2 - rect.size.height/2;
1106 rect.origin.x = SPACING;
1107 rect.size.width = totalw;
1108 [cfg_controls[k] setFrame:rect];
1115 assert(k == cfg_ncontrols);
1117 [cancel setFrame:NSMakeRect(SPACING+totalw/4-actw/2, SPACING, actw, acth)];
1118 [ok setFrame:NSMakeRect(SPACING+3*totalw/4-actw/2, SPACING, actw, acth)];
1120 sheet = [[NSWindow alloc]
1121 initWithContentRect:NSMakeRect(0,0,totalw + 2*SPACING,h)
1122 styleMask:NSTitledWindowMask | NSClosableWindowMask
1123 backing:NSBackingStoreBuffered
1126 [[sheet contentView] addSubview:cancel];
1127 [[sheet contentView] addSubview:ok];
1129 for (k = 0; k < cfg_ncontrols; k++)
1130 [[sheet contentView] addSubview:cfg_controls[k]];
1132 [NSApp beginSheet:sheet modalForWindow:self
1133 modalDelegate:nil didEndSelector:nil contextInfo:nil];
1136 - (void)specificGame:(id)sender
1138 [self startConfigureSheet:CFG_DESC];
1141 - (void)specificRandomGame:(id)sender
1143 [self startConfigureSheet:CFG_SEED];
1146 - (void)customGameType:(id)sender
1148 [self startConfigureSheet:CFG_SETTINGS];
1151 - (void)sheetEndWithStatus:(BOOL)update
1153 assert(sheet != NULL);
1154 [NSApp endSheet:sheet];
1155 [sheet orderOut:self];
1163 for (i = cfg; i->type != C_END; i++) {
1167 i->sval = dupstr([[[(id)cfg_controls[k+1] cell]
1172 i->ival = [(id)cfg_controls[k] state] == NSOnState;
1176 i->ival = [(id)cfg_controls[k+1] indexOfSelectedItem];
1182 error = midend_set_config(me, cfg_which, cfg);
1184 NSAlert *alert = [[[NSAlert alloc] init] autorelease];
1185 [alert addButtonWithTitle:@"Bah"];
1186 [alert setInformativeText:[NSString stringWithCString:error]];
1187 [alert beginSheetModalForWindow:self modalDelegate:nil
1188 didEndSelector:nil contextInfo:nil];
1190 midend_new_game(me);
1191 [self resizeForNewGameParams];
1194 sfree(cfg_controls);
1195 cfg_controls = NULL;
1197 - (void)sheetOKButton:(id)sender
1199 [self sheetEndWithStatus:YES];
1201 - (void)sheetCancelButton:(id)sender
1203 [self sheetEndWithStatus:NO];
1206 - (void)setStatusLine:(char *)text
1208 char *rewritten = midend_rewrite_statusbar(me, text);
1209 [[status cell] setTitle:[NSString stringWithCString:rewritten]];
1216 * Drawing routines called by the midend.
1218 void draw_polygon(frontend *fe, int *coords, int npoints,
1219 int fillcolour, int outlinecolour)
1221 NSBezierPath *path = [NSBezierPath bezierPath];
1224 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1226 for (i = 0; i < npoints; i++) {
1227 NSPoint p = { coords[i*2] + 0.5, coords[i*2+1] + 0.5 };
1229 [path moveToPoint:p];
1231 [path lineToPoint:p];
1236 if (fillcolour >= 0) {
1237 assert(fillcolour >= 0 && fillcolour < fe->ncolours);
1238 [fe->colours[fillcolour] set];
1242 assert(outlinecolour >= 0 && outlinecolour < fe->ncolours);
1243 [fe->colours[outlinecolour] set];
1246 void draw_circle(frontend *fe, int cx, int cy, int radius,
1247 int fillcolour, int outlinecolour)
1249 NSBezierPath *path = [NSBezierPath bezierPath];
1251 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1253 [path appendBezierPathWithArcWithCenter:NSMakePoint(cx + 0.5, cy + 0.5)
1254 radius:radius startAngle:0.0 endAngle:360.0];
1258 if (fillcolour >= 0) {
1259 assert(fillcolour >= 0 && fillcolour < fe->ncolours);
1260 [fe->colours[fillcolour] set];
1264 assert(outlinecolour >= 0 && outlinecolour < fe->ncolours);
1265 [fe->colours[outlinecolour] set];
1268 void draw_line(frontend *fe, int x1, int y1, int x2, int y2, int colour)
1270 NSBezierPath *path = [NSBezierPath bezierPath];
1271 NSPoint p1 = { x1 + 0.5, y1 + 0.5 }, p2 = { x2 + 0.5, y2 + 0.5 };
1273 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1275 assert(colour >= 0 && colour < fe->ncolours);
1276 [fe->colours[colour] set];
1278 [path moveToPoint:p1];
1279 [path lineToPoint:p2];
1282 void draw_rect(frontend *fe, int x, int y, int w, int h, int colour)
1284 NSRect r = { {x,y}, {w,h} };
1286 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1288 assert(colour >= 0 && colour < fe->ncolours);
1289 [fe->colours[colour] set];
1293 void draw_text(frontend *fe, int x, int y, int fonttype, int fontsize,
1294 int align, int colour, char *text)
1296 NSString *string = [NSString stringWithCString:text];
1302 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1304 assert(colour >= 0 && colour < fe->ncolours);
1306 if (fonttype == FONT_FIXED)
1307 font = [NSFont userFixedPitchFontOfSize:fontsize];
1309 font = [NSFont userFontOfSize:fontsize];
1311 attr = [NSDictionary dictionaryWithObjectsAndKeys:
1312 fe->colours[colour], NSForegroundColorAttributeName,
1313 font, NSFontAttributeName, nil];
1318 size = [string sizeWithAttributes:attr];
1319 if (align & ALIGN_HRIGHT)
1320 point.x -= size.width;
1321 else if (align & ALIGN_HCENTRE)
1322 point.x -= size.width / 2;
1323 if (align & ALIGN_VCENTRE)
1324 point.y -= size.height / 2;
1326 [string drawAtPoint:point withAttributes:attr];
1333 blitter *blitter_new(int w, int h)
1335 blitter *bl = snew(blitter);
1339 bl->img = [[NSImage alloc] initWithSize:NSMakeSize(w, h)];
1340 [bl->img setFlipped:YES];
1343 void blitter_free(blitter *bl)
1348 void blitter_save(frontend *fe, blitter *bl, int x, int y)
1350 [fe->image unlockFocus];
1351 [bl->img lockFocus];
1352 [fe->image drawInRect:NSMakeRect(0, 0, bl->w, bl->h)
1353 fromRect:NSMakeRect(x, y, bl->w, bl->h)
1354 operation:NSCompositeCopy fraction:1.0];
1355 [bl->img unlockFocus];
1356 [fe->image lockFocus];
1360 void blitter_load(frontend *fe, blitter *bl, int x, int y)
1362 if (x == BLITTER_FROMSAVED && y == BLITTER_FROMSAVED) {
1366 [bl->img drawInRect:NSMakeRect(x, y, bl->w, bl->h)
1367 fromRect:NSMakeRect(0, 0, bl->w, bl->h)
1368 operation:NSCompositeCopy fraction:1.0];
1370 void draw_update(frontend *fe, int x, int y, int w, int h)
1372 [fe->view setNeedsDisplayInRect:NSMakeRect(x,y,w,h)];
1374 void clip(frontend *fe, int x, int y, int w, int h)
1376 NSRect r = { {x,y}, {w,h} };
1379 [[NSGraphicsContext currentContext] saveGraphicsState];
1380 [NSBezierPath clipRect:r];
1383 void unclip(frontend *fe)
1386 [[NSGraphicsContext currentContext] restoreGraphicsState];
1387 fe->clipped = FALSE;
1389 void start_draw(frontend *fe)
1391 [fe->image lockFocus];
1392 fe->clipped = FALSE;
1394 void end_draw(frontend *fe)
1396 [fe->image unlockFocus];
1399 void deactivate_timer(frontend *fe)
1401 [fe->window deactivateTimer];
1403 void activate_timer(frontend *fe)
1405 [fe->window activateTimer];
1408 void status_bar(frontend *fe, char *text)
1410 [fe->window setStatusLine:text];
1413 /* ----------------------------------------------------------------------
1414 * AppController: the object which receives the messages from all
1415 * menu selections that aren't standard OS X functions.
1417 @interface AppController : NSObject
1420 - (void)newGameWindow:(id)sender;
1421 - (void)about:(id)sender;
1424 @implementation AppController
1426 - (void)newGameWindow:(id)sender
1428 const game *g = [sender getPayload];
1431 win = [[GameWindow alloc] initWithGame:g];
1432 [win makeKeyAndOrderFront:self];
1435 - (void)about:(id)sender
1439 win = [[AboutBox alloc] init];
1440 [win makeKeyAndOrderFront:self];
1443 - (NSMenu *)applicationDockMenu:(NSApplication *)sender
1445 NSMenu *menu = newmenu("Dock Menu");
1449 for (i = 0; i < gamecount; i++) {
1451 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1452 menu, gamelist[i]->name, "", self,
1453 @selector(newGameWindow:));
1454 [item setPayload:(void *)gamelist[i]];
1462 /* ----------------------------------------------------------------------
1463 * Main program. Constructs the menus and runs the application.
1465 int main(int argc, char **argv)
1467 NSAutoreleasePool *pool;
1470 AppController *controller;
1473 pool = [[NSAutoreleasePool alloc] init];
1475 icon = [NSImage imageNamed:@"NSApplicationIcon"];
1476 [NSApplication sharedApplication];
1477 [NSApp setApplicationIconImage:icon];
1479 controller = [[[AppController alloc] init] autorelease];
1480 [NSApp setDelegate:controller];
1482 [NSApp setMainMenu: newmenu("Main Menu")];
1484 menu = newsubmenu([NSApp mainMenu], "Apple Menu");
1485 item = newitem(menu, "About Puzzles", "", NULL, @selector(about:));
1486 [menu addItem:[NSMenuItem separatorItem]];
1487 [NSApp setServicesMenu:newsubmenu(menu, "Services")];
1488 [menu addItem:[NSMenuItem separatorItem]];
1489 item = newitem(menu, "Hide Puzzles", "h", NSApp, @selector(hide:));
1490 item = newitem(menu, "Hide Others", "o-h", NSApp, @selector(hideOtherApplications:));
1491 item = newitem(menu, "Show All", "", NSApp, @selector(unhideAllApplications:));
1492 [menu addItem:[NSMenuItem separatorItem]];
1493 item = newitem(menu, "Quit", "q", NSApp, @selector(terminate:));
1494 [NSApp setAppleMenu: menu];
1496 menu = newsubmenu([NSApp mainMenu], "File");
1497 item = newitem(menu, "Open", "o", NULL, @selector(loadSavedGame:));
1498 item = newitem(menu, "Save As", "s", NULL, @selector(saveGame:));
1499 item = newitem(menu, "New Game", "n", NULL, @selector(newGame:));
1500 item = newitem(menu, "Restart Game", "r", NULL, @selector(restartGame:));
1501 item = newitem(menu, "Specific Game", "", NULL, @selector(specificGame:));
1502 item = newitem(menu, "Specific Random Seed", "", NULL,
1503 @selector(specificRandomGame:));
1504 [menu addItem:[NSMenuItem separatorItem]];
1506 NSMenu *submenu = newsubmenu(menu, "New Window");
1509 for (i = 0; i < gamecount; i++) {
1511 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1512 submenu, gamelist[i]->name, "", controller,
1513 @selector(newGameWindow:));
1514 [item setPayload:(void *)gamelist[i]];
1517 [menu addItem:[NSMenuItem separatorItem]];
1518 item = newitem(menu, "Close", "w", NULL, @selector(performClose:));
1520 menu = newsubmenu([NSApp mainMenu], "Edit");
1521 item = newitem(menu, "Undo", "z", NULL, @selector(undoMove:));
1522 item = newitem(menu, "Redo", "S-z", NULL, @selector(redoMove:));
1523 [menu addItem:[NSMenuItem separatorItem]];
1524 item = newitem(menu, "Cut", "x", NULL, @selector(cut:));
1525 item = newitem(menu, "Copy", "c", NULL, @selector(copy:));
1526 item = newitem(menu, "Paste", "v", NULL, @selector(paste:));
1527 [menu addItem:[NSMenuItem separatorItem]];
1528 item = newitem(menu, "Solve", "S-s", NULL, @selector(solveGame:));
1530 menu = newsubmenu([NSApp mainMenu], "Type");
1532 item = newitem(menu, "Custom", "", NULL, @selector(customGameType:));
1534 menu = newsubmenu([NSApp mainMenu], "Window");
1535 [NSApp setWindowsMenu: menu];
1536 item = newitem(menu, "Minimise Window", "m", NULL, @selector(performMiniaturize:));
1538 menu = newsubmenu([NSApp mainMenu], "Help");
1539 item = newitem(menu, "Puzzles Help", "?", NSApp, @selector(showHelp:));