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