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