Status bar support.
[sgt/puzzles] / osx.m
CommitLineData
9494d866 1/*
2 * Mac OS X / Cocoa front end to puzzles.
00461804 3 *
a5102461 4 * Actually unfinished things left to do:
00461804 5 *
a5102461 6 * - proper fatal errors.
7 *
8 * - Find out how to do help, and do some. We have a help file; at
9 * _worst_ this should involve a new Halibut back end, but I
10 * think help is HTML round here anyway so perhaps we can work
11 * with what we already have.
12 *
13 * - Can we arrange for a pop-up menu from the Dock icon which
14 * launches specific games, perhaps?
15 * + apparently we can; see the NSApplication method
16 * `applicationDockMenu:'. Good good. Do so.
17 *
18 * - Why are the right and bottom edges of the Pattern grid one
19 * pixel thinner than they should be?
20 *
21 * Mac interface issues that possibly could be done better:
22 *
23 * - is there a better approach to frontend_default_colour?
24 *
25 * - do we need any more options in the Window menu?
00461804 26 *
9494d866 27 * - not sure what I should be doing about default window
28 * placement. Centring new windows is a bit feeble, but what's
29 * better? Is there a standard way to tell the OS "here's the
30 * _size_ of window I want, now use your best judgment about the
31 * initial position"?
00461804 32 *
9494d866 33 * - a brief frob of the Mac numeric keypad suggests that it
34 * generates numbers no matter what you do. I wonder if I should
35 * try to figure out a way of detecting keypad codes so I can
6d634196 36 * implement UP_LEFT and friends. Alternatively, perhaps I
37 * should simply assign the number keys to UP_LEFT et al?
38 * They're not in use for anything else right now.
00461804 39 *
00461804 40 * - see if we can do anything to one-button-ise the multi-button
41 * dependent puzzle UIs:
42 * - Pattern is a _little_ unwieldy but not too bad (since
43 * generally you never need the middle button unless you've
44 * made a mistake, so it's just click versus command-click).
45 * - Net is utterly vile; having normal click be one rotate and
46 * command-click be the other introduces a horrid asymmetry,
47 * and yet requiring a shift key for _each_ click would be
48 * even worse because rotation feels as if it ought to be the
49 * default action. I fear this is why the Flash Net had the
50 * UI it did...
51 *
e1107f8b 52 * - Should we _return_ to a game configuration sheet once an
53 * error is reported by midend_set_config, to allow the user to
54 * correct the one faulty input and keep the other five OK ones?
55 * The Apple `one sheet at a time' restriction would require me
56 * to do this by closing the config sheet, opening the alert
57 * sheet, and then reopening the config sheet when the alert is
58 * closed; and the human interface types, who presumably
59 * invented the one-sheet-at-a-time rule for good reasons, might
60 * look with disfavour on me trying to get round them to fake a
61 * nested sheet. On the other hand I think there are good
62 * practical reasons for wanting it that way. Uncertain.
63 *
7e04cb48 64 * Grotty implementation details that could probably be improved:
65 *
66 * - I am _utterly_ unconvinced that NSImageView was the right way
67 * to go about having a window with a reliable backing store! It
68 * just doesn't feel right; NSImageView is a _control_. Is there
69 * a simpler way?
70 *
71 * - Resizing is currently very bad; rather than bother to work
72 * out how to resize the NSImageView, I just splatter and
73 * recreate it.
9494d866 74 */
75
76#include <ctype.h>
77#include <sys/time.h>
78#import <Cocoa/Cocoa.h>
79#include "puzzles.h"
80
81void fatal(char *fmt, ...)
82{
83 /* FIXME: This will do for testing, but should be GUI-ish instead. */
84 va_list ap;
85
86 fprintf(stderr, "fatal error: ");
87
88 va_start(ap, fmt);
89 vfprintf(stderr, fmt, ap);
90 va_end(ap);
91
92 fprintf(stderr, "\n");
93 exit(1);
94}
95
96void frontend_default_colour(frontend *fe, float *output)
97{
98 /* FIXME */
99 output[0] = output[1] = output[2] = 0.8F;
100}
9494d866 101
102void get_random_seed(void **randseed, int *randseedsize)
103{
104 time_t *tp = snew(time_t);
105 time(tp);
106 *randseed = (void *)tp;
107 *randseedsize = sizeof(time_t);
108}
109
110/* ----------------------------------------------------------------------
7e04cb48 111 * Global variables.
112 */
113
114/*
115 * The `Type' menu. We frob this dynamically to allow the user to
116 * choose a preset set of settings from the current game.
117 */
118NSMenu *typemenu;
119
120/* ----------------------------------------------------------------------
121 * Tiny extension to NSMenuItem which carries a payload of a `void
122 * *', allowing several menu items to invoke the same message but
123 * pass different data through it.
124 */
125@interface DataMenuItem : NSMenuItem
126{
127 void *payload;
7e04cb48 128}
129- (void)setPayload:(void *)d;
7e04cb48 130- (void *)getPayload;
131@end
132@implementation DataMenuItem
7e04cb48 133- (void)setPayload:(void *)d
134{
135 payload = d;
136}
7e04cb48 137- (void *)getPayload
138{
139 return payload;
140}
7e04cb48 141@end
142
143/* ----------------------------------------------------------------------
e1107f8b 144 * Utility routines for constructing OS X menus.
145 */
146
147NSMenu *newmenu(const char *title)
148{
149 return [[[NSMenu allocWithZone:[NSMenu menuZone]]
150 initWithTitle:[NSString stringWithCString:title]]
151 autorelease];
152}
153
154NSMenu *newsubmenu(NSMenu *parent, const char *title)
155{
156 NSMenuItem *item;
157 NSMenu *child;
158
159 item = [[[NSMenuItem allocWithZone:[NSMenu menuZone]]
160 initWithTitle:[NSString stringWithCString:title]
161 action:NULL
162 keyEquivalent:@""]
163 autorelease];
164 child = newmenu(title);
165 [item setEnabled:YES];
166 [item setSubmenu:child];
167 [parent addItem:item];
168 return child;
169}
170
171id initnewitem(NSMenuItem *item, NSMenu *parent, const char *title,
172 const char *key, id target, SEL action)
173{
174 unsigned mask = NSCommandKeyMask;
175
176 if (key[strcspn(key, "-")]) {
177 while (*key && *key != '-') {
178 int c = tolower((unsigned char)*key);
179 if (c == 's') {
180 mask |= NSShiftKeyMask;
181 } else if (c == 'o' || c == 'a') {
182 mask |= NSAlternateKeyMask;
183 }
184 key++;
185 }
186 if (*key)
187 key++;
188 }
189
190 item = [[item initWithTitle:[NSString stringWithCString:title]
191 action:NULL
192 keyEquivalent:[NSString stringWithCString:key]]
193 autorelease];
194
195 if (*key)
196 [item setKeyEquivalentModifierMask: mask];
197
198 [item setEnabled:YES];
199 [item setTarget:target];
200 [item setAction:action];
201
202 [parent addItem:item];
203
204 return item;
205}
206
207NSMenuItem *newitem(NSMenu *parent, char *title, char *key,
208 id target, SEL action)
209{
210 return initnewitem([NSMenuItem allocWithZone:[NSMenu menuZone]],
211 parent, title, key, target, action);
212}
213
214/* ----------------------------------------------------------------------
9494d866 215 * The front end presented to midend.c.
216 *
217 * This is mostly a subclass of NSWindow. The actual `frontend'
218 * structure passed to the midend contains a variety of pointers,
219 * including that window object but also including the image we
220 * draw on, an ImageView to display it in the window, and so on.
221 */
222
223@class GameWindow;
224@class MyImageView;
225
226struct frontend {
227 GameWindow *window;
228 NSImage *image;
229 MyImageView *view;
230 NSColor **colours;
231 int ncolours;
232 int clipped;
233};
234
235@interface MyImageView : NSImageView
236{
237 GameWindow *ourwin;
238}
239- (void)setWindow:(GameWindow *)win;
240- (BOOL)isFlipped;
241- (void)mouseEvent:(NSEvent *)ev button:(int)b;
242- (void)mouseDown:(NSEvent *)ev;
243- (void)mouseDragged:(NSEvent *)ev;
244- (void)mouseUp:(NSEvent *)ev;
245- (void)rightMouseDown:(NSEvent *)ev;
246- (void)rightMouseDragged:(NSEvent *)ev;
247- (void)rightMouseUp:(NSEvent *)ev;
248- (void)otherMouseDown:(NSEvent *)ev;
249- (void)otherMouseDragged:(NSEvent *)ev;
250- (void)otherMouseUp:(NSEvent *)ev;
251@end
252
253@interface GameWindow : NSWindow
254{
255 const game *ourgame;
256 midend_data *me;
257 struct frontend fe;
258 struct timeval last_time;
259 NSTimer *timer;
e1107f8b 260 NSWindow *sheet;
261 config_item *cfg;
262 int cfg_which;
263 NSView **cfg_controls;
264 int cfg_ncontrols;
a5102461 265 NSTextField *status;
9494d866 266}
267- (id)initWithGame:(const game *)g;
268- dealloc;
269- (void)processButton:(int)b x:(int)x y:(int)y;
270- (void)keyDown:(NSEvent *)ev;
271- (void)activateTimer;
272- (void)deactivateTimer;
a5102461 273- (void)setStatusLine:(NSString *)text;
9494d866 274@end
275
276@implementation MyImageView
277
278- (void)setWindow:(GameWindow *)win
279{
280 ourwin = win;
281}
282
283- (BOOL)isFlipped
284{
285 return YES;
286}
287
288- (void)mouseEvent:(NSEvent *)ev button:(int)b
289{
290 NSPoint point = [self convertPoint:[ev locationInWindow] fromView:nil];
291 [ourwin processButton:b x:point.x y:point.y];
292}
293
294- (void)mouseDown:(NSEvent *)ev
295{
296 unsigned mod = [ev modifierFlags];
297 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_BUTTON :
298 (mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
299 LEFT_BUTTON)];
300}
301- (void)mouseDragged:(NSEvent *)ev
302{
303 unsigned mod = [ev modifierFlags];
304 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_DRAG :
305 (mod & NSShiftKeyMask) ? MIDDLE_DRAG :
306 LEFT_DRAG)];
307}
308- (void)mouseUp:(NSEvent *)ev
309{
310 unsigned mod = [ev modifierFlags];
311 [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_RELEASE :
312 (mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
313 LEFT_RELEASE)];
314}
315- (void)rightMouseDown:(NSEvent *)ev
316{
317 unsigned mod = [ev modifierFlags];
318 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
319 RIGHT_BUTTON)];
320}
321- (void)rightMouseDragged:(NSEvent *)ev
322{
323 unsigned mod = [ev modifierFlags];
324 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_DRAG :
325 RIGHT_DRAG)];
326}
327- (void)rightMouseUp:(NSEvent *)ev
328{
329 unsigned mod = [ev modifierFlags];
330 [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
331 RIGHT_RELEASE)];
332}
333- (void)otherMouseDown:(NSEvent *)ev
334{
335 [self mouseEvent:ev button:MIDDLE_BUTTON];
336}
337- (void)otherMouseDragged:(NSEvent *)ev
338{
339 [self mouseEvent:ev button:MIDDLE_DRAG];
340}
341- (void)otherMouseUp:(NSEvent *)ev
342{
343 [self mouseEvent:ev button:MIDDLE_RELEASE];
344}
345@end
346
347@implementation GameWindow
7e04cb48 348- (void)setupContentView
349{
a5102461 350 NSRect frame;
7e04cb48 351 int w, h;
352
a5102461 353 if (status) {
354 frame = [status frame];
355 frame.origin.y = frame.size.height;
356 } else
357 frame.origin.y = 0;
358 frame.origin.x = 0;
359
7e04cb48 360 midend_size(me, &w, &h);
a5102461 361 frame.size.width = w;
362 frame.size.height = h;
7e04cb48 363
a5102461 364 fe.image = [[NSImage alloc] initWithSize:frame.size];
7e04cb48 365 [fe.image setFlipped:YES];
a5102461 366 fe.view = [[MyImageView alloc] initWithFrame:frame];
7e04cb48 367 [fe.view setImage:fe.image];
368 [fe.view setWindow:self];
369
370 midend_redraw(me);
371
a5102461 372 [[self contentView] addSubview:fe.view];
7e04cb48 373}
9494d866 374- (id)initWithGame:(const game *)g
375{
a5102461 376 NSRect rect = { {0,0}, {0,0} }, rect2;
9494d866 377 int w, h;
378
379 ourgame = g;
380
381 fe.window = self;
382
383 me = midend_new(&fe, ourgame);
384 /*
385 * If we ever need to open a fresh window using a provided game
386 * ID, I think the right thing is to move most of this method
387 * into a new initWithGame:gameID: method, and have
388 * initWithGame: simply call that one and pass it NULL.
389 */
390 midend_new_game(me);
391 midend_size(me, &w, &h);
392 rect.size.width = w;
393 rect.size.height = h;
394
a5102461 395 /*
396 * Create the status bar, which will just be an NSTextField.
397 */
398 if (ourgame->wants_statusbar()) {
399 status = [[NSTextField alloc] initWithFrame:NSMakeRect(0,0,100,50)];
400 [status setEditable:NO];
401 [status setSelectable:NO];
402 [status setBordered:YES];
403 [status setBezeled:YES];
404 [status setBezelStyle:NSTextFieldSquareBezel];
405 [status setDrawsBackground:YES];
406 [[status cell] setTitle:@""];
407 [status sizeToFit];
408 rect2 = [status frame];
409 rect.size.height += rect2.size.height;
410 rect2.size.width = rect.size.width;
411 rect2.origin.x = rect2.origin.y = 0;
412 [status setFrame:rect2];
413 } else
414 status = nil;
415
9494d866 416 self = [super initWithContentRect:rect
417 styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
418 NSClosableWindowMask)
419 backing:NSBackingStoreBuffered
e1107f8b 420 defer:YES];
9494d866 421 [self setTitle:[NSString stringWithCString:ourgame->name]];
422
423 {
424 float *colours;
425 int i, ncolours;
426
427 colours = midend_colours(me, &ncolours);
428 fe.ncolours = ncolours;
429 fe.colours = snewn(ncolours, NSColor *);
430
431 for (i = 0; i < ncolours; i++) {
432 fe.colours[i] = [[NSColor colorWithDeviceRed:colours[i*3]
433 green:colours[i*3+1] blue:colours[i*3+2]
434 alpha:1.0] retain];
435 }
436 }
437
7e04cb48 438 [self setupContentView];
a5102461 439 if (status)
440 [[self contentView] addSubview:status];
9494d866 441 [self setIgnoresMouseEvents:NO];
442
9494d866 443 [self center]; /* :-) */
444
445 return self;
446}
447
448- dealloc
449{
450 int i;
451 for (i = 0; i < fe.ncolours; i++) {
452 [fe.colours[i] release];
453 }
454 sfree(fe.colours);
455 midend_free(me);
456 return [super dealloc];
457}
458
459- (void)processButton:(int)b x:(int)x y:(int)y
460{
461 if (!midend_process_key(me, x, y, b))
462 [self close];
463}
464
465- (void)keyDown:(NSEvent *)ev
466{
467 NSString *s = [ev characters];
468 int i, n = [s length];
469
470 for (i = 0; i < n; i++) {
471 int c = [s characterAtIndex:i];
472
473 /*
474 * ASCII gets passed straight to midend_process_key.
475 * Anything above that has to be translated to our own
476 * function key codes.
477 */
478 if (c >= 0x80) {
479 switch (c) {
480 case NSUpArrowFunctionKey:
481 c = CURSOR_UP;
482 break;
483 case NSDownArrowFunctionKey:
484 c = CURSOR_DOWN;
485 break;
486 case NSLeftArrowFunctionKey:
487 c = CURSOR_LEFT;
488 break;
489 case NSRightArrowFunctionKey:
490 c = CURSOR_RIGHT;
491 break;
492 default:
493 continue;
494 }
495 }
496
497 [self processButton:c x:-1 y:-1];
498 }
499}
500
501- (void)activateTimer
502{
503 if (timer != nil)
504 return;
505
506 timer = [NSTimer scheduledTimerWithTimeInterval:0.02
507 target:self selector:@selector(timerTick:)
508 userInfo:nil repeats:YES];
509 gettimeofday(&last_time, NULL);
510}
511
512- (void)deactivateTimer
513{
514 if (timer == nil)
515 return;
516
517 [timer invalidate];
518 timer = nil;
519}
520
521- (void)timerTick:(id)sender
522{
523 struct timeval now;
524 float elapsed;
525 gettimeofday(&now, NULL);
526 elapsed = ((now.tv_usec - last_time.tv_usec) * 0.000001F +
527 (now.tv_sec - last_time.tv_sec));
528 midend_timer(me, elapsed);
529 last_time = now;
530}
531
00461804 532- (void)newGame:(id)sender
533{
534 [self processButton:'n' x:-1 y:-1];
535}
536- (void)restartGame:(id)sender
537{
538 [self processButton:'r' x:-1 y:-1];
539}
540- (void)undoMove:(id)sender
541{
542 [self processButton:'u' x:-1 y:-1];
543}
544- (void)redoMove:(id)sender
545{
546 [self processButton:'r'&0x1F x:-1 y:-1];
547}
548
7e04cb48 549- (void)clearTypeMenu
550{
551 while ([typemenu numberOfItems] > 1)
552 [typemenu removeItemAtIndex:0];
553}
554
555- (void)becomeKeyWindow
556{
557 int n;
558
559 [self clearTypeMenu];
560
561 [super becomeKeyWindow];
562
563 n = midend_num_presets(me);
564
565 if (n > 0) {
566 [typemenu insertItem:[NSMenuItem separatorItem] atIndex:0];
567 while (n--) {
568 char *name;
569 game_params *params;
570 DataMenuItem *item;
571
572 midend_fetch_preset(me, n, &name, &params);
573
574 item = [[[DataMenuItem alloc]
575 initWithTitle:[NSString stringWithCString:name]
576 action:NULL keyEquivalent:@""]
577 autorelease];
578
579 [item setEnabled:YES];
580 [item setTarget:self];
581 [item setAction:@selector(presetGame:)];
582 [item setPayload:params];
7e04cb48 583
584 [typemenu insertItem:item atIndex:0];
585 }
586 }
587}
588
589- (void)resignKeyWindow
590{
591 [self clearTypeMenu];
592 [super resignKeyWindow];
593}
594
595- (void)close
596{
597 [self clearTypeMenu];
598 [super close];
599}
600
601- (void)resizeForNewGameParams
602{
603 NSSize size = {0,0};
604 int w, h;
605
606 midend_size(me, &w, &h);
607 size.width = w;
608 size.height = h;
609
610 NSDisableScreenUpdates();
611 [self setContentSize:size];
612 [self setupContentView];
613 NSEnableScreenUpdates();
614}
615
616- (void)presetGame:(id)sender
617{
618 game_params *params = [sender getPayload];
619
620 midend_set_params(me, params);
621 midend_new_game(me);
622
623 [self resizeForNewGameParams];
624}
625
e1107f8b 626- (void)startConfigureSheet:(int)which
627{
628 NSButton *ok, *cancel;
629 int actw, acth, leftw, rightw, totalw, h, thish, y;
630 int k;
631 NSRect rect, tmprect;
632 const int SPACING = 16;
633 char *title;
634 config_item *i;
635 int cfg_controlsize;
636 NSTextField *tf;
637 NSButton *b;
638 NSPopUpButton *pb;
639
640 assert(sheet == NULL);
641
642 /*
643 * Every control we create here is going to have this size
644 * until we tell it to calculate a better one.
645 */
646 tmprect = NSMakeRect(0, 0, 100, 50);
647
648 /*
649 * Set up OK and Cancel buttons. (Actually, MacOS doesn't seem
650 * to be fond of generic OK and Cancel wording, so I'm going to
651 * rename them to something nicer.)
652 */
653 actw = acth = 0;
654
655 cancel = [[NSButton alloc] initWithFrame:tmprect];
656 [cancel setBezelStyle:NSRoundedBezelStyle];
657 [cancel setTitle:@"Abandon"];
658 [cancel setTarget:self];
659 [cancel setKeyEquivalent:@"\033"];
660 [cancel setAction:@selector(sheetCancelButton:)];
661 [cancel sizeToFit];
662 rect = [cancel frame];
663 if (actw < rect.size.width) actw = rect.size.width;
664 if (acth < rect.size.height) acth = rect.size.height;
665
666 ok = [[NSButton alloc] initWithFrame:tmprect];
667 [ok setBezelStyle:NSRoundedBezelStyle];
668 [ok setTitle:@"Accept"];
669 [ok setTarget:self];
670 [ok setKeyEquivalent:@"\r"];
671 [ok setAction:@selector(sheetOKButton:)];
672 [ok sizeToFit];
673 rect = [ok frame];
674 if (actw < rect.size.width) actw = rect.size.width;
675 if (acth < rect.size.height) acth = rect.size.height;
676
677 totalw = SPACING + 2 * actw;
678 h = 2 * SPACING + acth;
679
680 /*
681 * Now fetch the midend config data and go through it creating
682 * controls.
683 */
684 cfg = midend_get_config(me, which, &title);
685 sfree(title); /* FIXME: should we use this somehow? */
686 cfg_which = which;
687
688 cfg_ncontrols = cfg_controlsize = 0;
689 cfg_controls = NULL;
690 leftw = rightw = 0;
691 for (i = cfg; i->type != C_END; i++) {
692 if (cfg_controlsize < cfg_ncontrols + 5) {
693 cfg_controlsize = cfg_ncontrols + 32;
694 cfg_controls = sresize(cfg_controls, cfg_controlsize, NSView *);
695 }
696
697 thish = 0;
698
699 switch (i->type) {
700 case C_STRING:
701 /*
702 * Two NSTextFields, one being a label and the other
703 * being an edit box.
704 */
705
706 tf = [[NSTextField alloc] initWithFrame:tmprect];
707 [tf setEditable:NO];
708 [tf setSelectable:NO];
709 [tf setBordered:NO];
710 [tf setDrawsBackground:NO];
711 [[tf cell] setTitle:[NSString stringWithCString:i->name]];
712 [tf sizeToFit];
713 rect = [tf frame];
714 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
715 if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
716 cfg_controls[cfg_ncontrols++] = tf;
717
718 /* We impose a minimum width on editable NSTextFields to
719 * stop them looking _completely_ silly. */
720 if (rightw < 75) rightw = 75;
721
722 tf = [[NSTextField alloc] initWithFrame:tmprect];
723 [tf setEditable:YES];
724 [tf setSelectable:YES];
725 [tf setBordered:YES];
726 [[tf cell] setTitle:[NSString stringWithCString:i->sval]];
727 [tf sizeToFit];
728 rect = [tf frame];
729 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
730 if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
731 cfg_controls[cfg_ncontrols++] = tf;
732 break;
733
734 case C_BOOLEAN:
735 /*
736 * A checkbox is an NSButton with a type of
737 * NSSwitchButton.
738 */
739 b = [[NSButton alloc] initWithFrame:tmprect];
740 [b setBezelStyle:NSRoundedBezelStyle];
741 [b setButtonType:NSSwitchButton];
742 [b setTitle:[NSString stringWithCString:i->name]];
743 [b sizeToFit];
744 [b setState:(i->ival ? NSOnState : NSOffState)];
745 rect = [b frame];
746 if (totalw < rect.size.width + 1) totalw = rect.size.width + 1;
747 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
748 cfg_controls[cfg_ncontrols++] = b;
749 break;
750
751 case C_CHOICES:
752 /*
753 * A pop-up menu control is an NSPopUpButton, which
754 * takes an embedded NSMenu. We also need an
755 * NSTextField to act as a label.
756 */
757
758 tf = [[NSTextField alloc] initWithFrame:tmprect];
759 [tf setEditable:NO];
760 [tf setSelectable:NO];
761 [tf setBordered:NO];
762 [tf setDrawsBackground:NO];
763 [[tf cell] setTitle:[NSString stringWithCString:i->name]];
764 [tf sizeToFit];
765 rect = [tf frame];
766 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
767 if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
768 cfg_controls[cfg_ncontrols++] = tf;
769
770 pb = [[NSPopUpButton alloc] initWithFrame:tmprect pullsDown:NO];
771 [pb setBezelStyle:NSRoundedBezelStyle];
772 {
773 char c, *p;
774
775 p = i->sval;
776 c = *p++;
777 while (*p) {
778 char *q;
779
780 q = p;
781 while (*p && *p != c) p++;
782
783 [pb addItemWithTitle:[NSString stringWithCString:q
784 length:p-q]];
785
786 if (*p) p++;
787 }
788 }
789 [pb selectItemAtIndex:i->ival];
790 [pb sizeToFit];
791
792 rect = [pb frame];
793 if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
794 if (thish < rect.size.height + 1) thish = rect.size.height + 1;
795 cfg_controls[cfg_ncontrols++] = pb;
796 break;
797 }
798
799 h += SPACING + thish;
800 }
801
802 if (totalw < leftw + SPACING + rightw)
803 totalw = leftw + SPACING + rightw;
804 if (totalw > leftw + SPACING + rightw) {
805 int excess = totalw - (leftw + SPACING + rightw);
806 int leftexcess = leftw * excess / (leftw + rightw);
807 int rightexcess = excess - leftexcess;
808 leftw += leftexcess;
809 rightw += rightexcess;
810 }
811
812 /*
813 * Now go through the list again, setting the final position
814 * for each control.
815 */
816 k = 0;
817 y = h;
818 for (i = cfg; i->type != C_END; i++) {
819 y -= SPACING;
820 thish = 0;
821 switch (i->type) {
822 case C_STRING:
823 case C_CHOICES:
824 /*
825 * These two are treated identically, since both expect
826 * a control on the left and another on the right.
827 */
828 rect = [cfg_controls[k] frame];
829 if (thish < rect.size.height + 1)
830 thish = rect.size.height + 1;
831 rect = [cfg_controls[k+1] frame];
832 if (thish < rect.size.height + 1)
833 thish = rect.size.height + 1;
834 rect = [cfg_controls[k] frame];
835 rect.origin.y = y - thish/2 - rect.size.height/2;
836 rect.origin.x = SPACING;
837 rect.size.width = leftw;
838 [cfg_controls[k] setFrame:rect];
839 rect = [cfg_controls[k+1] frame];
840 rect.origin.y = y - thish/2 - rect.size.height/2;
841 rect.origin.x = 2 * SPACING + leftw;
842 rect.size.width = rightw;
843 [cfg_controls[k+1] setFrame:rect];
844 k += 2;
845 break;
846
847 case C_BOOLEAN:
848 rect = [cfg_controls[k] frame];
849 if (thish < rect.size.height + 1)
850 thish = rect.size.height + 1;
851 rect.origin.y = y - thish/2 - rect.size.height/2;
852 rect.origin.x = SPACING;
853 rect.size.width = totalw;
854 [cfg_controls[k] setFrame:rect];
855 k++;
856 break;
857 }
858 y -= thish;
859 }
860
861 assert(k == cfg_ncontrols);
862
863 [cancel setFrame:NSMakeRect(SPACING+totalw/4-actw/2, SPACING, actw, acth)];
864 [ok setFrame:NSMakeRect(SPACING+3*totalw/4-actw/2, SPACING, actw, acth)];
865
866 sheet = [[NSWindow alloc]
867 initWithContentRect:NSMakeRect(0,0,totalw + 2*SPACING,h)
868 styleMask:NSTitledWindowMask | NSClosableWindowMask
869 backing:NSBackingStoreBuffered
870 defer:YES];
871
872 [[sheet contentView] addSubview:cancel];
873 [[sheet contentView] addSubview:ok];
874
875 for (k = 0; k < cfg_ncontrols; k++)
876 [[sheet contentView] addSubview:cfg_controls[k]];
877
878 [NSApp beginSheet:sheet modalForWindow:self
879 modalDelegate:nil didEndSelector:nil contextInfo:nil];
880}
881
882- (void)specificGame:(id)sender
883{
884 [self startConfigureSheet:CFG_SEED];
885}
886
887- (void)customGameType:(id)sender
888{
889 [self startConfigureSheet:CFG_SETTINGS];
890}
891
892- (void)sheetEndWithStatus:(BOOL)update
893{
894 assert(sheet != NULL);
895 [NSApp endSheet:sheet];
896 [sheet orderOut:self];
897 sheet = NULL;
898 if (update) {
899 int k;
900 config_item *i;
901 char *error;
902
903 k = 0;
904 for (i = cfg; i->type != C_END; i++) {
905 switch (i->type) {
906 case C_STRING:
907 sfree(i->sval);
908 i->sval = dupstr([[[(id)cfg_controls[k+1] cell]
909 title] cString]);
910 k += 2;
911 break;
912 case C_BOOLEAN:
913 i->ival = [(id)cfg_controls[k] state] == NSOnState;
914 k++;
915 break;
916 case C_CHOICES:
917 i->ival = [(id)cfg_controls[k+1] indexOfSelectedItem];
918 k += 2;
919 break;
920 }
921 }
922
923 error = midend_set_config(me, cfg_which, cfg);
924 if (error) {
925 NSAlert *alert = [[[NSAlert alloc] init] autorelease];
926 [alert addButtonWithTitle:@"OK"];
927 [alert setInformativeText:[NSString stringWithCString:error]];
928 [alert beginSheetModalForWindow:self modalDelegate:nil
929 didEndSelector:nil contextInfo:nil];
930 } else {
931 midend_new_game(me);
932 [self resizeForNewGameParams];
933 }
934 }
935 sfree(cfg_controls);
936 cfg_controls = NULL;
937}
938- (void)sheetOKButton:(id)sender
939{
940 [self sheetEndWithStatus:YES];
941}
942- (void)sheetCancelButton:(id)sender
943{
944 [self sheetEndWithStatus:NO];
945}
946
a5102461 947- (void)setStatusLine:(NSString *)text
948{
949 [[status cell] setTitle:text];
950}
951
9494d866 952@end
953
954/*
955 * Drawing routines called by the midend.
956 */
957void draw_polygon(frontend *fe, int *coords, int npoints,
958 int fill, int colour)
959{
960 NSBezierPath *path = [NSBezierPath bezierPath];
961 int i;
962
963 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
964
965 assert(colour >= 0 && colour < fe->ncolours);
966 [fe->colours[colour] set];
967
968 for (i = 0; i < npoints; i++) {
969 NSPoint p = { coords[i*2] + 0.5, coords[i*2+1] + 0.5 };
970 if (i == 0)
971 [path moveToPoint:p];
972 else
973 [path lineToPoint:p];
974 }
975
976 [path closePath];
977
978 if (fill)
979 [path fill];
980 else
981 [path stroke];
982}
983void draw_line(frontend *fe, int x1, int y1, int x2, int y2, int colour)
984{
985 NSBezierPath *path = [NSBezierPath bezierPath];
986 NSPoint p1 = { x1 + 0.5, y1 + 0.5 }, p2 = { x2 + 0.5, y2 + 0.5 };
987
988 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
989
990 assert(colour >= 0 && colour < fe->ncolours);
991 [fe->colours[colour] set];
992
993 [path moveToPoint:p1];
994 [path lineToPoint:p2];
995 [path stroke];
996}
997void draw_rect(frontend *fe, int x, int y, int w, int h, int colour)
998{
999 NSRect r = { {x,y}, {w,h} };
1000
1001 [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1002
1003 assert(colour >= 0 && colour < fe->ncolours);
1004 [fe->colours[colour] set];
1005
1006 NSRectFill(r);
1007}
1008void draw_text(frontend *fe, int x, int y, int fonttype, int fontsize,
1009 int align, int colour, char *text)
1010{
1011 NSString *string = [NSString stringWithCString:text];
1012 NSDictionary *attr;
1013 NSFont *font;
1014 NSSize size;
1015 NSPoint point;
1016
1017 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1018
1019 assert(colour >= 0 && colour < fe->ncolours);
1020
1021 if (fonttype == FONT_FIXED)
1022 font = [NSFont userFixedPitchFontOfSize:fontsize];
1023 else
1024 font = [NSFont userFontOfSize:fontsize];
1025
1026 attr = [NSDictionary dictionaryWithObjectsAndKeys:
1027 fe->colours[colour], NSForegroundColorAttributeName,
1028 font, NSFontAttributeName, nil];
1029
1030 point.x = x;
1031 point.y = y;
1032
1033 size = [string sizeWithAttributes:attr];
1034 if (align & ALIGN_HRIGHT)
1035 point.x -= size.width;
1036 else if (align & ALIGN_HCENTRE)
1037 point.x -= size.width / 2;
1038 if (align & ALIGN_VCENTRE)
1039 point.y -= size.height / 2;
1040
1041 [string drawAtPoint:point withAttributes:attr];
1042}
1043void draw_update(frontend *fe, int x, int y, int w, int h)
1044{
1045 /* FIXME */
1046}
1047void clip(frontend *fe, int x, int y, int w, int h)
1048{
1049 NSRect r = { {x,y}, {w,h} };
1050
1051 if (!fe->clipped)
1052 [[NSGraphicsContext currentContext] saveGraphicsState];
1053 [NSBezierPath clipRect:r];
1054 fe->clipped = TRUE;
1055}
1056void unclip(frontend *fe)
1057{
1058 if (fe->clipped)
1059 [[NSGraphicsContext currentContext] restoreGraphicsState];
1060 fe->clipped = FALSE;
1061}
1062void start_draw(frontend *fe)
1063{
1064 [fe->image lockFocus];
1065 fe->clipped = FALSE;
1066}
1067void end_draw(frontend *fe)
1068{
1069 [fe->image unlockFocus];
1070 [fe->view setNeedsDisplay];
1071}
1072
1073void deactivate_timer(frontend *fe)
1074{
1075 [fe->window deactivateTimer];
1076}
1077void activate_timer(frontend *fe)
1078{
1079 [fe->window activateTimer];
1080}
1081
a5102461 1082void status_bar(frontend *fe, char *text)
1083{
1084 [fe->window setStatusLine:[NSString stringWithCString:text]];
1085}
1086
9494d866 1087/* ----------------------------------------------------------------------
9494d866 1088 * AppController: the object which receives the messages from all
1089 * menu selections that aren't standard OS X functions.
1090 */
1091@interface AppController : NSObject
1092{
1093}
1094- (IBAction)newGame:(id)sender;
1095@end
1096
1097@implementation AppController
1098
1099- (IBAction)newGame:(id)sender
1100{
7e04cb48 1101 const game *g = [sender getPayload];
9494d866 1102 id win;
1103
1104 win = [[GameWindow alloc] initWithGame:g];
1105 [win makeKeyAndOrderFront:self];
1106}
1107
1108@end
1109
1110/* ----------------------------------------------------------------------
1111 * Main program. Constructs the menus and runs the application.
1112 */
1113int main(int argc, char **argv)
1114{
1115 NSAutoreleasePool *pool;
1116 NSMenu *menu;
1117 NSMenuItem *item;
1118 AppController *controller;
a96edf8a 1119 NSImage *icon;
9494d866 1120
1121 pool = [[NSAutoreleasePool alloc] init];
a96edf8a 1122
1123 icon = [NSImage imageNamed:@"NSApplicationIcon"];
9494d866 1124 [NSApplication sharedApplication];
a96edf8a 1125 [NSApp setApplicationIconImage:icon];
9494d866 1126
1127 controller = [[[AppController alloc] init] autorelease];
1128
1129 [NSApp setMainMenu: newmenu("Main Menu")];
1130
1131 menu = newsubmenu([NSApp mainMenu], "Apple Menu");
1132 [NSApp setServicesMenu:newsubmenu(menu, "Services")];
1133 [menu addItem:[NSMenuItem separatorItem]];
1134 item = newitem(menu, "Hide Puzzles", "h", NSApp, @selector(hide:));
1135 item = newitem(menu, "Hide Others", "o-h", NSApp, @selector(hideOtherApplications:));
1136 item = newitem(menu, "Show All", "", NSApp, @selector(unhideAllApplications:));
1137 [menu addItem:[NSMenuItem separatorItem]];
1138 item = newitem(menu, "Quit", "q", NSApp, @selector(terminate:));
1139 [NSApp setAppleMenu: menu];
1140
00461804 1141 menu = newsubmenu([NSApp mainMenu], "Open");
9494d866 1142 {
1143 int i;
1144
1145 for (i = 0; i < gamecount; i++) {
1146 id item =
7e04cb48 1147 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
9494d866 1148 menu, gamelist[i]->name, "", controller,
1149 @selector(newGame:));
7e04cb48 1150 [item setPayload:(void *)gamelist[i]];
9494d866 1151 }
1152 }
1153
00461804 1154 menu = newsubmenu([NSApp mainMenu], "Game");
1155 item = newitem(menu, "New", "n", NULL, @selector(newGame:));
1156 item = newitem(menu, "Restart", "r", NULL, @selector(restartGame:));
1157 item = newitem(menu, "Specific", "", NULL, @selector(specificGame:));
1158 [menu addItem:[NSMenuItem separatorItem]];
1159 item = newitem(menu, "Undo", "z", NULL, @selector(undoMove:));
1160 item = newitem(menu, "Redo", "S-z", NULL, @selector(redoMove:));
1161 [menu addItem:[NSMenuItem separatorItem]];
1162 item = newitem(menu, "Close", "w", NULL, @selector(performClose:));
1163
1164 menu = newsubmenu([NSApp mainMenu], "Type");
7e04cb48 1165 typemenu = menu;
00461804 1166 item = newitem(menu, "Custom", "", NULL, @selector(customGameType:));
1167
1168 menu = newsubmenu([NSApp mainMenu], "Window");
9494d866 1169 [NSApp setWindowsMenu: menu];
00461804 1170 item = newitem(menu, "Minimise Window", "m", NULL, @selector(performMiniaturize:));
9494d866 1171
1172 [NSApp run];
1173 [pool release];
1174}