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
80 #define COMBINED /* we put all the puzzles in one binary in this port */
85 #import <Cocoa/Cocoa.h>
88 /* ----------------------------------------------------------------------
93 * The `Type' menu. We frob this dynamically to allow the user to
94 * choose a preset set of settings from the current game.
101 extern const struct drawing_api osx_drawing;
103 /* ----------------------------------------------------------------------
104 * Miscellaneous support routines that aren't part of any object or
105 * clearly defined subsystem.
108 void fatal(char *fmt, ...)
115 vsnprintf(errorbuf, lenof(errorbuf), fmt, ap);
118 alert = [NSAlert alloc];
120 * We may have come here because we ran out of memory, in which
121 * case it's entirely likely that that alloc will fail, so we
122 * should have a fallback of some sort.
125 fprintf(stderr, "fatal error (and NSAlert failed): %s\n", errorbuf);
127 alert = [[alert init] autorelease];
128 [alert addButtonWithTitle:@"Oh dear"];
129 [alert setInformativeText:[NSString stringWithUTF8String:errorbuf]];
135 void frontend_default_colour(frontend *fe, float *output)
137 /* FIXME: Is there a system default we can tap into for this? */
138 output[0] = output[1] = output[2] = 0.8F;
141 void get_random_seed(void **randseed, int *randseedsize)
143 time_t *tp = snew(time_t);
145 *randseed = (void *)tp;
146 *randseedsize = sizeof(time_t);
149 static void savefile_write(void *wctx, void *buf, int len)
151 FILE *fp = (FILE *)wctx;
152 fwrite(buf, 1, len, fp);
155 static int savefile_read(void *wctx, void *buf, int len)
157 FILE *fp = (FILE *)wctx;
160 ret = fread(buf, 1, len, fp);
165 * Since this front end does not support printing (yet), we need
166 * this stub to satisfy the reference in midend_print_puzzle().
168 void document_add_puzzle(document *doc, const game *game, game_params *par,
169 game_state *st, game_state *st2)
174 * setAppleMenu isn't listed in the NSApplication header, but an
175 * NSApp responds to it, so we're adding it here to silence
176 * warnings. (This was removed from the headers in 10.4, so we
177 * only need to include it for 10.4+.)
179 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1040
180 @interface NSApplication(NSAppleMenu)
181 - (void)setAppleMenu:(NSMenu *)menu;
185 /* ----------------------------------------------------------------------
186 * Tiny extension to NSMenuItem which carries a payload of a `void
187 * *', allowing several menu items to invoke the same message but
188 * pass different data through it.
190 @interface DataMenuItem : NSMenuItem
194 - (void)setPayload:(void *)d;
195 - (void *)getPayload;
197 @implementation DataMenuItem
198 - (void)setPayload:(void *)d
208 /* ----------------------------------------------------------------------
209 * Utility routines for constructing OS X menus.
212 NSMenu *newmenu(const char *title)
214 return [[[NSMenu allocWithZone:[NSMenu menuZone]]
215 initWithTitle:[NSString stringWithUTF8String:title]]
219 NSMenu *newsubmenu(NSMenu *parent, const char *title)
224 item = [[[NSMenuItem allocWithZone:[NSMenu menuZone]]
225 initWithTitle:[NSString stringWithUTF8String:title]
229 child = newmenu(title);
230 [item setEnabled:YES];
231 [item setSubmenu:child];
232 [parent addItem:item];
236 id initnewitem(NSMenuItem *item, NSMenu *parent, const char *title,
237 const char *key, id target, SEL action)
239 unsigned mask = NSCommandKeyMask;
241 if (key[strcspn(key, "-")]) {
242 while (*key && *key != '-') {
243 int c = tolower((unsigned char)*key);
245 mask |= NSShiftKeyMask;
246 } else if (c == 'o' || c == 'a') {
247 mask |= NSAlternateKeyMask;
255 item = [[item initWithTitle:[NSString stringWithUTF8String:title]
257 keyEquivalent:[NSString stringWithUTF8String:key]]
261 [item setKeyEquivalentModifierMask: mask];
263 [item setEnabled:YES];
264 [item setTarget:target];
265 [item setAction:action];
267 [parent addItem:item];
272 NSMenuItem *newitem(NSMenu *parent, char *title, char *key,
273 id target, SEL action)
275 return initnewitem([NSMenuItem allocWithZone:[NSMenu menuZone]],
276 parent, title, key, target, action);
279 /* ----------------------------------------------------------------------
285 @interface AboutBox : NSWindow
291 @implementation AboutBox
299 NSFont *font1 = [NSFont systemFontOfSize:0];
300 NSFont *font2 = [NSFont boldSystemFontOfSize:[font1 pointSize] * 1.1];
301 const int border = 24;
306 * Construct the controls that go in the About box.
309 iv = [[NSImageView alloc] initWithFrame:NSMakeRect(0,0,64,64)];
310 [iv setImage:[NSImage imageNamed:@"NSApplicationIcon"]];
311 views[nviews++] = iv;
313 tf = [[NSTextField alloc]
314 initWithFrame:NSMakeRect(0,0,400,1)];
316 [tf setSelectable:NO];
318 [tf setDrawsBackground:NO];
320 [tf setStringValue:@"Simon Tatham's Portable Puzzle Collection"];
322 views[nviews++] = tf;
324 tf = [[NSTextField alloc]
325 initWithFrame:NSMakeRect(0,0,400,1)];
327 [tf setSelectable:NO];
329 [tf setDrawsBackground:NO];
331 [tf setStringValue:[NSString stringWithUTF8String:ver]];
333 views[nviews++] = tf;
336 * Lay the controls out.
338 totalrect = NSMakeRect(0,0,0,0);
339 for (i = 0; i < nviews; i++) {
340 NSRect r = [views[i] frame];
341 if (totalrect.size.width < r.size.width)
342 totalrect.size.width = r.size.width;
343 totalrect.size.height += border + r.size.height;
345 totalrect.size.width += 2 * border;
346 totalrect.size.height += border;
347 y = totalrect.size.height;
348 for (i = 0; i < nviews; i++) {
349 NSRect r = [views[i] frame];
350 r.origin.x = (totalrect.size.width - r.size.width) / 2;
351 y -= border + r.size.height;
353 [views[i] setFrame:r];
356 self = [super initWithContentRect:totalrect
357 styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
358 NSClosableWindowMask)
359 backing:NSBackingStoreBuffered
362 for (i = 0; i < nviews; i++)
363 [[self contentView] addSubview:views[i]];
365 [self center]; /* :-) */
371 /* ----------------------------------------------------------------------
372 * The front end presented to midend.c.
374 * This is mostly a subclass of NSWindow. The actual `frontend'
375 * structure passed to the midend contains a variety of pointers,
376 * including that window object but also including the image we
377 * draw on, an ImageView to display it in the window, and so on.
393 @interface MyImageView : NSImageView
397 - (void)setWindow:(GameWindow *)win;
398 - (void)mouseEvent:(NSEvent *)ev button:(int)b;
399 - (void)mouseDown:(NSEvent *)ev;
400 - (void)mouseDragged:(NSEvent *)ev;
401 - (void)mouseUp:(NSEvent *)ev;
402 - (void)rightMouseDown:(NSEvent *)ev;
403 - (void)rightMouseDragged:(NSEvent *)ev;
404 - (void)rightMouseUp:(NSEvent *)ev;
405 - (void)otherMouseDown:(NSEvent *)ev;
406 - (void)otherMouseDragged:(NSEvent *)ev;
407 - (void)otherMouseUp:(NSEvent *)ev;
410 @interface GameWindow : NSWindow
415 struct timeval last_time;
420 NSView **cfg_controls;
424 - (id)initWithGame:(const game *)g;
426 - (void)processButton:(int)b x:(int)x y:(int)y;
427 - (void)processKey:(int)b;
428 - (void)keyDown:(NSEvent *)ev;
429 - (void)activateTimer;
430 - (void)deactivateTimer;
431 - (void)setStatusLine:(char *)text;
432 - (void)resizeForNewGameParams;
433 - (void)updateTypeMenuTick;
436 @implementation MyImageView
438 - (void)setWindow:(GameWindow *)win
443 - (void)mouseEvent:(NSEvent *)ev button:(int)b
445 NSPoint point = [self convertPoint:[ev locationInWindow] fromView:nil];
446 [ourwin processButton:b x:point.x y:point.y];
449 - (void)mouseDown:(NSEvent *)ev
451 unsigned mod = [ev modifierFlags];
452 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_BUTTON :
453 (mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
456 - (void)mouseDragged:(NSEvent *)ev
458 unsigned mod = [ev modifierFlags];
459 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_DRAG :
460 (mod & NSShiftKeyMask) ? MIDDLE_DRAG :
463 - (void)mouseUp:(NSEvent *)ev
465 unsigned mod = [ev modifierFlags];
466 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_RELEASE :
467 (mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
470 - (void)rightMouseDown:(NSEvent *)ev
472 unsigned mod = [ev modifierFlags];
473 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
476 - (void)rightMouseDragged:(NSEvent *)ev
478 unsigned mod = [ev modifierFlags];
479 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_DRAG :
482 - (void)rightMouseUp:(NSEvent *)ev
484 unsigned mod = [ev modifierFlags];
485 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
488 - (void)otherMouseDown:(NSEvent *)ev
490 [self mouseEvent:ev button:MIDDLE_BUTTON];
492 - (void)otherMouseDragged:(NSEvent *)ev
494 [self mouseEvent:ev button:MIDDLE_DRAG];
496 - (void)otherMouseUp:(NSEvent *)ev
498 [self mouseEvent:ev button:MIDDLE_RELEASE];
502 @implementation GameWindow
503 - (void)setupContentView
509 frame = [status frame];
510 frame.origin.y = frame.size.height;
516 midend_size(me, &w, &h, FALSE);
517 frame.size.width = w;
518 frame.size.height = h;
522 fe.image = [[NSImage alloc] initWithSize:frame.size];
523 fe.view = [[MyImageView alloc] initWithFrame:frame];
524 [fe.view setImage:fe.image];
525 [fe.view setWindow:self];
529 [[self contentView] addSubview:fe.view];
531 - (id)initWithGame:(const game *)g
533 NSRect rect = { {0,0}, {0,0} }, rect2;
540 me = midend_new(&fe, ourgame, &osx_drawing, &fe);
542 * If we ever need to open a fresh window using a provided game
543 * ID, I think the right thing is to move most of this method
544 * into a new initWithGame:gameID: method, and have
545 * initWithGame: simply call that one and pass it NULL.
549 midend_size(me, &w, &h, FALSE);
551 rect.size.height = h;
556 * Create the status bar, which will just be an NSTextField.
558 if (midend_wants_statusbar(me)) {
559 status = [[NSTextField alloc] initWithFrame:NSMakeRect(0,0,100,50)];
560 [status setEditable:NO];
561 [status setSelectable:NO];
562 [status setBordered:YES];
563 [status setBezeled:YES];
564 [status setBezelStyle:NSTextFieldSquareBezel];
565 [status setDrawsBackground:YES];
566 [[status cell] setTitle:@""];
568 rect2 = [status frame];
569 rect.size.height += rect2.size.height;
570 rect2.size.width = rect.size.width;
571 rect2.origin.x = rect2.origin.y = 0;
572 [status setFrame:rect2];
576 self = [super initWithContentRect:rect
577 styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
578 NSClosableWindowMask)
579 backing:NSBackingStoreBuffered
581 [self setTitle:[NSString stringWithUTF8String:ourgame->name]];
587 colours = midend_colours(me, &ncolours);
588 fe.ncolours = ncolours;
589 fe.colours = snewn(ncolours, NSColor *);
591 for (i = 0; i < ncolours; i++) {
592 fe.colours[i] = [[NSColor colorWithDeviceRed:colours[i*3]
593 green:colours[i*3+1] blue:colours[i*3+2]
598 [self setupContentView];
600 [[self contentView] addSubview:status];
601 [self setIgnoresMouseEvents:NO];
603 [self center]; /* :-) */
611 for (i = 0; i < fe.ncolours; i++) {
612 [fe.colours[i] release];
619 - (void)processButton:(int)b x:(int)x y:(int)y
621 if (!midend_process_key(me, x, fe.h - 1 - y, b))
625 - (void)processKey:(int)b
627 if (!midend_process_key(me, -1, -1, b))
631 - (void)keyDown:(NSEvent *)ev
633 NSString *s = [ev characters];
634 int i, n = [s length];
636 for (i = 0; i < n; i++) {
637 int c = [s characterAtIndex:i];
640 * ASCII gets passed straight to midend_process_key.
641 * Anything above that has to be translated to our own
642 * function key codes.
647 case NSUpArrowFunctionKey:
651 case NSDownArrowFunctionKey:
655 case NSLeftArrowFunctionKey:
659 case NSRightArrowFunctionKey:
668 if ([ev modifierFlags] & NSShiftKeyMask)
670 if ([ev modifierFlags] & NSControlKeyMask)
675 if (c >= '0' && c <= '9' && ([ev modifierFlags] & NSNumericPadKeyMask))
682 - (void)activateTimer
687 timer = [NSTimer scheduledTimerWithTimeInterval:0.02
688 target:self selector:@selector(timerTick:)
689 userInfo:nil repeats:YES];
690 gettimeofday(&last_time, NULL);
693 - (void)deactivateTimer
702 - (void)timerTick:(id)sender
706 gettimeofday(&now, NULL);
707 elapsed = ((now.tv_usec - last_time.tv_usec) * 0.000001F +
708 (now.tv_sec - last_time.tv_sec));
709 midend_timer(me, elapsed);
713 - (void)showError:(char *)message
717 alert = [[[NSAlert alloc] init] autorelease];
718 [alert addButtonWithTitle:@"Bah"];
719 [alert setInformativeText:[NSString stringWithUTF8String:message]];
720 [alert beginSheetModalForWindow:self modalDelegate:nil
721 didEndSelector:NULL contextInfo:nil];
724 - (void)newGame:(id)sender
726 [self processKey:'n'];
728 - (void)restartGame:(id)sender
730 midend_restart_game(me);
732 - (void)saveGame:(id)sender
734 NSSavePanel *sp = [NSSavePanel savePanel];
736 if ([sp runModal] == NSFileHandlingPanelOKButton) {
737 const char *name = [[sp filename] UTF8String];
739 FILE *fp = fopen(name, "w");
742 [self showError:"Unable to open save file"];
746 midend_serialise(me, savefile_write, fp);
751 - (void)loadSavedGame:(id)sender
753 NSOpenPanel *op = [NSOpenPanel openPanel];
755 [op setAllowsMultipleSelection:NO];
757 if ([op runModalForTypes:nil] == NSOKButton) {
758 const char *name = [[[op filenames] objectAtIndex:0] cString];
761 FILE *fp = fopen(name, "r");
764 [self showError:"Unable to open saved game file"];
768 err = midend_deserialise(me, savefile_read, fp);
773 [self showError:err];
777 [self resizeForNewGameParams];
778 [self updateTypeMenuTick];
781 - (void)undoMove:(id)sender
783 [self processKey:'u'];
785 - (void)redoMove:(id)sender
787 [self processKey:'r'&0x1F];
790 - (void)copy:(id)sender
794 if ((text = midend_text_format(me)) != NULL) {
795 NSPasteboard *pb = [NSPasteboard generalPasteboard];
796 NSArray *a = [NSArray arrayWithObject:NSStringPboardType];
797 [pb declareTypes:a owner:nil];
798 [pb setString:[NSString stringWithUTF8String:text]
799 forType:NSStringPboardType];
804 - (void)solveGame:(id)sender
808 msg = midend_solve(me);
811 [self showError:msg];
814 - (BOOL)validateMenuItem:(NSMenuItem *)item
816 if ([item action] == @selector(copy:))
817 return (ourgame->can_format_as_text_ever &&
818 midend_can_format_as_text_now(me) ? YES : NO);
819 else if ([item action] == @selector(solveGame:))
820 return (ourgame->can_solve ? YES : NO);
822 return [super validateMenuItem:item];
825 - (void)clearTypeMenu
827 while ([typemenu numberOfItems] > 1)
828 [typemenu removeItemAtIndex:0];
829 [[typemenu itemAtIndex:0] setState:NSOffState];
832 - (void)updateTypeMenuTick
836 total = [typemenu numberOfItems];
837 n = midend_which_preset(me);
839 n = total - 1; /* that's always where "Custom" lives */
840 for (i = 0; i < total; i++)
841 [[typemenu itemAtIndex:i] setState:(i == n ? NSOnState : NSOffState)];
844 - (void)becomeKeyWindow
848 [self clearTypeMenu];
850 [super becomeKeyWindow];
852 n = midend_num_presets(me);
855 [typemenu insertItem:[NSMenuItem separatorItem] atIndex:0];
861 midend_fetch_preset(me, n, &name, ¶ms);
863 item = [[[DataMenuItem alloc]
864 initWithTitle:[NSString stringWithUTF8String:name]
865 action:NULL keyEquivalent:@""]
868 [item setEnabled:YES];
869 [item setTarget:self];
870 [item setAction:@selector(presetGame:)];
871 [item setPayload:params];
873 [typemenu insertItem:item atIndex:0];
877 [self updateTypeMenuTick];
880 - (void)resignKeyWindow
882 [self clearTypeMenu];
883 [super resignKeyWindow];
888 [self clearTypeMenu];
892 - (void)resizeForNewGameParams
898 midend_size(me, &w, &h, FALSE);
905 NSRect frame = [status frame];
906 size.height += frame.size.height;
907 frame.size.width = size.width;
908 [status setFrame:frame];
912 NSDisableScreenUpdates();
914 [self setContentSize:size];
915 [self setupContentView];
917 NSEnableScreenUpdates();
921 - (void)presetGame:(id)sender
923 game_params *params = [sender getPayload];
925 midend_set_params(me, params);
928 [self resizeForNewGameParams];
929 [self updateTypeMenuTick];
932 - (void)startConfigureSheet:(int)which
934 NSButton *ok, *cancel;
935 int actw, acth, leftw, rightw, totalw, h, thish, y;
937 NSRect rect, tmprect;
938 const int SPACING = 16;
946 assert(sheet == NULL);
949 * Every control we create here is going to have this size
950 * until we tell it to calculate a better one.
952 tmprect = NSMakeRect(0, 0, 100, 50);
955 * Set up OK and Cancel buttons. (Actually, MacOS doesn't seem
956 * to be fond of generic OK and Cancel wording, so I'm going to
957 * rename them to something nicer.)
961 cancel = [[NSButton alloc] initWithFrame:tmprect];
962 [cancel setBezelStyle:NSRoundedBezelStyle];
963 [cancel setTitle:@"Abandon"];
964 [cancel setTarget:self];
965 [cancel setKeyEquivalent:@"\033"];
966 [cancel setAction:@selector(sheetCancelButton:)];
968 rect = [cancel frame];
969 if (actw < rect.size.width) actw = rect.size.width;
970 if (acth < rect.size.height) acth = rect.size.height;
972 ok = [[NSButton alloc] initWithFrame:tmprect];
973 [ok setBezelStyle:NSRoundedBezelStyle];
974 [ok setTitle:@"Accept"];
976 [ok setKeyEquivalent:@"\r"];
977 [ok setAction:@selector(sheetOKButton:)];
980 if (actw < rect.size.width) actw = rect.size.width;
981 if (acth < rect.size.height) acth = rect.size.height;
983 totalw = SPACING + 2 * actw;
984 h = 2 * SPACING + acth;
987 * Now fetch the midend config data and go through it creating
990 cfg = midend_get_config(me, which, &title);
991 sfree(title); /* FIXME: should we use this somehow? */
994 cfg_ncontrols = cfg_controlsize = 0;
997 for (i = cfg; i->type != C_END; i++) {
998 if (cfg_controlsize < cfg_ncontrols + 5) {
999 cfg_controlsize = cfg_ncontrols + 32;
1000 cfg_controls = sresize(cfg_controls, cfg_controlsize, NSView *);
1008 * Two NSTextFields, one being a label and the other
1009 * being an edit box.
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 stringWithUTF8String: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 tf = [[NSTextField alloc] initWithFrame:tmprect];
1025 [tf setEditable:YES];
1026 [tf setSelectable:YES];
1027 [tf setBordered:YES];
1028 [[tf cell] setTitle:[NSString stringWithUTF8String:i->sval]];
1032 * We impose a minimum and maximum width on editable
1033 * NSTextFields. If we allow them to size themselves to
1034 * the contents of the text within them, then they will
1035 * look very silly if that text is only one or two
1036 * characters, and equally silly if it's an absolutely
1037 * enormous Rectangles or Pattern game ID!
1039 if (rect.size.width < 75) rect.size.width = 75;
1040 if (rect.size.width > 400) rect.size.width = 400;
1042 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1043 if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
1044 cfg_controls[cfg_ncontrols++] = tf;
1049 * A checkbox is an NSButton with a type of
1052 b = [[NSButton alloc] initWithFrame:tmprect];
1053 [b setBezelStyle:NSRoundedBezelStyle];
1054 [b setButtonType:NSSwitchButton];
1055 [b setTitle:[NSString stringWithUTF8String:i->name]];
1057 [b setState:(i->ival ? NSOnState : NSOffState)];
1059 if (totalw < rect.size.width + 1) totalw = rect.size.width + 1;
1060 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1061 cfg_controls[cfg_ncontrols++] = b;
1066 * A pop-up menu control is an NSPopUpButton, which
1067 * takes an embedded NSMenu. We also need an
1068 * NSTextField to act as a label.
1071 tf = [[NSTextField alloc] initWithFrame:tmprect];
1072 [tf setEditable:NO];
1073 [tf setSelectable:NO];
1074 [tf setBordered:NO];
1075 [tf setDrawsBackground:NO];
1076 [[tf cell] setTitle:[NSString stringWithUTF8String:i->name]];
1079 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1080 if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
1081 cfg_controls[cfg_ncontrols++] = tf;
1083 pb = [[NSPopUpButton alloc] initWithFrame:tmprect pullsDown:NO];
1084 [pb setBezelStyle:NSRoundedBezelStyle];
1094 while (*p && *p != c) p++;
1096 copy = snewn((p-q) + 1, char);
1097 memcpy(copy, q, p-q);
1099 [pb addItemWithTitle:[NSString stringWithUTF8String:copy]];
1105 [pb selectItemAtIndex:i->ival];
1109 if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
1110 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1111 cfg_controls[cfg_ncontrols++] = pb;
1115 h += SPACING + thish;
1118 if (totalw < leftw + SPACING + rightw)
1119 totalw = leftw + SPACING + rightw;
1120 if (totalw > leftw + SPACING + rightw) {
1121 int excess = totalw - (leftw + SPACING + rightw);
1122 int leftexcess = leftw * excess / (leftw + rightw);
1123 int rightexcess = excess - leftexcess;
1124 leftw += leftexcess;
1125 rightw += rightexcess;
1129 * Now go through the list again, setting the final position
1134 for (i = cfg; i->type != C_END; i++) {
1141 * These two are treated identically, since both expect
1142 * a control on the left and another on the right.
1144 rect = [cfg_controls[k] frame];
1145 if (thish < rect.size.height + 1)
1146 thish = rect.size.height + 1;
1147 rect = [cfg_controls[k+1] frame];
1148 if (thish < rect.size.height + 1)
1149 thish = rect.size.height + 1;
1150 rect = [cfg_controls[k] frame];
1151 rect.origin.y = y - thish/2 - rect.size.height/2;
1152 rect.origin.x = SPACING;
1153 rect.size.width = leftw;
1154 [cfg_controls[k] setFrame:rect];
1155 rect = [cfg_controls[k+1] frame];
1156 rect.origin.y = y - thish/2 - rect.size.height/2;
1157 rect.origin.x = 2 * SPACING + leftw;
1158 rect.size.width = rightw;
1159 [cfg_controls[k+1] setFrame:rect];
1164 rect = [cfg_controls[k] frame];
1165 if (thish < rect.size.height + 1)
1166 thish = rect.size.height + 1;
1167 rect.origin.y = y - thish/2 - rect.size.height/2;
1168 rect.origin.x = SPACING;
1169 rect.size.width = totalw;
1170 [cfg_controls[k] setFrame:rect];
1177 assert(k == cfg_ncontrols);
1179 [cancel setFrame:NSMakeRect(SPACING+totalw/4-actw/2, SPACING, actw, acth)];
1180 [ok setFrame:NSMakeRect(SPACING+3*totalw/4-actw/2, SPACING, actw, acth)];
1182 sheet = [[NSWindow alloc]
1183 initWithContentRect:NSMakeRect(0,0,totalw + 2*SPACING,h)
1184 styleMask:NSTitledWindowMask | NSClosableWindowMask
1185 backing:NSBackingStoreBuffered
1188 [[sheet contentView] addSubview:cancel];
1189 [[sheet contentView] addSubview:ok];
1191 for (k = 0; k < cfg_ncontrols; k++)
1192 [[sheet contentView] addSubview:cfg_controls[k]];
1194 [NSApp beginSheet:sheet modalForWindow:self
1195 modalDelegate:nil didEndSelector:NULL contextInfo:nil];
1198 - (void)specificGame:(id)sender
1200 [self startConfigureSheet:CFG_DESC];
1203 - (void)specificRandomGame:(id)sender
1205 [self startConfigureSheet:CFG_SEED];
1208 - (void)customGameType:(id)sender
1210 [self startConfigureSheet:CFG_SETTINGS];
1213 - (void)sheetEndWithStatus:(BOOL)update
1215 assert(sheet != NULL);
1216 [NSApp endSheet:sheet];
1217 [sheet orderOut:self];
1225 for (i = cfg; i->type != C_END; i++) {
1229 i->sval = dupstr([[[(id)cfg_controls[k+1] cell]
1230 title] UTF8String]);
1234 i->ival = [(id)cfg_controls[k] state] == NSOnState;
1238 i->ival = [(id)cfg_controls[k+1] indexOfSelectedItem];
1244 error = midend_set_config(me, cfg_which, cfg);
1246 NSAlert *alert = [[[NSAlert alloc] init] autorelease];
1247 [alert addButtonWithTitle:@"Bah"];
1248 [alert setInformativeText:[NSString stringWithUTF8String:error]];
1249 [alert beginSheetModalForWindow:self modalDelegate:nil
1250 didEndSelector:NULL contextInfo:nil];
1252 midend_new_game(me);
1253 [self resizeForNewGameParams];
1254 [self updateTypeMenuTick];
1257 sfree(cfg_controls);
1258 cfg_controls = NULL;
1260 - (void)sheetOKButton:(id)sender
1262 [self sheetEndWithStatus:YES];
1264 - (void)sheetCancelButton:(id)sender
1266 [self sheetEndWithStatus:NO];
1269 - (void)setStatusLine:(char *)text
1271 [[status cell] setTitle:[NSString stringWithUTF8String:text]];
1277 * Drawing routines called by the midend.
1279 static void osx_draw_polygon(void *handle, int *coords, int npoints,
1280 int fillcolour, int outlinecolour)
1282 frontend *fe = (frontend *)handle;
1283 NSBezierPath *path = [NSBezierPath bezierPath];
1286 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1288 for (i = 0; i < npoints; i++) {
1289 NSPoint p = { coords[i*2] + 0.5, fe->h - coords[i*2+1] - 0.5 };
1291 [path moveToPoint:p];
1293 [path lineToPoint:p];
1298 if (fillcolour >= 0) {
1299 assert(fillcolour >= 0 && fillcolour < fe->ncolours);
1300 [fe->colours[fillcolour] set];
1304 assert(outlinecolour >= 0 && outlinecolour < fe->ncolours);
1305 [fe->colours[outlinecolour] set];
1308 static void osx_draw_circle(void *handle, int cx, int cy, int radius,
1309 int fillcolour, int outlinecolour)
1311 frontend *fe = (frontend *)handle;
1312 NSBezierPath *path = [NSBezierPath bezierPath];
1314 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1316 [path appendBezierPathWithArcWithCenter:NSMakePoint(cx+0.5, fe->h-cy-0.5)
1317 radius:radius startAngle:0.0 endAngle:360.0];
1321 if (fillcolour >= 0) {
1322 assert(fillcolour >= 0 && fillcolour < fe->ncolours);
1323 [fe->colours[fillcolour] set];
1327 assert(outlinecolour >= 0 && outlinecolour < fe->ncolours);
1328 [fe->colours[outlinecolour] set];
1331 static void osx_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
1333 frontend *fe = (frontend *)handle;
1334 NSBezierPath *path = [NSBezierPath bezierPath];
1335 NSPoint p1 = { x1 + 0.5, fe->h - y1 - 0.5 };
1336 NSPoint p2 = { x2 + 0.5, fe->h - y2 - 0.5 };
1338 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1340 assert(colour >= 0 && colour < fe->ncolours);
1341 [fe->colours[colour] set];
1343 [path moveToPoint:p1];
1344 [path lineToPoint:p2];
1346 NSRectFill(NSMakeRect(x1, fe->h-y1-1, 1, 1));
1347 NSRectFill(NSMakeRect(x2, fe->h-y2-1, 1, 1));
1349 static void osx_draw_rect(void *handle, int x, int y, int w, int h, int colour)
1351 frontend *fe = (frontend *)handle;
1352 NSRect r = { {x, fe->h - y - h}, {w,h} };
1354 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1356 assert(colour >= 0 && colour < fe->ncolours);
1357 [fe->colours[colour] set];
1361 static void osx_draw_text(void *handle, int x, int y, int fonttype,
1362 int fontsize, int align, int colour, char *text)
1364 frontend *fe = (frontend *)handle;
1365 NSString *string = [NSString stringWithUTF8String:text];
1371 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1373 assert(colour >= 0 && colour < fe->ncolours);
1375 if (fonttype == FONT_FIXED)
1376 font = [NSFont userFixedPitchFontOfSize:fontsize];
1378 font = [NSFont userFontOfSize:fontsize];
1380 attr = [NSDictionary dictionaryWithObjectsAndKeys:
1381 fe->colours[colour], NSForegroundColorAttributeName,
1382 font, NSFontAttributeName, nil];
1385 point.y = fe->h - y;
1387 size = [string sizeWithAttributes:attr];
1388 if (align & ALIGN_HRIGHT)
1389 point.x -= size.width;
1390 else if (align & ALIGN_HCENTRE)
1391 point.x -= size.width / 2;
1392 if (align & ALIGN_VCENTRE)
1393 point.y -= size.height / 2;
1395 [string drawAtPoint:point withAttributes:attr];
1397 static char *osx_text_fallback(void *handle, const char *const *strings,
1401 * We assume OS X can cope with any UTF-8 likely to be emitted
1404 return dupstr(strings[0]);
1411 static blitter *osx_blitter_new(void *handle, int w, int h)
1413 blitter *bl = snew(blitter);
1417 bl->img = [[NSImage alloc] initWithSize:NSMakeSize(w, h)];
1420 static void osx_blitter_free(void *handle, blitter *bl)
1425 static void osx_blitter_save(void *handle, blitter *bl, int x, int y)
1427 frontend *fe = (frontend *)handle;
1428 int sx, sy, sX, sY, dx, dy, dX, dY;
1429 [fe->image unlockFocus];
1430 [bl->img lockFocus];
1433 * Find the intersection of the source and destination rectangles,
1434 * so as to avoid trying to copy from outside the source image,
1435 * which GNUstep dislikes.
1437 * Lower-case x,y coordinates are bottom left box corners;
1438 * upper-case X,Y are the top right.
1440 sx = x; sy = fe->h - y - bl->h;
1441 sX = sx + bl->w; sY = sy + bl->h;
1443 dX = bl->w; dY = bl->h;
1461 [fe->image drawInRect:NSMakeRect(dx, dy, dX-dx, dY-dy)
1462 fromRect:NSMakeRect(sx, sy, sX-sx, sY-sy)
1463 operation:NSCompositeCopy fraction:1.0];
1464 [bl->img unlockFocus];
1465 [fe->image lockFocus];
1469 static void osx_blitter_load(void *handle, blitter *bl, int x, int y)
1471 frontend *fe = (frontend *)handle;
1472 if (x == BLITTER_FROMSAVED && y == BLITTER_FROMSAVED) {
1476 [bl->img drawInRect:NSMakeRect(x, fe->h - y - bl->h, bl->w, bl->h)
1477 fromRect:NSMakeRect(0, 0, bl->w, bl->h)
1478 operation:NSCompositeCopy fraction:1.0];
1480 static void osx_draw_update(void *handle, int x, int y, int w, int h)
1482 frontend *fe = (frontend *)handle;
1483 [fe->view setNeedsDisplayInRect:NSMakeRect(x, fe->h - y - h, w, h)];
1485 static void osx_clip(void *handle, int x, int y, int w, int h)
1487 frontend *fe = (frontend *)handle;
1488 NSRect r = { {x, fe->h - y - h}, {w, h} };
1491 [[NSGraphicsContext currentContext] saveGraphicsState];
1492 [NSBezierPath clipRect:r];
1495 static void osx_unclip(void *handle)
1497 frontend *fe = (frontend *)handle;
1499 [[NSGraphicsContext currentContext] restoreGraphicsState];
1500 fe->clipped = FALSE;
1502 static void osx_start_draw(void *handle)
1504 frontend *fe = (frontend *)handle;
1505 [fe->image lockFocus];
1506 fe->clipped = FALSE;
1508 static void osx_end_draw(void *handle)
1510 frontend *fe = (frontend *)handle;
1511 [fe->image unlockFocus];
1513 static void osx_status_bar(void *handle, char *text)
1515 frontend *fe = (frontend *)handle;
1516 [fe->window setStatusLine:text];
1519 const struct drawing_api osx_drawing = {
1535 NULL, NULL, NULL, NULL, NULL, NULL, /* {begin,end}_{doc,page,puzzle} */
1536 NULL, NULL, /* line_width, line_dotted */
1540 void deactivate_timer(frontend *fe)
1542 [fe->window deactivateTimer];
1544 void activate_timer(frontend *fe)
1546 [fe->window activateTimer];
1549 /* ----------------------------------------------------------------------
1550 * AppController: the object which receives the messages from all
1551 * menu selections that aren't standard OS X functions.
1553 @interface AppController : NSObject
1556 - (void)newGameWindow:(id)sender;
1557 - (void)about:(id)sender;
1560 @implementation AppController
1562 - (void)newGameWindow:(id)sender
1564 const game *g = [sender getPayload];
1567 win = [[GameWindow alloc] initWithGame:g];
1568 [win makeKeyAndOrderFront:self];
1571 - (void)about:(id)sender
1575 win = [[AboutBox alloc] init];
1576 [win makeKeyAndOrderFront:self];
1579 - (NSMenu *)applicationDockMenu:(NSApplication *)sender
1581 NSMenu *menu = newmenu("Dock Menu");
1585 for (i = 0; i < gamecount; i++) {
1587 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1588 menu, gamelist[i]->name, "", self,
1589 @selector(newGameWindow:));
1590 [item setPayload:(void *)gamelist[i]];
1598 /* ----------------------------------------------------------------------
1599 * Main program. Constructs the menus and runs the application.
1601 int main(int argc, char **argv)
1603 NSAutoreleasePool *pool;
1605 AppController *controller;
1608 pool = [[NSAutoreleasePool alloc] init];
1610 icon = [NSImage imageNamed:@"NSApplicationIcon"];
1611 [NSApplication sharedApplication];
1612 [NSApp setApplicationIconImage:icon];
1614 controller = [[[AppController alloc] init] autorelease];
1615 [NSApp setDelegate:controller];
1617 [NSApp setMainMenu: newmenu("Main Menu")];
1619 menu = newsubmenu([NSApp mainMenu], "Apple Menu");
1620 newitem(menu, "About Puzzles", "", NULL, @selector(about:));
1621 [menu addItem:[NSMenuItem separatorItem]];
1622 [NSApp setServicesMenu:newsubmenu(menu, "Services")];
1623 [menu addItem:[NSMenuItem separatorItem]];
1624 newitem(menu, "Hide Puzzles", "h", NSApp, @selector(hide:));
1625 newitem(menu, "Hide Others", "o-h", NSApp, @selector(hideOtherApplications:));
1626 newitem(menu, "Show All", "", NSApp, @selector(unhideAllApplications:));
1627 [menu addItem:[NSMenuItem separatorItem]];
1628 newitem(menu, "Quit", "q", NSApp, @selector(terminate:));
1629 [NSApp setAppleMenu: menu];
1631 menu = newsubmenu([NSApp mainMenu], "File");
1632 newitem(menu, "Open", "o", NULL, @selector(loadSavedGame:));
1633 newitem(menu, "Save As", "s", NULL, @selector(saveGame:));
1634 newitem(menu, "New Game", "n", NULL, @selector(newGame:));
1635 newitem(menu, "Restart Game", "r", NULL, @selector(restartGame:));
1636 newitem(menu, "Specific Game", "", NULL, @selector(specificGame:));
1637 newitem(menu, "Specific Random Seed", "", NULL,
1638 @selector(specificRandomGame:));
1639 [menu addItem:[NSMenuItem separatorItem]];
1641 NSMenu *submenu = newsubmenu(menu, "New Window");
1644 for (i = 0; i < gamecount; i++) {
1646 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1647 submenu, gamelist[i]->name, "", controller,
1648 @selector(newGameWindow:));
1649 [item setPayload:(void *)gamelist[i]];
1652 [menu addItem:[NSMenuItem separatorItem]];
1653 newitem(menu, "Close", "w", NULL, @selector(performClose:));
1655 menu = newsubmenu([NSApp mainMenu], "Edit");
1656 newitem(menu, "Undo", "z", NULL, @selector(undoMove:));
1657 newitem(menu, "Redo", "S-z", NULL, @selector(redoMove:));
1658 [menu addItem:[NSMenuItem separatorItem]];
1659 newitem(menu, "Cut", "x", NULL, @selector(cut:));
1660 newitem(menu, "Copy", "c", NULL, @selector(copy:));
1661 newitem(menu, "Paste", "v", NULL, @selector(paste:));
1662 [menu addItem:[NSMenuItem separatorItem]];
1663 newitem(menu, "Solve", "S-s", NULL, @selector(solveGame:));
1665 menu = newsubmenu([NSApp mainMenu], "Type");
1667 newitem(menu, "Custom", "", NULL, @selector(customGameType:));
1669 menu = newsubmenu([NSApp mainMenu], "Window");
1670 [NSApp setWindowsMenu: menu];
1671 newitem(menu, "Minimise Window", "m", NULL, @selector(performMiniaturize:));
1673 menu = newsubmenu([NSApp mainMenu], "Help");
1674 newitem(menu, "Puzzles Help", "?", NSApp, @selector(showHelp:));