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