chiark / gitweb /
d9b9a276715421ef410d538aaa023980af4663c4
[sgt-puzzles.git] / gtk.c
1 /*
2  * gtk.c: GTK front end for my puzzle collection.
3  */
4
5 #include <stdio.h>
6 #include <assert.h>
7 #include <stdlib.h>
8 #include <time.h>
9 #include <stdarg.h>
10 #include <string.h>
11 #include <errno.h>
12
13 #include <sys/time.h>
14
15 #include <gtk/gtk.h>
16 #include <gdk/gdkkeysyms.h>
17
18 #include <gdk/gdkx.h>
19 #include <X11/Xlib.h>
20 #include <X11/Xutil.h>
21 #include <X11/Xatom.h>
22
23 #include "puzzles.h"
24
25 #if GTK_CHECK_VERSION(2,0,0)
26 #define USE_PANGO
27 #endif
28
29 #ifdef DEBUGGING
30 static FILE *debug_fp = NULL;
31
32 void dputs(char *buf)
33 {
34     if (!debug_fp) {
35         debug_fp = fopen("debug.log", "w");
36     }
37
38     fputs(buf, stderr);
39
40     if (debug_fp) {
41         fputs(buf, debug_fp);
42         fflush(debug_fp);
43     }
44 }
45
46 void debug_printf(char *fmt, ...)
47 {
48     char buf[4096];
49     va_list ap;
50
51     va_start(ap, fmt);
52     vsprintf(buf, fmt, ap);
53     dputs(buf);
54     va_end(ap);
55 }
56 #endif
57
58 /* ----------------------------------------------------------------------
59  * Error reporting functions used elsewhere.
60  */
61
62 void fatal(char *fmt, ...)
63 {
64     va_list ap;
65
66     fprintf(stderr, "fatal error: ");
67
68     va_start(ap, fmt);
69     vfprintf(stderr, fmt, ap);
70     va_end(ap);
71
72     fprintf(stderr, "\n");
73     exit(1);
74 }
75
76 /* ----------------------------------------------------------------------
77  * GTK front end to puzzles.
78  */
79
80 struct font {
81 #ifdef USE_PANGO
82     PangoFontDescription *desc;
83 #else
84     GdkFont *font;
85 #endif
86     int type;
87     int size;
88 };
89
90 /*
91  * This structure holds all the data relevant to a single window.
92  * In principle this would allow us to open multiple independent
93  * puzzle windows, although I can't currently see any real point in
94  * doing so. I'm just coding cleanly because there's no
95  * particularly good reason not to.
96  */
97 struct frontend {
98     GtkWidget *window;
99     GtkAccelGroup *accelgroup;
100     GtkWidget *area;
101     GtkWidget *statusbar;
102     guint statusctx;
103     GdkPixmap *pixmap;
104     GdkColor *colours;
105     int ncolours;
106     GdkColormap *colmap;
107     int w, h;
108     midend *me;
109     GdkGC *gc;
110     int bbox_l, bbox_r, bbox_u, bbox_d;
111     int timer_active, timer_id;
112     struct timeval last_time;
113     struct font *fonts;
114     int nfonts, fontsize;
115     config_item *cfg;
116     int cfg_which, cfgret;
117     GtkWidget *cfgbox;
118     void *paste_data;
119     int paste_data_len;
120     int pw, ph;                        /* pixmap size (w, h are area size) */
121     int ox, oy;                        /* offset of pixmap in drawing area */
122     char *filesel_name;
123 };
124
125 void get_random_seed(void **randseed, int *randseedsize)
126 {
127     struct timeval *tvp = snew(struct timeval);
128     gettimeofday(tvp, NULL);
129     *randseed = (void *)tvp;
130     *randseedsize = sizeof(struct timeval);
131 }
132
133 void frontend_default_colour(frontend *fe, float *output)
134 {
135     GdkColor col = fe->window->style->bg[GTK_STATE_NORMAL];
136     output[0] = col.red / 65535.0;
137     output[1] = col.green / 65535.0;
138     output[2] = col.blue / 65535.0;
139 }
140
141 void gtk_status_bar(void *handle, char *text)
142 {
143     frontend *fe = (frontend *)handle;
144
145     assert(fe->statusbar);
146
147     gtk_statusbar_pop(GTK_STATUSBAR(fe->statusbar), fe->statusctx);
148     gtk_statusbar_push(GTK_STATUSBAR(fe->statusbar), fe->statusctx, text);
149 }
150
151 void gtk_start_draw(void *handle)
152 {
153     frontend *fe = (frontend *)handle;
154     fe->gc = gdk_gc_new(fe->area->window);
155     fe->bbox_l = fe->w;
156     fe->bbox_r = 0;
157     fe->bbox_u = fe->h;
158     fe->bbox_d = 0;
159 }
160
161 void gtk_clip(void *handle, int x, int y, int w, int h)
162 {
163     frontend *fe = (frontend *)handle;
164     GdkRectangle rect;
165
166     rect.x = x;
167     rect.y = y;
168     rect.width = w;
169     rect.height = h;
170
171     gdk_gc_set_clip_rectangle(fe->gc, &rect);
172 }
173
174 void gtk_unclip(void *handle)
175 {
176     frontend *fe = (frontend *)handle;
177     GdkRectangle rect;
178
179     rect.x = 0;
180     rect.y = 0;
181     rect.width = fe->w;
182     rect.height = fe->h;
183
184     gdk_gc_set_clip_rectangle(fe->gc, &rect);
185 }
186
187 void gtk_draw_text(void *handle, int x, int y, int fonttype, int fontsize,
188                    int align, int colour, char *text)
189 {
190     frontend *fe = (frontend *)handle;
191     int i;
192
193     /*
194      * Find or create the font.
195      */
196     for (i = 0; i < fe->nfonts; i++)
197         if (fe->fonts[i].type == fonttype && fe->fonts[i].size == fontsize)
198             break;
199
200     if (i == fe->nfonts) {
201         if (fe->fontsize <= fe->nfonts) {
202             fe->fontsize = fe->nfonts + 10;
203             fe->fonts = sresize(fe->fonts, fe->fontsize, struct font);
204         }
205
206         fe->nfonts++;
207
208         fe->fonts[i].type = fonttype;
209         fe->fonts[i].size = fontsize;
210
211 #ifdef USE_PANGO
212         /*
213          * Use Pango to find the closest match to the requested
214          * font.
215          */
216         {
217             PangoFontDescription *fd;
218
219             fd = pango_font_description_new();
220             /* `Monospace' and `Sans' are meta-families guaranteed to exist */
221             pango_font_description_set_family(fd, fonttype == FONT_FIXED ?
222                                               "Monospace" : "Sans");
223             pango_font_description_set_weight(fd, PANGO_WEIGHT_BOLD);
224             /*
225              * I found some online Pango documentation which
226              * described a function called
227              * pango_font_description_set_absolute_size(), which is
228              * _exactly_ what I want here. Unfortunately, none of
229              * my local Pango installations have it (presumably
230              * they're too old), so I'm going to have to hack round
231              * it by figuring out the point size myself. This
232              * limits me to X and probably also breaks in later
233              * Pango installations, so ideally I should add another
234              * CHECK_VERSION type ifdef and use set_absolute_size
235              * where available. All very annoying.
236              */
237 #ifdef HAVE_SENSIBLE_ABSOLUTE_SIZE_FUNCTION
238             pango_font_description_set_absolute_size(fd, PANGO_SCALE*fontsize);
239 #else
240             {
241                 Display *d = GDK_DISPLAY();
242                 int s = DefaultScreen(d);
243                 double resolution =
244                     (PANGO_SCALE * 72.27 / 25.4) * 
245                     ((double) DisplayWidthMM(d, s) / DisplayWidth (d, s));
246                 pango_font_description_set_size(fd, resolution * fontsize);
247             }
248 #endif
249             fe->fonts[i].desc = fd;
250         }
251
252 #else
253         /*
254          * In GTK 1.2, I don't know of any plausible way to
255          * pick a suitable font, so I'm just going to be
256          * tedious.
257          */
258         fe->fonts[i].font = gdk_font_load(fonttype == FONT_FIXED ?
259                                           "fixed" : "variable");
260 #endif
261
262     }
263
264     /*
265      * Set the colour.
266      */
267     gdk_gc_set_foreground(fe->gc, &fe->colours[colour]);
268
269 #ifdef USE_PANGO
270
271     {
272         PangoLayout *layout;
273         PangoRectangle rect;
274
275         /*
276          * Create a layout.
277          */
278         layout = pango_layout_new(gtk_widget_get_pango_context(fe->area));
279         pango_layout_set_font_description(layout, fe->fonts[i].desc);
280         pango_layout_set_text(layout, text, strlen(text));
281         pango_layout_get_pixel_extents(layout, NULL, &rect);
282
283         if (align & ALIGN_VCENTRE)
284             rect.y -= rect.height / 2;
285         else
286             rect.y -= rect.height;
287
288         if (align & ALIGN_HCENTRE)
289             rect.x -= rect.width / 2;
290         else if (align & ALIGN_HRIGHT)
291             rect.x -= rect.width;
292
293         gdk_draw_layout(fe->pixmap, fe->gc, rect.x + x, rect.y + y, layout);
294
295         g_object_unref(layout);
296     }
297
298 #else
299     /*
300      * Find string dimensions and process alignment.
301      */
302     {
303         int lb, rb, wid, asc, desc;
304
305         /*
306          * Measure vertical string extents with respect to the same
307          * string always...
308          */
309         gdk_string_extents(fe->fonts[i].font,
310                            "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
311                            &lb, &rb, &wid, &asc, &desc);
312         if (align & ALIGN_VCENTRE)
313             y += asc - (asc+desc)/2;
314         else
315             y += asc;
316
317         /*
318          * ... but horizontal extents with respect to the provided
319          * string. This means that multiple pieces of text centred
320          * on the same y-coordinate don't have different baselines.
321          */
322         gdk_string_extents(fe->fonts[i].font, text,
323                            &lb, &rb, &wid, &asc, &desc);
324
325         if (align & ALIGN_HCENTRE)
326             x -= wid / 2;
327         else if (align & ALIGN_HRIGHT)
328             x -= wid;
329
330     }
331
332     /*
333      * Actually draw the text.
334      */
335     gdk_draw_string(fe->pixmap, fe->fonts[i].font, fe->gc, x, y, text);
336 #endif
337
338 }
339
340 void gtk_draw_rect(void *handle, int x, int y, int w, int h, int colour)
341 {
342     frontend *fe = (frontend *)handle;
343     gdk_gc_set_foreground(fe->gc, &fe->colours[colour]);
344     gdk_draw_rectangle(fe->pixmap, fe->gc, 1, x, y, w, h);
345 }
346
347 void gtk_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
348 {
349     frontend *fe = (frontend *)handle;
350     gdk_gc_set_foreground(fe->gc, &fe->colours[colour]);
351     gdk_draw_line(fe->pixmap, fe->gc, x1, y1, x2, y2);
352 }
353
354 void gtk_draw_poly(void *handle, int *coords, int npoints,
355                    int fillcolour, int outlinecolour)
356 {
357     frontend *fe = (frontend *)handle;
358     GdkPoint *points = snewn(npoints, GdkPoint);
359     int i;
360
361     for (i = 0; i < npoints; i++) {
362         points[i].x = coords[i*2];
363         points[i].y = coords[i*2+1];
364     }
365
366     if (fillcolour >= 0) {
367         gdk_gc_set_foreground(fe->gc, &fe->colours[fillcolour]);
368         gdk_draw_polygon(fe->pixmap, fe->gc, TRUE, points, npoints);
369     }
370     assert(outlinecolour >= 0);
371     gdk_gc_set_foreground(fe->gc, &fe->colours[outlinecolour]);
372
373     /*
374      * In principle we ought to be able to use gdk_draw_polygon for
375      * the outline as well. In fact, it turns out to interact badly
376      * with a clipping region, for no terribly obvious reason, so I
377      * draw the outline as a sequence of lines instead.
378      */
379     for (i = 0; i < npoints; i++)
380         gdk_draw_line(fe->pixmap, fe->gc,
381                       points[i].x, points[i].y,
382                       points[(i+1)%npoints].x, points[(i+1)%npoints].y);
383
384     sfree(points);
385 }
386
387 void gtk_draw_circle(void *handle, int cx, int cy, int radius,
388                      int fillcolour, int outlinecolour)
389 {
390     frontend *fe = (frontend *)handle;
391     if (fillcolour >= 0) {
392         gdk_gc_set_foreground(fe->gc, &fe->colours[fillcolour]);
393         gdk_draw_arc(fe->pixmap, fe->gc, TRUE,
394                      cx - radius, cy - radius,
395                      2 * radius, 2 * radius, 0, 360 * 64);
396     }
397
398     assert(outlinecolour >= 0);
399     gdk_gc_set_foreground(fe->gc, &fe->colours[outlinecolour]);
400     gdk_draw_arc(fe->pixmap, fe->gc, FALSE,
401                  cx - radius, cy - radius,
402                  2 * radius, 2 * radius, 0, 360 * 64);
403 }
404
405 struct blitter {
406     GdkPixmap *pixmap;
407     int w, h, x, y;
408 };
409
410 blitter *gtk_blitter_new(void *handle, int w, int h)
411 {
412     /*
413      * We can't create the pixmap right now, because fe->window
414      * might not yet exist. So we just cache w and h and create it
415      * during the firs call to blitter_save.
416      */
417     blitter *bl = snew(blitter);
418     bl->pixmap = NULL;
419     bl->w = w;
420     bl->h = h;
421     return bl;
422 }
423
424 void gtk_blitter_free(void *handle, blitter *bl)
425 {
426     if (bl->pixmap)
427         gdk_pixmap_unref(bl->pixmap);
428     sfree(bl);
429 }
430
431 void gtk_blitter_save(void *handle, blitter *bl, int x, int y)
432 {
433     frontend *fe = (frontend *)handle;
434     if (!bl->pixmap)
435         bl->pixmap = gdk_pixmap_new(fe->area->window, bl->w, bl->h, -1);
436     bl->x = x;
437     bl->y = y;
438     gdk_draw_pixmap(bl->pixmap,
439                     fe->area->style->fg_gc[GTK_WIDGET_STATE(fe->area)],
440                     fe->pixmap,
441                     x, y, 0, 0, bl->w, bl->h);
442 }
443
444 void gtk_blitter_load(void *handle, blitter *bl, int x, int y)
445 {
446     frontend *fe = (frontend *)handle;
447     assert(bl->pixmap);
448     if (x == BLITTER_FROMSAVED && y == BLITTER_FROMSAVED) {
449         x = bl->x;
450         y = bl->y;
451     }
452     gdk_draw_pixmap(fe->pixmap,
453                     fe->area->style->fg_gc[GTK_WIDGET_STATE(fe->area)],
454                     bl->pixmap,
455                     0, 0, x, y, bl->w, bl->h);
456 }
457
458 void gtk_draw_update(void *handle, int x, int y, int w, int h)
459 {
460     frontend *fe = (frontend *)handle;
461     if (fe->bbox_l > x  ) fe->bbox_l = x  ;
462     if (fe->bbox_r < x+w) fe->bbox_r = x+w;
463     if (fe->bbox_u > y  ) fe->bbox_u = y  ;
464     if (fe->bbox_d < y+h) fe->bbox_d = y+h;
465 }
466
467 void gtk_end_draw(void *handle)
468 {
469     frontend *fe = (frontend *)handle;
470     gdk_gc_unref(fe->gc);
471     fe->gc = NULL;
472
473     if (fe->bbox_l < fe->bbox_r && fe->bbox_u < fe->bbox_d) {
474         gdk_draw_pixmap(fe->area->window,
475                         fe->area->style->fg_gc[GTK_WIDGET_STATE(fe->area)],
476                         fe->pixmap,
477                         fe->bbox_l, fe->bbox_u,
478                         fe->ox + fe->bbox_l, fe->oy + fe->bbox_u,
479                         fe->bbox_r - fe->bbox_l, fe->bbox_d - fe->bbox_u);
480     }
481 }
482
483 const struct drawing_api gtk_drawing = {
484     gtk_draw_text,
485     gtk_draw_rect,
486     gtk_draw_line,
487     gtk_draw_poly,
488     gtk_draw_circle,
489     gtk_draw_update,
490     gtk_clip,
491     gtk_unclip,
492     gtk_start_draw,
493     gtk_end_draw,
494     gtk_status_bar,
495     gtk_blitter_new,
496     gtk_blitter_free,
497     gtk_blitter_save,
498     gtk_blitter_load,
499     NULL, NULL, NULL, NULL, NULL, NULL, /* {begin,end}_{doc,page,puzzle} */
500     NULL,                              /* line_width */
501 };
502
503 static void destroy(GtkWidget *widget, gpointer data)
504 {
505     frontend *fe = (frontend *)data;
506     deactivate_timer(fe);
507     midend_free(fe->me);
508     gtk_main_quit();
509 }
510
511 static gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data)
512 {
513     frontend *fe = (frontend *)data;
514     int keyval;
515     int shift = (event->state & GDK_SHIFT_MASK) ? MOD_SHFT : 0;
516     int ctrl = (event->state & GDK_CONTROL_MASK) ? MOD_CTRL : 0;
517
518     if (!fe->pixmap)
519         return TRUE;
520
521 #if !GTK_CHECK_VERSION(2,0,0)
522     /* Gtk 1.2 passes a key event to this function even if it's also
523      * defined as an accelerator.
524      * Gtk 2 doesn't do this, and this function appears not to exist there. */
525     if (fe->accelgroup &&
526         gtk_accel_group_get_entry(fe->accelgroup,
527         event->keyval, event->state))
528         return TRUE;
529 #endif
530
531     if (event->keyval == GDK_Up)
532         keyval = shift | ctrl | CURSOR_UP;
533     else if (event->keyval == GDK_KP_Up || event->keyval == GDK_KP_8)
534         keyval = MOD_NUM_KEYPAD | '8';
535     else if (event->keyval == GDK_Down)
536         keyval = shift | ctrl | CURSOR_DOWN;
537     else if (event->keyval == GDK_KP_Down || event->keyval == GDK_KP_2)
538         keyval = MOD_NUM_KEYPAD | '2';
539     else if (event->keyval == GDK_Left)
540         keyval = shift | ctrl | CURSOR_LEFT;
541     else if (event->keyval == GDK_KP_Left || event->keyval == GDK_KP_4)
542         keyval = MOD_NUM_KEYPAD | '4';
543     else if (event->keyval == GDK_Right)
544         keyval = shift | ctrl | CURSOR_RIGHT;
545     else if (event->keyval == GDK_KP_Right || event->keyval == GDK_KP_6)
546         keyval = MOD_NUM_KEYPAD | '6';
547     else if (event->keyval == GDK_KP_Home || event->keyval == GDK_KP_7)
548         keyval = MOD_NUM_KEYPAD | '7';
549     else if (event->keyval == GDK_KP_End || event->keyval == GDK_KP_1)
550         keyval = MOD_NUM_KEYPAD | '1';
551     else if (event->keyval == GDK_KP_Page_Up || event->keyval == GDK_KP_9)
552         keyval = MOD_NUM_KEYPAD | '9';
553     else if (event->keyval == GDK_KP_Page_Down || event->keyval == GDK_KP_3)
554         keyval = MOD_NUM_KEYPAD | '3';
555     else if (event->keyval == GDK_KP_Insert || event->keyval == GDK_KP_0)
556         keyval = MOD_NUM_KEYPAD | '0';
557     else if (event->keyval == GDK_KP_Begin || event->keyval == GDK_KP_5)
558         keyval = MOD_NUM_KEYPAD | '5';
559     else if (event->keyval == GDK_BackSpace ||
560              event->keyval == GDK_Delete ||
561              event->keyval == GDK_KP_Delete)
562         keyval = '\177';
563     else if (event->string[0] && !event->string[1])
564         keyval = (unsigned char)event->string[0];
565     else
566         keyval = -1;
567
568     if (keyval >= 0 &&
569         !midend_process_key(fe->me, 0, 0, keyval))
570         gtk_widget_destroy(fe->window);
571
572     return TRUE;
573 }
574
575 static gint button_event(GtkWidget *widget, GdkEventButton *event,
576                          gpointer data)
577 {
578     frontend *fe = (frontend *)data;
579     int button;
580
581     if (!fe->pixmap)
582         return TRUE;
583
584     if (event->type != GDK_BUTTON_PRESS && event->type != GDK_BUTTON_RELEASE)
585         return TRUE;
586
587     if (event->button == 2 || (event->state & GDK_SHIFT_MASK))
588         button = MIDDLE_BUTTON;
589     else if (event->button == 3 || (event->state & GDK_MOD1_MASK))
590         button = RIGHT_BUTTON;
591     else if (event->button == 1)
592         button = LEFT_BUTTON;
593     else
594         return FALSE;                  /* don't even know what button! */
595
596     if (event->type == GDK_BUTTON_RELEASE)
597         button += LEFT_RELEASE - LEFT_BUTTON;
598
599     if (!midend_process_key(fe->me, event->x - fe->ox,
600                             event->y - fe->oy, button))
601         gtk_widget_destroy(fe->window);
602
603     return TRUE;
604 }
605
606 static gint motion_event(GtkWidget *widget, GdkEventMotion *event,
607                          gpointer data)
608 {
609     frontend *fe = (frontend *)data;
610     int button;
611
612     if (!fe->pixmap)
613         return TRUE;
614
615     if (event->state & (GDK_BUTTON2_MASK | GDK_SHIFT_MASK))
616         button = MIDDLE_DRAG;
617     else if (event->state & GDK_BUTTON1_MASK)
618         button = LEFT_DRAG;
619     else if (event->state & GDK_BUTTON3_MASK)
620         button = RIGHT_DRAG;
621     else
622         return FALSE;                  /* don't even know what button! */
623
624     if (!midend_process_key(fe->me, event->x - fe->ox,
625                             event->y - fe->oy, button))
626         gtk_widget_destroy(fe->window);
627
628     return TRUE;
629 }
630
631 static gint expose_area(GtkWidget *widget, GdkEventExpose *event,
632                         gpointer data)
633 {
634     frontend *fe = (frontend *)data;
635
636     if (fe->pixmap) {
637         gdk_draw_pixmap(widget->window,
638                         widget->style->fg_gc[GTK_WIDGET_STATE(widget)],
639                         fe->pixmap,
640                         event->area.x - fe->ox, event->area.y - fe->oy,
641                         event->area.x, event->area.y,
642                         event->area.width, event->area.height);
643     }
644     return TRUE;
645 }
646
647 static gint map_window(GtkWidget *widget, GdkEvent *event,
648                        gpointer data)
649 {
650     frontend *fe = (frontend *)data;
651
652     /*
653      * Apparently we need to do this because otherwise the status
654      * bar will fail to update immediately. Annoying, but there we
655      * go.
656      */
657     gtk_widget_queue_draw(fe->window);
658
659     return TRUE;
660 }
661
662 static gint configure_area(GtkWidget *widget,
663                            GdkEventConfigure *event, gpointer data)
664 {
665     frontend *fe = (frontend *)data;
666     GdkGC *gc;
667     int x, y;
668
669     if (fe->pixmap)
670         gdk_pixmap_unref(fe->pixmap);
671
672     x = fe->w = event->width;
673     y = fe->h = event->height;
674     midend_size(fe->me, &x, &y, TRUE);
675     fe->pw = x;
676     fe->ph = y;
677     fe->ox = (fe->w - fe->pw) / 2;
678     fe->oy = (fe->h - fe->ph) / 2;
679
680     fe->pixmap = gdk_pixmap_new(widget->window, fe->pw, fe->ph, -1);
681
682     gc = gdk_gc_new(fe->area->window);
683     gdk_gc_set_foreground(gc, &fe->colours[0]);
684     gdk_draw_rectangle(fe->pixmap, gc, 1, 0, 0, fe->pw, fe->ph);
685     gdk_draw_rectangle(widget->window, gc, 1, 0, 0,
686                        event->width, event->height);
687     gdk_gc_unref(gc);
688
689     midend_force_redraw(fe->me);
690
691     return TRUE;
692 }
693
694 static gint timer_func(gpointer data)
695 {
696     frontend *fe = (frontend *)data;
697
698     if (fe->timer_active) {
699         struct timeval now;
700         float elapsed;
701         gettimeofday(&now, NULL);
702         elapsed = ((now.tv_usec - fe->last_time.tv_usec) * 0.000001F +
703                    (now.tv_sec - fe->last_time.tv_sec));
704         midend_timer(fe->me, elapsed);  /* may clear timer_active */
705         fe->last_time = now;
706     }
707
708     return fe->timer_active;
709 }
710
711 void deactivate_timer(frontend *fe)
712 {
713     if (!fe)
714         return;                        /* can happen due to --generate */
715     if (fe->timer_active)
716         gtk_timeout_remove(fe->timer_id);
717     fe->timer_active = FALSE;
718 }
719
720 void activate_timer(frontend *fe)
721 {
722     if (!fe)
723         return;                        /* can happen due to --generate */
724     if (!fe->timer_active) {
725         fe->timer_id = gtk_timeout_add(20, timer_func, fe);
726         gettimeofday(&fe->last_time, NULL);
727     }
728     fe->timer_active = TRUE;
729 }
730
731 static void window_destroy(GtkWidget *widget, gpointer data)
732 {
733     gtk_main_quit();
734 }
735
736 static void msgbox_button_clicked(GtkButton *button, gpointer data)
737 {
738     GtkWidget *window = GTK_WIDGET(data);
739     int v, *ip;
740
741     ip = (int *)gtk_object_get_data(GTK_OBJECT(window), "user-data");
742     v = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(button), "user-data"));
743     *ip = v;
744
745     gtk_widget_destroy(GTK_WIDGET(data));
746 }
747
748 static int win_key_press(GtkWidget *widget, GdkEventKey *event, gpointer data)
749 {
750     GtkObject *cancelbutton = GTK_OBJECT(data);
751
752     /*
753      * `Escape' effectively clicks the cancel button
754      */
755     if (event->keyval == GDK_Escape) {
756         gtk_signal_emit_by_name(GTK_OBJECT(cancelbutton), "clicked");
757         return TRUE;
758     }
759
760     return FALSE;
761 }
762
763 enum { MB_OK, MB_YESNO };
764
765 int message_box(GtkWidget *parent, char *title, char *msg, int centre,
766                 int type)
767 {
768     GtkWidget *window, *hbox, *text, *button;
769     char *titles;
770     int i, def, cancel;
771
772     window = gtk_dialog_new();
773     text = gtk_label_new(msg);
774     gtk_misc_set_alignment(GTK_MISC(text), 0.0, 0.0);
775     hbox = gtk_hbox_new(FALSE, 0);
776     gtk_box_pack_start(GTK_BOX(hbox), text, FALSE, FALSE, 20);
777     gtk_box_pack_start(GTK_BOX(GTK_DIALOG(window)->vbox),
778                        hbox, FALSE, FALSE, 20);
779     gtk_widget_show(text);
780     gtk_widget_show(hbox);
781     gtk_window_set_title(GTK_WINDOW(window), title);
782     gtk_label_set_line_wrap(GTK_LABEL(text), TRUE);
783
784     if (type == MB_OK) {
785         titles = "OK\0";
786         def = cancel = 0;
787     } else {
788         assert(type == MB_YESNO);
789         titles = "Yes\0No\0";
790         def = 0;
791         cancel = 1;
792     }
793     i = 0;
794     
795     while (*titles) {
796         button = gtk_button_new_with_label(titles);
797         gtk_box_pack_end(GTK_BOX(GTK_DIALOG(window)->action_area),
798                          button, FALSE, FALSE, 0);
799         gtk_widget_show(button);
800         if (i == def) {
801             GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
802             gtk_window_set_default(GTK_WINDOW(window), button);
803         }
804         if (i == cancel) {
805             gtk_signal_connect(GTK_OBJECT(window), "key_press_event",
806                                GTK_SIGNAL_FUNC(win_key_press), button);
807         }
808         gtk_signal_connect(GTK_OBJECT(button), "clicked",
809                            GTK_SIGNAL_FUNC(msgbox_button_clicked), window);
810         gtk_object_set_data(GTK_OBJECT(button), "user-data",
811                             GINT_TO_POINTER(i));
812         titles += strlen(titles)+1;
813         i++;
814     }
815     gtk_object_set_data(GTK_OBJECT(window), "user-data",
816                         GINT_TO_POINTER(&i));
817     gtk_signal_connect(GTK_OBJECT(window), "destroy",
818                        GTK_SIGNAL_FUNC(window_destroy), NULL);
819     gtk_window_set_modal(GTK_WINDOW(window), TRUE);
820     gtk_window_set_transient_for(GTK_WINDOW(window), GTK_WINDOW(parent));
821     /* set_transient_window_pos(parent, window); */
822     gtk_widget_show(window);
823     i = -1;
824     gtk_main();
825     return (type == MB_YESNO ? i == 0 : TRUE);
826 }
827
828 void error_box(GtkWidget *parent, char *msg)
829 {
830     message_box(parent, "Error", msg, FALSE, MB_OK);
831 }
832
833 static void config_ok_button_clicked(GtkButton *button, gpointer data)
834 {
835     frontend *fe = (frontend *)data;
836     char *err;
837
838     err = midend_set_config(fe->me, fe->cfg_which, fe->cfg);
839
840     if (err)
841         error_box(fe->cfgbox, err);
842     else {
843         fe->cfgret = TRUE;
844         gtk_widget_destroy(fe->cfgbox);
845     }
846 }
847
848 static void config_cancel_button_clicked(GtkButton *button, gpointer data)
849 {
850     frontend *fe = (frontend *)data;
851
852     gtk_widget_destroy(fe->cfgbox);
853 }
854
855 static int editbox_key(GtkWidget *widget, GdkEventKey *event, gpointer data)
856 {
857     /*
858      * GtkEntry has a nasty habit of eating the Return key, which
859      * is unhelpful since it doesn't actually _do_ anything with it
860      * (it calls gtk_widget_activate, but our edit boxes never need
861      * activating). So I catch Return before GtkEntry sees it, and
862      * pass it straight on to the parent widget. Effect: hitting
863      * Return in an edit box will now activate the default button
864      * in the dialog just like it will everywhere else.
865      */
866     if (event->keyval == GDK_Return && widget->parent != NULL) {
867         gint return_val;
868         gtk_signal_emit_stop_by_name(GTK_OBJECT(widget), "key_press_event");
869         gtk_signal_emit_by_name(GTK_OBJECT(widget->parent), "key_press_event",
870                                 event, &return_val);
871         return return_val;
872     }
873     return FALSE;
874 }
875
876 static void editbox_changed(GtkEditable *ed, gpointer data)
877 {
878     config_item *i = (config_item *)data;
879
880     sfree(i->sval);
881     i->sval = dupstr(gtk_entry_get_text(GTK_ENTRY(ed)));
882 }
883
884 static void button_toggled(GtkToggleButton *tb, gpointer data)
885 {
886     config_item *i = (config_item *)data;
887
888     i->ival = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(tb));
889 }
890
891 static void droplist_sel(GtkMenuItem *item, gpointer data)
892 {
893     config_item *i = (config_item *)data;
894
895     i->ival = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(item),
896                                                   "user-data"));
897 }
898
899 static int get_config(frontend *fe, int which)
900 {
901     GtkWidget *w, *table, *cancel;
902     char *title;
903     config_item *i;
904     int y;
905
906     fe->cfg = midend_get_config(fe->me, which, &title);
907     fe->cfg_which = which;
908     fe->cfgret = FALSE;
909
910     fe->cfgbox = gtk_dialog_new();
911     gtk_window_set_title(GTK_WINDOW(fe->cfgbox), title);
912     sfree(title);
913
914     w = gtk_button_new_with_label("OK");
915     gtk_box_pack_end(GTK_BOX(GTK_DIALOG(fe->cfgbox)->action_area),
916                      w, FALSE, FALSE, 0);
917     gtk_widget_show(w);
918     GTK_WIDGET_SET_FLAGS(w, GTK_CAN_DEFAULT);
919     gtk_window_set_default(GTK_WINDOW(fe->cfgbox), w);
920     gtk_signal_connect(GTK_OBJECT(w), "clicked",
921                        GTK_SIGNAL_FUNC(config_ok_button_clicked), fe);
922
923     w = gtk_button_new_with_label("Cancel");
924     gtk_box_pack_end(GTK_BOX(GTK_DIALOG(fe->cfgbox)->action_area),
925                      w, FALSE, FALSE, 0);
926     gtk_widget_show(w);
927     gtk_signal_connect(GTK_OBJECT(w), "clicked",
928                        GTK_SIGNAL_FUNC(config_cancel_button_clicked), fe);
929     cancel = w;
930
931     table = gtk_table_new(1, 2, FALSE);
932     y = 0;
933     gtk_box_pack_end(GTK_BOX(GTK_DIALOG(fe->cfgbox)->vbox),
934                      table, FALSE, FALSE, 0);
935     gtk_widget_show(table);
936
937     for (i = fe->cfg; i->type != C_END; i++) {
938         gtk_table_resize(GTK_TABLE(table), y+1, 2);
939
940         switch (i->type) {
941           case C_STRING:
942             /*
943              * Edit box with a label beside it.
944              */
945
946             w = gtk_label_new(i->name);
947             gtk_misc_set_alignment(GTK_MISC(w), 0.0, 0.5);
948             gtk_table_attach(GTK_TABLE(table), w, 0, 1, y, y+1,
949                              GTK_EXPAND | GTK_SHRINK | GTK_FILL,
950                              GTK_EXPAND | GTK_SHRINK | GTK_FILL,
951                              3, 3);
952             gtk_widget_show(w);
953
954             w = gtk_entry_new();
955             gtk_table_attach(GTK_TABLE(table), w, 1, 2, y, y+1,
956                              GTK_EXPAND | GTK_SHRINK | GTK_FILL,
957                              GTK_EXPAND | GTK_SHRINK | GTK_FILL,
958                              3, 3);
959             gtk_entry_set_text(GTK_ENTRY(w), i->sval);
960             gtk_signal_connect(GTK_OBJECT(w), "changed",
961                                GTK_SIGNAL_FUNC(editbox_changed), i);
962             gtk_signal_connect(GTK_OBJECT(w), "key_press_event",
963                                GTK_SIGNAL_FUNC(editbox_key), NULL);
964             gtk_widget_show(w);
965
966             break;
967
968           case C_BOOLEAN:
969             /*
970              * Simple checkbox.
971              */
972             w = gtk_check_button_new_with_label(i->name);
973             gtk_signal_connect(GTK_OBJECT(w), "toggled",
974                                GTK_SIGNAL_FUNC(button_toggled), i);
975             gtk_table_attach(GTK_TABLE(table), w, 0, 2, y, y+1,
976                              GTK_EXPAND | GTK_SHRINK | GTK_FILL,
977                              GTK_EXPAND | GTK_SHRINK | GTK_FILL,
978                              3, 3);
979             gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(w), i->ival);
980             gtk_widget_show(w);
981             break;
982
983           case C_CHOICES:
984             /*
985              * Drop-down list (GtkOptionMenu).
986              */
987
988             w = gtk_label_new(i->name);
989             gtk_misc_set_alignment(GTK_MISC(w), 0.0, 0.5);
990             gtk_table_attach(GTK_TABLE(table), w, 0, 1, y, y+1,
991                              GTK_EXPAND | GTK_SHRINK | GTK_FILL,
992                              GTK_EXPAND | GTK_SHRINK | GTK_FILL,
993                              3, 3);
994             gtk_widget_show(w);
995
996             w = gtk_option_menu_new();
997             gtk_table_attach(GTK_TABLE(table), w, 1, 2, y, y+1,
998                              GTK_EXPAND | GTK_SHRINK | GTK_FILL,
999                              GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1000                              3, 3);
1001             gtk_widget_show(w);
1002
1003             {
1004                 int c, val;
1005                 char *p, *q, *name;
1006                 GtkWidget *menuitem;
1007                 GtkWidget *menu = gtk_menu_new();
1008
1009                 gtk_option_menu_set_menu(GTK_OPTION_MENU(w), menu);
1010
1011                 c = *i->sval;
1012                 p = i->sval+1;
1013                 val = 0;
1014
1015                 while (*p) {
1016                     q = p;
1017                     while (*q && *q != c)
1018                         q++;
1019
1020                     name = snewn(q-p+1, char);
1021                     strncpy(name, p, q-p);
1022                     name[q-p] = '\0';
1023
1024                     if (*q) q++;       /* eat delimiter */
1025
1026                     menuitem = gtk_menu_item_new_with_label(name);
1027                     gtk_container_add(GTK_CONTAINER(menu), menuitem);
1028                     gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1029                                         GINT_TO_POINTER(val));
1030                     gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1031                                        GTK_SIGNAL_FUNC(droplist_sel), i);
1032                     gtk_widget_show(menuitem);
1033
1034                     val++;
1035
1036                     p = q;
1037                 }
1038
1039                 gtk_option_menu_set_history(GTK_OPTION_MENU(w), i->ival);
1040             }
1041
1042             break;
1043         }
1044
1045         y++;
1046     }
1047
1048     gtk_signal_connect(GTK_OBJECT(fe->cfgbox), "destroy",
1049                        GTK_SIGNAL_FUNC(window_destroy), NULL);
1050     gtk_signal_connect(GTK_OBJECT(fe->cfgbox), "key_press_event",
1051                        GTK_SIGNAL_FUNC(win_key_press), cancel);
1052     gtk_window_set_modal(GTK_WINDOW(fe->cfgbox), TRUE);
1053     gtk_window_set_transient_for(GTK_WINDOW(fe->cfgbox),
1054                                  GTK_WINDOW(fe->window));
1055     /* set_transient_window_pos(fe->window, fe->cfgbox); */
1056     gtk_widget_show(fe->cfgbox);
1057     gtk_main();
1058
1059     free_cfg(fe->cfg);
1060
1061     return fe->cfgret;
1062 }
1063
1064 static void menu_key_event(GtkMenuItem *menuitem, gpointer data)
1065 {
1066     frontend *fe = (frontend *)data;
1067     int key = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(menuitem),
1068                                                   "user-data"));
1069     if (!midend_process_key(fe->me, 0, 0, key))
1070         gtk_widget_destroy(fe->window);
1071 }
1072
1073 static void get_size(frontend *fe, int *px, int *py)
1074 {
1075     int x, y;
1076
1077     /*
1078      * Currently I don't want to make the GTK port scale large
1079      * puzzles to fit on the screen. This is because X does permit
1080      * extremely large windows and many window managers provide a
1081      * means of navigating round them, and the users I consulted
1082      * before deciding said that they'd rather have enormous puzzle
1083      * windows spanning multiple screen pages than have them
1084      * shrunk. I could change my mind later or introduce
1085      * configurability; this would be the place to do so, by
1086      * replacing the initial values of x and y with the screen
1087      * dimensions.
1088      */
1089     x = INT_MAX;
1090     y = INT_MAX;
1091     midend_size(fe->me, &x, &y, FALSE);
1092     *px = x;
1093     *py = y;
1094 }
1095
1096 #if !GTK_CHECK_VERSION(2,0,0)
1097 #define gtk_window_resize(win, x, y) \
1098         gdk_window_resize(GTK_WIDGET(win)->window, x, y)
1099 #endif
1100
1101 static void menu_preset_event(GtkMenuItem *menuitem, gpointer data)
1102 {
1103     frontend *fe = (frontend *)data;
1104     game_params *params =
1105         (game_params *)gtk_object_get_data(GTK_OBJECT(menuitem), "user-data");
1106     int x, y;
1107
1108     midend_set_params(fe->me, params);
1109     midend_new_game(fe->me);
1110     get_size(fe, &x, &y);
1111     fe->w = x;
1112     fe->h = y;
1113     gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
1114     {
1115         GtkRequisition req;
1116         gtk_widget_size_request(GTK_WIDGET(fe->window), &req);
1117         gtk_window_resize(GTK_WINDOW(fe->window), req.width, req.height);
1118     }
1119 }
1120
1121 GdkAtom compound_text_atom, utf8_string_atom;
1122 int paste_initialised = FALSE;
1123
1124 void init_paste()
1125 {
1126     unsigned char empty[] = { 0 };
1127
1128     if (paste_initialised)
1129         return;
1130
1131     if (!compound_text_atom)
1132         compound_text_atom = gdk_atom_intern("COMPOUND_TEXT", FALSE);
1133     if (!utf8_string_atom)
1134         utf8_string_atom = gdk_atom_intern("UTF8_STRING", FALSE);
1135
1136     /*
1137      * Ensure that all the cut buffers exist - according to the
1138      * ICCCM, we must do this before we start using cut buffers.
1139      */
1140     XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1141                     XA_CUT_BUFFER0, XA_STRING, 8, PropModeAppend, empty, 0);
1142     XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1143                     XA_CUT_BUFFER1, XA_STRING, 8, PropModeAppend, empty, 0);
1144     XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1145                     XA_CUT_BUFFER2, XA_STRING, 8, PropModeAppend, empty, 0);
1146     XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1147                     XA_CUT_BUFFER3, XA_STRING, 8, PropModeAppend, empty, 0);
1148     XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1149                     XA_CUT_BUFFER4, XA_STRING, 8, PropModeAppend, empty, 0);
1150     XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1151                     XA_CUT_BUFFER5, XA_STRING, 8, PropModeAppend, empty, 0);
1152     XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1153                     XA_CUT_BUFFER6, XA_STRING, 8, PropModeAppend, empty, 0);
1154     XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1155                     XA_CUT_BUFFER7, XA_STRING, 8, PropModeAppend, empty, 0);
1156 }
1157
1158 /* Store data in a cut-buffer. */
1159 void store_cutbuffer(char *ptr, int len)
1160 {
1161     /* ICCCM says we must rotate the buffers before storing to buffer 0. */
1162     XRotateBuffers(GDK_DISPLAY(), 1);
1163     XStoreBytes(GDK_DISPLAY(), ptr, len);
1164 }
1165
1166 void write_clip(frontend *fe, char *data)
1167 {
1168     init_paste();
1169
1170     if (fe->paste_data)
1171         sfree(fe->paste_data);
1172
1173     /*
1174      * For this simple application we can safely assume that the
1175      * data passed to this function is pure ASCII, which means we
1176      * can return precisely the same stuff for types STRING,
1177      * COMPOUND_TEXT or UTF8_STRING.
1178      */
1179
1180     fe->paste_data = data;
1181     fe->paste_data_len = strlen(data);
1182
1183     store_cutbuffer(fe->paste_data, fe->paste_data_len);
1184
1185     if (gtk_selection_owner_set(fe->area, GDK_SELECTION_PRIMARY,
1186                                 CurrentTime)) {
1187         gtk_selection_add_target(fe->area, GDK_SELECTION_PRIMARY,
1188                                  GDK_SELECTION_TYPE_STRING, 1);
1189         gtk_selection_add_target(fe->area, GDK_SELECTION_PRIMARY,
1190                                  compound_text_atom, 1);
1191         gtk_selection_add_target(fe->area, GDK_SELECTION_PRIMARY,
1192                                  utf8_string_atom, 1);
1193     }
1194 }
1195
1196 void selection_get(GtkWidget *widget, GtkSelectionData *seldata,
1197                    guint info, guint time_stamp, gpointer data)
1198 {
1199     frontend *fe = (frontend *)data;
1200     gtk_selection_data_set(seldata, seldata->target, 8,
1201                            fe->paste_data, fe->paste_data_len);
1202 }
1203
1204 gint selection_clear(GtkWidget *widget, GdkEventSelection *seldata,
1205                      gpointer data)
1206 {
1207     frontend *fe = (frontend *)data;
1208
1209     if (fe->paste_data)
1210         sfree(fe->paste_data);
1211     fe->paste_data = NULL;
1212     fe->paste_data_len = 0;
1213     return TRUE;
1214 }
1215
1216 static void menu_copy_event(GtkMenuItem *menuitem, gpointer data)
1217 {
1218     frontend *fe = (frontend *)data;
1219     char *text;
1220
1221     text = midend_text_format(fe->me);
1222
1223     if (text) {
1224         write_clip(fe, text);
1225     } else {
1226         gdk_beep();
1227     }
1228 }
1229
1230 static void filesel_ok(GtkButton *button, gpointer data)
1231 {
1232     frontend *fe = (frontend *)data;
1233
1234     gpointer filesel = gtk_object_get_data(GTK_OBJECT(button), "user-data");
1235
1236     const char *name =
1237         gtk_file_selection_get_filename(GTK_FILE_SELECTION(filesel));
1238
1239     fe->filesel_name = dupstr(name);
1240 }
1241
1242 static char *file_selector(frontend *fe, char *title, int save)
1243 {
1244     GtkWidget *filesel =
1245         gtk_file_selection_new(title);
1246
1247     fe->filesel_name = NULL;
1248
1249     gtk_window_set_modal(GTK_WINDOW(filesel), TRUE);
1250     gtk_object_set_data
1251         (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "user-data",
1252          (gpointer)filesel);
1253     gtk_signal_connect
1254         (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "clicked",
1255          GTK_SIGNAL_FUNC(filesel_ok), fe);
1256     gtk_signal_connect_object
1257         (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "clicked",
1258          GTK_SIGNAL_FUNC(gtk_widget_destroy), (gpointer)filesel);
1259     gtk_signal_connect_object
1260         (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->cancel_button), "clicked",
1261          GTK_SIGNAL_FUNC(gtk_widget_destroy), (gpointer)filesel);
1262     gtk_signal_connect(GTK_OBJECT(filesel), "destroy",
1263                        GTK_SIGNAL_FUNC(window_destroy), NULL);
1264     gtk_widget_show(filesel);
1265     gtk_window_set_transient_for(GTK_WINDOW(filesel), GTK_WINDOW(fe->window));
1266     gtk_main();
1267
1268     return fe->filesel_name;
1269 }
1270
1271 static void savefile_write(void *wctx, void *buf, int len)
1272 {
1273     FILE *fp = (FILE *)wctx;
1274     fwrite(buf, 1, len, fp);
1275 }
1276
1277 static int savefile_read(void *wctx, void *buf, int len)
1278 {
1279     FILE *fp = (FILE *)wctx;
1280     int ret;
1281
1282     ret = fread(buf, 1, len, fp);
1283     return (ret == len);
1284 }
1285
1286 static void menu_save_event(GtkMenuItem *menuitem, gpointer data)
1287 {
1288     frontend *fe = (frontend *)data;
1289     char *name;
1290
1291     name = file_selector(fe, "Enter name of game file to save", TRUE);
1292
1293     if (name) {
1294         FILE *fp;
1295
1296         if ((fp = fopen(name, "r")) != NULL) {
1297             char buf[256 + FILENAME_MAX];
1298             fclose(fp);
1299             /* file exists */
1300
1301             sprintf(buf, "Are you sure you want to overwrite the"
1302                     " file \"%.*s\"?",
1303                     FILENAME_MAX, name);
1304             if (!message_box(fe->window, "Question", buf, TRUE, MB_YESNO))
1305                 return;
1306         }
1307
1308         fp = fopen(name, "w");
1309         sfree(name);
1310
1311         if (!fp) {
1312             error_box(fe->window, "Unable to open save file");
1313             return;
1314         }
1315
1316         midend_serialise(fe->me, savefile_write, fp);
1317
1318         fclose(fp);
1319     }
1320 }
1321
1322 static void menu_load_event(GtkMenuItem *menuitem, gpointer data)
1323 {
1324     frontend *fe = (frontend *)data;
1325     char *name, *err;
1326     int x, y;
1327
1328     name = file_selector(fe, "Enter name of saved game file to load", FALSE);
1329
1330     if (name) {
1331         FILE *fp = fopen(name, "r");
1332         sfree(name);
1333
1334         if (!fp) {
1335             error_box(fe->window, "Unable to open saved game file");
1336             return;
1337         }
1338
1339         err = midend_deserialise(fe->me, savefile_read, fp);
1340
1341         fclose(fp);
1342
1343         if (err) {
1344             error_box(fe->window, err);
1345             return;
1346         }
1347
1348         get_size(fe, &x, &y);
1349         fe->w = x;
1350         fe->h = y;
1351         gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
1352         {
1353             GtkRequisition req;
1354             gtk_widget_size_request(GTK_WIDGET(fe->window), &req);
1355             gtk_window_resize(GTK_WINDOW(fe->window), req.width, req.height);
1356         }
1357
1358     }
1359 }
1360
1361 static void menu_solve_event(GtkMenuItem *menuitem, gpointer data)
1362 {
1363     frontend *fe = (frontend *)data;
1364     char *msg;
1365
1366     msg = midend_solve(fe->me);
1367
1368     if (msg)
1369         error_box(fe->window, msg);
1370 }
1371
1372 static void menu_restart_event(GtkMenuItem *menuitem, gpointer data)
1373 {
1374     frontend *fe = (frontend *)data;
1375
1376     midend_restart_game(fe->me);
1377 }
1378
1379 static void menu_config_event(GtkMenuItem *menuitem, gpointer data)
1380 {
1381     frontend *fe = (frontend *)data;
1382     int which = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(menuitem),
1383                                                     "user-data"));
1384     int x, y;
1385
1386     if (!get_config(fe, which))
1387         return;
1388
1389     midend_new_game(fe->me);
1390     get_size(fe, &x, &y);
1391     fe->w = x;
1392     fe->h = y;
1393     gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
1394     {
1395         GtkRequisition req;
1396         gtk_widget_size_request(GTK_WIDGET(fe->window), &req);
1397         gtk_window_resize(GTK_WINDOW(fe->window), req.width, req.height);
1398     }
1399 }
1400
1401 static void menu_about_event(GtkMenuItem *menuitem, gpointer data)
1402 {
1403     frontend *fe = (frontend *)data;
1404     char titlebuf[256];
1405     char textbuf[1024];
1406
1407     sprintf(titlebuf, "About %.200s", thegame.name);
1408     sprintf(textbuf,
1409             "%.200s\n\n"
1410             "from Simon Tatham's Portable Puzzle Collection\n\n"
1411             "%.500s", thegame.name, ver);
1412
1413     message_box(fe->window, titlebuf, textbuf, TRUE, MB_OK);
1414 }
1415
1416 static GtkWidget *add_menu_item_with_key(frontend *fe, GtkContainer *cont,
1417                                          char *text, int key)
1418 {
1419     GtkWidget *menuitem = gtk_menu_item_new_with_label(text);
1420     int keyqual;
1421     gtk_container_add(cont, menuitem);
1422     gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1423                         GINT_TO_POINTER(key));
1424     gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1425                        GTK_SIGNAL_FUNC(menu_key_event), fe);
1426     switch (key & ~0x1F) {
1427       case 0x00:
1428         key += 0x60;
1429         keyqual = GDK_CONTROL_MASK;
1430         break;
1431       case 0x40:
1432         key += 0x20;
1433         keyqual = GDK_SHIFT_MASK;
1434         break;
1435       default:
1436         keyqual = 0;
1437         break;
1438     }
1439     gtk_widget_add_accelerator(menuitem,
1440                                "activate", fe->accelgroup,
1441                                key, keyqual,
1442                                GTK_ACCEL_VISIBLE);
1443     gtk_widget_show(menuitem);
1444     return menuitem;
1445 }
1446
1447 static void add_menu_separator(GtkContainer *cont)
1448 {
1449     GtkWidget *menuitem = gtk_menu_item_new();
1450     gtk_container_add(cont, menuitem);
1451     gtk_widget_show(menuitem);
1452 }
1453
1454 enum { ARG_EITHER, ARG_SAVE, ARG_ID }; /* for argtype */
1455
1456 static frontend *new_window(char *arg, int argtype, char **error)
1457 {
1458     frontend *fe;
1459     GtkBox *vbox;
1460     GtkWidget *menubar, *menu, *menuitem;
1461     int x, y, n;
1462     char errbuf[1024];
1463
1464     fe = snew(frontend);
1465
1466     fe->timer_active = FALSE;
1467     fe->timer_id = -1;
1468
1469     fe->me = midend_new(fe, &thegame, &gtk_drawing, fe);
1470
1471     if (arg) {
1472         char *err;
1473         FILE *fp;
1474
1475         errbuf[0] = '\0';
1476
1477         switch (argtype) {
1478           case ARG_ID:
1479             err = midend_game_id(fe->me, arg);
1480             if (!err)
1481                 midend_new_game(fe->me);
1482             else
1483                 sprintf(errbuf, "Invalid game ID: %.800s", err);
1484             break;
1485           case ARG_SAVE:
1486             fp = fopen(arg, "r");
1487             if (!fp) {
1488                 sprintf(errbuf, "Error opening file: %.800s", strerror(errno));
1489             } else {
1490                 err = midend_deserialise(fe->me, savefile_read, fp);
1491                 if (err)
1492                     sprintf(errbuf, "Invalid save file: %.800s", err);
1493                 fclose(fp);
1494             }
1495             break;
1496           default /*case ARG_EITHER*/:
1497             /*
1498              * First try treating the argument as a game ID.
1499              */
1500             err = midend_game_id(fe->me, arg);
1501             if (!err) {
1502                 /*
1503                  * It's a valid game ID.
1504                  */
1505                 midend_new_game(fe->me);
1506             } else {
1507                 FILE *fp = fopen(arg, "r");
1508                 if (!fp) {
1509                     sprintf(errbuf, "Supplied argument is neither a game ID (%.400s)"
1510                             " nor a save file (%.400s)", err, strerror(errno));
1511                 } else {
1512                     err = midend_deserialise(fe->me, savefile_read, fp);
1513                     if (err)
1514                         sprintf(errbuf, "%.800s", err);
1515                     fclose(fp);
1516                 }
1517             }
1518             break;
1519         }
1520         if (*errbuf) {
1521             *error = dupstr(errbuf);
1522             midend_free(fe->me);
1523             sfree(fe);
1524             return NULL;
1525         }
1526
1527     } else {
1528         midend_new_game(fe->me);
1529     }
1530
1531     fe->window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1532     gtk_window_set_title(GTK_WINDOW(fe->window), thegame.name);
1533
1534     vbox = GTK_BOX(gtk_vbox_new(FALSE, 0));
1535     gtk_container_add(GTK_CONTAINER(fe->window), GTK_WIDGET(vbox));
1536     gtk_widget_show(GTK_WIDGET(vbox));
1537
1538     fe->accelgroup = gtk_accel_group_new();
1539     gtk_window_add_accel_group(GTK_WINDOW(fe->window), fe->accelgroup);
1540
1541     menubar = gtk_menu_bar_new();
1542     gtk_box_pack_start(vbox, menubar, FALSE, FALSE, 0);
1543     gtk_widget_show(menubar);
1544
1545     menuitem = gtk_menu_item_new_with_label("Game");
1546     gtk_container_add(GTK_CONTAINER(menubar), menuitem);
1547     gtk_widget_show(menuitem);
1548
1549     menu = gtk_menu_new();
1550     gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
1551
1552     add_menu_item_with_key(fe, GTK_CONTAINER(menu), "New", 'n');
1553
1554     menuitem = gtk_menu_item_new_with_label("Restart");
1555     gtk_container_add(GTK_CONTAINER(menu), menuitem);
1556     gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1557                        GTK_SIGNAL_FUNC(menu_restart_event), fe);
1558     gtk_widget_show(menuitem);
1559
1560     menuitem = gtk_menu_item_new_with_label("Specific...");
1561     gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1562                         GINT_TO_POINTER(CFG_DESC));
1563     gtk_container_add(GTK_CONTAINER(menu), menuitem);
1564     gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1565                        GTK_SIGNAL_FUNC(menu_config_event), fe);
1566     gtk_widget_show(menuitem);
1567
1568     menuitem = gtk_menu_item_new_with_label("Random Seed...");
1569     gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1570                         GINT_TO_POINTER(CFG_SEED));
1571     gtk_container_add(GTK_CONTAINER(menu), menuitem);
1572     gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1573                        GTK_SIGNAL_FUNC(menu_config_event), fe);
1574     gtk_widget_show(menuitem);
1575
1576     if ((n = midend_num_presets(fe->me)) > 0 || thegame.can_configure) {
1577         GtkWidget *submenu;
1578         int i;
1579
1580         menuitem = gtk_menu_item_new_with_label("Type");
1581         gtk_container_add(GTK_CONTAINER(menubar), menuitem);
1582         gtk_widget_show(menuitem);
1583
1584         submenu = gtk_menu_new();
1585         gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), submenu);
1586
1587         for (i = 0; i < n; i++) {
1588             char *name;
1589             game_params *params;
1590
1591             midend_fetch_preset(fe->me, i, &name, &params);
1592
1593             menuitem = gtk_menu_item_new_with_label(name);
1594             gtk_container_add(GTK_CONTAINER(submenu), menuitem);
1595             gtk_object_set_data(GTK_OBJECT(menuitem), "user-data", params);
1596             gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1597                                GTK_SIGNAL_FUNC(menu_preset_event), fe);
1598             gtk_widget_show(menuitem);
1599         }
1600
1601         if (thegame.can_configure) {
1602             menuitem = gtk_menu_item_new_with_label("Custom...");
1603             gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1604                                 GPOINTER_TO_INT(CFG_SETTINGS));
1605             gtk_container_add(GTK_CONTAINER(submenu), menuitem);
1606             gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1607                                GTK_SIGNAL_FUNC(menu_config_event), fe);
1608             gtk_widget_show(menuitem);
1609         }
1610     }
1611
1612     add_menu_separator(GTK_CONTAINER(menu));
1613     menuitem = gtk_menu_item_new_with_label("Load");
1614     gtk_container_add(GTK_CONTAINER(menu), menuitem);
1615     gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1616                        GTK_SIGNAL_FUNC(menu_load_event), fe);
1617     gtk_widget_show(menuitem);
1618     menuitem = gtk_menu_item_new_with_label("Save");
1619     gtk_container_add(GTK_CONTAINER(menu), menuitem);
1620     gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1621                        GTK_SIGNAL_FUNC(menu_save_event), fe);
1622     gtk_widget_show(menuitem);
1623     add_menu_separator(GTK_CONTAINER(menu));
1624     add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Undo", 'u');
1625     add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Redo", 'r');
1626     if (thegame.can_format_as_text) {
1627         add_menu_separator(GTK_CONTAINER(menu));
1628         menuitem = gtk_menu_item_new_with_label("Copy");
1629         gtk_container_add(GTK_CONTAINER(menu), menuitem);
1630         gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1631                            GTK_SIGNAL_FUNC(menu_copy_event), fe);
1632         gtk_widget_show(menuitem);
1633     }
1634     if (thegame.can_solve) {
1635         add_menu_separator(GTK_CONTAINER(menu));
1636         menuitem = gtk_menu_item_new_with_label("Solve");
1637         gtk_container_add(GTK_CONTAINER(menu), menuitem);
1638         gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1639                            GTK_SIGNAL_FUNC(menu_solve_event), fe);
1640         gtk_widget_show(menuitem);
1641     }
1642     add_menu_separator(GTK_CONTAINER(menu));
1643     add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Exit", 'q');
1644
1645     menuitem = gtk_menu_item_new_with_label("Help");
1646     gtk_container_add(GTK_CONTAINER(menubar), menuitem);
1647     gtk_widget_show(menuitem);
1648
1649     menu = gtk_menu_new();
1650     gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
1651
1652     menuitem = gtk_menu_item_new_with_label("About");
1653     gtk_container_add(GTK_CONTAINER(menu), menuitem);
1654     gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1655                        GTK_SIGNAL_FUNC(menu_about_event), fe);
1656     gtk_widget_show(menuitem);
1657
1658     {
1659         int i, ncolours;
1660         float *colours;
1661         gboolean *success;
1662
1663         fe->colmap = gdk_colormap_get_system();
1664         colours = midend_colours(fe->me, &ncolours);
1665         fe->ncolours = ncolours;
1666         fe->colours = snewn(ncolours, GdkColor);
1667         for (i = 0; i < ncolours; i++) {
1668             fe->colours[i].red = colours[i*3] * 0xFFFF;
1669             fe->colours[i].green = colours[i*3+1] * 0xFFFF;
1670             fe->colours[i].blue = colours[i*3+2] * 0xFFFF;
1671         }
1672         success = snewn(ncolours, gboolean);
1673         gdk_colormap_alloc_colors(fe->colmap, fe->colours, ncolours,
1674                                   FALSE, FALSE, success);
1675         for (i = 0; i < ncolours; i++) {
1676             if (!success[i])
1677                 g_error("couldn't allocate colour %d (#%02x%02x%02x)\n",
1678                         i, fe->colours[i].red >> 8,
1679                         fe->colours[i].green >> 8,
1680                         fe->colours[i].blue >> 8);
1681         }
1682     }
1683
1684     if (midend_wants_statusbar(fe->me)) {
1685         GtkWidget *viewport;
1686         GtkRequisition req;
1687
1688         viewport = gtk_viewport_new(NULL, NULL);
1689         gtk_viewport_set_shadow_type(GTK_VIEWPORT(viewport), GTK_SHADOW_NONE);
1690         fe->statusbar = gtk_statusbar_new();
1691         gtk_container_add(GTK_CONTAINER(viewport), fe->statusbar);
1692         gtk_widget_show(viewport);
1693         gtk_box_pack_end(vbox, viewport, FALSE, FALSE, 0);
1694         gtk_widget_show(fe->statusbar);
1695         fe->statusctx = gtk_statusbar_get_context_id
1696             (GTK_STATUSBAR(fe->statusbar), "game");
1697         gtk_statusbar_push(GTK_STATUSBAR(fe->statusbar), fe->statusctx,
1698                            "test");
1699         gtk_widget_size_request(fe->statusbar, &req);
1700 #if 0
1701         /* For GTK 2.0, should we be using gtk_widget_set_size_request? */
1702 #endif
1703         gtk_widget_set_usize(viewport, -1, req.height);
1704     } else
1705         fe->statusbar = NULL;
1706
1707     fe->area = gtk_drawing_area_new();
1708     get_size(fe, &x, &y);
1709     gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
1710     fe->w = x;
1711     fe->h = y;
1712
1713     gtk_box_pack_end(vbox, fe->area, TRUE, TRUE, 0);
1714
1715     fe->pixmap = NULL;
1716     fe->fonts = NULL;
1717     fe->nfonts = fe->fontsize = 0;
1718
1719     fe->paste_data = NULL;
1720     fe->paste_data_len = 0;
1721
1722     gtk_signal_connect(GTK_OBJECT(fe->window), "destroy",
1723                        GTK_SIGNAL_FUNC(destroy), fe);
1724     gtk_signal_connect(GTK_OBJECT(fe->window), "key_press_event",
1725                        GTK_SIGNAL_FUNC(key_event), fe);
1726     gtk_signal_connect(GTK_OBJECT(fe->area), "button_press_event",
1727                        GTK_SIGNAL_FUNC(button_event), fe);
1728     gtk_signal_connect(GTK_OBJECT(fe->area), "button_release_event",
1729                        GTK_SIGNAL_FUNC(button_event), fe);
1730     gtk_signal_connect(GTK_OBJECT(fe->area), "motion_notify_event",
1731                        GTK_SIGNAL_FUNC(motion_event), fe);
1732     gtk_signal_connect(GTK_OBJECT(fe->area), "selection_get",
1733                        GTK_SIGNAL_FUNC(selection_get), fe);
1734     gtk_signal_connect(GTK_OBJECT(fe->area), "selection_clear_event",
1735                        GTK_SIGNAL_FUNC(selection_clear), fe);
1736     gtk_signal_connect(GTK_OBJECT(fe->area), "expose_event",
1737                        GTK_SIGNAL_FUNC(expose_area), fe);
1738     gtk_signal_connect(GTK_OBJECT(fe->window), "map_event",
1739                        GTK_SIGNAL_FUNC(map_window), fe);
1740     gtk_signal_connect(GTK_OBJECT(fe->area), "configure_event",
1741                        GTK_SIGNAL_FUNC(configure_area), fe);
1742
1743     gtk_widget_add_events(GTK_WIDGET(fe->area),
1744                           GDK_BUTTON_PRESS_MASK |
1745                           GDK_BUTTON_RELEASE_MASK |
1746                           GDK_BUTTON_MOTION_MASK);
1747
1748     gtk_widget_show(fe->area);
1749     gtk_widget_show(fe->window);
1750
1751     gdk_window_set_background(fe->area->window, &fe->colours[0]);
1752     gdk_window_set_background(fe->window->window, &fe->colours[0]);
1753
1754     return fe;
1755 }
1756
1757 char *fgetline(FILE *fp)
1758 {
1759     char *ret = snewn(512, char);
1760     int size = 512, len = 0;
1761     while (fgets(ret + len, size - len, fp)) {
1762         len += strlen(ret + len);
1763         if (ret[len-1] == '\n')
1764             break;                     /* got a newline, we're done */
1765         size = len + 512;
1766         ret = sresize(ret, size, char);
1767     }
1768     if (len == 0) {                    /* first fgets returned NULL */
1769         sfree(ret);
1770         return NULL;
1771     }
1772     ret[len] = '\0';
1773     return ret;
1774 }
1775
1776 int main(int argc, char **argv)
1777 {
1778     char *pname = argv[0];
1779     char *error;
1780     int ngenerate = 0, print = FALSE, px = 1, py = 1;
1781     int soln = FALSE, colour = FALSE;
1782     float scale = 1.0F;
1783     float redo_proportion = 0.0F;
1784     char *arg = NULL;
1785     int argtype = ARG_EITHER;
1786     int output_window_id = FALSE;
1787     int doing_opts = TRUE;
1788     int ac = argc;
1789     char **av = argv;
1790     char errbuf[500];
1791
1792     /*
1793      * Command line parsing in this function is rather fiddly,
1794      * because GTK wants to have a go at argc/argv _first_ - and
1795      * yet we can't let it, because gtk_init() will bomb out if it
1796      * can't open an X display, whereas in fact we want to permit
1797      * our --generate and --print modes to run without an X
1798      * display.
1799      * 
1800      * So what we do is:
1801      *  - we parse the command line ourselves, without modifying
1802      *    argc/argv
1803      *  - if we encounter an error which might plausibly be the
1804      *    result of a GTK command line (i.e. not detailed errors in
1805      *    particular options of ours) we store the error message
1806      *    and terminate parsing.
1807      *  - if we got enough out of the command line to know it
1808      *    specifies a non-X mode of operation, we either display
1809      *    the stored error and return failure, or if there is no
1810      *    stored error we do the non-X operation and return
1811      *    success.
1812      *  - otherwise, we go straight to gtk_init().
1813      */
1814
1815     errbuf[0] = '\0';
1816     while (--ac > 0) {
1817         char *p = *++av;
1818         if (doing_opts && !strcmp(p, "--version")) {
1819             printf("%s, from Simon Tatham's Portable Puzzle Collection\n%s\n",
1820                    thegame.name, ver);
1821             return 0;
1822         } else if (doing_opts && !strcmp(p, "--generate")) {
1823             if (--ac > 0) {
1824                 ngenerate = atoi(*++av);
1825                 if (!ngenerate) {
1826                     fprintf(stderr, "%s: '--generate' expected a number\n",
1827                             pname);
1828                     return 1;
1829                 }
1830             } else
1831                 ngenerate = 1;
1832         } else if (doing_opts && !strcmp(p, "--print")) {
1833             if (!thegame.can_print) {
1834                 fprintf(stderr, "%s: this game does not support printing\n",
1835                         pname);
1836                 return 1;
1837             }
1838             print = TRUE;
1839             if (--ac > 0) {
1840                 char *dim = *++av;
1841                 if (sscanf(dim, "%dx%d", &px, &py) != 2) {
1842                     fprintf(stderr, "%s: unable to parse argument '%s' to "
1843                             "'--print'\n", pname, dim);
1844                     return 1;
1845                 }
1846             } else {
1847                 px = py = 1;
1848             }
1849         } else if (doing_opts && !strcmp(p, "--scale")) {
1850             if (--ac > 0) {
1851                 scale = atof(*++av);
1852             } else {
1853                 fprintf(stderr, "%s: no argument supplied to '--scale'\n",
1854                         pname);
1855                 return 1;
1856             }
1857         } else if (doing_opts && !strcmp(p, "--redo")) {
1858             /*
1859              * This is an internal option which I don't expect
1860              * users to have any particular use for. The effect of
1861              * --redo is that once the game has been loaded and
1862              * initialised, the next move in the redo chain is
1863              * replayed, and the game screen is redrawn part way
1864              * through the making of the move. This is only
1865              * meaningful if there _is_ a next move in the redo
1866              * chain, which means in turn that this option is only
1867              * useful if you're also passing a save file on the
1868              * command line.
1869              *
1870              * This option is used by the script which generates
1871              * the puzzle icons and website screenshots, and I
1872              * don't imagine it's useful for anything else.
1873              * (Unless, I suppose, users don't like my screenshots
1874              * and want to generate their own in the same way for
1875              * some repackaged version of the puzzles.)
1876              */
1877             if (--ac > 0) {
1878                 redo_proportion = atof(*++av);
1879             } else {
1880                 fprintf(stderr, "%s: no argument supplied to '--redo'\n",
1881                         pname);
1882                 return 1;
1883             }
1884         } else if (doing_opts && !strcmp(p, "--windowid")) {
1885             /*
1886              * Another internal option for the icon building
1887              * script. This causes the window ID of the central
1888              * drawing area (i.e. not including the menu bar or
1889              * status bar) to be printed on standard output once
1890              * the window has been drawn.
1891              */
1892             output_window_id = TRUE;
1893         } else if (doing_opts && (!strcmp(p, "--with-solutions") ||
1894                                   !strcmp(p, "--with-solution") ||
1895                                   !strcmp(p, "--with-solns") ||
1896                                   !strcmp(p, "--with-soln") ||
1897                                   !strcmp(p, "--solutions") ||
1898                                   !strcmp(p, "--solution") ||
1899                                   !strcmp(p, "--solns") ||
1900                                   !strcmp(p, "--soln"))) {
1901             soln = TRUE;
1902         } else if (doing_opts && !strcmp(p, "--colour")) {
1903             if (!thegame.can_print_in_colour) {
1904                 fprintf(stderr, "%s: this game does not support colour"
1905                         " printing\n", pname);
1906                 return 1;
1907             }
1908             colour = TRUE;
1909         } else if (doing_opts && !strcmp(p, "--load")) {
1910             argtype = ARG_SAVE;
1911         } else if (doing_opts && !strcmp(p, "--game")) {
1912             argtype = ARG_ID;
1913         } else if (doing_opts && !strcmp(p, "--")) {
1914             doing_opts = FALSE;
1915         } else if (!doing_opts || p[0] != '-') {
1916             if (arg) {
1917                 fprintf(stderr, "%s: more than one argument supplied\n",
1918                         pname);
1919                 return 1;
1920             }
1921             arg = p;
1922         } else {
1923             sprintf(errbuf, "%.100s: unrecognised option '%.100s'\n",
1924                     pname, p);
1925             break;
1926         }
1927     }
1928
1929     /*
1930      * Special standalone mode for generating puzzle IDs on the
1931      * command line. Useful for generating puzzles to be printed
1932      * out and solved offline (for puzzles where that even makes
1933      * sense - Solo, for example, is a lot more pencil-and-paper
1934      * friendly than Twiddle!)
1935      * 
1936      * Usage:
1937      * 
1938      *   <puzzle-name> --generate [<n> [<params>]]
1939      * 
1940      * <n>, if present, is the number of puzzle IDs to generate.
1941      * <params>, if present, is the same type of parameter string
1942      * you would pass to the puzzle when running it in GUI mode,
1943      * including optional extras such as the expansion factor in
1944      * Rectangles and the difficulty level in Solo.
1945      * 
1946      * If you specify <params>, you must also specify <n> (although
1947      * you may specify it to be 1). Sorry; that was the
1948      * simplest-to-parse command-line syntax I came up with.
1949      */
1950     if (ngenerate > 0 || print) {
1951         int i, n = 1;
1952         midend *me;
1953         char *id;
1954         document *doc = NULL;
1955
1956         if (*errbuf) {
1957             fputs(errbuf, stderr);
1958             return 1;
1959         }
1960
1961         n = ngenerate;
1962
1963         me = midend_new(NULL, &thegame, NULL, NULL);
1964         i = 0;
1965
1966         if (print)
1967             doc = document_new(px, py, scale);
1968
1969         /*
1970          * In this loop, we either generate a game ID or read one
1971          * from stdin depending on whether we're in generate mode;
1972          * then we either write it to stdout or print it, depending
1973          * on whether we're in print mode. Thus, this loop handles
1974          * generate-to-stdout, print-from-stdin and generate-and-
1975          * immediately-print modes.
1976          * 
1977          * (It could also handle a copy-stdin-to-stdout mode,
1978          * although there's currently no combination of options
1979          * which will cause this loop to be activated in that mode.
1980          * It wouldn't be _entirely_ pointless, though, because
1981          * stdin could contain bare params strings or random-seed
1982          * IDs, and stdout would contain nothing but fully
1983          * generated descriptive game IDs.)
1984          */
1985         while (ngenerate == 0 || i < n) {
1986             char *pstr, *err;
1987
1988             if (ngenerate == 0) {
1989                 pstr = fgetline(stdin);
1990                 if (!pstr)
1991                     break;
1992                 pstr[strcspn(pstr, "\r\n")] = '\0';
1993             } else {
1994                 if (arg) {
1995                     pstr = snewn(strlen(arg) + 40, char);
1996
1997                     strcpy(pstr, arg);
1998                     if (i > 0 && strchr(arg, '#'))
1999                         sprintf(pstr + strlen(pstr), "-%d", i);
2000                 } else
2001                     pstr = NULL;
2002             }
2003
2004             if (pstr) {
2005                 err = midend_game_id(me, pstr);
2006                 if (err) {
2007                     fprintf(stderr, "%s: error parsing '%s': %s\n",
2008                             pname, pstr, err);
2009                     return 1;
2010                 }
2011             }
2012             sfree(pstr);
2013
2014             midend_new_game(me);
2015
2016             if (doc) {
2017                 err = midend_print_puzzle(me, doc, soln);
2018                 if (err) {
2019                     fprintf(stderr, "%s: error in printing: %s\n", pname, err);
2020                     return 1;
2021                 }
2022             } else {
2023                 id = midend_get_game_id(me);
2024                 puts(id);
2025                 sfree(id);
2026             }
2027
2028             i++;
2029         }
2030
2031         if (doc) {
2032             psdata *ps = ps_init(stdout, colour);
2033             document_print(doc, ps_drawing_api(ps));
2034             document_free(doc);
2035             ps_free(ps);
2036         }
2037
2038         midend_free(me);
2039
2040         return 0;
2041     } else {
2042         frontend *fe;
2043
2044         gtk_init(&argc, &argv);
2045
2046         fe = new_window(arg, argtype, &error);
2047
2048         if (!fe) {
2049             fprintf(stderr, "%s: %s\n", pname, error);
2050             return 1;
2051         }
2052
2053         if (output_window_id) {
2054             /*
2055              * Some puzzles will not redraw their entire area if
2056              * given a partially completed animation, which means
2057              * we must redraw now and _then_ redraw again after
2058              * freezing the move timer.
2059              */
2060             midend_force_redraw(fe->me);
2061         }
2062
2063         if (redo_proportion) {
2064             /* Start a redo. */
2065             midend_process_key(fe->me, 0, 0, 'r');
2066             /* And freeze the timer at the specified position. */
2067             midend_freeze_timer(fe->me, redo_proportion);
2068         }
2069
2070         if (output_window_id) {
2071             midend_redraw(fe->me);
2072             printf("%p\n", (void *)GDK_WINDOW_XWINDOW(fe->area->window));
2073             fflush(stdout);
2074         }
2075
2076         gtk_main();
2077     }
2078
2079     return 0;
2080 }