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;
104 * The NSApplication shared instance, which I'll want to refer to from
105 * a few places here and there.
109 /* ----------------------------------------------------------------------
110 * Miscellaneous support routines that aren't part of any object or
111 * clearly defined subsystem.
114 void fatal(char *fmt, ...)
121 vsnprintf(errorbuf, lenof(errorbuf), fmt, ap);
124 alert = [NSAlert alloc];
126 * We may have come here because we ran out of memory, in which
127 * case it's entirely likely that that alloc will fail, so we
128 * should have a fallback of some sort.
131 fprintf(stderr, "fatal error (and NSAlert failed): %s\n", errorbuf);
133 alert = [[alert init] autorelease];
134 [alert addButtonWithTitle:@"Oh dear"];
135 [alert setInformativeText:[NSString stringWithUTF8String:errorbuf]];
141 void frontend_default_colour(frontend *fe, float *output)
143 /* FIXME: Is there a system default we can tap into for this? */
144 output[0] = output[1] = output[2] = 0.8F;
147 void get_random_seed(void **randseed, int *randseedsize)
149 time_t *tp = snew(time_t);
151 *randseed = (void *)tp;
152 *randseedsize = sizeof(time_t);
155 static void savefile_write(void *wctx, void *buf, int len)
157 FILE *fp = (FILE *)wctx;
158 fwrite(buf, 1, len, fp);
161 static int savefile_read(void *wctx, void *buf, int len)
163 FILE *fp = (FILE *)wctx;
166 ret = fread(buf, 1, len, fp);
171 * Since this front end does not support printing (yet), we need
172 * this stub to satisfy the reference in midend_print_puzzle().
174 void document_add_puzzle(document *doc, const game *game, game_params *par,
175 game_state *st, game_state *st2)
180 * setAppleMenu isn't listed in the NSApplication header, but an
181 * NSApp responds to it, so we're adding it here to silence
182 * warnings. (This was removed from the headers in 10.4, so we
183 * only need to include it for 10.4+.)
185 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1040
186 @interface NSApplication(NSAppleMenu)
187 - (void)setAppleMenu:(NSMenu *)menu;
191 /* ----------------------------------------------------------------------
192 * Tiny extension to NSMenuItem which carries a payload of a `void
193 * *', allowing several menu items to invoke the same message but
194 * pass different data through it.
196 @interface DataMenuItem : NSMenuItem
200 - (void)setPayload:(void *)d;
201 - (void *)getPayload;
203 @implementation DataMenuItem
204 - (void)setPayload:(void *)d
214 /* ----------------------------------------------------------------------
215 * Utility routines for constructing OS X menus.
218 NSMenu *newmenu(const char *title)
220 return [[[NSMenu allocWithZone:[NSMenu menuZone]]
221 initWithTitle:[NSString stringWithUTF8String:title]]
225 NSMenu *newsubmenu(NSMenu *parent, const char *title)
230 item = [[[NSMenuItem allocWithZone:[NSMenu menuZone]]
231 initWithTitle:[NSString stringWithUTF8String:title]
235 child = newmenu(title);
236 [item setEnabled:YES];
237 [item setSubmenu:child];
238 [parent addItem:item];
242 id initnewitem(NSMenuItem *item, NSMenu *parent, const char *title,
243 const char *key, id target, SEL action)
245 unsigned mask = NSCommandKeyMask;
247 if (key[strcspn(key, "-")]) {
248 while (*key && *key != '-') {
249 int c = tolower((unsigned char)*key);
251 mask |= NSShiftKeyMask;
252 } else if (c == 'o' || c == 'a') {
253 mask |= NSAlternateKeyMask;
261 item = [[item initWithTitle:[NSString stringWithUTF8String:title]
263 keyEquivalent:[NSString stringWithUTF8String:key]]
267 [item setKeyEquivalentModifierMask: mask];
269 [item setEnabled:YES];
270 [item setTarget:target];
271 [item setAction:action];
273 [parent addItem:item];
278 NSMenuItem *newitem(NSMenu *parent, char *title, char *key,
279 id target, SEL action)
281 return initnewitem([NSMenuItem allocWithZone:[NSMenu menuZone]],
282 parent, title, key, target, action);
285 /* ----------------------------------------------------------------------
291 @interface AboutBox : NSWindow
297 @implementation AboutBox
305 NSFont *font1 = [NSFont systemFontOfSize:0];
306 NSFont *font2 = [NSFont boldSystemFontOfSize:[font1 pointSize] * 1.1];
307 const int border = 24;
312 * Construct the controls that go in the About box.
315 iv = [[NSImageView alloc] initWithFrame:NSMakeRect(0,0,64,64)];
316 [iv setImage:[NSImage imageNamed:@"NSApplicationIcon"]];
317 views[nviews++] = iv;
319 tf = [[NSTextField alloc]
320 initWithFrame:NSMakeRect(0,0,400,1)];
322 [tf setSelectable:NO];
324 [tf setDrawsBackground:NO];
326 [tf setStringValue:@"Simon Tatham's Portable Puzzle Collection"];
328 views[nviews++] = tf;
330 tf = [[NSTextField alloc]
331 initWithFrame:NSMakeRect(0,0,400,1)];
333 [tf setSelectable:NO];
335 [tf setDrawsBackground:NO];
337 [tf setStringValue:[NSString stringWithUTF8String:ver]];
339 views[nviews++] = tf;
342 * Lay the controls out.
344 totalrect = NSMakeRect(0,0,0,0);
345 for (i = 0; i < nviews; i++) {
346 NSRect r = [views[i] frame];
347 if (totalrect.size.width < r.size.width)
348 totalrect.size.width = r.size.width;
349 totalrect.size.height += border + r.size.height;
351 totalrect.size.width += 2 * border;
352 totalrect.size.height += border;
353 y = totalrect.size.height;
354 for (i = 0; i < nviews; i++) {
355 NSRect r = [views[i] frame];
356 r.origin.x = (totalrect.size.width - r.size.width) / 2;
357 y -= border + r.size.height;
359 [views[i] setFrame:r];
362 self = [super initWithContentRect:totalrect
363 styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
364 NSClosableWindowMask)
365 backing:NSBackingStoreBuffered
368 for (i = 0; i < nviews; i++)
369 [[self contentView] addSubview:views[i]];
371 [self center]; /* :-) */
377 /* ----------------------------------------------------------------------
378 * The front end presented to midend.c.
380 * This is mostly a subclass of NSWindow. The actual `frontend'
381 * structure passed to the midend contains a variety of pointers,
382 * including that window object but also including the image we
383 * draw on, an ImageView to display it in the window, and so on.
399 @interface MyImageView : NSImageView
403 - (void)setWindow:(GameWindow *)win;
404 - (void)mouseEvent:(NSEvent *)ev button:(int)b;
405 - (void)mouseDown:(NSEvent *)ev;
406 - (void)mouseDragged:(NSEvent *)ev;
407 - (void)mouseUp:(NSEvent *)ev;
408 - (void)rightMouseDown:(NSEvent *)ev;
409 - (void)rightMouseDragged:(NSEvent *)ev;
410 - (void)rightMouseUp:(NSEvent *)ev;
411 - (void)otherMouseDown:(NSEvent *)ev;
412 - (void)otherMouseDragged:(NSEvent *)ev;
413 - (void)otherMouseUp:(NSEvent *)ev;
416 @interface GameWindow : NSWindow
421 struct timeval last_time;
426 NSView **cfg_controls;
429 struct preset_menu *preset_menu;
430 NSMenuItem **preset_menu_items;
431 int n_preset_menu_items;
433 - (id)initWithGame:(const game *)g;
435 - (void)processButton:(int)b x:(int)x y:(int)y;
436 - (void)processKey:(int)b;
437 - (void)keyDown:(NSEvent *)ev;
438 - (void)activateTimer;
439 - (void)deactivateTimer;
440 - (void)setStatusLine:(char *)text;
441 - (void)resizeForNewGameParams;
442 - (void)updateTypeMenuTick;
445 @implementation MyImageView
447 - (void)setWindow:(GameWindow *)win
452 - (void)mouseEvent:(NSEvent *)ev button:(int)b
454 NSPoint point = [self convertPoint:[ev locationInWindow] fromView:nil];
455 [ourwin processButton:b x:point.x y:point.y];
458 - (void)mouseDown:(NSEvent *)ev
460 unsigned mod = [ev modifierFlags];
461 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_BUTTON :
462 (mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
465 - (void)mouseDragged:(NSEvent *)ev
467 unsigned mod = [ev modifierFlags];
468 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_DRAG :
469 (mod & NSShiftKeyMask) ? MIDDLE_DRAG :
472 - (void)mouseUp:(NSEvent *)ev
474 unsigned mod = [ev modifierFlags];
475 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_RELEASE :
476 (mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
479 - (void)rightMouseDown:(NSEvent *)ev
481 unsigned mod = [ev modifierFlags];
482 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
485 - (void)rightMouseDragged:(NSEvent *)ev
487 unsigned mod = [ev modifierFlags];
488 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_DRAG :
491 - (void)rightMouseUp:(NSEvent *)ev
493 unsigned mod = [ev modifierFlags];
494 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
497 - (void)otherMouseDown:(NSEvent *)ev
499 [self mouseEvent:ev button:MIDDLE_BUTTON];
501 - (void)otherMouseDragged:(NSEvent *)ev
503 [self mouseEvent:ev button:MIDDLE_DRAG];
505 - (void)otherMouseUp:(NSEvent *)ev
507 [self mouseEvent:ev button:MIDDLE_RELEASE];
511 @implementation GameWindow
512 - (void)setupContentView
518 frame = [status frame];
519 frame.origin.y = frame.size.height;
525 midend_size(me, &w, &h, FALSE);
526 frame.size.width = w;
527 frame.size.height = h;
531 fe.image = [[NSImage alloc] initWithSize:frame.size];
532 fe.view = [[MyImageView alloc] initWithFrame:frame];
533 [fe.view setImage:fe.image];
534 [fe.view setWindow:self];
538 [[self contentView] addSubview:fe.view];
540 - (id)initWithGame:(const game *)g
542 NSRect rect = { {0,0}, {0,0} }, rect2;
547 preset_menu_items = NULL;
551 me = midend_new(&fe, ourgame, &osx_drawing, &fe);
553 * If we ever need to open a fresh window using a provided game
554 * ID, I think the right thing is to move most of this method
555 * into a new initWithGame:gameID: method, and have
556 * initWithGame: simply call that one and pass it NULL.
560 midend_size(me, &w, &h, FALSE);
562 rect.size.height = h;
567 * Create the status bar, which will just be an NSTextField.
569 if (midend_wants_statusbar(me)) {
570 status = [[NSTextField alloc] initWithFrame:NSMakeRect(0,0,100,50)];
571 [status setEditable:NO];
572 [status setSelectable:NO];
573 [status setBordered:YES];
574 [status setBezeled:YES];
575 [status setBezelStyle:NSTextFieldSquareBezel];
576 [status setDrawsBackground:YES];
577 [[status cell] setTitle:@DEFAULT_STATUSBAR_TEXT];
579 rect2 = [status frame];
580 rect.size.height += rect2.size.height;
581 rect2.size.width = rect.size.width;
582 rect2.origin.x = rect2.origin.y = 0;
583 [status setFrame:rect2];
587 self = [super initWithContentRect:rect
588 styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
589 NSClosableWindowMask)
590 backing:NSBackingStoreBuffered
592 [self setTitle:[NSString stringWithUTF8String:ourgame->name]];
598 colours = midend_colours(me, &ncolours);
599 fe.ncolours = ncolours;
600 fe.colours = snewn(ncolours, NSColor *);
602 for (i = 0; i < ncolours; i++) {
603 fe.colours[i] = [[NSColor colorWithDeviceRed:colours[i*3]
604 green:colours[i*3+1] blue:colours[i*3+2]
609 [self setupContentView];
611 [[self contentView] addSubview:status];
612 [self setIgnoresMouseEvents:NO];
614 [self center]; /* :-) */
622 for (i = 0; i < fe.ncolours; i++) {
623 [fe.colours[i] release];
626 sfree(preset_menu_items);
631 - (void)processButton:(int)b x:(int)x y:(int)y
633 if (!midend_process_key(me, x, fe.h - 1 - y, b))
637 - (void)processKey:(int)b
639 if (!midend_process_key(me, -1, -1, b))
643 - (void)keyDown:(NSEvent *)ev
645 NSString *s = [ev characters];
646 int i, n = [s length];
648 for (i = 0; i < n; i++) {
649 int c = [s characterAtIndex:i];
652 * ASCII gets passed straight to midend_process_key.
653 * Anything above that has to be translated to our own
654 * function key codes.
659 case NSUpArrowFunctionKey:
663 case NSDownArrowFunctionKey:
667 case NSLeftArrowFunctionKey:
671 case NSRightArrowFunctionKey:
680 if ([ev modifierFlags] & NSShiftKeyMask)
682 if ([ev modifierFlags] & NSControlKeyMask)
687 if (c >= '0' && c <= '9' && ([ev modifierFlags] & NSNumericPadKeyMask))
694 - (void)activateTimer
699 timer = [NSTimer scheduledTimerWithTimeInterval:0.02
700 target:self selector:@selector(timerTick:)
701 userInfo:nil repeats:YES];
702 gettimeofday(&last_time, NULL);
705 - (void)deactivateTimer
714 - (void)timerTick:(id)sender
718 gettimeofday(&now, NULL);
719 elapsed = ((now.tv_usec - last_time.tv_usec) * 0.000001F +
720 (now.tv_sec - last_time.tv_sec));
721 midend_timer(me, elapsed);
725 - (void)showError:(char *)message
729 alert = [[[NSAlert alloc] init] autorelease];
730 [alert addButtonWithTitle:@"Bah"];
731 [alert setInformativeText:[NSString stringWithUTF8String:message]];
732 [alert beginSheetModalForWindow:self modalDelegate:nil
733 didEndSelector:NULL contextInfo:nil];
736 - (void)newGame:(id)sender
738 [self processKey:'n'];
740 - (void)restartGame:(id)sender
742 midend_restart_game(me);
744 - (void)saveGame:(id)sender
746 NSSavePanel *sp = [NSSavePanel savePanel];
748 if ([sp runModal] == NSFileHandlingPanelOKButton) {
749 const char *name = [[sp filename] UTF8String];
751 FILE *fp = fopen(name, "w");
754 [self showError:"Unable to open save file"];
758 midend_serialise(me, savefile_write, fp);
763 - (void)loadSavedGame:(id)sender
765 NSOpenPanel *op = [NSOpenPanel openPanel];
767 [op setAllowsMultipleSelection:NO];
769 if ([op runModalForTypes:nil] == NSOKButton) {
773 * [[[op filenames] objectAtIndex:0] cString]
775 * but the plain cString method became deprecated and Xcode 7
776 * started complaining about it. Since OS X 10.9 we can
777 * apparently use the more modern API
779 * [[[op URLs] objectAtIndex:0] fileSystemRepresentation]
781 * but the alternative below still compiles with Xcode 7 and
782 * is a bit more backwards compatible, so I'll try it for the
785 const char *name = [[[op filenames] objectAtIndex:0]
786 cStringUsingEncoding:
787 [NSString defaultCStringEncoding]];
790 FILE *fp = fopen(name, "r");
793 [self showError:"Unable to open saved game file"];
797 err = midend_deserialise(me, savefile_read, fp);
802 [self showError:err];
806 [self resizeForNewGameParams];
807 [self updateTypeMenuTick];
810 - (void)undoMove:(id)sender
812 [self processKey:'u'];
814 - (void)redoMove:(id)sender
816 [self processKey:'r'&0x1F];
819 - (void)copy:(id)sender
823 if ((text = midend_text_format(me)) != NULL) {
824 NSPasteboard *pb = [NSPasteboard generalPasteboard];
825 NSArray *a = [NSArray arrayWithObject:NSStringPboardType];
826 [pb declareTypes:a owner:nil];
827 [pb setString:[NSString stringWithUTF8String:text]
828 forType:NSStringPboardType];
833 - (void)solveGame:(id)sender
837 msg = midend_solve(me);
840 [self showError:msg];
843 - (BOOL)validateMenuItem:(NSMenuItem *)item
845 if ([item action] == @selector(copy:))
846 return (ourgame->can_format_as_text_ever &&
847 midend_can_format_as_text_now(me) ? YES : NO);
848 else if ([item action] == @selector(solveGame:))
849 return (ourgame->can_solve ? YES : NO);
851 return [super validateMenuItem:item];
854 - (void)clearTypeMenu
858 while ([typemenu numberOfItems] > 1)
859 [typemenu removeItemAtIndex:0];
860 [[typemenu itemAtIndex:0] setState:NSOffState];
862 for (i = 0; i < n_preset_menu_items; i++)
863 preset_menu_items[i] = NULL;
866 - (void)updateTypeMenuTick
870 n = midend_which_preset(me);
872 for (i = 0; i < n_preset_menu_items; i++)
873 if (preset_menu_items[i])
874 [preset_menu_items[i] setState:(i == n ? NSOnState : NSOffState)];
877 * The Custom menu item is always right at the bottom of the
880 [[typemenu itemAtIndex:[typemenu numberOfItems]-1]
881 setState:(n < 0 ? NSOnState : NSOffState)];
884 - (void)populateTypeMenu:(NSMenu *)nsmenu from:(struct preset_menu *)menu
889 * We process the entries in reverse order so that (in the
890 * top-level Type menu at least) we don't disturb the 'Custom'
891 * item which remains fixed even when we change back and forth
892 * between puzzle type windows.
894 for (i = menu->n_entries; i-- > 0 ;) {
895 struct preset_menu_entry *entry = &menu->entries[i];
900 ditem = [[[DataMenuItem alloc]
901 initWithTitle:[NSString stringWithUTF8String:
903 action:NULL keyEquivalent:@""]
906 [ditem setTarget:self];
907 [ditem setAction:@selector(presetGame:)];
908 [ditem setPayload:entry->params];
910 preset_menu_items[entry->id] = ditem;
916 item = [[[NSMenuItem alloc]
917 initWithTitle:[NSString stringWithUTF8String:
919 action:NULL keyEquivalent:@""]
921 nssubmenu = newmenu(entry->title);
922 [item setSubmenu:nssubmenu];
924 [self populateTypeMenu:nssubmenu from:entry->submenu];
927 [item setEnabled:YES];
928 [nsmenu insertItem:item atIndex:0];
932 - (void)becomeKeyWindow
934 [self clearTypeMenu];
936 [super becomeKeyWindow];
940 preset_menu = midend_get_presets(me, &n_preset_menu_items);
941 preset_menu_items = snewn(n_preset_menu_items, NSMenuItem *);
942 for (i = 0; i < n_preset_menu_items; i++)
943 preset_menu_items[i] = NULL;
946 if (preset_menu->n_entries > 0) {
947 [typemenu insertItem:[NSMenuItem separatorItem] atIndex:0];
948 [self populateTypeMenu:typemenu from:preset_menu];
951 [self updateTypeMenuTick];
954 - (void)resignKeyWindow
956 [self clearTypeMenu];
957 [super resignKeyWindow];
962 [self clearTypeMenu];
966 - (void)resizeForNewGameParams
972 midend_size(me, &w, &h, FALSE);
979 NSRect frame = [status frame];
980 size.height += frame.size.height;
981 frame.size.width = size.width;
982 [status setFrame:frame];
986 NSDisableScreenUpdates();
988 [self setContentSize:size];
989 [self setupContentView];
991 NSEnableScreenUpdates();
995 - (void)presetGame:(id)sender
997 game_params *params = [sender getPayload];
999 midend_set_params(me, params);
1000 midend_new_game(me);
1002 [self resizeForNewGameParams];
1003 [self updateTypeMenuTick];
1006 - (void)startConfigureSheet:(int)which
1008 NSButton *ok, *cancel;
1009 int actw, acth, leftw, rightw, totalw, h, thish, y;
1011 NSRect rect, tmprect;
1012 const int SPACING = 16;
1015 int cfg_controlsize;
1020 assert(sheet == NULL);
1023 * Every control we create here is going to have this size
1024 * until we tell it to calculate a better one.
1026 tmprect = NSMakeRect(0, 0, 100, 50);
1029 * Set up OK and Cancel buttons. (Actually, MacOS doesn't seem
1030 * to be fond of generic OK and Cancel wording, so I'm going to
1031 * rename them to something nicer.)
1035 cancel = [[NSButton alloc] initWithFrame:tmprect];
1036 [cancel setBezelStyle:NSRoundedBezelStyle];
1037 [cancel setTitle:@"Abandon"];
1038 [cancel setTarget:self];
1039 [cancel setKeyEquivalent:@"\033"];
1040 [cancel setAction:@selector(sheetCancelButton:)];
1042 rect = [cancel frame];
1043 if (actw < rect.size.width) actw = rect.size.width;
1044 if (acth < rect.size.height) acth = rect.size.height;
1046 ok = [[NSButton alloc] initWithFrame:tmprect];
1047 [ok setBezelStyle:NSRoundedBezelStyle];
1048 [ok setTitle:@"Accept"];
1049 [ok setTarget:self];
1050 [ok setKeyEquivalent:@"\r"];
1051 [ok setAction:@selector(sheetOKButton:)];
1054 if (actw < rect.size.width) actw = rect.size.width;
1055 if (acth < rect.size.height) acth = rect.size.height;
1057 totalw = SPACING + 2 * actw;
1058 h = 2 * SPACING + acth;
1061 * Now fetch the midend config data and go through it creating
1064 cfg = midend_get_config(me, which, &title);
1065 sfree(title); /* FIXME: should we use this somehow? */
1068 cfg_ncontrols = cfg_controlsize = 0;
1069 cfg_controls = NULL;
1071 for (i = cfg; i->type != C_END; i++) {
1072 if (cfg_controlsize < cfg_ncontrols + 5) {
1073 cfg_controlsize = cfg_ncontrols + 32;
1074 cfg_controls = sresize(cfg_controls, cfg_controlsize, NSView *);
1082 * Two NSTextFields, one being a label and the other
1083 * being an edit box.
1086 tf = [[NSTextField alloc] initWithFrame:tmprect];
1087 [tf setEditable:NO];
1088 [tf setSelectable:NO];
1089 [tf setBordered:NO];
1090 [tf setDrawsBackground:NO];
1091 [[tf cell] setTitle:[NSString stringWithUTF8String:i->name]];
1094 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1095 if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
1096 cfg_controls[cfg_ncontrols++] = tf;
1098 tf = [[NSTextField alloc] initWithFrame:tmprect];
1099 [tf setEditable:YES];
1100 [tf setSelectable:YES];
1101 [tf setBordered:YES];
1102 [[tf cell] setTitle:[NSString stringWithUTF8String:i->sval]];
1106 * We impose a minimum and maximum width on editable
1107 * NSTextFields. If we allow them to size themselves to
1108 * the contents of the text within them, then they will
1109 * look very silly if that text is only one or two
1110 * characters, and equally silly if it's an absolutely
1111 * enormous Rectangles or Pattern game ID!
1113 if (rect.size.width < 75) rect.size.width = 75;
1114 if (rect.size.width > 400) rect.size.width = 400;
1116 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1117 if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
1118 cfg_controls[cfg_ncontrols++] = tf;
1123 * A checkbox is an NSButton with a type of
1126 b = [[NSButton alloc] initWithFrame:tmprect];
1127 [b setBezelStyle:NSRoundedBezelStyle];
1128 [b setButtonType:NSSwitchButton];
1129 [b setTitle:[NSString stringWithUTF8String:i->name]];
1131 [b setState:(i->ival ? NSOnState : NSOffState)];
1133 if (totalw < rect.size.width + 1) totalw = rect.size.width + 1;
1134 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1135 cfg_controls[cfg_ncontrols++] = b;
1140 * A pop-up menu control is an NSPopUpButton, which
1141 * takes an embedded NSMenu. We also need an
1142 * NSTextField to act as a label.
1145 tf = [[NSTextField alloc] initWithFrame:tmprect];
1146 [tf setEditable:NO];
1147 [tf setSelectable:NO];
1148 [tf setBordered:NO];
1149 [tf setDrawsBackground:NO];
1150 [[tf cell] setTitle:[NSString stringWithUTF8String:i->name]];
1153 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1154 if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
1155 cfg_controls[cfg_ncontrols++] = tf;
1157 pb = [[NSPopUpButton alloc] initWithFrame:tmprect pullsDown:NO];
1158 [pb setBezelStyle:NSRoundedBezelStyle];
1168 while (*p && *p != c) p++;
1170 copy = snewn((p-q) + 1, char);
1171 memcpy(copy, q, p-q);
1173 [pb addItemWithTitle:[NSString stringWithUTF8String:copy]];
1179 [pb selectItemAtIndex:i->ival];
1183 if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
1184 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1185 cfg_controls[cfg_ncontrols++] = pb;
1189 h += SPACING + thish;
1192 if (totalw < leftw + SPACING + rightw)
1193 totalw = leftw + SPACING + rightw;
1194 if (totalw > leftw + SPACING + rightw) {
1195 int excess = totalw - (leftw + SPACING + rightw);
1196 int leftexcess = leftw * excess / (leftw + rightw);
1197 int rightexcess = excess - leftexcess;
1198 leftw += leftexcess;
1199 rightw += rightexcess;
1203 * Now go through the list again, setting the final position
1208 for (i = cfg; i->type != C_END; i++) {
1215 * These two are treated identically, since both expect
1216 * a control on the left and another on the right.
1218 rect = [cfg_controls[k] frame];
1219 if (thish < rect.size.height + 1)
1220 thish = rect.size.height + 1;
1221 rect = [cfg_controls[k+1] frame];
1222 if (thish < rect.size.height + 1)
1223 thish = rect.size.height + 1;
1224 rect = [cfg_controls[k] frame];
1225 rect.origin.y = y - thish/2 - rect.size.height/2;
1226 rect.origin.x = SPACING;
1227 rect.size.width = leftw;
1228 [cfg_controls[k] setFrame:rect];
1229 rect = [cfg_controls[k+1] frame];
1230 rect.origin.y = y - thish/2 - rect.size.height/2;
1231 rect.origin.x = 2 * SPACING + leftw;
1232 rect.size.width = rightw;
1233 [cfg_controls[k+1] setFrame:rect];
1238 rect = [cfg_controls[k] frame];
1239 if (thish < rect.size.height + 1)
1240 thish = rect.size.height + 1;
1241 rect.origin.y = y - thish/2 - rect.size.height/2;
1242 rect.origin.x = SPACING;
1243 rect.size.width = totalw;
1244 [cfg_controls[k] setFrame:rect];
1251 assert(k == cfg_ncontrols);
1253 [cancel setFrame:NSMakeRect(SPACING+totalw/4-actw/2, SPACING, actw, acth)];
1254 [ok setFrame:NSMakeRect(SPACING+3*totalw/4-actw/2, SPACING, actw, acth)];
1256 sheet = [[NSWindow alloc]
1257 initWithContentRect:NSMakeRect(0,0,totalw + 2*SPACING,h)
1258 styleMask:NSTitledWindowMask | NSClosableWindowMask
1259 backing:NSBackingStoreBuffered
1262 [[sheet contentView] addSubview:cancel];
1263 [[sheet contentView] addSubview:ok];
1265 for (k = 0; k < cfg_ncontrols; k++)
1266 [[sheet contentView] addSubview:cfg_controls[k]];
1268 [app beginSheet:sheet modalForWindow:self
1269 modalDelegate:nil didEndSelector:NULL contextInfo:nil];
1272 - (void)specificGame:(id)sender
1274 [self startConfigureSheet:CFG_DESC];
1277 - (void)specificRandomGame:(id)sender
1279 [self startConfigureSheet:CFG_SEED];
1282 - (void)customGameType:(id)sender
1284 [self startConfigureSheet:CFG_SETTINGS];
1287 - (void)sheetEndWithStatus:(BOOL)update
1289 assert(sheet != NULL);
1290 [app endSheet:sheet];
1291 [sheet orderOut:self];
1299 for (i = cfg; i->type != C_END; i++) {
1303 i->sval = dupstr([[[(id)cfg_controls[k+1] cell]
1304 title] UTF8String]);
1308 i->ival = [(id)cfg_controls[k] state] == NSOnState;
1312 i->ival = [(id)cfg_controls[k+1] indexOfSelectedItem];
1318 error = midend_set_config(me, cfg_which, cfg);
1320 NSAlert *alert = [[[NSAlert alloc] init] autorelease];
1321 [alert addButtonWithTitle:@"Bah"];
1322 [alert setInformativeText:[NSString stringWithUTF8String:error]];
1323 [alert beginSheetModalForWindow:self modalDelegate:nil
1324 didEndSelector:NULL contextInfo:nil];
1326 midend_new_game(me);
1327 [self resizeForNewGameParams];
1328 [self updateTypeMenuTick];
1331 sfree(cfg_controls);
1332 cfg_controls = NULL;
1334 - (void)sheetOKButton:(id)sender
1336 [self sheetEndWithStatus:YES];
1338 - (void)sheetCancelButton:(id)sender
1340 [self sheetEndWithStatus:NO];
1343 - (void)setStatusLine:(char *)text
1345 [[status cell] setTitle:[NSString stringWithUTF8String:text]];
1351 * Drawing routines called by the midend.
1353 static void osx_draw_polygon(void *handle, int *coords, int npoints,
1354 int fillcolour, int outlinecolour)
1356 frontend *fe = (frontend *)handle;
1357 NSBezierPath *path = [NSBezierPath bezierPath];
1360 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1362 for (i = 0; i < npoints; i++) {
1363 NSPoint p = { coords[i*2] + 0.5, fe->h - coords[i*2+1] - 0.5 };
1365 [path moveToPoint:p];
1367 [path lineToPoint:p];
1372 if (fillcolour >= 0) {
1373 assert(fillcolour >= 0 && fillcolour < fe->ncolours);
1374 [fe->colours[fillcolour] set];
1378 assert(outlinecolour >= 0 && outlinecolour < fe->ncolours);
1379 [fe->colours[outlinecolour] set];
1382 static void osx_draw_circle(void *handle, int cx, int cy, int radius,
1383 int fillcolour, int outlinecolour)
1385 frontend *fe = (frontend *)handle;
1386 NSBezierPath *path = [NSBezierPath bezierPath];
1388 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1390 [path appendBezierPathWithArcWithCenter:NSMakePoint(cx+0.5, fe->h-cy-0.5)
1391 radius:radius startAngle:0.0 endAngle:360.0];
1395 if (fillcolour >= 0) {
1396 assert(fillcolour >= 0 && fillcolour < fe->ncolours);
1397 [fe->colours[fillcolour] set];
1401 assert(outlinecolour >= 0 && outlinecolour < fe->ncolours);
1402 [fe->colours[outlinecolour] set];
1405 static void osx_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
1407 frontend *fe = (frontend *)handle;
1408 NSBezierPath *path = [NSBezierPath bezierPath];
1409 NSPoint p1 = { x1 + 0.5, fe->h - y1 - 0.5 };
1410 NSPoint p2 = { x2 + 0.5, fe->h - y2 - 0.5 };
1412 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1414 assert(colour >= 0 && colour < fe->ncolours);
1415 [fe->colours[colour] set];
1417 [path moveToPoint:p1];
1418 [path lineToPoint:p2];
1420 NSRectFill(NSMakeRect(x1, fe->h-y1-1, 1, 1));
1421 NSRectFill(NSMakeRect(x2, fe->h-y2-1, 1, 1));
1424 static void osx_draw_thick_line(
1425 void *handle, float thickness,
1430 frontend *fe = (frontend *)handle;
1431 NSBezierPath *path = [NSBezierPath bezierPath];
1433 assert(colour >= 0 && colour < fe->ncolours);
1434 [fe->colours[colour] set];
1435 [[NSGraphicsContext currentContext] setShouldAntialias: YES];
1436 [path setLineWidth: thickness];
1437 [path setLineCapStyle: NSButtLineCapStyle];
1438 [path moveToPoint: NSMakePoint(x1, fe->h-y1)];
1439 [path lineToPoint: NSMakePoint(x2, fe->h-y2)];
1443 static void osx_draw_rect(void *handle, int x, int y, int w, int h, int colour)
1445 frontend *fe = (frontend *)handle;
1446 NSRect r = { {x, fe->h - y - h}, {w,h} };
1448 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1450 assert(colour >= 0 && colour < fe->ncolours);
1451 [fe->colours[colour] set];
1455 static void osx_draw_text(void *handle, int x, int y, int fonttype,
1456 int fontsize, int align, int colour, char *text)
1458 frontend *fe = (frontend *)handle;
1459 NSString *string = [NSString stringWithUTF8String:text];
1465 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1467 assert(colour >= 0 && colour < fe->ncolours);
1469 if (fonttype == FONT_FIXED)
1470 font = [NSFont userFixedPitchFontOfSize:fontsize];
1472 font = [NSFont userFontOfSize:fontsize];
1474 attr = [NSDictionary dictionaryWithObjectsAndKeys:
1475 fe->colours[colour], NSForegroundColorAttributeName,
1476 font, NSFontAttributeName, nil];
1479 point.y = fe->h - y;
1481 size = [string sizeWithAttributes:attr];
1482 if (align & ALIGN_HRIGHT)
1483 point.x -= size.width;
1484 else if (align & ALIGN_HCENTRE)
1485 point.x -= size.width / 2;
1486 if (align & ALIGN_VCENTRE)
1487 point.y -= size.height / 2;
1489 [string drawAtPoint:point withAttributes:attr];
1491 static char *osx_text_fallback(void *handle, const char *const *strings,
1495 * We assume OS X can cope with any UTF-8 likely to be emitted
1498 return dupstr(strings[0]);
1505 static blitter *osx_blitter_new(void *handle, int w, int h)
1507 blitter *bl = snew(blitter);
1511 bl->img = [[NSImage alloc] initWithSize:NSMakeSize(w, h)];
1514 static void osx_blitter_free(void *handle, blitter *bl)
1519 static void osx_blitter_save(void *handle, blitter *bl, int x, int y)
1521 frontend *fe = (frontend *)handle;
1522 int sx, sy, sX, sY, dx, dy, dX, dY;
1523 [fe->image unlockFocus];
1524 [bl->img lockFocus];
1527 * Find the intersection of the source and destination rectangles,
1528 * so as to avoid trying to copy from outside the source image,
1529 * which GNUstep dislikes.
1531 * Lower-case x,y coordinates are bottom left box corners;
1532 * upper-case X,Y are the top right.
1534 sx = x; sy = fe->h - y - bl->h;
1535 sX = sx + bl->w; sY = sy + bl->h;
1537 dX = bl->w; dY = bl->h;
1555 [fe->image drawInRect:NSMakeRect(dx, dy, dX-dx, dY-dy)
1556 fromRect:NSMakeRect(sx, sy, sX-sx, sY-sy)
1557 operation:NSCompositeCopy fraction:1.0];
1558 [bl->img unlockFocus];
1559 [fe->image lockFocus];
1563 static void osx_blitter_load(void *handle, blitter *bl, int x, int y)
1565 frontend *fe = (frontend *)handle;
1566 if (x == BLITTER_FROMSAVED && y == BLITTER_FROMSAVED) {
1570 [bl->img drawInRect:NSMakeRect(x, fe->h - y - bl->h, bl->w, bl->h)
1571 fromRect:NSMakeRect(0, 0, bl->w, bl->h)
1572 operation:NSCompositeCopy fraction:1.0];
1574 static void osx_draw_update(void *handle, int x, int y, int w, int h)
1576 frontend *fe = (frontend *)handle;
1577 [fe->view setNeedsDisplayInRect:NSMakeRect(x, fe->h - y - h, w, h)];
1579 static void osx_clip(void *handle, int x, int y, int w, int h)
1581 frontend *fe = (frontend *)handle;
1582 NSRect r = { {x, fe->h - y - h}, {w, h} };
1585 [[NSGraphicsContext currentContext] saveGraphicsState];
1586 [NSBezierPath clipRect:r];
1589 static void osx_unclip(void *handle)
1591 frontend *fe = (frontend *)handle;
1593 [[NSGraphicsContext currentContext] restoreGraphicsState];
1594 fe->clipped = FALSE;
1596 static void osx_start_draw(void *handle)
1598 frontend *fe = (frontend *)handle;
1599 [fe->image lockFocus];
1600 fe->clipped = FALSE;
1602 static void osx_end_draw(void *handle)
1604 frontend *fe = (frontend *)handle;
1605 [fe->image unlockFocus];
1607 static void osx_status_bar(void *handle, char *text)
1609 frontend *fe = (frontend *)handle;
1610 [fe->window setStatusLine:text];
1613 const struct drawing_api osx_drawing = {
1629 NULL, NULL, NULL, NULL, NULL, NULL, /* {begin,end}_{doc,page,puzzle} */
1630 NULL, NULL, /* line_width, line_dotted */
1632 osx_draw_thick_line,
1635 void deactivate_timer(frontend *fe)
1637 [fe->window deactivateTimer];
1639 void activate_timer(frontend *fe)
1641 [fe->window activateTimer];
1644 /* ----------------------------------------------------------------------
1645 * AppController: the object which receives the messages from all
1646 * menu selections that aren't standard OS X functions.
1648 @interface AppController : NSObject <NSApplicationDelegate>
1651 - (void)newGameWindow:(id)sender;
1652 - (void)about:(id)sender;
1655 @implementation AppController
1657 - (void)newGameWindow:(id)sender
1659 const game *g = [sender getPayload];
1662 win = [[GameWindow alloc] initWithGame:g];
1663 [win makeKeyAndOrderFront:self];
1666 - (void)about:(id)sender
1670 win = [[AboutBox alloc] init];
1671 [win makeKeyAndOrderFront:self];
1674 - (NSMenu *)applicationDockMenu:(NSApplication *)sender
1676 NSMenu *menu = newmenu("Dock Menu");
1680 for (i = 0; i < gamecount; i++) {
1682 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1683 menu, gamelist[i]->name, "", self,
1684 @selector(newGameWindow:));
1685 [item setPayload:(void *)gamelist[i]];
1693 /* ----------------------------------------------------------------------
1694 * Main program. Constructs the menus and runs the application.
1696 int main(int argc, char **argv)
1698 NSAutoreleasePool *pool;
1700 AppController *controller;
1703 pool = [[NSAutoreleasePool alloc] init];
1705 icon = [NSImage imageNamed:@"NSApplicationIcon"];
1706 app = [NSApplication sharedApplication];
1707 [app setApplicationIconImage:icon];
1709 controller = [[[AppController alloc] init] autorelease];
1710 [app setDelegate:controller];
1712 [app setMainMenu: newmenu("Main Menu")];
1714 menu = newsubmenu([app mainMenu], "Apple Menu");
1715 newitem(menu, "About Puzzles", "", NULL, @selector(about:));
1716 [menu addItem:[NSMenuItem separatorItem]];
1717 [app setServicesMenu:newsubmenu(menu, "Services")];
1718 [menu addItem:[NSMenuItem separatorItem]];
1719 newitem(menu, "Hide Puzzles", "h", app, @selector(hide:));
1720 newitem(menu, "Hide Others", "o-h", app, @selector(hideOtherApplications:));
1721 newitem(menu, "Show All", "", app, @selector(unhideAllApplications:));
1722 [menu addItem:[NSMenuItem separatorItem]];
1723 newitem(menu, "Quit", "q", app, @selector(terminate:));
1724 [app setAppleMenu: menu];
1726 menu = newsubmenu([app mainMenu], "File");
1727 newitem(menu, "Open", "o", NULL, @selector(loadSavedGame:));
1728 newitem(menu, "Save As", "s", NULL, @selector(saveGame:));
1729 newitem(menu, "New Game", "n", NULL, @selector(newGame:));
1730 newitem(menu, "Restart Game", "r", NULL, @selector(restartGame:));
1731 newitem(menu, "Specific Game", "", NULL, @selector(specificGame:));
1732 newitem(menu, "Specific Random Seed", "", NULL,
1733 @selector(specificRandomGame:));
1734 [menu addItem:[NSMenuItem separatorItem]];
1736 NSMenu *submenu = newsubmenu(menu, "New Window");
1739 for (i = 0; i < gamecount; i++) {
1741 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1742 submenu, gamelist[i]->name, "", controller,
1743 @selector(newGameWindow:));
1744 [item setPayload:(void *)gamelist[i]];
1747 [menu addItem:[NSMenuItem separatorItem]];
1748 newitem(menu, "Close", "w", NULL, @selector(performClose:));
1750 menu = newsubmenu([app mainMenu], "Edit");
1751 newitem(menu, "Undo", "z", NULL, @selector(undoMove:));
1752 newitem(menu, "Redo", "S-z", NULL, @selector(redoMove:));
1753 [menu addItem:[NSMenuItem separatorItem]];
1754 newitem(menu, "Cut", "x", NULL, @selector(cut:));
1755 newitem(menu, "Copy", "c", NULL, @selector(copy:));
1756 newitem(menu, "Paste", "v", NULL, @selector(paste:));
1757 [menu addItem:[NSMenuItem separatorItem]];
1758 newitem(menu, "Solve", "S-s", NULL, @selector(solveGame:));
1760 menu = newsubmenu([app mainMenu], "Type");
1762 newitem(menu, "Custom", "", NULL, @selector(customGameType:));
1764 menu = newsubmenu([app mainMenu], "Window");
1765 [app setWindowsMenu: menu];
1766 newitem(menu, "Minimise Window", "m", NULL, @selector(performMiniaturize:));
1768 menu = newsubmenu([app mainMenu], "Help");
1769 newitem(menu, "Puzzles Help", "?", app, @selector(showHelp:));