chiark / gitweb /
Implement osx_draw_thick_line
[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 #define COMBINED /* we put all the puzzles in one binary in this port */
81
82 #include <ctype.h>
83 #include <time.h>
84 #include <sys/time.h>
85 #import <Cocoa/Cocoa.h>
86 #include "puzzles.h"
87
88 /* ----------------------------------------------------------------------
89  * Global variables.
90  */
91
92 /*
93  * The `Type' menu. We frob this dynamically to allow the user to
94  * choose a preset set of settings from the current game.
95  */
96 NSMenu *typemenu;
97
98 /*
99  * Forward reference.
100  */
101 extern const struct drawing_api osx_drawing;
102
103 /*
104  * The NSApplication shared instance, which I'll want to refer to from
105  * a few places here and there.
106  */
107 NSApplication *app;
108
109 /* ----------------------------------------------------------------------
110  * Miscellaneous support routines that aren't part of any object or
111  * clearly defined subsystem.
112  */
113
114 void fatal(char *fmt, ...)
115 {
116     va_list ap;
117     char errorbuf[2048];
118     NSAlert *alert;
119
120     va_start(ap, fmt);
121     vsnprintf(errorbuf, lenof(errorbuf), fmt, ap);
122     va_end(ap);
123
124     alert = [NSAlert alloc];
125     /*
126      * We may have come here because we ran out of memory, in which
127      * case it's entirely likely that that alloc will fail, so we
128      * should have a fallback of some sort.
129      */
130     if (!alert) {
131         fprintf(stderr, "fatal error (and NSAlert failed): %s\n", errorbuf);
132     } else {
133         alert = [[alert init] autorelease];
134         [alert addButtonWithTitle:@"Oh dear"];
135         [alert setInformativeText:[NSString stringWithUTF8String:errorbuf]];
136         [alert runModal];
137     }
138     exit(1);
139 }
140
141 void frontend_default_colour(frontend *fe, float *output)
142 {
143     /* FIXME: Is there a system default we can tap into for this? */
144     output[0] = output[1] = output[2] = 0.8F;
145 }
146
147 void get_random_seed(void **randseed, int *randseedsize)
148 {
149     time_t *tp = snew(time_t);
150     time(tp);
151     *randseed = (void *)tp;
152     *randseedsize = sizeof(time_t);
153 }
154
155 static void savefile_write(void *wctx, void *buf, int len)
156 {
157     FILE *fp = (FILE *)wctx;
158     fwrite(buf, 1, len, fp);
159 }
160
161 static int savefile_read(void *wctx, void *buf, int len)
162 {
163     FILE *fp = (FILE *)wctx;
164     int ret;
165
166     ret = fread(buf, 1, len, fp);
167     return (ret == len);
168 }
169
170 /*
171  * Since this front end does not support printing (yet), we need
172  * this stub to satisfy the reference in midend_print_puzzle().
173  */
174 void document_add_puzzle(document *doc, const game *game, game_params *par,
175                          game_state *st, game_state *st2)
176 {
177 }
178
179 /*
180  * setAppleMenu isn't listed in the NSApplication header, but an
181  * NSApp responds to it, so we're adding it here to silence
182  * warnings. (This was removed from the headers in 10.4, so we
183  * only need to include it for 10.4+.)
184  */
185 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1040
186 @interface NSApplication(NSAppleMenu)
187 - (void)setAppleMenu:(NSMenu *)menu;
188 @end
189 #endif
190
191 /* ----------------------------------------------------------------------
192  * Tiny extension to NSMenuItem which carries a payload of a `void
193  * *', allowing several menu items to invoke the same message but
194  * pass different data through it.
195  */
196 @interface DataMenuItem : NSMenuItem
197 {
198     void *payload;
199 }
200 - (void)setPayload:(void *)d;
201 - (void *)getPayload;
202 @end
203 @implementation DataMenuItem
204 - (void)setPayload:(void *)d
205 {
206     payload = d;
207 }
208 - (void *)getPayload
209 {
210     return payload;
211 }
212 @end
213
214 /* ----------------------------------------------------------------------
215  * Utility routines for constructing OS X menus.
216  */
217
218 NSMenu *newmenu(const char *title)
219 {
220     return [[[NSMenu allocWithZone:[NSMenu menuZone]]
221              initWithTitle:[NSString stringWithUTF8String:title]]
222             autorelease];
223 }
224
225 NSMenu *newsubmenu(NSMenu *parent, const char *title)
226 {
227     NSMenuItem *item;
228     NSMenu *child;
229
230     item = [[[NSMenuItem allocWithZone:[NSMenu menuZone]]
231              initWithTitle:[NSString stringWithUTF8String:title]
232              action:NULL
233              keyEquivalent:@""]
234             autorelease];
235     child = newmenu(title);
236     [item setEnabled:YES];
237     [item setSubmenu:child];
238     [parent addItem:item];
239     return child;
240 }
241
242 id initnewitem(NSMenuItem *item, NSMenu *parent, const char *title,
243                const char *key, id target, SEL action)
244 {
245     unsigned mask = NSCommandKeyMask;
246
247     if (key[strcspn(key, "-")]) {
248         while (*key && *key != '-') {
249             int c = tolower((unsigned char)*key);
250             if (c == 's') {
251                 mask |= NSShiftKeyMask;
252             } else if (c == 'o' || c == 'a') {
253                 mask |= NSAlternateKeyMask;
254             }
255             key++;
256         }
257         if (*key)
258             key++;
259     }
260
261     item = [[item initWithTitle:[NSString stringWithUTF8String:title]
262              action:NULL
263              keyEquivalent:[NSString stringWithUTF8String:key]]
264             autorelease];
265
266     if (*key)
267         [item setKeyEquivalentModifierMask: mask];
268
269     [item setEnabled:YES];
270     [item setTarget:target];
271     [item setAction:action];
272
273     [parent addItem:item];
274
275     return item;
276 }
277
278 NSMenuItem *newitem(NSMenu *parent, char *title, char *key,
279                     id target, SEL action)
280 {
281     return initnewitem([NSMenuItem allocWithZone:[NSMenu menuZone]],
282                        parent, title, key, target, action);
283 }
284
285 /* ----------------------------------------------------------------------
286  * About box.
287  */
288
289 @class AboutBox;
290
291 @interface AboutBox : NSWindow
292 {
293 }
294 - (id)init;
295 @end
296
297 @implementation AboutBox
298 - (id)init
299 {
300     NSRect totalrect;
301     NSView *views[16];
302     int nviews = 0;
303     NSImageView *iv;
304     NSTextField *tf;
305     NSFont *font1 = [NSFont systemFontOfSize:0];
306     NSFont *font2 = [NSFont boldSystemFontOfSize:[font1 pointSize] * 1.1];
307     const int border = 24;
308     int i;
309     double y;
310
311     /*
312      * Construct the controls that go in the About box.
313      */
314
315     iv = [[NSImageView alloc] initWithFrame:NSMakeRect(0,0,64,64)];
316     [iv setImage:[NSImage imageNamed:@"NSApplicationIcon"]];
317     views[nviews++] = iv;
318
319     tf = [[NSTextField alloc]
320           initWithFrame:NSMakeRect(0,0,400,1)];
321     [tf setEditable:NO];
322     [tf setSelectable:NO];
323     [tf setBordered:NO];
324     [tf setDrawsBackground:NO];
325     [tf setFont:font2];
326     [tf setStringValue:@"Simon Tatham's Portable Puzzle Collection"];
327     [tf sizeToFit];
328     views[nviews++] = tf;
329
330     tf = [[NSTextField alloc]
331           initWithFrame:NSMakeRect(0,0,400,1)];
332     [tf setEditable:NO];
333     [tf setSelectable:NO];
334     [tf setBordered:NO];
335     [tf setDrawsBackground:NO];
336     [tf setFont:font1];
337     [tf setStringValue:[NSString stringWithUTF8String:ver]];
338     [tf sizeToFit];
339     views[nviews++] = tf;
340
341     /*
342      * Lay the controls out.
343      */
344     totalrect = NSMakeRect(0,0,0,0);
345     for (i = 0; i < nviews; i++) {
346         NSRect r = [views[i] frame];
347         if (totalrect.size.width < r.size.width)
348             totalrect.size.width = r.size.width;
349         totalrect.size.height += border + r.size.height;
350     }
351     totalrect.size.width += 2 * border;
352     totalrect.size.height += border;
353     y = totalrect.size.height;
354     for (i = 0; i < nviews; i++) {
355         NSRect r = [views[i] frame];
356         r.origin.x = (totalrect.size.width - r.size.width) / 2;
357         y -= border + r.size.height;
358         r.origin.y = y;
359         [views[i] setFrame:r];
360     }
361
362     self = [super initWithContentRect:totalrect
363             styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
364                        NSClosableWindowMask)
365             backing:NSBackingStoreBuffered
366             defer:YES];
367
368     for (i = 0; i < nviews; i++)
369         [[self contentView] addSubview:views[i]];
370
371     [self center];                     /* :-) */
372
373     return self;
374 }
375 @end
376
377 /* ----------------------------------------------------------------------
378  * The front end presented to midend.c.
379  * 
380  * This is mostly a subclass of NSWindow. The actual `frontend'
381  * structure passed to the midend contains a variety of pointers,
382  * including that window object but also including the image we
383  * draw on, an ImageView to display it in the window, and so on.
384  */
385
386 @class GameWindow;
387 @class MyImageView;
388
389 struct frontend {
390     GameWindow *window;
391     NSImage *image;
392     MyImageView *view;
393     NSColor **colours;
394     int ncolours;
395     int clipped;
396     int w, h;
397 };
398
399 @interface MyImageView : NSImageView
400 {
401     GameWindow *ourwin;
402 }
403 - (void)setWindow:(GameWindow *)win;
404 - (void)mouseEvent:(NSEvent *)ev button:(int)b;
405 - (void)mouseDown:(NSEvent *)ev;
406 - (void)mouseDragged:(NSEvent *)ev;
407 - (void)mouseUp:(NSEvent *)ev;
408 - (void)rightMouseDown:(NSEvent *)ev;
409 - (void)rightMouseDragged:(NSEvent *)ev;
410 - (void)rightMouseUp:(NSEvent *)ev;
411 - (void)otherMouseDown:(NSEvent *)ev;
412 - (void)otherMouseDragged:(NSEvent *)ev;
413 - (void)otherMouseUp:(NSEvent *)ev;
414 @end
415
416 @interface GameWindow : NSWindow
417 {
418     const game *ourgame;
419     midend *me;
420     struct frontend fe;
421     struct timeval last_time;
422     NSTimer *timer;
423     NSWindow *sheet;
424     config_item *cfg;
425     int cfg_which;
426     NSView **cfg_controls;
427     int cfg_ncontrols;
428     NSTextField *status;
429 }
430 - (id)initWithGame:(const game *)g;
431 - (void)dealloc;
432 - (void)processButton:(int)b x:(int)x y:(int)y;
433 - (void)processKey:(int)b;
434 - (void)keyDown:(NSEvent *)ev;
435 - (void)activateTimer;
436 - (void)deactivateTimer;
437 - (void)setStatusLine:(char *)text;
438 - (void)resizeForNewGameParams;
439 - (void)updateTypeMenuTick;
440 @end
441
442 @implementation MyImageView
443
444 - (void)setWindow:(GameWindow *)win
445 {
446     ourwin = win;
447 }
448
449 - (void)mouseEvent:(NSEvent *)ev button:(int)b
450 {
451     NSPoint point = [self convertPoint:[ev locationInWindow] fromView:nil];
452     [ourwin processButton:b x:point.x y:point.y];
453 }
454
455 - (void)mouseDown:(NSEvent *)ev
456 {
457     unsigned mod = [ev modifierFlags];
458     [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_BUTTON :
459                                 (mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
460                                 LEFT_BUTTON)];
461 }
462 - (void)mouseDragged:(NSEvent *)ev
463 {
464     unsigned mod = [ev modifierFlags];
465     [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_DRAG :
466                                 (mod & NSShiftKeyMask) ? MIDDLE_DRAG :
467                                 LEFT_DRAG)];
468 }
469 - (void)mouseUp:(NSEvent *)ev
470 {
471     unsigned mod = [ev modifierFlags];
472     [self mouseEvent:ev button:((mod & NSCommandKeyMask) ? RIGHT_RELEASE :
473                                 (mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
474                                 LEFT_RELEASE)];
475 }
476 - (void)rightMouseDown:(NSEvent *)ev
477 {
478     unsigned mod = [ev modifierFlags];
479     [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_BUTTON :
480                                 RIGHT_BUTTON)];
481 }
482 - (void)rightMouseDragged:(NSEvent *)ev
483 {
484     unsigned mod = [ev modifierFlags];
485     [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_DRAG :
486                                 RIGHT_DRAG)];
487 }
488 - (void)rightMouseUp:(NSEvent *)ev
489 {
490     unsigned mod = [ev modifierFlags];
491     [self mouseEvent:ev button:((mod & NSShiftKeyMask) ? MIDDLE_RELEASE :
492                                 RIGHT_RELEASE)];
493 }
494 - (void)otherMouseDown:(NSEvent *)ev
495 {
496     [self mouseEvent:ev button:MIDDLE_BUTTON];
497 }
498 - (void)otherMouseDragged:(NSEvent *)ev
499 {
500     [self mouseEvent:ev button:MIDDLE_DRAG];
501 }
502 - (void)otherMouseUp:(NSEvent *)ev
503 {
504     [self mouseEvent:ev button:MIDDLE_RELEASE];
505 }
506 @end
507
508 @implementation GameWindow
509 - (void)setupContentView
510 {
511     NSRect frame;
512     int w, h;
513
514     if (status) {
515         frame = [status frame];
516         frame.origin.y = frame.size.height;
517     } else
518         frame.origin.y = 0;
519     frame.origin.x = 0;
520
521     w = h = INT_MAX;
522     midend_size(me, &w, &h, FALSE);
523     frame.size.width = w;
524     frame.size.height = h;
525     fe.w = w;
526     fe.h = h;
527
528     fe.image = [[NSImage alloc] initWithSize:frame.size];
529     fe.view = [[MyImageView alloc] initWithFrame:frame];
530     [fe.view setImage:fe.image];
531     [fe.view setWindow:self];
532
533     midend_redraw(me);
534
535     [[self contentView] addSubview:fe.view];
536 }
537 - (id)initWithGame:(const game *)g
538 {
539     NSRect rect = { {0,0}, {0,0} }, rect2;
540     int w, h;
541
542     ourgame = g;
543
544     fe.window = self;
545
546     me = midend_new(&fe, ourgame, &osx_drawing, &fe);
547     /*
548      * If we ever need to open a fresh window using a provided game
549      * ID, I think the right thing is to move most of this method
550      * into a new initWithGame:gameID: method, and have
551      * initWithGame: simply call that one and pass it NULL.
552      */
553     midend_new_game(me);
554     w = h = INT_MAX;
555     midend_size(me, &w, &h, FALSE);
556     rect.size.width = w;
557     rect.size.height = h;
558     fe.w = w;
559     fe.h = h;
560
561     /*
562      * Create the status bar, which will just be an NSTextField.
563      */
564     if (midend_wants_statusbar(me)) {
565         status = [[NSTextField alloc] initWithFrame:NSMakeRect(0,0,100,50)];
566         [status setEditable:NO];
567         [status setSelectable:NO];
568         [status setBordered:YES];
569         [status setBezeled:YES];
570         [status setBezelStyle:NSTextFieldSquareBezel];
571         [status setDrawsBackground:YES];
572         [[status cell] setTitle:@""];
573         [status sizeToFit];
574         rect2 = [status frame];
575         rect.size.height += rect2.size.height;
576         rect2.size.width = rect.size.width;
577         rect2.origin.x = rect2.origin.y = 0;
578         [status setFrame:rect2];
579     } else
580         status = nil;
581
582     self = [super initWithContentRect:rect
583             styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
584                        NSClosableWindowMask)
585             backing:NSBackingStoreBuffered
586             defer:YES];
587     [self setTitle:[NSString stringWithUTF8String:ourgame->name]];
588
589     {
590         float *colours;
591         int i, ncolours;
592
593         colours = midend_colours(me, &ncolours);
594         fe.ncolours = ncolours;
595         fe.colours = snewn(ncolours, NSColor *);
596
597         for (i = 0; i < ncolours; i++) {
598             fe.colours[i] = [[NSColor colorWithDeviceRed:colours[i*3]
599                               green:colours[i*3+1] blue:colours[i*3+2]
600                               alpha:1.0] retain];
601         }
602     }
603
604     [self setupContentView];
605     if (status)
606         [[self contentView] addSubview:status];
607     [self setIgnoresMouseEvents:NO];
608
609     [self center];                     /* :-) */
610
611     return self;
612 }
613
614 - (void)dealloc
615 {
616     int i;
617     for (i = 0; i < fe.ncolours; i++) {
618         [fe.colours[i] release];
619     }
620     sfree(fe.colours);
621     midend_free(me);
622     [super dealloc];
623 }
624
625 - (void)processButton:(int)b x:(int)x y:(int)y
626 {
627     if (!midend_process_key(me, x, fe.h - 1 - y, b))
628         [self close];
629 }
630
631 - (void)processKey:(int)b
632 {
633     if (!midend_process_key(me, -1, -1, b))
634         [self close];
635 }
636
637 - (void)keyDown:(NSEvent *)ev
638 {
639     NSString *s = [ev characters];
640     int i, n = [s length];
641
642     for (i = 0; i < n; i++) {
643         int c = [s characterAtIndex:i];
644
645         /*
646          * ASCII gets passed straight to midend_process_key.
647          * Anything above that has to be translated to our own
648          * function key codes.
649          */
650         if (c >= 0x80) {
651             int mods = FALSE;
652             switch (c) {
653               case NSUpArrowFunctionKey:
654                 c = CURSOR_UP;
655                 mods = TRUE;
656                 break;
657               case NSDownArrowFunctionKey:
658                 c = CURSOR_DOWN;
659                 mods = TRUE;
660                 break;
661               case NSLeftArrowFunctionKey:
662                 c = CURSOR_LEFT;
663                 mods = TRUE;
664                 break;
665               case NSRightArrowFunctionKey:
666                 c = CURSOR_RIGHT;
667                 mods = TRUE;
668                 break;
669               default:
670                 continue;
671             }
672
673             if (mods) {
674                 if ([ev modifierFlags] & NSShiftKeyMask)
675                     c |= MOD_SHFT;
676                 if ([ev modifierFlags] & NSControlKeyMask)
677                     c |= MOD_CTRL;
678             }
679         }
680
681         if (c >= '0' && c <= '9' && ([ev modifierFlags] & NSNumericPadKeyMask))
682             c |= MOD_NUM_KEYPAD;
683
684         [self processKey:c];
685     }
686 }
687
688 - (void)activateTimer
689 {
690     if (timer != nil)
691         return;
692
693     timer = [NSTimer scheduledTimerWithTimeInterval:0.02
694              target:self selector:@selector(timerTick:)
695              userInfo:nil repeats:YES];
696     gettimeofday(&last_time, NULL);
697 }
698
699 - (void)deactivateTimer
700 {
701     if (timer == nil)
702         return;
703
704     [timer invalidate];
705     timer = nil;
706 }
707
708 - (void)timerTick:(id)sender
709 {
710     struct timeval now;
711     float elapsed;
712     gettimeofday(&now, NULL);
713     elapsed = ((now.tv_usec - last_time.tv_usec) * 0.000001F +
714                (now.tv_sec - last_time.tv_sec));
715     midend_timer(me, elapsed);
716     last_time = now;
717 }
718
719 - (void)showError:(char *)message
720 {
721     NSAlert *alert;
722
723     alert = [[[NSAlert alloc] init] autorelease];
724     [alert addButtonWithTitle:@"Bah"];
725     [alert setInformativeText:[NSString stringWithUTF8String:message]];
726     [alert beginSheetModalForWindow:self modalDelegate:nil
727      didEndSelector:NULL contextInfo:nil];
728 }
729
730 - (void)newGame:(id)sender
731 {
732     [self processKey:'n'];
733 }
734 - (void)restartGame:(id)sender
735 {
736     midend_restart_game(me);
737 }
738 - (void)saveGame:(id)sender
739 {
740     NSSavePanel *sp = [NSSavePanel savePanel];
741
742     if ([sp runModal] == NSFileHandlingPanelOKButton) {
743        const char *name = [[sp filename] UTF8String];
744
745         FILE *fp = fopen(name, "w");
746
747         if (!fp) {
748             [self showError:"Unable to open save file"];
749             return;
750         }
751
752         midend_serialise(me, savefile_write, fp);
753
754         fclose(fp);
755     }
756 }
757 - (void)loadSavedGame:(id)sender
758 {
759     NSOpenPanel *op = [NSOpenPanel openPanel];
760
761     [op setAllowsMultipleSelection:NO];
762
763     if ([op runModalForTypes:nil] == NSOKButton) {
764         const char *name = [[[op filenames] objectAtIndex:0] cString];
765         char *err;
766
767         FILE *fp = fopen(name, "r");
768
769         if (!fp) {
770             [self showError:"Unable to open saved game file"];
771             return;
772         }
773
774         err = midend_deserialise(me, savefile_read, fp);
775
776         fclose(fp);
777
778         if (err) {
779             [self showError:err];
780             return;
781         }
782
783         [self resizeForNewGameParams];
784         [self updateTypeMenuTick];
785     }
786 }
787 - (void)undoMove:(id)sender
788 {
789     [self processKey:'u'];
790 }
791 - (void)redoMove:(id)sender
792 {
793     [self processKey:'r'&0x1F];
794 }
795
796 - (void)copy:(id)sender
797 {
798     char *text;
799
800     if ((text = midend_text_format(me)) != NULL) {
801         NSPasteboard *pb = [NSPasteboard generalPasteboard];
802         NSArray *a = [NSArray arrayWithObject:NSStringPboardType];
803         [pb declareTypes:a owner:nil];
804         [pb setString:[NSString stringWithUTF8String:text]
805          forType:NSStringPboardType];
806     } else
807         NSBeep();
808 }
809
810 - (void)solveGame:(id)sender
811 {
812     char *msg;
813
814     msg = midend_solve(me);
815
816     if (msg)
817         [self showError:msg];
818 }
819
820 - (BOOL)validateMenuItem:(NSMenuItem *)item
821 {
822     if ([item action] == @selector(copy:))
823         return (ourgame->can_format_as_text_ever &&
824                 midend_can_format_as_text_now(me) ? YES : NO);
825     else if ([item action] == @selector(solveGame:))
826         return (ourgame->can_solve ? YES : NO);
827     else
828         return [super validateMenuItem:item];
829 }
830
831 - (void)clearTypeMenu
832 {
833     while ([typemenu numberOfItems] > 1)
834         [typemenu removeItemAtIndex:0];
835     [[typemenu itemAtIndex:0] setState:NSOffState];
836 }
837
838 - (void)updateTypeMenuTick
839 {
840     int i, total, n;
841
842     total = [typemenu numberOfItems];
843     n = midend_which_preset(me);
844     if (n < 0)
845         n = total - 1;                 /* that's always where "Custom" lives */
846     for (i = 0; i < total; i++)
847         [[typemenu itemAtIndex:i] setState:(i == n ? NSOnState : NSOffState)];
848 }
849
850 - (void)becomeKeyWindow
851 {
852     int n;
853
854     [self clearTypeMenu];
855
856     [super becomeKeyWindow];
857
858     n = midend_num_presets(me);
859
860     if (n > 0) {
861         [typemenu insertItem:[NSMenuItem separatorItem] atIndex:0];
862         while (n--) {
863             char *name;
864             game_params *params;
865             DataMenuItem *item;
866
867             midend_fetch_preset(me, n, &name, &params);
868
869             item = [[[DataMenuItem alloc]
870                      initWithTitle:[NSString stringWithUTF8String:name]
871                      action:NULL keyEquivalent:@""]
872                     autorelease];
873
874             [item setEnabled:YES];
875             [item setTarget:self];
876             [item setAction:@selector(presetGame:)];
877             [item setPayload:params];
878
879             [typemenu insertItem:item atIndex:0];
880         }
881     }
882
883     [self updateTypeMenuTick];
884 }
885
886 - (void)resignKeyWindow
887 {
888     [self clearTypeMenu];
889     [super resignKeyWindow];
890 }
891
892 - (void)close
893 {
894     [self clearTypeMenu];
895     [super close];
896 }
897
898 - (void)resizeForNewGameParams
899 {
900     NSSize size = {0,0};
901     int w, h;
902
903     w = h = INT_MAX;
904     midend_size(me, &w, &h, FALSE);
905     size.width = w;
906     size.height = h;
907     fe.w = w;
908     fe.h = h;
909
910     if (status) {
911         NSRect frame = [status frame];
912         size.height += frame.size.height;
913         frame.size.width = size.width;
914         [status setFrame:frame];
915     }
916
917 #ifndef GNUSTEP
918     NSDisableScreenUpdates();
919 #endif
920     [self setContentSize:size];
921     [self setupContentView];
922 #ifndef GNUSTEP
923     NSEnableScreenUpdates();
924 #endif
925 }
926
927 - (void)presetGame:(id)sender
928 {
929     game_params *params = [sender getPayload];
930
931     midend_set_params(me, params);
932     midend_new_game(me);
933
934     [self resizeForNewGameParams];
935     [self updateTypeMenuTick];
936 }
937
938 - (void)startConfigureSheet:(int)which
939 {
940     NSButton *ok, *cancel;
941     int actw, acth, leftw, rightw, totalw, h, thish, y;
942     int k;
943     NSRect rect, tmprect;
944     const int SPACING = 16;
945     char *title;
946     config_item *i;
947     int cfg_controlsize;
948     NSTextField *tf;
949     NSButton *b;
950     NSPopUpButton *pb;
951
952     assert(sheet == NULL);
953
954     /*
955      * Every control we create here is going to have this size
956      * until we tell it to calculate a better one.
957      */
958     tmprect = NSMakeRect(0, 0, 100, 50);
959
960     /*
961      * Set up OK and Cancel buttons. (Actually, MacOS doesn't seem
962      * to be fond of generic OK and Cancel wording, so I'm going to
963      * rename them to something nicer.)
964      */
965     actw = acth = 0;
966
967     cancel = [[NSButton alloc] initWithFrame:tmprect];
968     [cancel setBezelStyle:NSRoundedBezelStyle];
969     [cancel setTitle:@"Abandon"];
970     [cancel setTarget:self];
971     [cancel setKeyEquivalent:@"\033"];
972     [cancel setAction:@selector(sheetCancelButton:)];
973     [cancel sizeToFit];
974     rect = [cancel frame];
975     if (actw < rect.size.width) actw = rect.size.width;
976     if (acth < rect.size.height) acth = rect.size.height;
977
978     ok = [[NSButton alloc] initWithFrame:tmprect];
979     [ok setBezelStyle:NSRoundedBezelStyle];
980     [ok setTitle:@"Accept"];
981     [ok setTarget:self];
982     [ok setKeyEquivalent:@"\r"];
983     [ok setAction:@selector(sheetOKButton:)];
984     [ok sizeToFit];
985     rect = [ok frame];
986     if (actw < rect.size.width) actw = rect.size.width;
987     if (acth < rect.size.height) acth = rect.size.height;
988
989     totalw = SPACING + 2 * actw;
990     h = 2 * SPACING + acth;
991
992     /*
993      * Now fetch the midend config data and go through it creating
994      * controls.
995      */
996     cfg = midend_get_config(me, which, &title);
997     sfree(title);                      /* FIXME: should we use this somehow? */
998     cfg_which = which;
999
1000     cfg_ncontrols = cfg_controlsize = 0;
1001     cfg_controls = NULL;
1002     leftw = rightw = 0;
1003     for (i = cfg; i->type != C_END; i++) {
1004         if (cfg_controlsize < cfg_ncontrols + 5) {
1005             cfg_controlsize = cfg_ncontrols + 32;
1006             cfg_controls = sresize(cfg_controls, cfg_controlsize, NSView *);
1007         }
1008
1009         thish = 0;
1010
1011         switch (i->type) {
1012           case C_STRING:
1013             /*
1014              * Two NSTextFields, one being a label and the other
1015              * being an edit box.
1016              */
1017
1018             tf = [[NSTextField alloc] initWithFrame:tmprect];
1019             [tf setEditable:NO];
1020             [tf setSelectable:NO];
1021             [tf setBordered:NO];
1022             [tf setDrawsBackground:NO];
1023             [[tf cell] setTitle:[NSString stringWithUTF8String:i->name]];
1024             [tf sizeToFit];
1025             rect = [tf frame];
1026             if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1027             if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
1028             cfg_controls[cfg_ncontrols++] = tf;
1029
1030             tf = [[NSTextField alloc] initWithFrame:tmprect];
1031             [tf setEditable:YES];
1032             [tf setSelectable:YES];
1033             [tf setBordered:YES];
1034             [[tf cell] setTitle:[NSString stringWithUTF8String:i->sval]];
1035             [tf sizeToFit];
1036             rect = [tf frame];
1037             /*
1038              * We impose a minimum and maximum width on editable
1039              * NSTextFields. If we allow them to size themselves to
1040              * the contents of the text within them, then they will
1041              * look very silly if that text is only one or two
1042              * characters, and equally silly if it's an absolutely
1043              * enormous Rectangles or Pattern game ID!
1044              */
1045             if (rect.size.width < 75) rect.size.width = 75;
1046             if (rect.size.width > 400) rect.size.width = 400;
1047
1048             if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1049             if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
1050             cfg_controls[cfg_ncontrols++] = tf;
1051             break;
1052
1053           case C_BOOLEAN:
1054             /*
1055              * A checkbox is an NSButton with a type of
1056              * NSSwitchButton.
1057              */
1058             b = [[NSButton alloc] initWithFrame:tmprect];
1059             [b setBezelStyle:NSRoundedBezelStyle];
1060             [b setButtonType:NSSwitchButton];
1061             [b setTitle:[NSString stringWithUTF8String:i->name]];
1062             [b sizeToFit];
1063             [b setState:(i->ival ? NSOnState : NSOffState)];
1064             rect = [b frame];
1065             if (totalw < rect.size.width + 1) totalw = rect.size.width + 1;
1066             if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1067             cfg_controls[cfg_ncontrols++] = b;
1068             break;
1069
1070           case C_CHOICES:
1071             /*
1072              * A pop-up menu control is an NSPopUpButton, which
1073              * takes an embedded NSMenu. We also need an
1074              * NSTextField to act as a label.
1075              */
1076
1077             tf = [[NSTextField alloc] initWithFrame:tmprect];
1078             [tf setEditable:NO];
1079             [tf setSelectable:NO];
1080             [tf setBordered:NO];
1081             [tf setDrawsBackground:NO];
1082             [[tf cell] setTitle:[NSString stringWithUTF8String:i->name]];
1083             [tf sizeToFit];
1084             rect = [tf frame];
1085             if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1086             if (leftw < rect.size.width + 1) leftw = rect.size.width + 1;
1087             cfg_controls[cfg_ncontrols++] = tf;
1088
1089             pb = [[NSPopUpButton alloc] initWithFrame:tmprect pullsDown:NO];
1090             [pb setBezelStyle:NSRoundedBezelStyle];
1091             {
1092                 char c, *p;
1093
1094                 p = i->sval;
1095                 c = *p++;
1096                 while (*p) {
1097                     char *q, *copy;
1098
1099                     q = p;
1100                     while (*p && *p != c) p++;
1101
1102                     copy = snewn((p-q) + 1, char);
1103                     memcpy(copy, q, p-q);
1104                     copy[p-q] = '\0';
1105                     [pb addItemWithTitle:[NSString stringWithUTF8String:copy]];
1106                     sfree(copy);
1107
1108                     if (*p) p++;
1109                 }
1110             }
1111             [pb selectItemAtIndex:i->ival];
1112             [pb sizeToFit];
1113
1114             rect = [pb frame];
1115             if (rightw < rect.size.width + 1) rightw = rect.size.width + 1;
1116             if (thish < rect.size.height + 1) thish = rect.size.height + 1;
1117             cfg_controls[cfg_ncontrols++] = pb;
1118             break;
1119         }
1120
1121         h += SPACING + thish;
1122     }
1123
1124     if (totalw < leftw + SPACING + rightw)
1125         totalw = leftw + SPACING + rightw;
1126     if (totalw > leftw + SPACING + rightw) {
1127         int excess = totalw - (leftw + SPACING + rightw);
1128         int leftexcess = leftw * excess / (leftw + rightw);
1129         int rightexcess = excess - leftexcess;
1130         leftw += leftexcess;
1131         rightw += rightexcess;
1132     }
1133
1134     /*
1135      * Now go through the list again, setting the final position
1136      * for each control.
1137      */
1138     k = 0;
1139     y = h;
1140     for (i = cfg; i->type != C_END; i++) {
1141         y -= SPACING;
1142         thish = 0;
1143         switch (i->type) {
1144           case C_STRING:
1145           case C_CHOICES:
1146             /*
1147              * These two are treated identically, since both expect
1148              * a control on the left and another on the right.
1149              */
1150             rect = [cfg_controls[k] frame];
1151             if (thish < rect.size.height + 1)
1152                 thish = rect.size.height + 1;
1153             rect = [cfg_controls[k+1] frame];
1154             if (thish < rect.size.height + 1)
1155                 thish = rect.size.height + 1;
1156             rect = [cfg_controls[k] frame];
1157             rect.origin.y = y - thish/2 - rect.size.height/2;
1158             rect.origin.x = SPACING;
1159             rect.size.width = leftw;
1160             [cfg_controls[k] setFrame:rect];
1161             rect = [cfg_controls[k+1] frame];
1162             rect.origin.y = y - thish/2 - rect.size.height/2;
1163             rect.origin.x = 2 * SPACING + leftw;
1164             rect.size.width = rightw;
1165             [cfg_controls[k+1] setFrame:rect];
1166             k += 2;
1167             break;
1168
1169           case C_BOOLEAN:
1170             rect = [cfg_controls[k] frame];
1171             if (thish < rect.size.height + 1)
1172                 thish = rect.size.height + 1;
1173             rect.origin.y = y - thish/2 - rect.size.height/2;
1174             rect.origin.x = SPACING;
1175             rect.size.width = totalw;
1176             [cfg_controls[k] setFrame:rect];
1177             k++;
1178             break;
1179         }
1180         y -= thish;
1181     }
1182
1183     assert(k == cfg_ncontrols);
1184
1185     [cancel setFrame:NSMakeRect(SPACING+totalw/4-actw/2, SPACING, actw, acth)];
1186     [ok setFrame:NSMakeRect(SPACING+3*totalw/4-actw/2, SPACING, actw, acth)];
1187
1188     sheet = [[NSWindow alloc]
1189              initWithContentRect:NSMakeRect(0,0,totalw + 2*SPACING,h)
1190              styleMask:NSTitledWindowMask | NSClosableWindowMask
1191              backing:NSBackingStoreBuffered
1192              defer:YES];
1193
1194     [[sheet contentView] addSubview:cancel];
1195     [[sheet contentView] addSubview:ok];
1196
1197     for (k = 0; k < cfg_ncontrols; k++)
1198         [[sheet contentView] addSubview:cfg_controls[k]];
1199
1200     [app beginSheet:sheet modalForWindow:self
1201      modalDelegate:nil didEndSelector:NULL contextInfo:nil];
1202 }
1203
1204 - (void)specificGame:(id)sender
1205 {
1206     [self startConfigureSheet:CFG_DESC];
1207 }
1208
1209 - (void)specificRandomGame:(id)sender
1210 {
1211     [self startConfigureSheet:CFG_SEED];
1212 }
1213
1214 - (void)customGameType:(id)sender
1215 {
1216     [self startConfigureSheet:CFG_SETTINGS];
1217 }
1218
1219 - (void)sheetEndWithStatus:(BOOL)update
1220 {
1221     assert(sheet != NULL);
1222     [app endSheet:sheet];
1223     [sheet orderOut:self];
1224     sheet = NULL;
1225     if (update) {
1226         int k;
1227         config_item *i;
1228         char *error;
1229
1230         k = 0;
1231         for (i = cfg; i->type != C_END; i++) {
1232             switch (i->type) {
1233               case C_STRING:
1234                 sfree(i->sval);
1235                 i->sval = dupstr([[[(id)cfg_controls[k+1] cell]
1236                                   title] UTF8String]);
1237                 k += 2;
1238                 break;
1239               case C_BOOLEAN:
1240                 i->ival = [(id)cfg_controls[k] state] == NSOnState;
1241                 k++;
1242                 break;
1243               case C_CHOICES:
1244                 i->ival = [(id)cfg_controls[k+1] indexOfSelectedItem];
1245                 k += 2;
1246                 break;
1247             }
1248         }
1249
1250         error = midend_set_config(me, cfg_which, cfg);
1251         if (error) {
1252             NSAlert *alert = [[[NSAlert alloc] init] autorelease];
1253             [alert addButtonWithTitle:@"Bah"];
1254             [alert setInformativeText:[NSString stringWithUTF8String:error]];
1255             [alert beginSheetModalForWindow:self modalDelegate:nil
1256              didEndSelector:NULL contextInfo:nil];
1257         } else {
1258             midend_new_game(me);
1259             [self resizeForNewGameParams];
1260             [self updateTypeMenuTick];
1261         }
1262     }
1263     sfree(cfg_controls);
1264     cfg_controls = NULL;
1265 }
1266 - (void)sheetOKButton:(id)sender
1267 {
1268     [self sheetEndWithStatus:YES];
1269 }
1270 - (void)sheetCancelButton:(id)sender
1271 {
1272     [self sheetEndWithStatus:NO];
1273 }
1274
1275 - (void)setStatusLine:(char *)text
1276 {
1277     [[status cell] setTitle:[NSString stringWithUTF8String:text]];
1278 }
1279
1280 @end
1281
1282 /*
1283  * Drawing routines called by the midend.
1284  */
1285 static void osx_draw_polygon(void *handle, int *coords, int npoints,
1286                              int fillcolour, int outlinecolour)
1287 {
1288     frontend *fe = (frontend *)handle;
1289     NSBezierPath *path = [NSBezierPath bezierPath];
1290     int i;
1291
1292     [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1293
1294     for (i = 0; i < npoints; i++) {
1295         NSPoint p = { coords[i*2] + 0.5, fe->h - coords[i*2+1] - 0.5 };
1296         if (i == 0)
1297             [path moveToPoint:p];
1298         else
1299             [path lineToPoint:p];
1300     }
1301
1302     [path closePath];
1303
1304     if (fillcolour >= 0) {
1305         assert(fillcolour >= 0 && fillcolour < fe->ncolours);
1306         [fe->colours[fillcolour] set];
1307         [path fill];
1308     }
1309
1310     assert(outlinecolour >= 0 && outlinecolour < fe->ncolours);
1311     [fe->colours[outlinecolour] set];
1312     [path stroke];
1313 }
1314 static void osx_draw_circle(void *handle, int cx, int cy, int radius,
1315                             int fillcolour, int outlinecolour)
1316 {
1317     frontend *fe = (frontend *)handle;
1318     NSBezierPath *path = [NSBezierPath bezierPath];
1319
1320     [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1321
1322     [path appendBezierPathWithArcWithCenter:NSMakePoint(cx+0.5, fe->h-cy-0.5)
1323         radius:radius startAngle:0.0 endAngle:360.0];
1324
1325     [path closePath];
1326
1327     if (fillcolour >= 0) {
1328         assert(fillcolour >= 0 && fillcolour < fe->ncolours);
1329         [fe->colours[fillcolour] set];
1330         [path fill];
1331     }
1332
1333     assert(outlinecolour >= 0 && outlinecolour < fe->ncolours);
1334     [fe->colours[outlinecolour] set];
1335     [path stroke];
1336 }
1337 static void osx_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
1338 {
1339     frontend *fe = (frontend *)handle;
1340     NSBezierPath *path = [NSBezierPath bezierPath];
1341     NSPoint p1 = { x1 + 0.5, fe->h - y1 - 0.5 };
1342     NSPoint p2 = { x2 + 0.5, fe->h - y2 - 0.5 };
1343
1344     [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1345
1346     assert(colour >= 0 && colour < fe->ncolours);
1347     [fe->colours[colour] set];
1348
1349     [path moveToPoint:p1];
1350     [path lineToPoint:p2];
1351     [path stroke];
1352     NSRectFill(NSMakeRect(x1, fe->h-y1-1, 1, 1));
1353     NSRectFill(NSMakeRect(x2, fe->h-y2-1, 1, 1));
1354 }
1355
1356 static void osx_draw_thick_line(
1357     void *handle, float thickness,
1358     float x1, float y1,
1359     float x2, float y2,
1360     int colour)
1361 {
1362     frontend *fe = (frontend *)handle;
1363     NSBezierPath *path = [NSBezierPath bezierPath];
1364
1365     assert(colour >= 0 && colour < fe->ncolours);
1366     [fe->colours[colour] set];
1367     [[NSGraphicsContext currentContext] setShouldAntialias: YES];
1368     [path setLineWidth: thickness];
1369     [path setLineCapStyle: NSButtLineCapStyle];
1370     [path moveToPoint: NSMakePoint(x1, fe->h-y1)];
1371     [path lineToPoint: NSMakePoint(x2, fe->h-y2)];
1372     [path stroke];
1373 }
1374
1375 static void osx_draw_rect(void *handle, int x, int y, int w, int h, int colour)
1376 {
1377     frontend *fe = (frontend *)handle;
1378     NSRect r = { {x, fe->h - y - h}, {w,h} };
1379     
1380     [[NSGraphicsContext currentContext] setShouldAntialias:NO];
1381
1382     assert(colour >= 0 && colour < fe->ncolours);
1383     [fe->colours[colour] set];
1384
1385     NSRectFill(r);
1386 }
1387 static void osx_draw_text(void *handle, int x, int y, int fonttype,
1388                           int fontsize, int align, int colour, char *text)
1389 {
1390     frontend *fe = (frontend *)handle;
1391     NSString *string = [NSString stringWithUTF8String:text];
1392     NSDictionary *attr;
1393     NSFont *font;
1394     NSSize size;
1395     NSPoint point;
1396
1397     [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1398
1399     assert(colour >= 0 && colour < fe->ncolours);
1400
1401     if (fonttype == FONT_FIXED)
1402         font = [NSFont userFixedPitchFontOfSize:fontsize];
1403     else
1404         font = [NSFont userFontOfSize:fontsize];
1405
1406     attr = [NSDictionary dictionaryWithObjectsAndKeys:
1407             fe->colours[colour], NSForegroundColorAttributeName,
1408             font, NSFontAttributeName, nil];
1409
1410     point.x = x;
1411     point.y = fe->h - y;
1412
1413     size = [string sizeWithAttributes:attr];
1414     if (align & ALIGN_HRIGHT)
1415         point.x -= size.width;
1416     else if (align & ALIGN_HCENTRE)
1417         point.x -= size.width / 2;
1418     if (align & ALIGN_VCENTRE)
1419         point.y -= size.height / 2;
1420
1421     [string drawAtPoint:point withAttributes:attr];
1422 }
1423 static char *osx_text_fallback(void *handle, const char *const *strings,
1424                                int nstrings)
1425 {
1426     /*
1427      * We assume OS X can cope with any UTF-8 likely to be emitted
1428      * by a puzzle.
1429      */
1430     return dupstr(strings[0]);
1431 }
1432 struct blitter {
1433     int w, h;
1434     int x, y;
1435     NSImage *img;
1436 };
1437 static blitter *osx_blitter_new(void *handle, int w, int h)
1438 {
1439     blitter *bl = snew(blitter);
1440     bl->x = bl->y = -1;
1441     bl->w = w;
1442     bl->h = h;
1443     bl->img = [[NSImage alloc] initWithSize:NSMakeSize(w, h)];
1444     return bl;
1445 }
1446 static void osx_blitter_free(void *handle, blitter *bl)
1447 {
1448     [bl->img release];
1449     sfree(bl);
1450 }
1451 static void osx_blitter_save(void *handle, blitter *bl, int x, int y)
1452 {
1453     frontend *fe = (frontend *)handle;
1454     int sx, sy, sX, sY, dx, dy, dX, dY;
1455     [fe->image unlockFocus];
1456     [bl->img lockFocus];
1457
1458     /*
1459      * Find the intersection of the source and destination rectangles,
1460      * so as to avoid trying to copy from outside the source image,
1461      * which GNUstep dislikes.
1462      *
1463      * Lower-case x,y coordinates are bottom left box corners;
1464      * upper-case X,Y are the top right.
1465      */
1466     sx = x; sy = fe->h - y - bl->h;
1467     sX = sx + bl->w; sY = sy + bl->h;
1468     dx = dy = 0;
1469     dX = bl->w; dY = bl->h;
1470     if (sx < 0) {
1471         dx += -sx;
1472         sx = 0;
1473     }
1474     if (sy < 0) {
1475         dy += -sy;
1476         sy = 0;
1477     }
1478     if (sX > fe->w) {
1479         dX -= (sX - fe->w);
1480         sX = fe->w;
1481     }
1482     if (sY > fe->h) {
1483         dY -= (sY - fe->h);
1484         sY = fe->h;
1485     }
1486
1487     [fe->image drawInRect:NSMakeRect(dx, dy, dX-dx, dY-dy)
1488                  fromRect:NSMakeRect(sx, sy, sX-sx, sY-sy)
1489                 operation:NSCompositeCopy fraction:1.0];
1490     [bl->img unlockFocus];
1491     [fe->image lockFocus];
1492     bl->x = x;
1493     bl->y = y;
1494 }
1495 static void osx_blitter_load(void *handle, blitter *bl, int x, int y)
1496 {
1497     frontend *fe = (frontend *)handle;
1498     if (x == BLITTER_FROMSAVED && y == BLITTER_FROMSAVED) {
1499         x = bl->x;
1500         y = bl->y;
1501     }
1502     [bl->img drawInRect:NSMakeRect(x, fe->h - y - bl->h, bl->w, bl->h)
1503         fromRect:NSMakeRect(0, 0, bl->w, bl->h)
1504         operation:NSCompositeCopy fraction:1.0];
1505 }
1506 static void osx_draw_update(void *handle, int x, int y, int w, int h)
1507 {
1508     frontend *fe = (frontend *)handle;
1509     [fe->view setNeedsDisplayInRect:NSMakeRect(x, fe->h - y - h, w, h)];
1510 }
1511 static void osx_clip(void *handle, int x, int y, int w, int h)
1512 {
1513     frontend *fe = (frontend *)handle;
1514     NSRect r = { {x, fe->h - y - h}, {w, h} };
1515     
1516     if (!fe->clipped)
1517         [[NSGraphicsContext currentContext] saveGraphicsState];
1518     [NSBezierPath clipRect:r];
1519     fe->clipped = TRUE;
1520 }
1521 static void osx_unclip(void *handle)
1522 {
1523     frontend *fe = (frontend *)handle;
1524     if (fe->clipped)
1525         [[NSGraphicsContext currentContext] restoreGraphicsState];
1526     fe->clipped = FALSE;
1527 }
1528 static void osx_start_draw(void *handle)
1529 {
1530     frontend *fe = (frontend *)handle;
1531     [fe->image lockFocus];
1532     fe->clipped = FALSE;
1533 }
1534 static void osx_end_draw(void *handle)
1535 {
1536     frontend *fe = (frontend *)handle;
1537     [fe->image unlockFocus];
1538 }
1539 static void osx_status_bar(void *handle, char *text)
1540 {
1541     frontend *fe = (frontend *)handle;
1542     [fe->window setStatusLine:text];
1543 }
1544
1545 const struct drawing_api osx_drawing = {
1546     osx_draw_text,
1547     osx_draw_rect,
1548     osx_draw_line,
1549     osx_draw_polygon,
1550     osx_draw_circle,
1551     osx_draw_update,
1552     osx_clip,
1553     osx_unclip,
1554     osx_start_draw,
1555     osx_end_draw,
1556     osx_status_bar,
1557     osx_blitter_new,
1558     osx_blitter_free,
1559     osx_blitter_save,
1560     osx_blitter_load,
1561     NULL, NULL, NULL, NULL, NULL, NULL, /* {begin,end}_{doc,page,puzzle} */
1562     NULL, NULL,                        /* line_width, line_dotted */
1563     osx_text_fallback,
1564     osx_draw_thick_line,
1565 };
1566
1567 void deactivate_timer(frontend *fe)
1568 {
1569     [fe->window deactivateTimer];
1570 }
1571 void activate_timer(frontend *fe)
1572 {
1573     [fe->window activateTimer];
1574 }
1575
1576 /* ----------------------------------------------------------------------
1577  * AppController: the object which receives the messages from all
1578  * menu selections that aren't standard OS X functions.
1579  */
1580 @interface AppController : NSObject <NSApplicationDelegate>
1581 {
1582 }
1583 - (void)newGameWindow:(id)sender;
1584 - (void)about:(id)sender;
1585 @end
1586
1587 @implementation AppController
1588
1589 - (void)newGameWindow:(id)sender
1590 {
1591     const game *g = [sender getPayload];
1592     id win;
1593
1594     win = [[GameWindow alloc] initWithGame:g];
1595     [win makeKeyAndOrderFront:self];
1596 }
1597
1598 - (void)about:(id)sender
1599 {
1600     id win;
1601
1602     win = [[AboutBox alloc] init];
1603     [win makeKeyAndOrderFront:self];    
1604 }
1605
1606 - (NSMenu *)applicationDockMenu:(NSApplication *)sender
1607 {
1608     NSMenu *menu = newmenu("Dock Menu");
1609     {
1610         int i;
1611
1612         for (i = 0; i < gamecount; i++) {
1613             id item =
1614                 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1615                             menu, gamelist[i]->name, "", self,
1616                             @selector(newGameWindow:));
1617             [item setPayload:(void *)gamelist[i]];
1618         }
1619     }
1620     return menu;
1621 }
1622
1623 @end
1624
1625 /* ----------------------------------------------------------------------
1626  * Main program. Constructs the menus and runs the application.
1627  */
1628 int main(int argc, char **argv)
1629 {
1630     NSAutoreleasePool *pool;
1631     NSMenu *menu;
1632     AppController *controller;
1633     NSImage *icon;
1634
1635     pool = [[NSAutoreleasePool alloc] init];
1636
1637     icon = [NSImage imageNamed:@"NSApplicationIcon"];
1638     app = [NSApplication sharedApplication];
1639     [app setApplicationIconImage:icon];
1640
1641     controller = [[[AppController alloc] init] autorelease];
1642     [app setDelegate:controller];
1643
1644     [app setMainMenu: newmenu("Main Menu")];
1645
1646     menu = newsubmenu([app mainMenu], "Apple Menu");
1647     newitem(menu, "About Puzzles", "", NULL, @selector(about:));
1648     [menu addItem:[NSMenuItem separatorItem]];
1649     [app setServicesMenu:newsubmenu(menu, "Services")];
1650     [menu addItem:[NSMenuItem separatorItem]];
1651     newitem(menu, "Hide Puzzles", "h", app, @selector(hide:));
1652     newitem(menu, "Hide Others", "o-h", app, @selector(hideOtherApplications:));
1653     newitem(menu, "Show All", "", app, @selector(unhideAllApplications:));
1654     [menu addItem:[NSMenuItem separatorItem]];
1655     newitem(menu, "Quit", "q", app, @selector(terminate:));
1656     [app setAppleMenu: menu];
1657
1658     menu = newsubmenu([app mainMenu], "File");
1659     newitem(menu, "Open", "o", NULL, @selector(loadSavedGame:));
1660     newitem(menu, "Save As", "s", NULL, @selector(saveGame:));
1661     newitem(menu, "New Game", "n", NULL, @selector(newGame:));
1662     newitem(menu, "Restart Game", "r", NULL, @selector(restartGame:));
1663     newitem(menu, "Specific Game", "", NULL, @selector(specificGame:));
1664     newitem(menu, "Specific Random Seed", "", NULL,
1665                    @selector(specificRandomGame:));
1666     [menu addItem:[NSMenuItem separatorItem]];
1667     {
1668         NSMenu *submenu = newsubmenu(menu, "New Window");
1669         int i;
1670
1671         for (i = 0; i < gamecount; i++) {
1672             id item =
1673                 initnewitem([DataMenuItem allocWithZone:[NSMenu menuZone]],
1674                             submenu, gamelist[i]->name, "", controller,
1675                             @selector(newGameWindow:));
1676             [item setPayload:(void *)gamelist[i]];
1677         }
1678     }
1679     [menu addItem:[NSMenuItem separatorItem]];
1680     newitem(menu, "Close", "w", NULL, @selector(performClose:));
1681
1682     menu = newsubmenu([app mainMenu], "Edit");
1683     newitem(menu, "Undo", "z", NULL, @selector(undoMove:));
1684     newitem(menu, "Redo", "S-z", NULL, @selector(redoMove:));
1685     [menu addItem:[NSMenuItem separatorItem]];
1686     newitem(menu, "Cut", "x", NULL, @selector(cut:));
1687     newitem(menu, "Copy", "c", NULL, @selector(copy:));
1688     newitem(menu, "Paste", "v", NULL, @selector(paste:));
1689     [menu addItem:[NSMenuItem separatorItem]];
1690     newitem(menu, "Solve", "S-s", NULL, @selector(solveGame:));
1691
1692     menu = newsubmenu([app mainMenu], "Type");
1693     typemenu = menu;
1694     newitem(menu, "Custom", "", NULL, @selector(customGameType:));
1695
1696     menu = newsubmenu([app mainMenu], "Window");
1697     [app setWindowsMenu: menu];
1698     newitem(menu, "Minimise Window", "m", NULL, @selector(performMiniaturize:));
1699
1700     menu = newsubmenu([app mainMenu], "Help");
1701     newitem(menu, "Puzzles Help", "?", app, @selector(showHelp:));
1702
1703     [app run];
1704     [pool release];
1705
1706     return 0;
1707 }