chiark / gitweb /
Add support for Jacob's new cursor-key modifier flags in the OS X frontend.
[sgt-puzzles.git] / 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  * About box.
237  */
238
239 @class AboutBox;
240
241 @interface AboutBox : NSWindow
242 {
243 }
244 - (id)init;
245 @end
246
247 @implementation AboutBox
248 - (id)init
249 {
250     NSRect totalrect;
251     NSView *views[16];
252     int nviews = 0;
253     NSImageView *iv;
254     NSTextField *tf;
255     NSFont *font1 = [NSFont systemFontOfSize:0];
256     NSFont *font2 = [NSFont boldSystemFontOfSize:[font1 pointSize] * 1.1];
257     const int border = 24;
258     int i;
259     double y;
260
261     /*
262      * Construct the controls that go in the About box.
263      */
264
265     iv = [[NSImageView alloc] initWithFrame:NSMakeRect(0,0,64,64)];
266     [iv setImage:[NSImage imageNamed:@"NSApplicationIcon"]];
267     views[nviews++] = iv;
268
269     tf = [[NSTextField alloc]
270           initWithFrame:NSMakeRect(0,0,400,1)];
271     [tf setEditable:NO];
272     [tf setSelectable:NO];
273     [tf setBordered:NO];
274     [tf setDrawsBackground:NO];
275     [tf setFont:font2];
276     [tf setStringValue:@"Simon Tatham's Portable Puzzle Collection"];
277     [tf sizeToFit];
278     views[nviews++] = tf;
279
280     tf = [[NSTextField alloc]
281           initWithFrame:NSMakeRect(0,0,400,1)];
282     [tf setEditable:NO];
283     [tf setSelectable:NO];
284     [tf setBordered:NO];
285     [tf setDrawsBackground:NO];
286     [tf setFont:font1];
287     [tf setStringValue:[NSString stringWithCString:ver]];
288     [tf sizeToFit];
289     views[nviews++] = tf;
290
291     /*
292      * Lay the controls out.
293      */
294     totalrect = NSMakeRect(0,0,0,0);
295     for (i = 0; i < nviews; i++) {
296         NSRect r = [views[i] frame];
297         if (totalrect.size.width < r.size.width)
298             totalrect.size.width = r.size.width;
299         totalrect.size.height += border + r.size.height;
300     }
301     totalrect.size.width += 2 * border;
302     totalrect.size.height += border;
303     y = totalrect.size.height;
304     for (i = 0; i < nviews; i++) {
305         NSRect r = [views[i] frame];
306         r.origin.x = (totalrect.size.width - r.size.width) / 2;
307         y -= border + r.size.height;
308         r.origin.y = y;
309         [views[i] setFrame:r];
310     }
311
312     self = [super initWithContentRect:totalrect
313             styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
314                        NSClosableWindowMask)
315             backing:NSBackingStoreBuffered
316             defer:YES];
317
318     for (i = 0; i < nviews; i++)
319         [[self contentView] addSubview:views[i]];
320
321     [self center];                     /* :-) */
322
323     return self;
324 }
325 @end
326
327 /* ----------------------------------------------------------------------
328  * The front end presented to midend.c.
329  * 
330  * This is mostly a subclass of NSWindow. The actual `frontend'
331  * structure passed to the midend contains a variety of pointers,
332  * including that window object but also including the image we
333  * draw on, an ImageView to display it in the window, and so on.
334  */
335
336 @class GameWindow;
337 @class MyImageView;
338
339 struct frontend {
340     GameWindow *window;
341     NSImage *image;
342     MyImageView *view;
343     NSColor **colours;
344     int ncolours;
345     int clipped;
346 };
347
348 @interface MyImageView : NSImageView
349 {
350     GameWindow *ourwin;
351 }
352 - (void)setWindow:(GameWindow *)win;
353 - (BOOL)isFlipped;
354 - (void)mouseEvent:(NSEvent *)ev button:(int)b;
355 - (void)mouseDown:(NSEvent *)ev;
356 - (void)mouseDragged:(NSEvent *)ev;
357 - (void)mouseUp:(NSEvent *)ev;
358 - (void)rightMouseDown:(NSEvent *)ev;
359 - (void)rightMouseDragged:(NSEvent *)ev;
360 - (void)rightMouseUp:(NSEvent *)ev;
361 - (void)otherMouseDown:(NSEvent *)ev;
362 - (void)otherMouseDragged:(NSEvent *)ev;
363 - (void)otherMouseUp:(NSEvent *)ev;
364 @end
365
366 @interface GameWindow : NSWindow
367 {
368     const game *ourgame;
369     midend_data *me;
370     struct frontend fe;
371     struct timeval last_time;
372     NSTimer *timer;
373     NSWindow *sheet;
374     config_item *cfg;
375     int cfg_which;
376     NSView **cfg_controls;
377     int cfg_ncontrols;
378     NSTextField *status;
379 }
380 - (id)initWithGame:(const game *)g;
381 - dealloc;
382 - (void)processButton:(int)b x:(int)x y:(int)y;
383 - (void)keyDown:(NSEvent *)ev;
384 - (void)activateTimer;
385 - (void)deactivateTimer;
386 - (void)setStatusLine:(NSString *)text;
387 @end
388
389 @implementation MyImageView
390
391 - (void)setWindow:(GameWindow *)win
392 {
393     ourwin = win;
394 }
395
396 - (BOOL)isFlipped
397 {
398     return YES;
399 }
400
401 - (void)mouseEvent:(NSEvent *)ev button:(int)b
402 {
403     NSPoint point = [self convertPoint:[ev locationInWindow] fromView:nil];
404     [ourwin processButton:b x:point.x y:point.y];
405 }
406
407 - (void)mouseDown:(NSEvent *)ev
408 {
409     unsigned mod = [ev modifierFlags];
410     [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_BUTTON :
411                                 (mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
412                                 LEFT_BUTTON)];
413 }
414 - (void)mouseDragged:(NSEvent *)ev
415 {
416     unsigned mod = [ev modifierFlags];
417     [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_DRAG :
418                                 (mod & NSShiftKeyMask) ? MIDDLE_DRAG :
419                                 LEFT_DRAG)];
420 }
421 - (void)mouseUp:(NSEvent *)ev
422 {
423     unsigned mod = [ev modifierFlags];
424     [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_RELEASE :
425                                 (mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
426                                 LEFT_RELEASE)];
427 }
428 - (void)rightMouseDown:(NSEvent *)ev
429 {
430     unsigned mod = [ev modifierFlags];
431     [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
432                                 RIGHT_BUTTON)];
433 }
434 - (void)rightMouseDragged:(NSEvent *)ev
435 {
436     unsigned mod = [ev modifierFlags];
437     [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_DRAG :
438                                 RIGHT_DRAG)];
439 }
440 - (void)rightMouseUp:(NSEvent *)ev
441 {
442     unsigned mod = [ev modifierFlags];
443     [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
444                                 RIGHT_RELEASE)];
445 }
446 - (void)otherMouseDown:(NSEvent *)ev
447 {
448     [self mouseEvent:ev button:MIDDLE_BUTTON];
449 }
450 - (void)otherMouseDragged:(NSEvent *)ev
451 {
452     [self mouseEvent:ev button:MIDDLE_DRAG];
453 }
454 - (void)otherMouseUp:(NSEvent *)ev
455 {
456     [self mouseEvent:ev button:MIDDLE_RELEASE];
457 }
458 @end
459
460 @implementation GameWindow
461 - (void)setupContentView
462 {
463     NSRect frame;
464     int w, h;
465
466     if (status) {
467         frame = [status frame];
468         frame.origin.y = frame.size.height;
469     } else
470         frame.origin.y = 0;
471     frame.origin.x = 0;
472
473     midend_size(me, &w, &h);
474     frame.size.width = w;
475     frame.size.height = h;
476
477     fe.image = [[NSImage alloc] initWithSize:frame.size];
478     [fe.image setFlipped:YES];
479     fe.view = [[MyImageView alloc] initWithFrame:frame];
480     [fe.view setImage:fe.image];
481     [fe.view setWindow:self];
482
483     midend_redraw(me);
484
485     [[self contentView] addSubview:fe.view];
486 }
487 - (id)initWithGame:(const game *)g
488 {
489     NSRect rect = { {0,0}, {0,0} }, rect2;
490     int w, h;
491
492     ourgame = g;
493
494     fe.window = self;
495
496     me = midend_new(&fe, ourgame);
497     /*
498      * If we ever need to open a fresh window using a provided game
499      * ID, I think the right thing is to move most of this method
500      * into a new initWithGame:gameID: method, and have
501      * initWithGame: simply call that one and pass it NULL.
502      */
503     midend_new_game(me);
504     midend_size(me, &w, &h);
505     rect.size.width = w;
506     rect.size.height = h;
507
508     /*
509      * Create the status bar, which will just be an NSTextField.
510      */
511     if (ourgame->wants_statusbar()) {
512         status = [[NSTextField alloc] initWithFrame:NSMakeRect(0,0,100,50)];
513         [status setEditable:NO];
514         [status setSelectable:NO];
515         [status setBordered:YES];
516         [status setBezeled:YES];
517         [status setBezelStyle:NSTextFieldSquareBezel];
518         [status setDrawsBackground:YES];
519         [[status cell] setTitle:@""];
520         [status sizeToFit];
521         rect2 = [status frame];
522         rect.size.height += rect2.size.height;
523         rect2.size.width = rect.size.width;
524         rect2.origin.x = rect2.origin.y = 0;
525         [status setFrame:rect2];
526     } else
527         status = nil;
528
529     self = [super initWithContentRect:rect
530             styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
531                        NSClosableWindowMask)
532             backing:NSBackingStoreBuffered
533             defer:YES];
534     [self setTitle:[NSString stringWithCString:ourgame->name]];
535
536     {
537         float *colours;
538         int i, ncolours;
539
540         colours = midend_colours(me, &ncolours);
541         fe.ncolours = ncolours;
542         fe.colours = snewn(ncolours, NSColor *);
543
544         for (i = 0; i < ncolours; i++) {
545             fe.colours[i] = [[NSColor colorWithDeviceRed:colours[i*3]
546                               green:colours[i*3+1] blue:colours[i*3+2]
547                               alpha:1.0] retain];
548         }
549     }
550
551     [self setupContentView];
552     if (status)
553         [[self contentView] addSubview:status];
554     [self setIgnoresMouseEvents:NO];
555
556     [self center];                     /* :-) */
557
558     return self;
559 }
560
561 - dealloc
562 {
563     int i;
564     for (i = 0; i < fe.ncolours; i++) {
565         [fe.colours[i] release];
566     }
567     sfree(fe.colours);
568     midend_free(me);
569     return [super dealloc];
570 }
571
572 - (void)processButton:(int)b x:(int)x y:(int)y
573 {
574     if (!midend_process_key(me, x, y, b))
575         [self close];
576 }
577
578 - (void)keyDown:(NSEvent *)ev
579 {
580     NSString *s = [ev characters];
581     int i, n = [s length];
582
583     for (i = 0; i < n; i++) {
584         int c = [s characterAtIndex:i];
585
586         /*
587          * ASCII gets passed straight to midend_process_key.
588          * Anything above that has to be translated to our own
589          * function key codes.
590          */
591         if (c >= 0x80) {
592             int mods = FALSE;
593             switch (c) {
594               case NSUpArrowFunctionKey:
595                 c = CURSOR_UP;
596                 mods = TRUE;
597                 break;
598               case NSDownArrowFunctionKey:
599                 c = CURSOR_DOWN;
600                 mods = TRUE;
601                 break;
602               case NSLeftArrowFunctionKey:
603                 c = CURSOR_LEFT;
604                 mods = TRUE;
605                 break;
606               case NSRightArrowFunctionKey:
607                 c = CURSOR_RIGHT;
608                 mods = TRUE;
609                 break;
610               default:
611                 continue;
612             }
613
614             if (mods) {
615                 if ([ev modifierFlags] & NSShiftKeyMask)
616                     c |= MOD_SHFT;
617                 if ([ev modifierFlags] & NSControlKeyMask)
618                     c |= MOD_CTRL;
619             }
620         }
621
622         if (c >= '0' && c <= '9' && ([ev modifierFlags] & NSNumericPadKeyMask))
623             c |= MOD_NUM_KEYPAD;
624
625         [self processButton:c x:-1 y:-1];
626     }
627 }
628
629 - (void)activateTimer
630 {
631     if (timer != nil)
632         return;
633
634     timer = [NSTimer scheduledTimerWithTimeInterval:0.02
635              target:self selector:@selector(timerTick:)
636              userInfo:nil repeats:YES];
637     gettimeofday(&last_time, NULL);
638 }
639
640 - (void)deactivateTimer
641 {
642     if (timer == nil)
643         return;
644
645     [timer invalidate];
646     timer = nil;
647 }
648
649 - (void)timerTick:(id)sender
650 {
651     struct timeval now;
652     float elapsed;
653     gettimeofday(&now, NULL);
654     elapsed = ((now.tv_usec - last_time.tv_usec) * 0.000001F +
655                (now.tv_sec - last_time.tv_sec));
656     midend_timer(me, elapsed);
657     last_time = now;
658 }
659
660 - (void)newGame:(id)sender
661 {
662     [self processButton:'n' x:-1 y:-1];
663 }
664 - (void)restartGame:(id)sender
665 {
666     midend_restart_game(me);
667 }
668 - (void)undoMove:(id)sender
669 {
670     [self processButton:'u' x:-1 y:-1];
671 }
672 - (void)redoMove:(id)sender
673 {
674     [self processButton:'r'&0x1F x:-1 y:-1];
675 }
676
677 - (void)copy:(id)sender
678 {
679     char *text;
680
681     if ((text = midend_text_format(me)) != NULL) {
682         NSPasteboard *pb = [NSPasteboard generalPasteboard];
683         NSArray *a = [NSArray arrayWithObject:NSStringPboardType];
684         [pb declareTypes:a owner:nil];
685         [pb setString:[NSString stringWithCString:text]
686          forType:NSStringPboardType];
687     } else
688         NSBeep();
689 }
690
691 - (void)solveGame:(id)sender
692 {
693     char *msg;
694     NSAlert *alert;
695
696     msg = midend_solve(me);
697
698     if (msg) {
699         alert = [[[NSAlert alloc] init] autorelease];
700         [alert addButtonWithTitle:@"Bah"];
701         [alert setInformativeText:[NSString stringWithCString:msg]];
702         [alert beginSheetModalForWindow:self modalDelegate:nil
703          didEndSelector:nil contextInfo:nil];
704     }
705 }
706
707 - (BOOL)validateMenuItem:(NSMenuItem *)item
708 {
709     if ([item action] == @selector(copy:))
710         return (ourgame->can_format_as_text ? YES : NO);
711     else if ([item action] == @selector(solveGame:))
712         return (ourgame->can_solve ? YES : NO);
713     else
714         return [super validateMenuItem:item];
715 }
716
717 - (void)clearTypeMenu
718 {
719     while ([typemenu numberOfItems] > 1)
720         [typemenu removeItemAtIndex:0];
721 }
722
723 - (void)becomeKeyWindow
724 {
725     int n;
726
727     [self clearTypeMenu];
728
729     [super becomeKeyWindow];
730
731     n = midend_num_presets(me);
732
733     if (n > 0) {
734         [typemenu insertItem:[NSMenuItem separatorItem] atIndex:0];
735         while (n--) {
736             char *name;
737             game_params *params;
738             DataMenuItem *item;
739
740             midend_fetch_preset(me, n, &name, &params);
741
742             item = [[[DataMenuItem alloc]
743                      initWithTitle:[NSString stringWithCString:name]
744                      action:NULL keyEquivalent:@""]
745                     autorelease];
746
747             [item setEnabled:YES];
748             [item setTarget:self];
749             [item setAction:@selector(presetGame:)];
750             [item setPayload:params];
751
752             [typemenu insertItem:item atIndex:0];
753         }
754     }
755 }
756
757 - (void)resignKeyWindow
758 {
759     [self clearTypeMenu];
760     [super resignKeyWindow];
761 }
762
763 - (void)close
764 {
765     [self clearTypeMenu];
766     [super close];
767 }
768
769 - (void)resizeForNewGameParams
770 {
771     NSSize size = {0,0};
772     int w, h;
773
774     midend_size(me, &w, &h);
775     size.width = w;
776     size.height = h;
777
778     if (status) {
779         NSRect frame = [status frame];
780         size.height += frame.size.height;
781         frame.size.width = size.width;
782         [status setFrame:frame];
783     }
784
785     NSDisableScreenUpdates();
786     [self setContentSize:size];
787     [self setupContentView];
788     NSEnableScreenUpdates();
789 }
790
791 - (void)presetGame:(id)sender
792 {
793     game_params *params = [sender getPayload];
794
795     midend_set_params(me, params);
796     midend_new_game(me);
797
798     [self resizeForNewGameParams];
799 }
800
801 - (void)startConfigureSheet:(int)which
802 {
803     NSButton *ok, *cancel;
804     int actw, acth, leftw, rightw, totalw, h, thish, y;
805     int k;
806     NSRect rect, tmprect;
807     const int SPACING = 16;
808     char *title;
809     config_item *i;
810     int cfg_controlsize;
811     NSTextField *tf;
812     NSButton *b;
813     NSPopUpButton *pb;
814
815     assert(sheet == NULL);
816
817     /*
818      * Every control we create here is going to have this size
819      * until we tell it to calculate a better one.
820      */
821     tmprect = NSMakeRect(0, 0, 100, 50);
822
823     /*
824      * Set up OK and Cancel buttons. (Actually, MacOS doesn't seem
825      * to be fond of generic OK and Cancel wording, so I'm going to
826      * rename them to something nicer.)
827      */
828     actw = acth = 0;
829
830     cancel = [[NSButton alloc] initWithFrame:tmprect];
831     [cancel setBezelStyle:NSRoundedBezelStyle];
832     [cancel setTitle:@"Abandon"];
833     [cancel setTarget:self];
834     [cancel setKeyEquivalent:@"\033"];
835     [cancel setAction:@selector(sheetCancelButton:)];
836     [cancel sizeToFit];
837     rect = [cancel frame];
838     if (actw < rect.size.width) actw = rect.size.width;
839     if (acth < rect.size.height) acth = rect.size.height;
840
841     ok = [[NSButton alloc] initWithFrame:tmprect];
842     [ok setBezelStyle:NSRoundedBezelStyle];
843     [ok setTitle:@"Accept"];
844     [ok setTarget:self];
845     [ok setKeyEquivalent:@"\r"];
846     [ok setAction:@selector(sheetOKButton:)];
847     [ok sizeToFit];
848     rect = [ok frame];
849     if (actw < rect.size.width) actw = rect.size.width;
850     if (acth < rect.size.height) acth = rect.size.height;
851
852     totalw = SPACING + 2 * actw;
853     h = 2 * SPACING + acth;
854
855     /*
856      * Now fetch the midend config data and go through it creating
857      * controls.
858      */
859     cfg = midend_get_config(me, which, &title);
860     sfree(title);                      /* FIXME: should we use this somehow? */
861     cfg_which = which;
862
863     cfg_ncontrols = cfg_controlsize = 0;
864     cfg_controls = NULL;
865     leftw = rightw = 0;
866     for (i = cfg; i->type != C_END; i++) {
867         if (cfg_controlsize < cfg_ncontrols + 5) {
868             cfg_controlsize = cfg_ncontrols + 32;
869             cfg_controls = sresize(cfg_controls, cfg_controlsize, NSView *);
870         }
871
872         thish = 0;
873
874         switch (i->type) {
875           case C_STRING:
876             /*
877              * Two NSTextFields, one being a label and the other
878              * being an edit box.
879              */
880
881             tf = [[NSTextField alloc] initWithFrame:tmprect];
882             [tf setEditable:NO];
883             [tf setSelectable:NO];
884             [tf setBordered:NO];
885             [tf setDrawsBackground:NO];
886             [[tf cell] setTitle:[NSString stringWithCString:i->name]];
887             [tf sizeToFit];
888             rect = [tf frame];
889             if (thish < rect.size.height + 1) thish = rect.size.height + 1;
890             if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
891             cfg_controls[cfg_ncontrols++] = tf;
892
893             tf = [[NSTextField alloc] initWithFrame:tmprect];
894             [tf setEditable:YES];
895             [tf setSelectable:YES];
896             [tf setBordered:YES];
897             [[tf cell] setTitle:[NSString stringWithCString:i->sval]];
898             [tf sizeToFit];
899             rect = [tf frame];
900             /*
901              * We impose a minimum and maximum width on editable
902              * NSTextFields. If we allow them to size themselves to
903              * the contents of the text within them, then they will
904              * look very silly if that text is only one or two
905              * characters, and equally silly if it's an absolutely
906              * enormous Rectangles or Pattern game ID!
907              */
908             if (rect.size.width < 75) rect.size.width = 75;
909             if (rect.size.width > 400) rect.size.width = 400;
910
911             if (thish < rect.size.height + 1) thish = rect.size.height + 1;
912             if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
913             cfg_controls[cfg_ncontrols++] = tf;
914             break;
915
916           case C_BOOLEAN:
917             /*
918              * A checkbox is an NSButton with a type of
919              * NSSwitchButton.
920              */
921             b = [[NSButton alloc] initWithFrame:tmprect];
922             [b setBezelStyle:NSRoundedBezelStyle];
923             [b setButtonType:NSSwitchButton];
924             [b setTitle:[NSString stringWithCString:i->name]];
925             [b sizeToFit];
926             [b setState:(i->ival ? NSOnState : NSOffState)];
927             rect = [b frame];
928             if (totalw < rect.size.width + 1) totalw = rect.size.width + 1;
929             if (thish < rect.size.height + 1) thish = rect.size.height + 1;
930             cfg_controls[cfg_ncontrols++] = b;
931             break;
932
933           case C_CHOICES:
934             /*
935              * A pop-up menu control is an NSPopUpButton, which
936              * takes an embedded NSMenu. We also need an
937              * NSTextField to act as a label.
938              */
939
940             tf = [[NSTextField alloc] initWithFrame:tmprect];
941             [tf setEditable:NO];
942             [tf setSelectable:NO];
943             [tf setBordered:NO];
944             [tf setDrawsBackground:NO];
945             [[tf cell] setTitle:[NSString stringWithCString:i->name]];
946             [tf sizeToFit];
947             rect = [tf frame];
948             if (thish < rect.size.height + 1) thish = rect.size.height + 1;
949             if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
950             cfg_controls[cfg_ncontrols++] = tf;
951
952             pb = [[NSPopUpButton alloc] initWithFrame:tmprect pullsDown:NO];
953             [pb setBezelStyle:NSRoundedBezelStyle];
954             {
955                 char c, *p;
956
957                 p = i->sval;
958                 c = *p++;
959                 while (*p) {
960                     char *q;
961
962                     q = p;
963                     while (*p && *p != c) p++;
964
965                     [pb addItemWithTitle:[NSString stringWithCString:q
966                                           length:p-q]];
967
968                     if (*p) p++;
969                 }
970             }
971             [pb selectItemAtIndex:i->ival];
972             [pb sizeToFit];
973
974             rect = [pb frame];
975             if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
976             if (thish < rect.size.height + 1) thish = rect.size.height + 1;
977             cfg_controls[cfg_ncontrols++] = pb;
978             break;
979         }
980
981         h += SPACING + thish;
982     }
983
984     if (totalw < leftw + SPACING + rightw)
985         totalw = leftw + SPACING + rightw;
986     if (totalw > leftw + SPACING + rightw) {
987         int excess = totalw - (leftw + SPACING + rightw);
988         int leftexcess = leftw * excess / (leftw + rightw);
989         int rightexcess = excess - leftexcess;
990         leftw += leftexcess;
991         rightw += rightexcess;
992     }
993
994     /*
995      * Now go through the list again, setting the final position
996      * for each control.
997      */
998     k = 0;
999     y = h;
1000     for (i = cfg; i->type != C_END; i++) {
1001         y -= SPACING;
1002         thish = 0;
1003         switch (i->type) {
1004           case C_STRING:
1005           case C_CHOICES:
1006             /*
1007              * These two are treated identically, since both expect
1008              * a control on the left and another on the right.
1009              */
1010             rect = [cfg_controls[k] frame];
1011             if (thish < rect.size.height + 1)
1012                 thish = rect.size.height + 1;
1013             rect = [cfg_controls[k+1] frame];
1014             if (thish < rect.size.height + 1)
1015                 thish = rect.size.height + 1;
1016             rect = [cfg_controls[k] frame];
1017             rect.origin.y = y - thish/2 - rect.size.height/2;
1018             rect.origin.x = SPACING;
1019             rect.size.width = leftw;
1020             [cfg_controls[k] setFrame:rect];
1021             rect = [cfg_controls[k+1] frame];
1022             rect.origin.y = y - thish/2 - rect.size.height/2;
1023             rect.origin.x = 2 * SPACING + leftw;
1024             rect.size.width = rightw;
1025             [cfg_controls[k+1] setFrame:rect];
1026             k += 2;
1027             break;
1028
1029           case C_BOOLEAN:
1030             rect = [cfg_controls[k] frame];
1031             if (thish < rect.size.height + 1)
1032                 thish = rect.size.height + 1;
1033             rect.origin.y = y - thish/2 - rect.size.height/2;
1034             rect.origin.x = SPACING;
1035             rect.size.width = totalw;
1036             [cfg_controls[k] setFrame:rect];
1037             k++;
1038             break;
1039         }
1040         y -= thish;
1041     }
1042
1043     assert(k == cfg_ncontrols);
1044
1045     [cancel setFrame:NSMakeRect(SPACING+totalw/4-actw/2, SPACING, actw, acth)];
1046     [ok setFrame:NSMakeRect(SPACING+3*totalw/4-actw/2, SPACING, actw, acth)];
1047
1048     sheet = [[NSWindow alloc]
1049              initWithContentRect:NSMakeRect(0,0,totalw + 2*SPACING,h)
1050              styleMask:NSTitledWindowMask | NSClosableWindowMask
1051              backing:NSBackingStoreBuffered
1052              defer:YES];
1053
1054     [[sheet contentView] addSubview:cancel];
1055     [[sheet contentView] addSubview:ok];
1056
1057     for (k = 0; k < cfg_ncontrols; k++)
1058         [[sheet contentView] addSubview:cfg_controls[k]];
1059
1060     [NSApp beginSheet:sheet modalForWindow:self
1061      modalDelegate:nil didEndSelector:nil contextInfo:nil];
1062 }
1063
1064 - (void)specificGame:(id)sender
1065 {
1066     [self startConfigureSheet:CFG_DESC];
1067 }
1068
1069 - (void)specificRandomGame:(id)sender
1070 {
1071     [self startConfigureSheet:CFG_SEED];
1072 }
1073
1074 - (void)customGameType:(id)sender
1075 {
1076     [self startConfigureSheet:CFG_SETTINGS];
1077 }
1078
1079 - (void)sheetEndWithStatus:(BOOL)update
1080 {
1081     assert(sheet != NULL);
1082     [NSApp endSheet:sheet];
1083     [sheet orderOut:self];
1084     sheet = NULL;
1085     if (update) {
1086         int k;
1087         config_item *i;
1088         char *error;
1089
1090         k = 0;
1091         for (i = cfg; i->type != C_END; i++) {
1092             switch (i->type) {
1093               case C_STRING:
1094                 sfree(i->sval);
1095                 i->sval = dupstr([[[(id)cfg_controls[k+1] cell]
1096                                    title] cString]);
1097                 k += 2;
1098                 break;
1099               case C_BOOLEAN:
1100                 i->ival = [(id)cfg_controls[k] state] == NSOnState;
1101                 k++;
1102                 break;
1103               case C_CHOICES:
1104                 i->ival = [(id)cfg_controls[k+1] indexOfSelectedItem];
1105                 k += 2;
1106                 break;
1107             }
1108         }
1109
1110         error = midend_set_config(me, cfg_which, cfg);
1111         if (error) {
1112             NSAlert *alert = [[[NSAlert alloc] init] autorelease];
1113             [alert addButtonWithTitle:@"Bah"];
1114             [alert setInformativeText:[NSString stringWithCString:error]];
1115             [alert beginSheetModalForWindow:self modalDelegate:nil
1116              didEndSelector:nil contextInfo:nil];
1117         } else {
1118             midend_new_game(me);
1119             [self resizeForNewGameParams];
1120         }
1121     }
1122     sfree(cfg_controls);
1123     cfg_controls = NULL;
1124 }
1125 - (void)sheetOKButton:(id)sender
1126 {
1127     [self sheetEndWithStatus:YES];
1128 }
1129 - (void)sheetCancelButton:(id)sender
1130 {
1131     [self sheetEndWithStatus:NO];
1132 }
1133
1134 - (void)setStatusLine:(NSString *)text
1135 {
1136     [[status cell] setTitle:text];
1137 }
1138
1139 @end
1140
1141 /*
1142  * Drawing routines called by the midend.
1143  */
1144 void draw_polygon(frontend *fe, int *coords, int npoints,
1145                   int fill, int colour)
1146 {
1147     NSBezierPath *path = [NSBezierPath bezierPath];
1148     int i;
1149
1150     [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1151
1152     assert(colour >= 0 && colour < fe->ncolours);
1153     [fe->colours[colour] set];
1154
1155     for (i = 0; i < npoints; i++) {
1156         NSPoint p = { coords[i*2] + 0.5, coords[i*2+1] + 0.5 };
1157         if (i == 0)
1158             [path moveToPoint:p];
1159         else
1160             [path lineToPoint:p];
1161     }
1162
1163     [path closePath];
1164
1165     if (fill)
1166         [path fill];
1167     else
1168         [path stroke];
1169 }
1170 void draw_line(frontend *fe, int x1, int y1, int x2, int y2, int colour)
1171 {
1172     NSBezierPath *path = [NSBezierPath bezierPath];
1173     NSPoint p1 = { x1 + 0.5, y1 + 0.5 }, p2 = { x2 + 0.5, y2 + 0.5 };
1174
1175     [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1176
1177     assert(colour >= 0 && colour < fe->ncolours);
1178     [fe->colours[colour] set];
1179
1180     [path moveToPoint:p1];
1181     [path lineToPoint:p2];
1182     [path stroke];
1183 }
1184 void draw_rect(frontend *fe, int x, int y, int w, int h, int colour)
1185 {
1186     NSRect r = { {x,y}, {w,h} };
1187
1188     [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1189
1190     assert(colour >= 0 && colour < fe->ncolours);
1191     [fe->colours[colour] set];
1192
1193     NSRectFill(r);
1194 }
1195 void draw_text(frontend *fe, int x, int y, int fonttype, int fontsize,
1196                int align, int colour, char *text)
1197 {
1198     NSString *string = [NSString stringWithCString:text];
1199     NSDictionary *attr;
1200     NSFont *font;
1201     NSSize size;
1202     NSPoint point;
1203
1204     [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1205
1206     assert(colour >= 0 && colour < fe->ncolours);
1207
1208     if (fonttype == FONT_FIXED)
1209         font = [NSFont userFixedPitchFontOfSize:fontsize];
1210     else
1211         font = [NSFont userFontOfSize:fontsize];
1212
1213     attr = [NSDictionary dictionaryWithObjectsAndKeys:
1214             fe->colours[colour], NSForegroundColorAttributeName,
1215             font, NSFontAttributeName, nil];
1216
1217     point.x = x;
1218     point.y = y;
1219
1220     size = [string sizeWithAttributes:attr];
1221     if (align & ALIGN_HRIGHT)
1222         point.x -= size.width;
1223     else if (align & ALIGN_HCENTRE)
1224         point.x -= size.width / 2;
1225     if (align & ALIGN_VCENTRE)
1226         point.y -= size.height / 2;
1227
1228     [string drawAtPoint:point withAttributes:attr];
1229 }
1230 void draw_update(frontend *fe, int x, int y, int w, int h)
1231 {
1232     [fe->view setNeedsDisplayInRect:NSMakeRect(x,y,w,h)];
1233 }
1234 void clip(frontend *fe, int x, int y, int w, int h)
1235 {
1236     NSRect r = { {x,y}, {w,h} };
1237
1238     if (!fe->clipped)
1239         [[NSGraphicsContext currentContext] saveGraphicsState];
1240     [NSBezierPath clipRect:r];
1241     fe->clipped = TRUE;
1242 }
1243 void unclip(frontend *fe)
1244 {
1245     if (fe->clipped)
1246         [[NSGraphicsContext currentContext] restoreGraphicsState];
1247     fe->clipped = FALSE;
1248 }
1249 void start_draw(frontend *fe)
1250 {
1251     [fe->image lockFocus];
1252     fe->clipped = FALSE;
1253 }
1254 void end_draw(frontend *fe)
1255 {
1256     [fe->image unlockFocus];
1257 }
1258
1259 void deactivate_timer(frontend *fe)
1260 {
1261     [fe->window deactivateTimer];
1262 }
1263 void activate_timer(frontend *fe)
1264 {
1265     [fe->window activateTimer];
1266 }
1267
1268 void status_bar(frontend *fe, char *text)
1269 {
1270     [fe->window setStatusLine:[NSString stringWithCString:text]];
1271 }
1272
1273 /* ----------------------------------------------------------------------
1274  * AppController: the object which receives the messages from all
1275  * menu selections that aren't standard OS X functions.
1276  */
1277 @interface AppController : NSObject
1278 {
1279 }
1280 - (void)newGameWindow:(id)sender;
1281 - (void)about:(id)sender;
1282 @end
1283
1284 @implementation AppController
1285
1286 - (void)newGameWindow:(id)sender
1287 {
1288     const game *g = [sender getPayload];
1289     id win;
1290
1291     win = [[GameWindow alloc] initWithGame:g];
1292     [win makeKeyAndOrderFront:self];
1293 }
1294
1295 - (void)about:(id)sender
1296 {
1297     id win;
1298
1299     win = [[AboutBox alloc] init];
1300     [win makeKeyAndOrderFront:self];    
1301 }
1302
1303 - (NSMenu *)applicationDockMenu:(NSApplication *)sender
1304 {
1305     NSMenu *menu = newmenu("Dock Menu");
1306     {
1307         int i;
1308
1309         for (i = 0; i < gamecount; i++) {
1310             id item =
1311                 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1312                             menu, gamelist[i]->name, "", self,
1313                             @selector(newGameWindow:));
1314             [item setPayload:(void *)gamelist[i]];
1315         }
1316     }
1317     return menu;
1318 }
1319
1320 @end
1321
1322 /* ----------------------------------------------------------------------
1323  * Main program. Constructs the menus and runs the application.
1324  */
1325 int main(int argc, char **argv)
1326 {
1327     NSAutoreleasePool *pool;
1328     NSMenu *menu;
1329     NSMenuItem *item;
1330     AppController *controller;
1331     NSImage *icon;
1332
1333     pool = [[NSAutoreleasePool alloc] init];
1334
1335     icon = [NSImage imageNamed:@"NSApplicationIcon"];
1336     [NSApplication sharedApplication];
1337     [NSApp setApplicationIconImage:icon];
1338
1339     controller = [[[AppController alloc] init] autorelease];
1340     [NSApp setDelegate:controller];
1341
1342     [NSApp setMainMenu: newmenu("Main Menu")];
1343
1344     menu = newsubmenu([NSApp mainMenu], "Apple Menu");
1345     item = newitem(menu, "About Puzzles", "", NULL, @selector(about:));
1346     [menu addItem:[NSMenuItem separatorItem]];
1347     [NSApp setServicesMenu:newsubmenu(menu, "Services")];
1348     [menu addItem:[NSMenuItem separatorItem]];
1349     item = newitem(menu, "Hide Puzzles", "h", NSApp, @selector(hide:));
1350     item = newitem(menu, "Hide Others", "o-h", NSApp, @selector(hideOtherApplications:));
1351     item = newitem(menu, "Show All", "", NSApp, @selector(unhideAllApplications:));
1352     [menu addItem:[NSMenuItem separatorItem]];
1353     item = newitem(menu, "Quit", "q", NSApp, @selector(terminate:));
1354     [NSApp setAppleMenu: menu];
1355
1356     menu = newsubmenu([NSApp mainMenu], "File");
1357     item = newitem(menu, "New Game", "n", NULL, @selector(newGame:));
1358     item = newitem(menu, "Restart Game", "r", NULL, @selector(restartGame:));
1359     item = newitem(menu, "Specific Game", "", NULL, @selector(specificGame:));
1360     item = newitem(menu, "Specific Random Seed", "", NULL,
1361                    @selector(specificRandomGame:));
1362     [menu addItem:[NSMenuItem separatorItem]];
1363     {
1364         NSMenu *submenu = newsubmenu(menu, "New Window");
1365         int i;
1366
1367         for (i = 0; i < gamecount; i++) {
1368             id item =
1369                 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1370                             submenu, gamelist[i]->name, "", controller,
1371                             @selector(newGameWindow:));
1372             [item setPayload:(void *)gamelist[i]];
1373         }
1374     }
1375     [menu addItem:[NSMenuItem separatorItem]];
1376     item = newitem(menu, "Close", "w", NULL, @selector(performClose:));
1377
1378     menu = newsubmenu([NSApp mainMenu], "Edit");
1379     item = newitem(menu, "Undo", "z", NULL, @selector(undoMove:));
1380     item = newitem(menu, "Redo", "S-z", NULL, @selector(redoMove:));
1381     [menu addItem:[NSMenuItem separatorItem]];
1382     item = newitem(menu, "Cut", "x", NULL, @selector(cut:));
1383     item = newitem(menu, "Copy", "c", NULL, @selector(copy:));
1384     item = newitem(menu, "Paste", "v", NULL, @selector(paste:));
1385     [menu addItem:[NSMenuItem separatorItem]];
1386     item = newitem(menu, "Solve", "S-s", NULL, @selector(solveGame:));
1387
1388     menu = newsubmenu([NSApp mainMenu], "Type");
1389     typemenu = menu;
1390     item = newitem(menu, "Custom", "", NULL, @selector(customGameType:));
1391
1392     menu = newsubmenu([NSApp mainMenu], "Window");
1393     [NSApp setWindowsMenu: menu];
1394     item = newitem(menu, "Minimise Window", "m", NULL, @selector(performMiniaturize:));
1395
1396     menu = newsubmenu([NSApp mainMenu], "Help");
1397     item = newitem(menu, "Puzzles Help", "?", NSApp, @selector(showHelp:));
1398
1399     [NSApp run];
1400     [pool release];
1401 }