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