chiark / gitweb /
Support for loading games in Javascript puzzles.
[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 #include <math.h>
13
14 #include <sys/time.h>
15 #include <sys/resource.h>
16
17 #include <gtk/gtk.h>
18 #include <gdk/gdkkeysyms.h>
19
20 #include <gdk-pixbuf/gdk-pixbuf.h>
21
22 #include <gdk/gdkx.h>
23 #include <X11/Xlib.h>
24 #include <X11/Xutil.h>
25 #include <X11/Xatom.h>
26
27 #include "puzzles.h"
28
29 #if GTK_CHECK_VERSION(2,0,0)
30 # define USE_PANGO
31 # ifdef PANGO_VERSION_CHECK
32 #  if PANGO_VERSION_CHECK(1,8,0)
33 #   define HAVE_SENSIBLE_ABSOLUTE_SIZE_FUNCTION
34 #  endif
35 # endif
36 #endif
37 #if !GTK_CHECK_VERSION(2,4,0)
38 # define OLD_FILESEL
39 #endif
40 #if GTK_CHECK_VERSION(2,8,0)
41 # define USE_CAIRO
42 # if GTK_CHECK_VERSION(3,0,0) || defined(GDK_DISABLE_DEPRECATED)
43 #  define USE_CAIRO_WITHOUT_PIXMAP
44 # endif
45 #endif
46
47 #if GTK_CHECK_VERSION(3,0,0)
48 /* The old names are still more concise! */
49 #define gtk_hbox_new(x,y) gtk_box_new(GTK_ORIENTATION_HORIZONTAL,y)
50 #define gtk_vbox_new(x,y) gtk_box_new(GTK_ORIENTATION_VERTICAL,y)
51 /* GTK 3 has retired stock button labels */
52 #define LABEL_OK "_OK"
53 #define LABEL_CANCEL "_Cancel"
54 #define LABEL_NO "_No"
55 #define LABEL_YES "_Yes"
56 #define LABEL_SAVE "_Save"
57 #define LABEL_OPEN "_Open"
58 #define gtk_button_new_with_our_label gtk_button_new_with_mnemonic
59 #else
60 #define LABEL_OK GTK_STOCK_OK
61 #define LABEL_CANCEL GTK_STOCK_CANCEL
62 #define LABEL_NO GTK_STOCK_NO
63 #define LABEL_YES GTK_STOCK_YES
64 #define LABEL_SAVE GTK_STOCK_SAVE
65 #define LABEL_OPEN GTK_STOCK_OPEN
66 #define gtk_button_new_with_our_label gtk_button_new_from_stock
67 #endif
68
69 /* #undef USE_CAIRO */
70 /* #define NO_THICK_LINE */
71 #ifdef DEBUGGING
72 static FILE *debug_fp = NULL;
73
74 void dputs(char *buf)
75 {
76     if (!debug_fp) {
77         debug_fp = fopen("debug.log", "w");
78     }
79
80     fputs(buf, stderr);
81
82     if (debug_fp) {
83         fputs(buf, debug_fp);
84         fflush(debug_fp);
85     }
86 }
87
88 void debug_printf(char *fmt, ...)
89 {
90     char buf[4096];
91     va_list ap;
92
93     va_start(ap, fmt);
94     vsprintf(buf, fmt, ap);
95     dputs(buf);
96     va_end(ap);
97 }
98 #endif
99
100 /* ----------------------------------------------------------------------
101  * Error reporting functions used elsewhere.
102  */
103
104 void fatal(char *fmt, ...)
105 {
106     va_list ap;
107
108     fprintf(stderr, "fatal error: ");
109
110     va_start(ap, fmt);
111     vfprintf(stderr, fmt, ap);
112     va_end(ap);
113
114     fprintf(stderr, "\n");
115     exit(1);
116 }
117
118 /* ----------------------------------------------------------------------
119  * GTK front end to puzzles.
120  */
121
122 static void changed_preset(frontend *fe);
123
124 struct font {
125 #ifdef USE_PANGO
126     PangoFontDescription *desc;
127 #else
128     GdkFont *font;
129 #endif
130     int type;
131     int size;
132 };
133
134 /*
135  * This structure holds all the data relevant to a single window.
136  * In principle this would allow us to open multiple independent
137  * puzzle windows, although I can't currently see any real point in
138  * doing so. I'm just coding cleanly because there's no
139  * particularly good reason not to.
140  */
141 struct frontend {
142     GtkWidget *window;
143     GtkAccelGroup *accelgroup;
144     GtkWidget *area;
145     GtkWidget *statusbar;
146     GtkWidget *menubar;
147 #if GTK_CHECK_VERSION(3,20,0)
148     GtkCssProvider *css_provider;
149 #endif
150     guint statusctx;
151     int w, h;
152     midend *me;
153 #ifdef USE_CAIRO
154     const float *colours;
155     cairo_t *cr;
156     cairo_surface_t *image;
157 #ifndef USE_CAIRO_WITHOUT_PIXMAP
158     GdkPixmap *pixmap;
159 #endif
160     GdkColor background;               /* for painting outside puzzle area */
161 #else
162     GdkPixmap *pixmap;
163     GdkGC *gc;
164     GdkColor *colours;
165     GdkColormap *colmap;
166     int backgroundindex;               /* which of colours[] is background */
167 #endif
168     int ncolours;
169     int bbox_l, bbox_r, bbox_u, bbox_d;
170     int timer_active, timer_id;
171     struct timeval last_time;
172     struct font *fonts;
173     int nfonts, fontsize;
174     config_item *cfg;
175     int cfg_which, cfgret;
176     GtkWidget *cfgbox;
177     void *paste_data;
178     int paste_data_len;
179     int pw, ph;                        /* pixmap size (w, h are area size) */
180     int ox, oy;                        /* offset of pixmap in drawing area */
181 #ifdef OLD_FILESEL
182     char *filesel_name;
183 #endif
184     GSList *preset_radio;
185     int preset_threaded;
186     GtkWidget *preset_custom;
187     GtkWidget *copy_menu_item;
188 #if !GTK_CHECK_VERSION(3,0,0)
189     int drawing_area_shrink_pending;
190     int menubar_is_local;
191 #endif
192 };
193
194 struct blitter {
195 #ifdef USE_CAIRO
196     cairo_surface_t *image;
197 #else
198     GdkPixmap *pixmap;
199 #endif
200     int w, h, x, y;
201 };
202
203 void get_random_seed(void **randseed, int *randseedsize)
204 {
205     struct timeval *tvp = snew(struct timeval);
206     gettimeofday(tvp, NULL);
207     *randseed = (void *)tvp;
208     *randseedsize = sizeof(struct timeval);
209 }
210
211 void frontend_default_colour(frontend *fe, float *output)
212 {
213 #if !GTK_CHECK_VERSION(3,0,0)
214     /*
215      * Use the widget style's default background colour as the
216      * background for the puzzle drawing area.
217      */
218     GdkColor col = gtk_widget_get_style(fe->window)->bg[GTK_STATE_NORMAL];
219     output[0] = col.red / 65535.0;
220     output[1] = col.green / 65535.0;
221     output[2] = col.blue / 65535.0;
222 #else
223     /*
224      * GTK 3 has decided that there's no such thing as a 'default
225      * background colour' any more, because widget styles might set
226      * the background to something more complicated like a background
227      * image. We don't want to get into overlaying our entire puzzle
228      * on an arbitrary background image, so we'll just make up a
229      * reasonable shade of grey.
230      */
231     output[0] = output[1] = output[2] = 0.9F;
232 #endif
233 }
234
235 void gtk_status_bar(void *handle, char *text)
236 {
237     frontend *fe = (frontend *)handle;
238
239     assert(fe->statusbar);
240
241     gtk_statusbar_pop(GTK_STATUSBAR(fe->statusbar), fe->statusctx);
242     gtk_statusbar_push(GTK_STATUSBAR(fe->statusbar), fe->statusctx, text);
243 }
244
245 /* ----------------------------------------------------------------------
246  * Cairo drawing functions.
247  */
248
249 #ifdef USE_CAIRO
250
251 static void setup_drawing(frontend *fe)
252 {
253     fe->cr = cairo_create(fe->image);
254     cairo_set_antialias(fe->cr, CAIRO_ANTIALIAS_GRAY);
255     cairo_set_line_width(fe->cr, 1.0);
256     cairo_set_line_cap(fe->cr, CAIRO_LINE_CAP_SQUARE);
257     cairo_set_line_join(fe->cr, CAIRO_LINE_JOIN_ROUND);
258 }
259
260 static void teardown_drawing(frontend *fe)
261 {
262     cairo_destroy(fe->cr);
263     fe->cr = NULL;
264
265 #ifndef USE_CAIRO_WITHOUT_PIXMAP
266     {
267         cairo_t *cr = gdk_cairo_create(fe->pixmap);
268         cairo_set_source_surface(cr, fe->image, 0, 0);
269         cairo_rectangle(cr,
270                         fe->bbox_l - 1,
271                         fe->bbox_u - 1,
272                         fe->bbox_r - fe->bbox_l + 2,
273                         fe->bbox_d - fe->bbox_u + 2);
274         cairo_fill(cr);
275         cairo_destroy(cr);
276     }
277 #endif
278 }
279
280 static void snaffle_colours(frontend *fe)
281 {
282     fe->colours = midend_colours(fe->me, &fe->ncolours);
283 }
284
285 static void set_colour(frontend *fe, int colour)
286 {
287     cairo_set_source_rgb(fe->cr,
288                          fe->colours[3*colour + 0],
289                          fe->colours[3*colour + 1],
290                          fe->colours[3*colour + 2]);
291 }
292
293 static void set_window_background(frontend *fe, int colour)
294 {
295 #if GTK_CHECK_VERSION(3,20,0)
296     char css_buf[512];
297     sprintf(css_buf, ".background { "
298             "background-color: #%02x%02x%02x; }",
299             (unsigned)(fe->colours[3*colour + 0] * 255),
300             (unsigned)(fe->colours[3*colour + 1] * 255),
301             (unsigned)(fe->colours[3*colour + 2] * 255));
302     if (!fe->css_provider)
303         fe->css_provider = gtk_css_provider_new();
304     if (!gtk_css_provider_load_from_data(
305             GTK_CSS_PROVIDER(fe->css_provider), css_buf, -1, NULL))
306         assert(0 && "Couldn't load CSS");
307     gtk_style_context_add_provider(
308         gtk_widget_get_style_context(fe->window),
309         GTK_STYLE_PROVIDER(fe->css_provider),
310         GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
311     gtk_style_context_add_provider(
312         gtk_widget_get_style_context(fe->area),
313         GTK_STYLE_PROVIDER(fe->css_provider),
314         GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
315 #elif GTK_CHECK_VERSION(3,0,0)
316     GdkRGBA rgba;
317     rgba.red = fe->colours[3*colour + 0];
318     rgba.green = fe->colours[3*colour + 1];
319     rgba.blue = fe->colours[3*colour + 2];
320     rgba.alpha = 1.0;
321     gdk_window_set_background_rgba(gtk_widget_get_window(fe->area), &rgba);
322     gdk_window_set_background_rgba(gtk_widget_get_window(fe->window), &rgba);
323 #else
324     GdkColormap *colmap;
325
326     colmap = gdk_colormap_get_system();
327     fe->background.red = fe->colours[3*colour + 0] * 65535;
328     fe->background.green = fe->colours[3*colour + 1] * 65535;
329     fe->background.blue = fe->colours[3*colour + 2] * 65535;
330     if (!gdk_colormap_alloc_color(colmap, &fe->background, FALSE, FALSE)) {
331         g_error("couldn't allocate background (#%02x%02x%02x)\n",
332                 fe->background.red >> 8, fe->background.green >> 8,
333                 fe->background.blue >> 8);
334     }
335     gdk_window_set_background(gtk_widget_get_window(fe->area),
336                               &fe->background);
337     gdk_window_set_background(gtk_widget_get_window(fe->window),
338                               &fe->background);
339 #endif
340 }
341
342 static PangoLayout *make_pango_layout(frontend *fe)
343 {
344     return (pango_cairo_create_layout(fe->cr));
345 }
346
347 static void draw_pango_layout(frontend *fe, PangoLayout *layout,
348                               int x, int y)
349 {
350     cairo_move_to(fe->cr, x, y);
351     pango_cairo_show_layout(fe->cr, layout);
352 }
353
354 static void save_screenshot_png(frontend *fe, const char *screenshot_file)
355 {
356     cairo_surface_write_to_png(fe->image, screenshot_file);
357 }
358
359 static void do_clip(frontend *fe, int x, int y, int w, int h)
360 {
361     cairo_new_path(fe->cr);
362     cairo_rectangle(fe->cr, x, y, w, h);
363     cairo_clip(fe->cr);
364 }
365
366 static void do_unclip(frontend *fe)
367 {
368     cairo_reset_clip(fe->cr);
369 }
370
371 static void do_draw_rect(frontend *fe, int x, int y, int w, int h)
372 {
373     cairo_save(fe->cr);
374     cairo_new_path(fe->cr);
375     cairo_set_antialias(fe->cr, CAIRO_ANTIALIAS_NONE);
376     cairo_rectangle(fe->cr, x, y, w, h);
377     cairo_fill(fe->cr);
378     cairo_restore(fe->cr);
379 }
380
381 static void do_draw_line(frontend *fe, int x1, int y1, int x2, int y2)
382 {
383     cairo_new_path(fe->cr);
384     cairo_move_to(fe->cr, x1 + 0.5, y1 + 0.5);
385     cairo_line_to(fe->cr, x2 + 0.5, y2 + 0.5);
386     cairo_stroke(fe->cr);
387 }
388
389 static void do_draw_thick_line(frontend *fe, float thickness,
390                                float x1, float y1, float x2, float y2)
391 {
392     cairo_save(fe->cr);
393     cairo_set_line_width(fe->cr, thickness);
394     cairo_new_path(fe->cr);
395     cairo_move_to(fe->cr, x1, y1);
396     cairo_line_to(fe->cr, x2, y2);
397     cairo_stroke(fe->cr);
398     cairo_restore(fe->cr);
399 }
400
401 static void do_draw_poly(frontend *fe, int *coords, int npoints,
402                          int fillcolour, int outlinecolour)
403 {
404     int i;
405
406     cairo_new_path(fe->cr);
407     for (i = 0; i < npoints; i++)
408         cairo_line_to(fe->cr, coords[i*2] + 0.5, coords[i*2 + 1] + 0.5);
409     cairo_close_path(fe->cr);
410     if (fillcolour >= 0) {
411         set_colour(fe, fillcolour);
412         cairo_fill_preserve(fe->cr);
413     }
414     assert(outlinecolour >= 0);
415     set_colour(fe, outlinecolour);
416     cairo_stroke(fe->cr);
417 }
418
419 static void do_draw_circle(frontend *fe, int cx, int cy, int radius,
420                            int fillcolour, int outlinecolour)
421 {
422     cairo_new_path(fe->cr);
423     cairo_arc(fe->cr, cx + 0.5, cy + 0.5, radius, 0, 2*PI);
424     cairo_close_path(fe->cr);           /* Just in case... */
425     if (fillcolour >= 0) {
426         set_colour(fe, fillcolour);
427         cairo_fill_preserve(fe->cr);
428     }
429     assert(outlinecolour >= 0);
430     set_colour(fe, outlinecolour);
431     cairo_stroke(fe->cr);
432 }
433
434 static void setup_blitter(blitter *bl, int w, int h)
435 {
436     bl->image = cairo_image_surface_create(CAIRO_FORMAT_RGB24, w, h);
437 }
438
439 static void teardown_blitter(blitter *bl)
440 {
441     cairo_surface_destroy(bl->image);
442 }
443
444 static void do_blitter_save(frontend *fe, blitter *bl, int x, int y)
445 {
446     cairo_t *cr = cairo_create(bl->image);
447
448     cairo_set_source_surface(cr, fe->image, -x, -y);
449     cairo_paint(cr);
450     cairo_destroy(cr);
451 }
452
453 static void do_blitter_load(frontend *fe, blitter *bl, int x, int y)
454 {
455     cairo_set_source_surface(fe->cr, bl->image, x, y);
456     cairo_paint(fe->cr);
457 }
458
459 static void clear_backing_store(frontend *fe)
460 {
461     fe->image = NULL;
462 }
463
464 static void wipe_and_maybe_destroy_cairo(frontend *fe, cairo_t *cr,
465                                          int destroy)
466 {
467     cairo_set_source_rgb(cr, fe->colours[0], fe->colours[1], fe->colours[2]);
468     cairo_paint(cr);
469     if (destroy)
470         cairo_destroy(cr);
471 }
472
473 static void setup_backing_store(frontend *fe)
474 {
475 #ifndef USE_CAIRO_WITHOUT_PIXMAP
476     fe->pixmap = gdk_pixmap_new(gtk_widget_get_window(fe->area),
477                                 fe->pw, fe->ph, -1);
478 #endif
479     fe->image = cairo_image_surface_create(CAIRO_FORMAT_RGB24,
480                                            fe->pw, fe->ph);
481
482     wipe_and_maybe_destroy_cairo(fe, cairo_create(fe->image), TRUE);
483 #ifndef USE_CAIRO_WITHOUT_PIXMAP
484     wipe_and_maybe_destroy_cairo(fe, gdk_cairo_create(fe->pixmap), TRUE);
485 #endif
486 #if GTK_CHECK_VERSION(3,22,0)
487     {
488         GdkWindow *gdkwin;
489         cairo_region_t *region;
490         GdkDrawingContext *drawctx;
491         cairo_t *cr;
492
493         gdkwin = gtk_widget_get_window(fe->area);
494         region = gdk_window_get_clip_region(gdkwin);
495         drawctx = gdk_window_begin_draw_frame(gdkwin, region);
496         cr = gdk_drawing_context_get_cairo_context(drawctx);
497         wipe_and_maybe_destroy_cairo(fe, cr, FALSE);
498         gdk_window_end_draw_frame(gdkwin, drawctx);
499         cairo_region_destroy(region);
500     }
501 #else
502     wipe_and_maybe_destroy_cairo(
503         fe, gdk_cairo_create(gtk_widget_get_window(fe->area)), TRUE);
504 #endif
505 }
506
507 static int backing_store_ok(frontend *fe)
508 {
509     return (!!fe->image);
510 }
511
512 static void teardown_backing_store(frontend *fe)
513 {
514     cairo_surface_destroy(fe->image);
515 #ifndef USE_CAIRO_WITHOUT_PIXMAP
516     gdk_pixmap_unref(fe->pixmap);
517 #endif
518     fe->image = NULL;
519 }
520
521 #endif
522
523 /* ----------------------------------------------------------------------
524  * GDK drawing functions.
525  */
526
527 #ifndef USE_CAIRO
528
529 static void setup_drawing(frontend *fe)
530 {
531     fe->gc = gdk_gc_new(fe->area->window);
532 }
533
534 static void teardown_drawing(frontend *fe)
535 {
536     gdk_gc_unref(fe->gc);
537     fe->gc = NULL;
538 }
539
540 static void snaffle_colours(frontend *fe)
541 {
542     int i, ncolours;
543     float *colours;
544     gboolean *success;
545
546     fe->colmap = gdk_colormap_get_system();
547     colours = midend_colours(fe->me, &ncolours);
548     fe->ncolours = ncolours;
549     fe->colours = snewn(ncolours, GdkColor);
550     for (i = 0; i < ncolours; i++) {
551         fe->colours[i].red = colours[i*3] * 0xFFFF;
552         fe->colours[i].green = colours[i*3+1] * 0xFFFF;
553         fe->colours[i].blue = colours[i*3+2] * 0xFFFF;
554     }
555     success = snewn(ncolours, gboolean);
556     gdk_colormap_alloc_colors(fe->colmap, fe->colours, ncolours,
557                               FALSE, FALSE, success);
558     for (i = 0; i < ncolours; i++) {
559         if (!success[i]) {
560             g_error("couldn't allocate colour %d (#%02x%02x%02x)\n",
561                     i, fe->colours[i].red >> 8,
562                     fe->colours[i].green >> 8,
563                     fe->colours[i].blue >> 8);
564         }
565     }
566 }
567
568 static void set_window_background(frontend *fe, int colour)
569 {
570     fe->backgroundindex = colour;
571     gdk_window_set_background(fe->area->window, &fe->colours[colour]);
572     gdk_window_set_background(fe->window->window, &fe->colours[colour]);
573 }
574
575 static void set_colour(frontend *fe, int colour)
576 {
577     gdk_gc_set_foreground(fe->gc, &fe->colours[colour]);
578 }
579
580 #ifdef USE_PANGO
581 static PangoLayout *make_pango_layout(frontend *fe)
582 {
583     return (pango_layout_new(gtk_widget_get_pango_context(fe->area)));
584 }
585
586 static void draw_pango_layout(frontend *fe, PangoLayout *layout,
587                               int x, int y)
588 {
589     gdk_draw_layout(fe->pixmap, fe->gc, x, y, layout);
590 }
591 #endif
592
593 static void save_screenshot_png(frontend *fe, const char *screenshot_file)
594 {
595     GdkPixbuf *pb;
596     GError *gerror = NULL;
597
598     midend_redraw(fe->me);
599
600     pb = gdk_pixbuf_get_from_drawable(NULL, fe->pixmap,
601                                       NULL, 0, 0, 0, 0, -1, -1);
602     gdk_pixbuf_save(pb, screenshot_file, "png", &gerror, NULL);
603 }
604
605 static void do_clip(frontend *fe, int x, int y, int w, int h)
606 {
607     GdkRectangle rect;
608
609     rect.x = x;
610     rect.y = y;
611     rect.width = w;
612     rect.height = h;
613     gdk_gc_set_clip_rectangle(fe->gc, &rect);
614 }
615
616 static void do_unclip(frontend *fe)
617 {
618     GdkRectangle rect;
619
620     rect.x = 0;
621     rect.y = 0;
622     rect.width = fe->w;
623     rect.height = fe->h;
624     gdk_gc_set_clip_rectangle(fe->gc, &rect);
625 }
626
627 static void do_draw_rect(frontend *fe, int x, int y, int w, int h)
628 {
629     gdk_draw_rectangle(fe->pixmap, fe->gc, 1, x, y, w, h);
630 }
631
632 static void do_draw_line(frontend *fe, int x1, int y1, int x2, int y2)
633 {
634     gdk_draw_line(fe->pixmap, fe->gc, x1, y1, x2, y2);
635 }
636
637 static void do_draw_thick_line(frontend *fe, float thickness,
638                                float x1, float y1, float x2, float y2)
639 {
640     GdkGCValues save;
641
642     gdk_gc_get_values(fe->gc, &save);
643     gdk_gc_set_line_attributes(fe->gc,
644                                thickness,
645                                GDK_LINE_SOLID,
646                                GDK_CAP_BUTT,
647                                GDK_JOIN_BEVEL);
648     gdk_draw_line(fe->pixmap, fe->gc, x1, y1, x2, y2);
649     gdk_gc_set_line_attributes(fe->gc,
650                                save.line_width,
651                                save.line_style,
652                                save.cap_style,
653                                save.join_style);
654 }
655
656 static void do_draw_poly(frontend *fe, int *coords, int npoints,
657                          int fillcolour, int outlinecolour)
658 {
659     GdkPoint *points = snewn(npoints, GdkPoint);
660     int i;
661
662     for (i = 0; i < npoints; i++) {
663         points[i].x = coords[i*2];
664         points[i].y = coords[i*2+1];
665     }
666
667     if (fillcolour >= 0) {
668         set_colour(fe, fillcolour);
669         gdk_draw_polygon(fe->pixmap, fe->gc, TRUE, points, npoints);
670     }
671     assert(outlinecolour >= 0);
672     set_colour(fe, outlinecolour);
673
674     /*
675      * In principle we ought to be able to use gdk_draw_polygon for
676      * the outline as well. In fact, it turns out to interact badly
677      * with a clipping region, for no terribly obvious reason, so I
678      * draw the outline as a sequence of lines instead.
679      */
680     for (i = 0; i < npoints; i++)
681         gdk_draw_line(fe->pixmap, fe->gc,
682                       points[i].x, points[i].y,
683                       points[(i+1)%npoints].x, points[(i+1)%npoints].y);
684
685     sfree(points);
686 }
687
688 static void do_draw_circle(frontend *fe, int cx, int cy, int radius,
689                            int fillcolour, int outlinecolour)
690 {
691     if (fillcolour >= 0) {
692         set_colour(fe, fillcolour);
693         gdk_draw_arc(fe->pixmap, fe->gc, TRUE,
694                      cx - radius, cy - radius,
695                      2 * radius, 2 * radius, 0, 360 * 64);
696     }
697
698     assert(outlinecolour >= 0);
699     set_colour(fe, outlinecolour);
700     gdk_draw_arc(fe->pixmap, fe->gc, FALSE,
701                  cx - radius, cy - radius,
702                  2 * radius, 2 * radius, 0, 360 * 64);
703 }
704
705 static void setup_blitter(blitter *bl, int w, int h)
706 {
707     /*
708      * We can't create the pixmap right now, because fe->window
709      * might not yet exist. So we just cache w and h and create it
710      * during the firs call to blitter_save.
711      */
712     bl->pixmap = NULL;
713 }
714
715 static void teardown_blitter(blitter *bl)
716 {
717     if (bl->pixmap)
718         gdk_pixmap_unref(bl->pixmap);
719 }
720
721 static void do_blitter_save(frontend *fe, blitter *bl, int x, int y)
722 {
723     if (!bl->pixmap)
724         bl->pixmap = gdk_pixmap_new(fe->area->window, bl->w, bl->h, -1);
725     gdk_draw_pixmap(bl->pixmap,
726                     fe->area->style->fg_gc[GTK_WIDGET_STATE(fe->area)],
727                     fe->pixmap,
728                     x, y, 0, 0, bl->w, bl->h);
729 }
730
731 static void do_blitter_load(frontend *fe, blitter *bl, int x, int y)
732 {
733     assert(bl->pixmap);
734     gdk_draw_pixmap(fe->pixmap,
735                     fe->area->style->fg_gc[GTK_WIDGET_STATE(fe->area)],
736                     bl->pixmap,
737                     0, 0, x, y, bl->w, bl->h);
738 }
739
740 static void clear_backing_store(frontend *fe)
741 {
742     fe->pixmap = NULL;
743 }
744
745 static void setup_backing_store(frontend *fe)
746 {
747     GdkGC *gc;
748
749     fe->pixmap = gdk_pixmap_new(fe->area->window, fe->pw, fe->ph, -1);
750
751     gc = gdk_gc_new(fe->area->window);
752     gdk_gc_set_foreground(gc, &fe->colours[0]);
753     gdk_draw_rectangle(fe->pixmap, gc, 1, 0, 0, fe->pw, fe->ph);
754     gdk_draw_rectangle(fe->area->window, gc, 1, 0, 0, fe->w, fe->h);
755     gdk_gc_unref(gc);
756 }
757
758 static int backing_store_ok(frontend *fe)
759 {
760     return (!!fe->pixmap);
761 }
762
763 static void teardown_backing_store(frontend *fe)
764 {
765     gdk_pixmap_unref(fe->pixmap);
766     fe->pixmap = NULL;
767 }
768
769 #endif
770
771 #ifndef USE_CAIRO_WITHOUT_PIXMAP
772 static void repaint_rectangle(frontend *fe, GtkWidget *widget,
773                               int x, int y, int w, int h)
774 {
775     GdkGC *gc = gdk_gc_new(gtk_widget_get_window(widget));
776 #ifdef USE_CAIRO
777     gdk_gc_set_foreground(gc, &fe->background);
778 #else
779     gdk_gc_set_foreground(gc, &fe->colours[fe->backgroundindex]);
780 #endif
781     if (x < fe->ox) {
782         gdk_draw_rectangle(gtk_widget_get_window(widget), gc,
783                            TRUE, x, y, fe->ox - x, h);
784         w -= (fe->ox - x);
785         x = fe->ox;
786     }
787     if (y < fe->oy) {
788         gdk_draw_rectangle(gtk_widget_get_window(widget), gc,
789                            TRUE, x, y, w, fe->oy - y);
790         h -= (fe->oy - y);
791         y = fe->oy;
792     }
793     if (w > fe->pw) {
794         gdk_draw_rectangle(gtk_widget_get_window(widget), gc,
795                            TRUE, x + fe->pw, y, w - fe->pw, h);
796         w = fe->pw;
797     }
798     if (h > fe->ph) {
799         gdk_draw_rectangle(gtk_widget_get_window(widget), gc,
800                            TRUE, x, y + fe->ph, w, h - fe->ph);
801         h = fe->ph;
802     }
803     gdk_draw_pixmap(gtk_widget_get_window(widget), gc, fe->pixmap,
804                     x - fe->ox, y - fe->oy, x, y, w, h);
805     gdk_gc_unref(gc);
806 }
807 #endif
808
809 /* ----------------------------------------------------------------------
810  * Pango font functions.
811  */
812
813 #ifdef USE_PANGO
814
815 static void add_font(frontend *fe, int index, int fonttype, int fontsize)
816 {
817     /*
818      * Use Pango to find the closest match to the requested
819      * font.
820      */
821     PangoFontDescription *fd;
822
823     fd = pango_font_description_new();
824     /* `Monospace' and `Sans' are meta-families guaranteed to exist */
825     pango_font_description_set_family(fd, fonttype == FONT_FIXED ?
826                                       "Monospace" : "Sans");
827     pango_font_description_set_weight(fd, PANGO_WEIGHT_BOLD);
828     /*
829      * I found some online Pango documentation which
830      * described a function called
831      * pango_font_description_set_absolute_size(), which is
832      * _exactly_ what I want here. Unfortunately, none of
833      * my local Pango installations have it (presumably
834      * they're too old), so I'm going to have to hack round
835      * it by figuring out the point size myself. This
836      * limits me to X and probably also breaks in later
837      * Pango installations, so ideally I should add another
838      * CHECK_VERSION type ifdef and use set_absolute_size
839      * where available. All very annoying.
840      */
841 #ifdef HAVE_SENSIBLE_ABSOLUTE_SIZE_FUNCTION
842     pango_font_description_set_absolute_size(fd, PANGO_SCALE*fontsize);
843 #else
844     {
845         Display *d = GDK_DISPLAY();
846         int s = DefaultScreen(d);
847         double resolution =
848             (PANGO_SCALE * 72.27 / 25.4) *
849             ((double) DisplayWidthMM(d, s) / DisplayWidth (d, s));
850         pango_font_description_set_size(fd, resolution * fontsize);
851     }
852 #endif
853     fe->fonts[index].desc = fd;
854 }
855
856 static void align_and_draw_text(frontend *fe,
857                                 int index, int align, int x, int y,
858                                 const char *text)
859 {
860     PangoLayout *layout;
861     PangoRectangle rect;
862
863     layout = make_pango_layout(fe);
864
865     /*
866      * Create a layout.
867      */
868     pango_layout_set_font_description(layout, fe->fonts[index].desc);
869     pango_layout_set_text(layout, text, strlen(text));
870     pango_layout_get_pixel_extents(layout, NULL, &rect);
871
872     if (align & ALIGN_VCENTRE)
873         rect.y -= rect.height / 2;
874     else
875         rect.y -= rect.height;
876
877     if (align & ALIGN_HCENTRE)
878         rect.x -= rect.width / 2;
879     else if (align & ALIGN_HRIGHT)
880         rect.x -= rect.width;
881
882     draw_pango_layout(fe, layout, rect.x + x, rect.y + y);
883
884     g_object_unref(layout);
885 }
886
887 #endif
888
889 /* ----------------------------------------------------------------------
890  * Old-fashioned font functions.
891  */
892
893 #ifndef USE_PANGO
894
895 static void add_font(int index, int fonttype, int fontsize)
896 {
897     /*
898      * In GTK 1.2, I don't know of any plausible way to
899      * pick a suitable font, so I'm just going to be
900      * tedious.
901      */
902     fe->fonts[i].font = gdk_font_load(fonttype == FONT_FIXED ?
903                                       "fixed" : "variable");
904 }
905
906 static void align_and_draw_text(int index, int align, int x, int y,
907                                 const char *text)
908 {
909     int lb, rb, wid, asc, desc;
910
911     /*
912      * Measure vertical string extents with respect to the same
913      * string always...
914      */
915     gdk_string_extents(fe->fonts[i].font,
916                        "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
917                        &lb, &rb, &wid, &asc, &desc);
918     if (align & ALIGN_VCENTRE)
919         y += asc - (asc+desc)/2;
920     else
921         y += asc;
922
923     /*
924      * ... but horizontal extents with respect to the provided
925      * string. This means that multiple pieces of text centred
926      * on the same y-coordinate don't have different baselines.
927      */
928     gdk_string_extents(fe->fonts[i].font, text,
929                        &lb, &rb, &wid, &asc, &desc);
930
931     if (align & ALIGN_HCENTRE)
932         x -= wid / 2;
933     else if (align & ALIGN_HRIGHT)
934         x -= wid;
935
936     /*
937      * Actually draw the text.
938      */
939     gdk_draw_string(fe->pixmap, fe->fonts[i].font, fe->gc, x, y, text);
940 }
941
942 #endif
943
944 /* ----------------------------------------------------------------------
945  * The exported drawing functions.
946  */
947
948 void gtk_start_draw(void *handle)
949 {
950     frontend *fe = (frontend *)handle;
951     fe->bbox_l = fe->w;
952     fe->bbox_r = 0;
953     fe->bbox_u = fe->h;
954     fe->bbox_d = 0;
955     setup_drawing(fe);
956 }
957
958 void gtk_clip(void *handle, int x, int y, int w, int h)
959 {
960     frontend *fe = (frontend *)handle;
961     do_clip(fe, x, y, w, h);
962 }
963
964 void gtk_unclip(void *handle)
965 {
966     frontend *fe = (frontend *)handle;
967     do_unclip(fe);
968 }
969
970 void gtk_draw_text(void *handle, int x, int y, int fonttype, int fontsize,
971                    int align, int colour, char *text)
972 {
973     frontend *fe = (frontend *)handle;
974     int i;
975
976     /*
977      * Find or create the font.
978      */
979     for (i = 0; i < fe->nfonts; i++)
980         if (fe->fonts[i].type == fonttype && fe->fonts[i].size == fontsize)
981             break;
982
983     if (i == fe->nfonts) {
984         if (fe->fontsize <= fe->nfonts) {
985             fe->fontsize = fe->nfonts + 10;
986             fe->fonts = sresize(fe->fonts, fe->fontsize, struct font);
987         }
988
989         fe->nfonts++;
990
991         fe->fonts[i].type = fonttype;
992         fe->fonts[i].size = fontsize;
993         add_font(fe, i, fonttype, fontsize);
994     }
995
996     /*
997      * Do the job.
998      */
999     set_colour(fe, colour);
1000     align_and_draw_text(fe, i, align, x, y, text);
1001 }
1002
1003 void gtk_draw_rect(void *handle, int x, int y, int w, int h, int colour)
1004 {
1005     frontend *fe = (frontend *)handle;
1006     set_colour(fe, colour);
1007     do_draw_rect(fe, x, y, w, h);
1008 }
1009
1010 void gtk_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
1011 {
1012     frontend *fe = (frontend *)handle;
1013     set_colour(fe, colour);
1014     do_draw_line(fe, x1, y1, x2, y2);
1015 }
1016
1017 void gtk_draw_thick_line(void *handle, float thickness,
1018                          float x1, float y1, float x2, float y2, int colour)
1019 {
1020     frontend *fe = (frontend *)handle;
1021     set_colour(fe, colour);
1022     do_draw_thick_line(fe, thickness, x1, y1, x2, y2);
1023 }
1024
1025 void gtk_draw_poly(void *handle, int *coords, int npoints,
1026                    int fillcolour, int outlinecolour)
1027 {
1028     frontend *fe = (frontend *)handle;
1029     do_draw_poly(fe, coords, npoints, fillcolour, outlinecolour);
1030 }
1031
1032 void gtk_draw_circle(void *handle, int cx, int cy, int radius,
1033                      int fillcolour, int outlinecolour)
1034 {
1035     frontend *fe = (frontend *)handle;
1036     do_draw_circle(fe, cx, cy, radius, fillcolour, outlinecolour);
1037 }
1038
1039 blitter *gtk_blitter_new(void *handle, int w, int h)
1040 {
1041     blitter *bl = snew(blitter);
1042     setup_blitter(bl, w, h);
1043     bl->w = w;
1044     bl->h = h;
1045     return bl;
1046 }
1047
1048 void gtk_blitter_free(void *handle, blitter *bl)
1049 {
1050     teardown_blitter(bl);
1051     sfree(bl);
1052 }
1053
1054 void gtk_blitter_save(void *handle, blitter *bl, int x, int y)
1055 {
1056     frontend *fe = (frontend *)handle;
1057     do_blitter_save(fe, bl, x, y);
1058     bl->x = x;
1059     bl->y = y;
1060 }
1061
1062 void gtk_blitter_load(void *handle, blitter *bl, int x, int y)
1063 {
1064     frontend *fe = (frontend *)handle;
1065     if (x == BLITTER_FROMSAVED && y == BLITTER_FROMSAVED) {
1066         x = bl->x;
1067         y = bl->y;
1068     }
1069     do_blitter_load(fe, bl, x, y);
1070 }
1071
1072 void gtk_draw_update(void *handle, int x, int y, int w, int h)
1073 {
1074     frontend *fe = (frontend *)handle;
1075     if (fe->bbox_l > x  ) fe->bbox_l = x  ;
1076     if (fe->bbox_r < x+w) fe->bbox_r = x+w;
1077     if (fe->bbox_u > y  ) fe->bbox_u = y  ;
1078     if (fe->bbox_d < y+h) fe->bbox_d = y+h;
1079 }
1080
1081 void gtk_end_draw(void *handle)
1082 {
1083     frontend *fe = (frontend *)handle;
1084
1085     teardown_drawing(fe);
1086
1087     if (fe->bbox_l < fe->bbox_r && fe->bbox_u < fe->bbox_d) {
1088 #ifdef USE_CAIRO_WITHOUT_PIXMAP
1089         gtk_widget_queue_draw_area(fe->area,
1090                                    fe->bbox_l - 1 + fe->ox,
1091                                    fe->bbox_u - 1 + fe->oy,
1092                                    fe->bbox_r - fe->bbox_l + 2,
1093                                    fe->bbox_d - fe->bbox_u + 2);
1094 #else
1095         repaint_rectangle(fe, fe->area,
1096                           fe->bbox_l - 1 + fe->ox,
1097                           fe->bbox_u - 1 + fe->oy,
1098                           fe->bbox_r - fe->bbox_l + 2,
1099                           fe->bbox_d - fe->bbox_u + 2);
1100 #endif
1101     }
1102 }
1103
1104 #ifdef USE_PANGO
1105 char *gtk_text_fallback(void *handle, const char *const *strings, int nstrings)
1106 {
1107     /*
1108      * We assume Pango can cope with any UTF-8 likely to be emitted
1109      * by a puzzle.
1110      */
1111     return dupstr(strings[0]);
1112 }
1113 #endif
1114
1115 const struct drawing_api gtk_drawing = {
1116     gtk_draw_text,
1117     gtk_draw_rect,
1118     gtk_draw_line,
1119     gtk_draw_poly,
1120     gtk_draw_circle,
1121     gtk_draw_update,
1122     gtk_clip,
1123     gtk_unclip,
1124     gtk_start_draw,
1125     gtk_end_draw,
1126     gtk_status_bar,
1127     gtk_blitter_new,
1128     gtk_blitter_free,
1129     gtk_blitter_save,
1130     gtk_blitter_load,
1131     NULL, NULL, NULL, NULL, NULL, NULL, /* {begin,end}_{doc,page,puzzle} */
1132     NULL, NULL,                        /* line_width, line_dotted */
1133 #ifdef USE_PANGO
1134     gtk_text_fallback,
1135 #else
1136     NULL,
1137 #endif
1138 #ifdef NO_THICK_LINE
1139     NULL,
1140 #else
1141     gtk_draw_thick_line,
1142 #endif
1143 };
1144
1145 static void destroy(GtkWidget *widget, gpointer data)
1146 {
1147     frontend *fe = (frontend *)data;
1148     deactivate_timer(fe);
1149     midend_free(fe->me);
1150     gtk_main_quit();
1151 }
1152
1153 static gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data)
1154 {
1155     frontend *fe = (frontend *)data;
1156     int keyval;
1157     int shift = (event->state & GDK_SHIFT_MASK) ? MOD_SHFT : 0;
1158     int ctrl = (event->state & GDK_CONTROL_MASK) ? MOD_CTRL : 0;
1159
1160     if (!backing_store_ok(fe))
1161         return TRUE;
1162
1163 #if !GTK_CHECK_VERSION(2,0,0)
1164     /* Gtk 1.2 passes a key event to this function even if it's also
1165      * defined as an accelerator.
1166      * Gtk 2 doesn't do this, and this function appears not to exist there. */
1167     if (fe->accelgroup &&
1168         gtk_accel_group_get_entry(fe->accelgroup,
1169         event->keyval, event->state))
1170         return TRUE;
1171 #endif
1172
1173     /* Handle mnemonics. */
1174     if (gtk_window_activate_key(GTK_WINDOW(fe->window), event))
1175         return TRUE;
1176
1177     if (event->keyval == GDK_KEY_Up)
1178         keyval = shift | ctrl | CURSOR_UP;
1179     else if (event->keyval == GDK_KEY_KP_Up ||
1180              event->keyval == GDK_KEY_KP_8)
1181         keyval = MOD_NUM_KEYPAD | '8';
1182     else if (event->keyval == GDK_KEY_Down)
1183         keyval = shift | ctrl | CURSOR_DOWN;
1184     else if (event->keyval == GDK_KEY_KP_Down ||
1185              event->keyval == GDK_KEY_KP_2)
1186         keyval = MOD_NUM_KEYPAD | '2';
1187     else if (event->keyval == GDK_KEY_Left)
1188         keyval = shift | ctrl | CURSOR_LEFT;
1189     else if (event->keyval == GDK_KEY_KP_Left ||
1190              event->keyval == GDK_KEY_KP_4)
1191         keyval = MOD_NUM_KEYPAD | '4';
1192     else if (event->keyval == GDK_KEY_Right)
1193         keyval = shift | ctrl | CURSOR_RIGHT;
1194     else if (event->keyval == GDK_KEY_KP_Right ||
1195              event->keyval == GDK_KEY_KP_6)
1196         keyval = MOD_NUM_KEYPAD | '6';
1197     else if (event->keyval == GDK_KEY_KP_Home ||
1198              event->keyval == GDK_KEY_KP_7)
1199         keyval = MOD_NUM_KEYPAD | '7';
1200     else if (event->keyval == GDK_KEY_KP_End ||
1201              event->keyval == GDK_KEY_KP_1)
1202         keyval = MOD_NUM_KEYPAD | '1';
1203     else if (event->keyval == GDK_KEY_KP_Page_Up ||
1204              event->keyval == GDK_KEY_KP_9)
1205         keyval = MOD_NUM_KEYPAD | '9';
1206     else if (event->keyval == GDK_KEY_KP_Page_Down ||
1207              event->keyval == GDK_KEY_KP_3)
1208         keyval = MOD_NUM_KEYPAD | '3';
1209     else if (event->keyval == GDK_KEY_KP_Insert ||
1210              event->keyval == GDK_KEY_KP_0)
1211         keyval = MOD_NUM_KEYPAD | '0';
1212     else if (event->keyval == GDK_KEY_KP_Begin ||
1213              event->keyval == GDK_KEY_KP_5)
1214         keyval = MOD_NUM_KEYPAD | '5';
1215     else if (event->keyval == GDK_KEY_BackSpace ||
1216              event->keyval == GDK_KEY_Delete ||
1217              event->keyval == GDK_KEY_KP_Delete)
1218         keyval = '\177';
1219     else if (event->string[0] && !event->string[1])
1220         keyval = (unsigned char)event->string[0];
1221     else
1222         keyval = -1;
1223
1224     if (keyval >= 0 &&
1225         !midend_process_key(fe->me, 0, 0, keyval))
1226         gtk_widget_destroy(fe->window);
1227
1228     return TRUE;
1229 }
1230
1231 static gint button_event(GtkWidget *widget, GdkEventButton *event,
1232                          gpointer data)
1233 {
1234     frontend *fe = (frontend *)data;
1235     int button;
1236
1237     if (!backing_store_ok(fe))
1238         return TRUE;
1239
1240     if (event->type != GDK_BUTTON_PRESS && event->type != GDK_BUTTON_RELEASE)
1241         return TRUE;
1242
1243     if (event->button == 2 || (event->state & GDK_SHIFT_MASK))
1244         button = MIDDLE_BUTTON;
1245     else if (event->button == 3 || (event->state & GDK_MOD1_MASK))
1246         button = RIGHT_BUTTON;
1247     else if (event->button == 1)
1248         button = LEFT_BUTTON;
1249     else if (event->button == 8 && event->type == GDK_BUTTON_PRESS)
1250         button = 'u';
1251     else if (event->button == 9 && event->type == GDK_BUTTON_PRESS)
1252         button = 'r';
1253     else
1254         return FALSE;                  /* don't even know what button! */
1255
1256     if (event->type == GDK_BUTTON_RELEASE && button >= LEFT_BUTTON)
1257         button += LEFT_RELEASE - LEFT_BUTTON;
1258
1259     if (!midend_process_key(fe->me, event->x - fe->ox,
1260                             event->y - fe->oy, button))
1261         gtk_widget_destroy(fe->window);
1262
1263     return TRUE;
1264 }
1265
1266 static gint motion_event(GtkWidget *widget, GdkEventMotion *event,
1267                          gpointer data)
1268 {
1269     frontend *fe = (frontend *)data;
1270     int button;
1271
1272     if (!backing_store_ok(fe))
1273         return TRUE;
1274
1275     if (event->state & (GDK_BUTTON2_MASK | GDK_SHIFT_MASK))
1276         button = MIDDLE_DRAG;
1277     else if (event->state & GDK_BUTTON1_MASK)
1278         button = LEFT_DRAG;
1279     else if (event->state & GDK_BUTTON3_MASK)
1280         button = RIGHT_DRAG;
1281     else
1282         return FALSE;                  /* don't even know what button! */
1283
1284     if (!midend_process_key(fe->me, event->x - fe->ox,
1285                             event->y - fe->oy, button))
1286         gtk_widget_destroy(fe->window);
1287 #if GTK_CHECK_VERSION(2,12,0)
1288     gdk_event_request_motions(event);
1289 #else
1290     gdk_window_get_pointer(gtk_widget_get_window(widget), NULL, NULL, NULL);
1291 #endif
1292
1293     return TRUE;
1294 }
1295
1296 #if GTK_CHECK_VERSION(3,0,0)
1297 static gint draw_area(GtkWidget *widget, cairo_t *cr, gpointer data)
1298 {
1299     frontend *fe = (frontend *)data;
1300     GdkRectangle dirtyrect;
1301
1302     gdk_cairo_get_clip_rectangle(cr, &dirtyrect);
1303     cairo_set_source_surface(cr, fe->image, fe->ox, fe->oy);
1304     cairo_rectangle(cr, dirtyrect.x, dirtyrect.y,
1305                     dirtyrect.width, dirtyrect.height);
1306     cairo_fill(cr);
1307
1308     return TRUE;
1309 }
1310 #else
1311 static gint expose_area(GtkWidget *widget, GdkEventExpose *event,
1312                         gpointer data)
1313 {
1314     frontend *fe = (frontend *)data;
1315
1316     if (backing_store_ok(fe)) {
1317 #ifdef USE_CAIRO_WITHOUT_PIXMAP
1318         cairo_t *cr = gdk_cairo_create(gtk_widget_get_window(widget));
1319         cairo_set_source_surface(cr, fe->image, fe->ox, fe->oy);
1320         cairo_rectangle(cr, event->area.x, event->area.y,
1321                         event->area.width, event->area.height);
1322         cairo_fill(cr);
1323         cairo_destroy(cr);
1324 #else
1325         repaint_rectangle(fe, widget,
1326                           event->area.x, event->area.y,
1327                           event->area.width, event->area.height);
1328 #endif
1329     }
1330     return TRUE;
1331 }
1332 #endif
1333
1334 static gint map_window(GtkWidget *widget, GdkEvent *event,
1335                        gpointer data)
1336 {
1337     frontend *fe = (frontend *)data;
1338
1339     /*
1340      * Apparently we need to do this because otherwise the status
1341      * bar will fail to update immediately. Annoying, but there we
1342      * go.
1343      */
1344     gtk_widget_queue_draw(fe->window);
1345
1346     return TRUE;
1347 }
1348
1349 static gint configure_area(GtkWidget *widget,
1350                            GdkEventConfigure *event, gpointer data)
1351 {
1352     frontend *fe = (frontend *)data;
1353     int x, y;
1354     int oldw = fe->w, oldpw = fe->pw, oldh = fe->h, oldph = fe->ph;
1355
1356     x = event->width;
1357     y = event->height;
1358     fe->w = x;
1359     fe->h = y;
1360     midend_size(fe->me, &x, &y, TRUE);
1361     fe->pw = x;
1362     fe->ph = y;
1363     fe->ox = (fe->w - fe->pw) / 2;
1364     fe->oy = (fe->h - fe->ph) / 2;
1365
1366     if (oldw != fe->w || oldpw != fe->pw ||
1367         oldh != fe->h || oldph != fe->ph || !backing_store_ok(fe)) {
1368         if (backing_store_ok(fe))
1369             teardown_backing_store(fe);
1370         setup_backing_store(fe);
1371     }
1372
1373     midend_force_redraw(fe->me);
1374
1375     return TRUE;
1376 }
1377
1378 static gint timer_func(gpointer data)
1379 {
1380     frontend *fe = (frontend *)data;
1381
1382     if (fe->timer_active) {
1383         struct timeval now;
1384         float elapsed;
1385         gettimeofday(&now, NULL);
1386         elapsed = ((now.tv_usec - fe->last_time.tv_usec) * 0.000001F +
1387                    (now.tv_sec - fe->last_time.tv_sec));
1388         midend_timer(fe->me, elapsed);  /* may clear timer_active */
1389         fe->last_time = now;
1390     }
1391
1392     return fe->timer_active;
1393 }
1394
1395 void deactivate_timer(frontend *fe)
1396 {
1397     if (!fe)
1398         return;                        /* can happen due to --generate */
1399     if (fe->timer_active)
1400         g_source_remove(fe->timer_id);
1401     fe->timer_active = FALSE;
1402 }
1403
1404 void activate_timer(frontend *fe)
1405 {
1406     if (!fe)
1407         return;                        /* can happen due to --generate */
1408     if (!fe->timer_active) {
1409         fe->timer_id = g_timeout_add(20, timer_func, fe);
1410         gettimeofday(&fe->last_time, NULL);
1411     }
1412     fe->timer_active = TRUE;
1413 }
1414
1415 static void window_destroy(GtkWidget *widget, gpointer data)
1416 {
1417     gtk_main_quit();
1418 }
1419
1420 static int win_key_press(GtkWidget *widget, GdkEventKey *event, gpointer data)
1421 {
1422     GObject *cancelbutton = G_OBJECT(data);
1423
1424     /*
1425      * `Escape' effectively clicks the cancel button
1426      */
1427     if (event->keyval == GDK_KEY_Escape) {
1428         g_signal_emit_by_name(cancelbutton, "clicked");
1429         return TRUE;
1430     }
1431
1432     return FALSE;
1433 }
1434
1435 enum { MB_OK, MB_YESNO };
1436
1437 static void align_label(GtkLabel *label, double x, double y)
1438 {
1439 #if GTK_CHECK_VERSION(3,16,0)
1440     gtk_label_set_xalign(label, x);
1441     gtk_label_set_yalign(label, y);
1442 #elif GTK_CHECK_VERSION(3,14,0)
1443     gtk_widget_set_halign(GTK_WIDGET(label),
1444                           x == 0 ? GTK_ALIGN_START :
1445                           x == 1 ? GTK_ALIGN_END : GTK_ALIGN_CENTER);
1446     gtk_widget_set_valign(GTK_WIDGET(label),
1447                           y == 0 ? GTK_ALIGN_START :
1448                           y == 1 ? GTK_ALIGN_END : GTK_ALIGN_CENTER);
1449 #else
1450     gtk_misc_set_alignment(GTK_MISC(label), x, y);
1451 #endif
1452 }
1453
1454 #if GTK_CHECK_VERSION(3,0,0)
1455 int message_box(GtkWidget *parent, char *title, char *msg, int centre,
1456                 int type)
1457 {
1458     GtkWidget *window;
1459     gint ret;
1460
1461     window = gtk_message_dialog_new
1462         (GTK_WINDOW(parent),
1463          (GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT),
1464          (type == MB_OK ? GTK_MESSAGE_INFO : GTK_MESSAGE_QUESTION),
1465          (type == MB_OK ? GTK_BUTTONS_OK   : GTK_BUTTONS_YES_NO),
1466          "%s", msg);
1467     gtk_window_set_title(GTK_WINDOW(window), title);
1468     ret = gtk_dialog_run(GTK_DIALOG(window));
1469     gtk_widget_destroy(window);
1470     return (type == MB_OK ? TRUE : (ret == GTK_RESPONSE_YES));
1471 }
1472 #else /* GTK_CHECK_VERSION(3,0,0) */
1473 static void msgbox_button_clicked(GtkButton *button, gpointer data)
1474 {
1475     GtkWidget *window = GTK_WIDGET(data);
1476     int v, *ip;
1477
1478     ip = (int *)g_object_get_data(G_OBJECT(window), "user-data");
1479     v = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(button), "user-data"));
1480     *ip = v;
1481
1482     gtk_widget_destroy(GTK_WIDGET(data));
1483 }
1484
1485 int message_box(GtkWidget *parent, char *title, char *msg, int centre,
1486                 int type)
1487 {
1488     GtkWidget *window, *hbox, *text, *button;
1489     char *titles;
1490     int i, def, cancel;
1491
1492     window = gtk_dialog_new();
1493     text = gtk_label_new(msg);
1494     align_label(GTK_LABEL(text), 0.0, 0.0);
1495     hbox = gtk_hbox_new(FALSE, 0);
1496     gtk_box_pack_start(GTK_BOX(hbox), text, FALSE, FALSE, 20);
1497     gtk_box_pack_start
1498         (GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(window))),
1499          hbox, FALSE, FALSE, 20);
1500     gtk_widget_show(text);
1501     gtk_widget_show(hbox);
1502     gtk_window_set_title(GTK_WINDOW(window), title);
1503     gtk_label_set_line_wrap(GTK_LABEL(text), TRUE);
1504
1505     if (type == MB_OK) {
1506         titles = LABEL_OK "\0";
1507         def = cancel = 0;
1508     } else {
1509         assert(type == MB_YESNO);
1510         titles = LABEL_NO "\0" LABEL_YES "\0";
1511         def = 1;
1512         cancel = 0;
1513     }
1514     i = 0;
1515     
1516     while (*titles) {
1517         button = gtk_button_new_with_our_label(titles);
1518         gtk_box_pack_end
1519             (GTK_BOX(gtk_dialog_get_action_area(GTK_DIALOG(window))),
1520              button, FALSE, FALSE, 0);
1521         gtk_widget_show(button);
1522         if (i == def) {
1523             gtk_widget_set_can_default(button, TRUE);
1524             gtk_window_set_default(GTK_WINDOW(window), button);
1525         }
1526         if (i == cancel) {
1527             g_signal_connect(G_OBJECT(window), "key_press_event",
1528                              G_CALLBACK(win_key_press), button);
1529         }
1530         g_signal_connect(G_OBJECT(button), "clicked",
1531                          G_CALLBACK(msgbox_button_clicked), window);
1532         g_object_set_data(G_OBJECT(button), "user-data",
1533                           GINT_TO_POINTER(i));
1534         titles += strlen(titles)+1;
1535         i++;
1536     }
1537     g_object_set_data(G_OBJECT(window), "user-data", &i);
1538     g_signal_connect(G_OBJECT(window), "destroy",
1539                      G_CALLBACK(window_destroy), NULL);
1540     gtk_window_set_modal(GTK_WINDOW(window), TRUE);
1541     gtk_window_set_transient_for(GTK_WINDOW(window), GTK_WINDOW(parent));
1542     /* set_transient_window_pos(parent, window); */
1543     gtk_widget_show(window);
1544     i = -1;
1545     gtk_main();
1546     return (type == MB_YESNO ? i == 1 : TRUE);
1547 }
1548 #endif /* GTK_CHECK_VERSION(3,0,0) */
1549
1550 void error_box(GtkWidget *parent, char *msg)
1551 {
1552     message_box(parent, "Error", msg, FALSE, MB_OK);
1553 }
1554
1555 static void config_ok_button_clicked(GtkButton *button, gpointer data)
1556 {
1557     frontend *fe = (frontend *)data;
1558     char *err;
1559
1560     err = midend_set_config(fe->me, fe->cfg_which, fe->cfg);
1561
1562     if (err)
1563         error_box(fe->cfgbox, err);
1564     else {
1565         fe->cfgret = TRUE;
1566         gtk_widget_destroy(fe->cfgbox);
1567         changed_preset(fe);
1568     }
1569 }
1570
1571 static void config_cancel_button_clicked(GtkButton *button, gpointer data)
1572 {
1573     frontend *fe = (frontend *)data;
1574
1575     gtk_widget_destroy(fe->cfgbox);
1576 }
1577
1578 static int editbox_key(GtkWidget *widget, GdkEventKey *event, gpointer data)
1579 {
1580     /*
1581      * GtkEntry has a nasty habit of eating the Return key, which
1582      * is unhelpful since it doesn't actually _do_ anything with it
1583      * (it calls gtk_widget_activate, but our edit boxes never need
1584      * activating). So I catch Return before GtkEntry sees it, and
1585      * pass it straight on to the parent widget. Effect: hitting
1586      * Return in an edit box will now activate the default button
1587      * in the dialog just like it will everywhere else.
1588      */
1589     if (event->keyval == GDK_KEY_Return &&
1590         gtk_widget_get_parent(widget) != NULL) {
1591         gint return_val;
1592         g_signal_stop_emission_by_name(G_OBJECT(widget), "key_press_event");
1593         g_signal_emit_by_name(G_OBJECT(gtk_widget_get_parent(widget)),
1594                               "key_press_event", event, &return_val);
1595         return return_val;
1596     }
1597     return FALSE;
1598 }
1599
1600 static void editbox_changed(GtkEditable *ed, gpointer data)
1601 {
1602     config_item *i = (config_item *)data;
1603
1604     sfree(i->sval);
1605     i->sval = dupstr(gtk_entry_get_text(GTK_ENTRY(ed)));
1606 }
1607
1608 static void button_toggled(GtkToggleButton *tb, gpointer data)
1609 {
1610     config_item *i = (config_item *)data;
1611
1612     i->ival = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(tb));
1613 }
1614
1615 static void droplist_sel(GtkComboBox *combo, gpointer data)
1616 {
1617     config_item *i = (config_item *)data;
1618
1619     i->ival = gtk_combo_box_get_active(combo);
1620 }
1621
1622 static int get_config(frontend *fe, int which)
1623 {
1624     GtkWidget *w, *table, *cancel;
1625     GtkBox *content_box, *button_box;
1626     char *title;
1627     config_item *i;
1628     int y;
1629
1630     fe->cfg = midend_get_config(fe->me, which, &title);
1631     fe->cfg_which = which;
1632     fe->cfgret = FALSE;
1633
1634 #if GTK_CHECK_VERSION(3,0,0)
1635     /* GtkDialog isn't quite flexible enough */
1636     fe->cfgbox = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1637     content_box = GTK_BOX(gtk_vbox_new(FALSE, 8));
1638     g_object_set(G_OBJECT(content_box), "margin", 8, (const char *)NULL);
1639     gtk_widget_show(GTK_WIDGET(content_box));
1640     gtk_container_add(GTK_CONTAINER(fe->cfgbox), GTK_WIDGET(content_box));
1641     button_box = GTK_BOX(gtk_hbox_new(FALSE, 8));
1642     gtk_widget_show(GTK_WIDGET(button_box));
1643     gtk_box_pack_end(content_box, GTK_WIDGET(button_box), FALSE, FALSE, 0);
1644     {
1645         GtkWidget *sep = gtk_separator_new(GTK_ORIENTATION_HORIZONTAL);
1646         gtk_widget_show(sep);
1647         gtk_box_pack_end(content_box, sep, FALSE, FALSE, 0);
1648     }
1649 #else
1650     fe->cfgbox = gtk_dialog_new();
1651     content_box = GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(fe->cfgbox)));
1652     button_box = GTK_BOX(gtk_dialog_get_action_area(GTK_DIALOG(fe->cfgbox)));
1653 #endif
1654     gtk_window_set_title(GTK_WINDOW(fe->cfgbox), title);
1655     sfree(title);
1656
1657     w = gtk_button_new_with_our_label(LABEL_CANCEL);
1658     gtk_box_pack_end(button_box, w, FALSE, FALSE, 0);
1659     gtk_widget_show(w);
1660     g_signal_connect(G_OBJECT(w), "clicked",
1661                      G_CALLBACK(config_cancel_button_clicked), fe);
1662     cancel = w;
1663
1664     w = gtk_button_new_with_our_label(LABEL_OK);
1665     gtk_box_pack_end(button_box, w, FALSE, FALSE, 0);
1666     gtk_widget_show(w);
1667     gtk_widget_set_can_default(w, TRUE);
1668     gtk_window_set_default(GTK_WINDOW(fe->cfgbox), w);
1669     g_signal_connect(G_OBJECT(w), "clicked",
1670                      G_CALLBACK(config_ok_button_clicked), fe);
1671
1672 #if GTK_CHECK_VERSION(3,0,0)
1673     table = gtk_grid_new();
1674 #else
1675     table = gtk_table_new(1, 2, FALSE);
1676 #endif
1677     y = 0;
1678     gtk_box_pack_start(content_box, table, FALSE, FALSE, 0);
1679     gtk_widget_show(table);
1680
1681     for (i = fe->cfg; i->type != C_END; i++) {
1682 #if !GTK_CHECK_VERSION(3,0,0)
1683         gtk_table_resize(GTK_TABLE(table), y+1, 2);
1684 #endif
1685
1686         switch (i->type) {
1687           case C_STRING:
1688             /*
1689              * Edit box with a label beside it.
1690              */
1691
1692             w = gtk_label_new(i->name);
1693             align_label(GTK_LABEL(w), 0.0, 0.5);
1694 #if GTK_CHECK_VERSION(3,0,0)
1695             gtk_grid_attach(GTK_GRID(table), w, 0, y, 1, 1);
1696 #else
1697             gtk_table_attach(GTK_TABLE(table), w, 0, 1, y, y+1,
1698                              GTK_SHRINK | GTK_FILL,
1699                              GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1700                              3, 3);
1701 #endif
1702             gtk_widget_show(w);
1703
1704             w = gtk_entry_new();
1705 #if GTK_CHECK_VERSION(3,0,0)
1706             gtk_grid_attach(GTK_GRID(table), w, 1, y, 1, 1);
1707             g_object_set(G_OBJECT(w), "hexpand", TRUE, (const char *)NULL);
1708 #else
1709             gtk_table_attach(GTK_TABLE(table), w, 1, 2, y, y+1,
1710                              GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1711                              GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1712                              3, 3);
1713 #endif
1714             gtk_entry_set_text(GTK_ENTRY(w), i->sval);
1715             g_signal_connect(G_OBJECT(w), "changed",
1716                              G_CALLBACK(editbox_changed), i);
1717             g_signal_connect(G_OBJECT(w), "key_press_event",
1718                              G_CALLBACK(editbox_key), NULL);
1719             gtk_widget_show(w);
1720
1721             break;
1722
1723           case C_BOOLEAN:
1724             /*
1725              * Simple checkbox.
1726              */
1727             w = gtk_check_button_new_with_label(i->name);
1728             g_signal_connect(G_OBJECT(w), "toggled",
1729                              G_CALLBACK(button_toggled), i);
1730 #if GTK_CHECK_VERSION(3,0,0)
1731             gtk_grid_attach(GTK_GRID(table), w, 0, y, 2, 1);
1732             g_object_set(G_OBJECT(w), "hexpand", TRUE, (const char *)NULL);
1733 #else
1734             gtk_table_attach(GTK_TABLE(table), w, 0, 2, y, y+1,
1735                              GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1736                              GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1737                              3, 3);
1738 #endif
1739             gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(w), i->ival);
1740             gtk_widget_show(w);
1741             break;
1742
1743           case C_CHOICES:
1744             /*
1745              * Drop-down list (GtkComboBox).
1746              */
1747
1748             w = gtk_label_new(i->name);
1749             align_label(GTK_LABEL(w), 0.0, 0.5);
1750 #if GTK_CHECK_VERSION(3,0,0)
1751             gtk_grid_attach(GTK_GRID(table), w, 0, y, 1, 1);
1752 #else
1753             gtk_table_attach(GTK_TABLE(table), w, 0, 1, y, y+1,
1754                              GTK_SHRINK | GTK_FILL,
1755                              GTK_EXPAND | GTK_SHRINK | GTK_FILL ,
1756                              3, 3);
1757 #endif
1758             gtk_widget_show(w);
1759
1760             {
1761                 int c;
1762                 char *p, *q, *name;
1763                 GtkListStore *model;
1764                 GtkCellRenderer *cr;
1765                 GtkTreeIter iter;
1766
1767                 model = gtk_list_store_new(1, G_TYPE_STRING);
1768
1769                 c = *i->sval;
1770                 p = i->sval+1;
1771
1772                 while (*p) {
1773                     q = p;
1774                     while (*q && *q != c)
1775                         q++;
1776
1777                     name = snewn(q-p+1, char);
1778                     strncpy(name, p, q-p);
1779                     name[q-p] = '\0';
1780
1781                     if (*q) q++;       /* eat delimiter */
1782
1783                     gtk_list_store_append(model, &iter);
1784                     gtk_list_store_set(model, &iter, 0, name, -1);
1785
1786                     p = q;
1787                 }
1788
1789                 w = gtk_combo_box_new_with_model(GTK_TREE_MODEL(model));
1790
1791                 gtk_combo_box_set_active(GTK_COMBO_BOX(w), i->ival);
1792
1793                 cr = gtk_cell_renderer_text_new();
1794                 gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(w), cr, TRUE);
1795                 gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(w), cr,
1796                                                "text", 0, NULL);
1797
1798                 g_signal_connect(G_OBJECT(w), "changed",
1799                                  G_CALLBACK(droplist_sel), i);
1800             }
1801
1802 #if GTK_CHECK_VERSION(3,0,0)
1803             gtk_grid_attach(GTK_GRID(table), w, 1, y, 1, 1);
1804             g_object_set(G_OBJECT(w), "hexpand", TRUE, (const char *)NULL);
1805 #else
1806             gtk_table_attach(GTK_TABLE(table), w, 1, 2, y, y+1,
1807                              GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1808                              GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1809                              3, 3);
1810 #endif
1811             gtk_widget_show(w);
1812             break;
1813         }
1814
1815         y++;
1816     }
1817
1818     g_signal_connect(G_OBJECT(fe->cfgbox), "destroy",
1819                      G_CALLBACK(window_destroy), NULL);
1820     g_signal_connect(G_OBJECT(fe->cfgbox), "key_press_event",
1821                      G_CALLBACK(win_key_press), cancel);
1822     gtk_window_set_modal(GTK_WINDOW(fe->cfgbox), TRUE);
1823     gtk_window_set_transient_for(GTK_WINDOW(fe->cfgbox),
1824                                  GTK_WINDOW(fe->window));
1825     /* set_transient_window_pos(fe->window, fe->cfgbox); */
1826     gtk_widget_show(fe->cfgbox);
1827     gtk_main();
1828
1829     free_cfg(fe->cfg);
1830
1831     return fe->cfgret;
1832 }
1833
1834 static void menu_key_event(GtkMenuItem *menuitem, gpointer data)
1835 {
1836     frontend *fe = (frontend *)data;
1837     int key = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(menuitem),
1838                                                 "user-data"));
1839     if (!midend_process_key(fe->me, 0, 0, key))
1840         gtk_widget_destroy(fe->window);
1841 }
1842
1843 static void get_size(frontend *fe, int *px, int *py)
1844 {
1845     int x, y;
1846
1847     /*
1848      * Currently I don't want to make the GTK port scale large
1849      * puzzles to fit on the screen. This is because X does permit
1850      * extremely large windows and many window managers provide a
1851      * means of navigating round them, and the users I consulted
1852      * before deciding said that they'd rather have enormous puzzle
1853      * windows spanning multiple screen pages than have them
1854      * shrunk. I could change my mind later or introduce
1855      * configurability; this would be the place to do so, by
1856      * replacing the initial values of x and y with the screen
1857      * dimensions.
1858      */
1859     x = INT_MAX;
1860     y = INT_MAX;
1861     midend_size(fe->me, &x, &y, FALSE);
1862     *px = x;
1863     *py = y;
1864 }
1865
1866 #if !GTK_CHECK_VERSION(2,0,0)
1867 #define gtk_window_resize(win, x, y) \
1868         gdk_window_resize(GTK_WIDGET(win)->window, x, y)
1869 #endif
1870
1871 /*
1872  * Called when any other code in this file has changed the
1873  * selected game parameters.
1874  */
1875 static void changed_preset(frontend *fe)
1876 {
1877     int n = midend_which_preset(fe->me);
1878
1879     fe->preset_threaded = TRUE;
1880     if (n < 0 && fe->preset_custom) {
1881         gtk_check_menu_item_set_active(
1882             GTK_CHECK_MENU_ITEM(fe->preset_custom),
1883             TRUE);
1884     } else {
1885         GSList *gs = fe->preset_radio;
1886         GSList *found = NULL;
1887
1888         for (gs = fe->preset_radio; gs; gs = gs->next) {
1889             struct preset_menu_entry *entry =
1890                 (struct preset_menu_entry *)g_object_get_data(
1891                     G_OBJECT(gs->data), "user-data");
1892
1893             if (entry && entry->id != n)
1894                 gtk_check_menu_item_set_active(
1895                     GTK_CHECK_MENU_ITEM(gs->data), FALSE);
1896             else
1897                 found = gs;
1898         }
1899         if (found)
1900             gtk_check_menu_item_set_active(
1901                 GTK_CHECK_MENU_ITEM(found->data), FALSE);
1902     }
1903     fe->preset_threaded = FALSE;
1904
1905     /*
1906      * Update the greying on the Copy menu option.
1907      */
1908     if (fe->copy_menu_item) {
1909         int enabled = midend_can_format_as_text_now(fe->me);
1910         gtk_widget_set_sensitive(fe->copy_menu_item, enabled);
1911     }
1912 }
1913
1914 #if !GTK_CHECK_VERSION(3,0,0)
1915 static gboolean not_size_allocated_yet(GtkWidget *w)
1916 {
1917     /*
1918      * This function tests whether a widget has not yet taken up space
1919      * on the screen which it will occupy in future. (Therefore, it
1920      * returns true only if the widget does exist but does not have a
1921      * size allocation. A null widget is already taking up all the
1922      * space it ever will.)
1923      */
1924     if (!w)
1925         return FALSE;        /* nonexistent widgets aren't a problem */
1926
1927 #if GTK_CHECK_VERSION(2,18,0)  /* skip if no gtk_widget_get_allocation */
1928     {
1929         GtkAllocation a;
1930         gtk_widget_get_allocation(w, &a);
1931         if (a.height == 0 || a.width == 0)
1932             return TRUE;       /* widget exists but has no size yet */
1933     }
1934 #endif
1935
1936     return FALSE;
1937 }
1938
1939 static void try_shrink_drawing_area(frontend *fe)
1940 {
1941     if (fe->drawing_area_shrink_pending &&
1942         (!fe->menubar_is_local || !not_size_allocated_yet(fe->menubar)) &&
1943         !not_size_allocated_yet(fe->statusbar)) {
1944         /*
1945          * In order to permit the user to resize the window smaller as
1946          * well as bigger, we call this function after the window size
1947          * has ended up where we want it. This shouldn't shrink the
1948          * window immediately; it just arranges that the next time the
1949          * user tries to shrink it, they can.
1950          *
1951          * However, at puzzle creation time, we defer the first of
1952          * these operations until after the menu bar and status bar
1953          * are actually visible. On Ubuntu 12.04 I've found that these
1954          * can take a while to be displayed, and that it's a mistake
1955          * to reduce the drawing area's size allocation before they've
1956          * turned up or else the drawing area makes room for them by
1957          * shrinking to less than the size we intended.
1958          */
1959         gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), 1, 1);
1960         fe->drawing_area_shrink_pending = FALSE;
1961     }
1962 }
1963 #endif /* !GTK_CHECK_VERSION(3,0,0) */
1964
1965 static gint configure_window(GtkWidget *widget,
1966                              GdkEventConfigure *event, gpointer data)
1967 {
1968 #if !GTK_CHECK_VERSION(3,0,0)
1969     /*
1970      * When the main puzzle window changes size, it might be because
1971      * the menu bar or status bar has turned up after starting off
1972      * absent, in which case we should have another go at enacting a
1973      * pending shrink of the drawing area.
1974      */
1975     frontend *fe = (frontend *)data;
1976     try_shrink_drawing_area(fe);
1977 #endif
1978     return FALSE;
1979 }
1980
1981 #if GTK_CHECK_VERSION(3,0,0)
1982 static int window_extra_height(frontend *fe)
1983 {
1984     int ret = 0;
1985     if (fe->menubar) {
1986         GtkRequisition req;
1987         gtk_widget_get_preferred_size(fe->menubar, &req, NULL);
1988         ret += req.height;
1989     }
1990     if (fe->statusbar) {
1991         GtkRequisition req;
1992         gtk_widget_get_preferred_size(fe->statusbar, &req, NULL);
1993         ret += req.height;
1994     }
1995     return ret;
1996 }
1997 #endif
1998
1999 static void resize_fe(frontend *fe)
2000 {
2001     int x, y;
2002
2003     get_size(fe, &x, &y);
2004
2005 #if GTK_CHECK_VERSION(3,0,0)
2006     gtk_window_resize(GTK_WINDOW(fe->window), x, y + window_extra_height(fe));
2007 #else
2008     fe->drawing_area_shrink_pending = FALSE;
2009     gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
2010     {
2011         GtkRequisition req;
2012         gtk_widget_size_request(GTK_WIDGET(fe->window), &req);
2013         gtk_window_resize(GTK_WINDOW(fe->window), req.width, req.height);
2014     }
2015     fe->drawing_area_shrink_pending = TRUE;
2016     try_shrink_drawing_area(fe);
2017 #endif
2018 }
2019
2020 static void menu_preset_event(GtkMenuItem *menuitem, gpointer data)
2021 {
2022     frontend *fe = (frontend *)data;
2023     struct preset_menu_entry *entry =
2024         (struct preset_menu_entry *)g_object_get_data(
2025             G_OBJECT(menuitem), "user-data");
2026
2027     if (fe->preset_threaded ||
2028         (GTK_IS_CHECK_MENU_ITEM(menuitem) &&
2029          !gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(menuitem))))
2030         return;
2031     midend_set_params(fe->me, entry->params);
2032     midend_new_game(fe->me);
2033     changed_preset(fe);
2034     resize_fe(fe);
2035     midend_redraw(fe->me);
2036 }
2037
2038 GdkAtom compound_text_atom, utf8_string_atom;
2039 int paste_initialised = FALSE;
2040
2041 static void set_selection(frontend *fe, GdkAtom selection)
2042 {
2043     if (!paste_initialised) {
2044         compound_text_atom = gdk_atom_intern("COMPOUND_TEXT", FALSE);
2045         utf8_string_atom = gdk_atom_intern("UTF8_STRING", FALSE);
2046         paste_initialised = TRUE;
2047     }
2048
2049     /*
2050      * For this simple application we can safely assume that the
2051      * data passed to this function is pure ASCII, which means we
2052      * can return precisely the same stuff for types STRING,
2053      * COMPOUND_TEXT or UTF8_STRING.
2054      */
2055
2056     if (gtk_selection_owner_set(fe->area, selection, CurrentTime)) {
2057         gtk_selection_clear_targets(fe->area, selection);
2058         gtk_selection_add_target(fe->area, selection,
2059                                  GDK_SELECTION_TYPE_STRING, 1);
2060         gtk_selection_add_target(fe->area, selection, compound_text_atom, 1);
2061         gtk_selection_add_target(fe->area, selection, utf8_string_atom, 1);
2062     }
2063 }
2064
2065 void write_clip(frontend *fe, char *data)
2066 {
2067     if (fe->paste_data)
2068         sfree(fe->paste_data);
2069
2070     fe->paste_data = data;
2071     fe->paste_data_len = strlen(data);
2072
2073     set_selection(fe, GDK_SELECTION_PRIMARY);
2074     set_selection(fe, GDK_SELECTION_CLIPBOARD);
2075 }
2076
2077 void selection_get(GtkWidget *widget, GtkSelectionData *seldata,
2078                    guint info, guint time_stamp, gpointer data)
2079 {
2080     frontend *fe = (frontend *)data;
2081     gtk_selection_data_set(seldata, gtk_selection_data_get_target(seldata), 8,
2082                            fe->paste_data, fe->paste_data_len);
2083 }
2084
2085 gint selection_clear(GtkWidget *widget, GdkEventSelection *seldata,
2086                      gpointer data)
2087 {
2088     frontend *fe = (frontend *)data;
2089
2090     if (fe->paste_data)
2091         sfree(fe->paste_data);
2092     fe->paste_data = NULL;
2093     fe->paste_data_len = 0;
2094     return TRUE;
2095 }
2096
2097 static void menu_copy_event(GtkMenuItem *menuitem, gpointer data)
2098 {
2099     frontend *fe = (frontend *)data;
2100     char *text;
2101
2102     text = midend_text_format(fe->me);
2103
2104     if (text) {
2105         write_clip(fe, text);
2106     } else {
2107         gdk_beep();
2108     }
2109 }
2110
2111 #ifdef OLD_FILESEL
2112
2113 static void filesel_ok(GtkButton *button, gpointer data)
2114 {
2115     frontend *fe = (frontend *)data;
2116
2117     gpointer filesel = g_object_get_data(G_OBJECT(button), "user-data");
2118
2119     const char *name =
2120         gtk_file_selection_get_filename(GTK_FILE_SELECTION(filesel));
2121
2122     fe->filesel_name = dupstr(name);
2123 }
2124
2125 static char *file_selector(frontend *fe, char *title, int save)
2126 {
2127     GtkWidget *filesel =
2128         gtk_file_selection_new(title);
2129
2130     fe->filesel_name = NULL;
2131
2132     gtk_window_set_modal(GTK_WINDOW(filesel), TRUE);
2133     g_object_set_data
2134         (G_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "user-data",
2135          (gpointer)filesel);
2136     g_signal_connect
2137         (G_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "clicked",
2138          G_CALLBACK(filesel_ok), fe);
2139     g_signal_connect_swapped
2140         (G_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "clicked",
2141          G_CALLBACK(gtk_widget_destroy), (gpointer)filesel);
2142     g_signal_connect_object
2143         (G_OBJECT(GTK_FILE_SELECTION(filesel)->cancel_button), "clicked",
2144          G_CALLBACK(gtk_widget_destroy), (gpointer)filesel);
2145     g_signal_connect(G_OBJECT(filesel), "destroy",
2146                      G_CALLBACK(window_destroy), NULL);
2147     gtk_widget_show(filesel);
2148     gtk_window_set_transient_for(GTK_WINDOW(filesel), GTK_WINDOW(fe->window));
2149     gtk_main();
2150
2151     return fe->filesel_name;
2152 }
2153
2154 #else
2155
2156 static char *file_selector(frontend *fe, char *title, int save)
2157 {
2158     char *filesel_name = NULL;
2159
2160     GtkWidget *filesel =
2161         gtk_file_chooser_dialog_new(title,
2162                                     GTK_WINDOW(fe->window),
2163                                     save ? GTK_FILE_CHOOSER_ACTION_SAVE :
2164                                     GTK_FILE_CHOOSER_ACTION_OPEN,
2165                                     LABEL_CANCEL, GTK_RESPONSE_CANCEL,
2166                                     save ? LABEL_SAVE : LABEL_OPEN,
2167                                     GTK_RESPONSE_ACCEPT,
2168                                     NULL);
2169
2170     if (gtk_dialog_run(GTK_DIALOG(filesel)) == GTK_RESPONSE_ACCEPT) {
2171         char *name = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(filesel));
2172         filesel_name = dupstr(name);
2173         g_free(name);
2174     }
2175
2176     gtk_widget_destroy(filesel);
2177
2178     return filesel_name;
2179 }
2180
2181 #endif
2182
2183 struct savefile_write_ctx {
2184     FILE *fp;
2185     int error;
2186 };
2187
2188 static void savefile_write(void *wctx, void *buf, int len)
2189 {
2190     struct savefile_write_ctx *ctx = (struct savefile_write_ctx *)wctx;
2191     if (fwrite(buf, 1, len, ctx->fp) < len)
2192         ctx->error = errno;
2193 }
2194
2195 static int savefile_read(void *wctx, void *buf, int len)
2196 {
2197     FILE *fp = (FILE *)wctx;
2198     int ret;
2199
2200     ret = fread(buf, 1, len, fp);
2201     return (ret == len);
2202 }
2203
2204 static void menu_save_event(GtkMenuItem *menuitem, gpointer data)
2205 {
2206     frontend *fe = (frontend *)data;
2207     char *name;
2208
2209     name = file_selector(fe, "Enter name of game file to save", TRUE);
2210
2211     if (name) {
2212         FILE *fp;
2213
2214         if ((fp = fopen(name, "r")) != NULL) {
2215             char buf[256 + FILENAME_MAX];
2216             fclose(fp);
2217             /* file exists */
2218
2219             sprintf(buf, "Are you sure you want to overwrite the"
2220                     " file \"%.*s\"?",
2221                     FILENAME_MAX, name);
2222             if (!message_box(fe->window, "Question", buf, TRUE, MB_YESNO))
2223                 goto free_and_return;
2224         }
2225
2226         fp = fopen(name, "w");
2227
2228         if (!fp) {
2229             error_box(fe->window, "Unable to open save file");
2230             goto free_and_return;
2231         }
2232
2233         {
2234             struct savefile_write_ctx ctx;
2235             ctx.fp = fp;
2236             ctx.error = 0;
2237             midend_serialise(fe->me, savefile_write, &ctx);
2238             fclose(fp);
2239             if (ctx.error) {
2240                 char boxmsg[512];
2241                 sprintf(boxmsg, "Error writing save file: %.400s",
2242                         strerror(errno));
2243                 error_box(fe->window, boxmsg);
2244                 goto free_and_return;
2245             }
2246         }
2247     free_and_return:
2248         sfree(name);
2249     }
2250 }
2251
2252 static void menu_load_event(GtkMenuItem *menuitem, gpointer data)
2253 {
2254     frontend *fe = (frontend *)data;
2255     char *name, *err;
2256
2257     name = file_selector(fe, "Enter name of saved game file to load", FALSE);
2258
2259     if (name) {
2260         FILE *fp = fopen(name, "r");
2261         sfree(name);
2262
2263         if (!fp) {
2264             error_box(fe->window, "Unable to open saved game file");
2265             return;
2266         }
2267
2268         err = midend_deserialise(fe->me, savefile_read, fp);
2269
2270         fclose(fp);
2271
2272         if (err) {
2273             error_box(fe->window, err);
2274             return;
2275         }
2276
2277         changed_preset(fe);
2278         resize_fe(fe);
2279         midend_redraw(fe->me);
2280     }
2281 }
2282
2283 static void menu_solve_event(GtkMenuItem *menuitem, gpointer data)
2284 {
2285     frontend *fe = (frontend *)data;
2286     char *msg;
2287
2288     msg = midend_solve(fe->me);
2289
2290     if (msg)
2291         error_box(fe->window, msg);
2292 }
2293
2294 static void menu_restart_event(GtkMenuItem *menuitem, gpointer data)
2295 {
2296     frontend *fe = (frontend *)data;
2297
2298     midend_restart_game(fe->me);
2299 }
2300
2301 static void menu_config_event(GtkMenuItem *menuitem, gpointer data)
2302 {
2303     frontend *fe = (frontend *)data;
2304     int which = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(menuitem),
2305                                                   "user-data"));
2306
2307     if (fe->preset_threaded ||
2308         (GTK_IS_CHECK_MENU_ITEM(menuitem) &&
2309          !gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(menuitem))))
2310         return;
2311     changed_preset(fe);                 /* Put the old preset back! */
2312     if (!get_config(fe, which))
2313         return;
2314
2315     midend_new_game(fe->me);
2316     resize_fe(fe);
2317     midend_redraw(fe->me);
2318 }
2319
2320 static void menu_about_event(GtkMenuItem *menuitem, gpointer data)
2321 {
2322     frontend *fe = (frontend *)data;
2323
2324 #if GTK_CHECK_VERSION(3,0,0)
2325     extern char *const *const xpm_icons[];
2326     extern const int n_xpm_icons;
2327     GdkPixbuf *icon = gdk_pixbuf_new_from_xpm_data
2328         ((const gchar **)xpm_icons[n_xpm_icons-1]);
2329     gtk_show_about_dialog
2330         (GTK_WINDOW(fe->window),
2331          "program-name", thegame.name,
2332          "version", ver,
2333          "comments", "Part of Simon Tatham's Portable Puzzle Collection",
2334          "logo", icon,
2335          (const gchar *)NULL);
2336     g_object_unref(G_OBJECT(icon));
2337 #else
2338     char titlebuf[256];
2339     char textbuf[1024];
2340
2341     sprintf(titlebuf, "About %.200s", thegame.name);
2342     sprintf(textbuf,
2343             "%.200s\n\n"
2344             "from Simon Tatham's Portable Puzzle Collection\n\n"
2345             "%.500s", thegame.name, ver);
2346
2347     message_box(fe->window, titlebuf, textbuf, TRUE, MB_OK);
2348 #endif
2349 }
2350
2351 static GtkWidget *add_menu_item_with_key(frontend *fe, GtkContainer *cont,
2352                                          char *text, int key)
2353 {
2354     GtkWidget *menuitem = gtk_menu_item_new_with_label(text);
2355     int keyqual;
2356     gtk_container_add(cont, menuitem);
2357     g_object_set_data(G_OBJECT(menuitem), "user-data", GINT_TO_POINTER(key));
2358     g_signal_connect(G_OBJECT(menuitem), "activate",
2359                      G_CALLBACK(menu_key_event), fe);
2360     switch (key & ~0x1F) {
2361       case 0x00:
2362         key += 0x60;
2363         keyqual = GDK_CONTROL_MASK;
2364         break;
2365       case 0x40:
2366         key += 0x20;
2367         keyqual = GDK_SHIFT_MASK;
2368         break;
2369       default:
2370         keyqual = 0;
2371         break;
2372     }
2373     gtk_widget_add_accelerator(menuitem,
2374                                "activate", fe->accelgroup,
2375                                key, keyqual,
2376                                GTK_ACCEL_VISIBLE);
2377     gtk_widget_show(menuitem);
2378     return menuitem;
2379 }
2380
2381 static void add_menu_separator(GtkContainer *cont)
2382 {
2383     GtkWidget *menuitem = gtk_menu_item_new();
2384     gtk_container_add(cont, menuitem);
2385     gtk_widget_show(menuitem);
2386 }
2387
2388 static void populate_gtk_preset_menu(frontend *fe, struct preset_menu *menu,
2389                                      GtkWidget *gtkmenu)
2390 {
2391     int i;
2392
2393     for (i = 0; i < menu->n_entries; i++) {
2394         struct preset_menu_entry *entry = &menu->entries[i];
2395         GtkWidget *menuitem;
2396
2397         if (entry->params) {
2398             menuitem = gtk_radio_menu_item_new_with_label(
2399                 fe->preset_radio, entry->title);
2400             fe->preset_radio = gtk_radio_menu_item_get_group(
2401                 GTK_RADIO_MENU_ITEM(menuitem));
2402             g_object_set_data(G_OBJECT(menuitem), "user-data", entry);
2403             g_signal_connect(G_OBJECT(menuitem), "activate",
2404                              G_CALLBACK(menu_preset_event), fe);
2405         } else {
2406             GtkWidget *submenu;
2407             menuitem = gtk_menu_item_new_with_label(entry->title);
2408             submenu = gtk_menu_new();
2409             gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), submenu);
2410             populate_gtk_preset_menu(fe, entry->submenu, submenu);
2411         }
2412
2413         gtk_container_add(GTK_CONTAINER(gtkmenu), menuitem);
2414         gtk_widget_show(menuitem);
2415     }
2416 }
2417
2418 enum { ARG_EITHER, ARG_SAVE, ARG_ID }; /* for argtype */
2419
2420 static frontend *new_window(char *arg, int argtype, char **error)
2421 {
2422     frontend *fe;
2423     GtkBox *vbox, *hbox;
2424     GtkWidget *menu, *menuitem;
2425     GList *iconlist;
2426     int x, y, n;
2427     char errbuf[1024];
2428     extern char *const *const xpm_icons[];
2429     extern const int n_xpm_icons;
2430     struct preset_menu *preset_menu;
2431
2432     fe = snew(frontend);
2433 #if GTK_CHECK_VERSION(3,20,0)
2434     fe->css_provider = NULL;
2435 #endif
2436
2437     fe->timer_active = FALSE;
2438     fe->timer_id = -1;
2439
2440     fe->me = midend_new(fe, &thegame, &gtk_drawing, fe);
2441
2442     if (arg) {
2443         char *err;
2444         FILE *fp;
2445
2446         errbuf[0] = '\0';
2447
2448         switch (argtype) {
2449           case ARG_ID:
2450             err = midend_game_id(fe->me, arg);
2451             if (!err)
2452                 midend_new_game(fe->me);
2453             else
2454                 sprintf(errbuf, "Invalid game ID: %.800s", err);
2455             break;
2456           case ARG_SAVE:
2457             fp = fopen(arg, "r");
2458             if (!fp) {
2459                 sprintf(errbuf, "Error opening file: %.800s", strerror(errno));
2460             } else {
2461                 err = midend_deserialise(fe->me, savefile_read, fp);
2462                 if (err)
2463                     sprintf(errbuf, "Invalid save file: %.800s", err);
2464                 fclose(fp);
2465             }
2466             break;
2467           default /*case ARG_EITHER*/:
2468             /*
2469              * First try treating the argument as a game ID.
2470              */
2471             err = midend_game_id(fe->me, arg);
2472             if (!err) {
2473                 /*
2474                  * It's a valid game ID.
2475                  */
2476                 midend_new_game(fe->me);
2477             } else {
2478                 FILE *fp = fopen(arg, "r");
2479                 if (!fp) {
2480                     sprintf(errbuf, "Supplied argument is neither a game ID (%.400s)"
2481                             " nor a save file (%.400s)", err, strerror(errno));
2482                 } else {
2483                     err = midend_deserialise(fe->me, savefile_read, fp);
2484                     if (err)
2485                         sprintf(errbuf, "%.800s", err);
2486                     fclose(fp);
2487                 }
2488             }
2489             break;
2490         }
2491         if (*errbuf) {
2492             *error = dupstr(errbuf);
2493             midend_free(fe->me);
2494             sfree(fe);
2495             return NULL;
2496         }
2497
2498     } else {
2499         midend_new_game(fe->me);
2500     }
2501
2502 #if !GTK_CHECK_VERSION(3,0,0)
2503     {
2504         /*
2505          * try_shrink_drawing_area() will do some fiddling with the
2506          * window size request (see comment in that function) after
2507          * all the bits and pieces such as the menu bar and status bar
2508          * have appeared in the puzzle window.
2509          *
2510          * However, on Unity systems, the menu bar _doesn't_ appear in
2511          * the puzzle window, because the Unity shell hijacks it into
2512          * the menu bar at the very top of the screen. We therefore
2513          * try to detect that situation here, so that we don't sit
2514          * here forever waiting for a menu bar.
2515          */
2516         const char prop[] = "gtk-shell-shows-menubar";
2517         GtkSettings *settings = gtk_settings_get_default();
2518         if (!g_object_class_find_property(G_OBJECT_GET_CLASS(settings),
2519                                           prop)) {
2520             fe->menubar_is_local = TRUE;
2521         } else {
2522             int unity_mode;
2523             g_object_get(gtk_settings_get_default(),
2524                          prop, &unity_mode,
2525                          (const gchar *)NULL);
2526             fe->menubar_is_local = !unity_mode;
2527         }
2528     }
2529 #endif
2530
2531     fe->window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
2532     gtk_window_set_title(GTK_WINDOW(fe->window), thegame.name);
2533
2534     vbox = GTK_BOX(gtk_vbox_new(FALSE, 0));
2535     gtk_container_add(GTK_CONTAINER(fe->window), GTK_WIDGET(vbox));
2536     gtk_widget_show(GTK_WIDGET(vbox));
2537
2538     fe->accelgroup = gtk_accel_group_new();
2539     gtk_window_add_accel_group(GTK_WINDOW(fe->window), fe->accelgroup);
2540
2541     hbox = GTK_BOX(gtk_hbox_new(FALSE, 0));
2542     gtk_box_pack_start(vbox, GTK_WIDGET(hbox), FALSE, FALSE, 0);
2543     gtk_widget_show(GTK_WIDGET(hbox));
2544
2545     fe->menubar = gtk_menu_bar_new();
2546     gtk_box_pack_start(hbox, fe->menubar, TRUE, TRUE, 0);
2547     gtk_widget_show(fe->menubar);
2548
2549     menuitem = gtk_menu_item_new_with_mnemonic("_Game");
2550     gtk_container_add(GTK_CONTAINER(fe->menubar), menuitem);
2551     gtk_widget_show(menuitem);
2552
2553     menu = gtk_menu_new();
2554     gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
2555
2556     add_menu_item_with_key(fe, GTK_CONTAINER(menu), "New", 'n');
2557
2558     menuitem = gtk_menu_item_new_with_label("Restart");
2559     gtk_container_add(GTK_CONTAINER(menu), menuitem);
2560     g_signal_connect(G_OBJECT(menuitem), "activate",
2561                      G_CALLBACK(menu_restart_event), fe);
2562     gtk_widget_show(menuitem);
2563
2564     menuitem = gtk_menu_item_new_with_label("Specific...");
2565     g_object_set_data(G_OBJECT(menuitem), "user-data",
2566                       GINT_TO_POINTER(CFG_DESC));
2567     gtk_container_add(GTK_CONTAINER(menu), menuitem);
2568     g_signal_connect(G_OBJECT(menuitem), "activate",
2569                      G_CALLBACK(menu_config_event), fe);
2570     gtk_widget_show(menuitem);
2571
2572     menuitem = gtk_menu_item_new_with_label("Random Seed...");
2573     g_object_set_data(G_OBJECT(menuitem), "user-data",
2574                       GINT_TO_POINTER(CFG_SEED));
2575     gtk_container_add(GTK_CONTAINER(menu), menuitem);
2576     g_signal_connect(G_OBJECT(menuitem), "activate",
2577                      G_CALLBACK(menu_config_event), fe);
2578     gtk_widget_show(menuitem);
2579
2580     fe->preset_radio = NULL;
2581     fe->preset_custom = NULL;
2582     fe->preset_threaded = FALSE;
2583
2584     preset_menu = midend_get_presets(fe->me, NULL);
2585     if (preset_menu->n_entries > 0 || thegame.can_configure) {
2586         GtkWidget *submenu;
2587
2588         menuitem = gtk_menu_item_new_with_mnemonic("_Type");
2589         gtk_container_add(GTK_CONTAINER(fe->menubar), menuitem);
2590         gtk_widget_show(menuitem);
2591
2592         submenu = gtk_menu_new();
2593         gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), submenu);
2594
2595         populate_gtk_preset_menu(fe, preset_menu, submenu);
2596
2597         if (thegame.can_configure) {
2598             menuitem = fe->preset_custom =
2599                 gtk_radio_menu_item_new_with_label(fe->preset_radio,
2600                                                    "Custom...");
2601             fe->preset_radio =
2602                 gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(menuitem));
2603             gtk_container_add(GTK_CONTAINER(submenu), menuitem);
2604             g_object_set_data(G_OBJECT(menuitem), "user-data",
2605                               GINT_TO_POINTER(CFG_SETTINGS));
2606             g_signal_connect(G_OBJECT(menuitem), "activate",
2607                              G_CALLBACK(menu_config_event), fe);
2608             gtk_widget_show(menuitem);
2609         }
2610
2611     }
2612
2613     add_menu_separator(GTK_CONTAINER(menu));
2614     menuitem = gtk_menu_item_new_with_label("Load...");
2615     gtk_container_add(GTK_CONTAINER(menu), menuitem);
2616     g_signal_connect(G_OBJECT(menuitem), "activate",
2617                      G_CALLBACK(menu_load_event), fe);
2618     gtk_widget_show(menuitem);
2619     menuitem = gtk_menu_item_new_with_label("Save...");
2620     gtk_container_add(GTK_CONTAINER(menu), menuitem);
2621     g_signal_connect(G_OBJECT(menuitem), "activate",
2622                      G_CALLBACK(menu_save_event), fe);
2623     gtk_widget_show(menuitem);
2624 #ifndef STYLUS_BASED
2625     add_menu_separator(GTK_CONTAINER(menu));
2626     add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Undo", 'u');
2627     add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Redo", 'r');
2628 #endif
2629     if (thegame.can_format_as_text_ever) {
2630         add_menu_separator(GTK_CONTAINER(menu));
2631         menuitem = gtk_menu_item_new_with_label("Copy");
2632         gtk_container_add(GTK_CONTAINER(menu), menuitem);
2633         g_signal_connect(G_OBJECT(menuitem), "activate",
2634                          G_CALLBACK(menu_copy_event), fe);
2635         gtk_widget_show(menuitem);
2636         fe->copy_menu_item = menuitem;
2637     } else {
2638         fe->copy_menu_item = NULL;
2639     }
2640     if (thegame.can_solve) {
2641         add_menu_separator(GTK_CONTAINER(menu));
2642         menuitem = gtk_menu_item_new_with_label("Solve");
2643         gtk_container_add(GTK_CONTAINER(menu), menuitem);
2644         g_signal_connect(G_OBJECT(menuitem), "activate",
2645                          G_CALLBACK(menu_solve_event), fe);
2646         gtk_widget_show(menuitem);
2647     }
2648     add_menu_separator(GTK_CONTAINER(menu));
2649     add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Exit", 'q');
2650
2651     menuitem = gtk_menu_item_new_with_mnemonic("_Help");
2652     gtk_container_add(GTK_CONTAINER(fe->menubar), menuitem);
2653     gtk_widget_show(menuitem);
2654
2655     menu = gtk_menu_new();
2656     gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
2657
2658     menuitem = gtk_menu_item_new_with_label("About");
2659     gtk_container_add(GTK_CONTAINER(menu), menuitem);
2660     g_signal_connect(G_OBJECT(menuitem), "activate",
2661                      G_CALLBACK(menu_about_event), fe);
2662     gtk_widget_show(menuitem);
2663
2664 #ifdef STYLUS_BASED
2665     menuitem=gtk_button_new_with_mnemonic("_Redo");
2666     g_object_set_data(G_OBJECT(menuitem), "user-data",
2667                       GINT_TO_POINTER((int)('r')));
2668     g_signal_connect(G_OBJECT(menuitem), "clicked",
2669                      G_CALLBACK(menu_key_event), fe);
2670     gtk_box_pack_end(hbox, menuitem, FALSE, FALSE, 0);
2671     gtk_widget_show(menuitem);
2672
2673     menuitem=gtk_button_new_with_mnemonic("_Undo");
2674     g_object_set_data(G_OBJECT(menuitem), "user-data",
2675                       GINT_TO_POINTER((int)('u')));
2676     g_signal_connect(G_OBJECT(menuitem), "clicked",
2677                      G_CALLBACK(menu_key_event), fe);
2678     gtk_box_pack_end(hbox, menuitem, FALSE, FALSE, 0);
2679     gtk_widget_show(menuitem);
2680
2681     if (thegame.flags & REQUIRE_NUMPAD) {
2682         hbox = GTK_BOX(gtk_hbox_new(FALSE, 0));
2683         gtk_box_pack_start(vbox, GTK_WIDGET(hbox), FALSE, FALSE, 0);
2684         gtk_widget_show(GTK_WIDGET(hbox));
2685
2686         *((int*)errbuf)=0;
2687         errbuf[1]='\0';
2688         for(errbuf[0]='0';errbuf[0]<='9';errbuf[0]++) {
2689             menuitem=gtk_button_new_with_label(errbuf);
2690             g_object_set_data(G_OBJECT(menuitem), "user-data",
2691                               GINT_TO_POINTER((int)(errbuf[0])));
2692             g_signal_connect(G_OBJECT(menuitem), "clicked",
2693                              G_CALLBACK(menu_key_event), fe);
2694             gtk_box_pack_start(hbox, menuitem, TRUE, TRUE, 0);
2695             gtk_widget_show(menuitem);
2696         }
2697     }
2698 #endif /* STYLUS_BASED */
2699
2700     changed_preset(fe);
2701
2702     snaffle_colours(fe);
2703
2704     if (midend_wants_statusbar(fe->me)) {
2705         GtkWidget *viewport;
2706         GtkRequisition req;
2707
2708         viewport = gtk_viewport_new(NULL, NULL);
2709         gtk_viewport_set_shadow_type(GTK_VIEWPORT(viewport), GTK_SHADOW_NONE);
2710         fe->statusbar = gtk_statusbar_new();
2711         gtk_container_add(GTK_CONTAINER(viewport), fe->statusbar);
2712         gtk_widget_show(viewport);
2713         gtk_box_pack_end(vbox, viewport, FALSE, FALSE, 0);
2714         gtk_widget_show(fe->statusbar);
2715         fe->statusctx = gtk_statusbar_get_context_id
2716             (GTK_STATUSBAR(fe->statusbar), "game");
2717         gtk_statusbar_push(GTK_STATUSBAR(fe->statusbar), fe->statusctx,
2718                            DEFAULT_STATUSBAR_TEXT);
2719 #if GTK_CHECK_VERSION(3,0,0)
2720         gtk_widget_get_preferred_size(fe->statusbar, &req, NULL);
2721 #else
2722         gtk_widget_size_request(fe->statusbar, &req);
2723 #endif
2724         gtk_widget_set_size_request(viewport, -1, req.height);
2725     } else
2726         fe->statusbar = NULL;
2727
2728     fe->area = gtk_drawing_area_new();
2729 #if GTK_CHECK_VERSION(2,0,0) && !GTK_CHECK_VERSION(3,0,0)
2730     gtk_widget_set_double_buffered(fe->area, FALSE);
2731 #endif
2732     {
2733         GdkGeometry geom;
2734         geom.base_width = 0;
2735 #if GTK_CHECK_VERSION(3,0,0)
2736         geom.base_height = window_extra_height(fe);
2737         gtk_window_set_geometry_hints(GTK_WINDOW(fe->window), NULL,
2738                                       &geom, GDK_HINT_BASE_SIZE);
2739 #else
2740         geom.base_height = 0;
2741         gtk_window_set_geometry_hints(GTK_WINDOW(fe->window), fe->area,
2742                                       &geom, GDK_HINT_BASE_SIZE);
2743 #endif
2744     }
2745     fe->w = -1;
2746     fe->h = -1;
2747     get_size(fe, &x, &y);
2748 #if GTK_CHECK_VERSION(3,0,0)
2749     gtk_window_set_default_size(GTK_WINDOW(fe->window),
2750                                 x, y + window_extra_height(fe));
2751 #else
2752     fe->drawing_area_shrink_pending = FALSE;
2753     gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
2754 #endif
2755
2756     gtk_box_pack_end(vbox, fe->area, TRUE, TRUE, 0);
2757
2758     clear_backing_store(fe);
2759     fe->fonts = NULL;
2760     fe->nfonts = fe->fontsize = 0;
2761
2762     fe->paste_data = NULL;
2763     fe->paste_data_len = 0;
2764
2765     g_signal_connect(G_OBJECT(fe->window), "destroy",
2766                      G_CALLBACK(destroy), fe);
2767     g_signal_connect(G_OBJECT(fe->window), "key_press_event",
2768                      G_CALLBACK(key_event), fe);
2769     g_signal_connect(G_OBJECT(fe->area), "button_press_event",
2770                      G_CALLBACK(button_event), fe);
2771     g_signal_connect(G_OBJECT(fe->area), "button_release_event",
2772                      G_CALLBACK(button_event), fe);
2773     g_signal_connect(G_OBJECT(fe->area), "motion_notify_event",
2774                      G_CALLBACK(motion_event), fe);
2775     g_signal_connect(G_OBJECT(fe->area), "selection_get",
2776                      G_CALLBACK(selection_get), fe);
2777     g_signal_connect(G_OBJECT(fe->area), "selection_clear_event",
2778                      G_CALLBACK(selection_clear), fe);
2779 #if GTK_CHECK_VERSION(3,0,0)
2780     g_signal_connect(G_OBJECT(fe->area), "draw",
2781                      G_CALLBACK(draw_area), fe);
2782 #else
2783     g_signal_connect(G_OBJECT(fe->area), "expose_event",
2784                      G_CALLBACK(expose_area), fe);
2785 #endif
2786     g_signal_connect(G_OBJECT(fe->window), "map_event",
2787                      G_CALLBACK(map_window), fe);
2788     g_signal_connect(G_OBJECT(fe->area), "configure_event",
2789                      G_CALLBACK(configure_area), fe);
2790     g_signal_connect(G_OBJECT(fe->window), "configure_event",
2791                      G_CALLBACK(configure_window), fe);
2792
2793     gtk_widget_add_events(GTK_WIDGET(fe->area),
2794                           GDK_BUTTON_PRESS_MASK |
2795                           GDK_BUTTON_RELEASE_MASK |
2796                           GDK_BUTTON_MOTION_MASK |
2797                           GDK_POINTER_MOTION_HINT_MASK);
2798
2799     if (n_xpm_icons) {
2800         gtk_window_set_icon(GTK_WINDOW(fe->window),
2801                             gdk_pixbuf_new_from_xpm_data
2802                             ((const gchar **)xpm_icons[0]));
2803
2804         iconlist = NULL;
2805         for (n = 0; n < n_xpm_icons; n++) {
2806             iconlist =
2807                 g_list_append(iconlist,
2808                               gdk_pixbuf_new_from_xpm_data((const gchar **)
2809                                                            xpm_icons[n]));
2810         }
2811         gtk_window_set_icon_list(GTK_WINDOW(fe->window), iconlist);
2812     }
2813
2814     gtk_widget_show(fe->area);
2815     gtk_widget_show(fe->window);
2816
2817 #if !GTK_CHECK_VERSION(3,0,0)
2818     fe->drawing_area_shrink_pending = TRUE;
2819     try_shrink_drawing_area(fe);
2820 #endif
2821
2822     set_window_background(fe, 0);
2823
2824     return fe;
2825 }
2826
2827 char *fgetline(FILE *fp)
2828 {
2829     char *ret = snewn(512, char);
2830     int size = 512, len = 0;
2831     while (fgets(ret + len, size - len, fp)) {
2832         len += strlen(ret + len);
2833         if (ret[len-1] == '\n')
2834             break;                     /* got a newline, we're done */
2835         size = len + 512;
2836         ret = sresize(ret, size, char);
2837     }
2838     if (len == 0) {                    /* first fgets returned NULL */
2839         sfree(ret);
2840         return NULL;
2841     }
2842     ret[len] = '\0';
2843     return ret;
2844 }
2845
2846 static void list_presets_from_menu(struct preset_menu *menu)
2847 {
2848     int i;
2849
2850     for (i = 0; i < menu->n_entries; i++) {
2851         if (menu->entries[i].params) {
2852             char *paramstr = thegame.encode_params(
2853                 menu->entries[i].params, TRUE);
2854             printf("%s %s\n", paramstr, menu->entries[i].title);
2855             sfree(paramstr);
2856         } else {
2857             list_presets_from_menu(menu->entries[i].submenu);
2858         }
2859     }
2860 }
2861
2862 int main(int argc, char **argv)
2863 {
2864     char *pname = argv[0];
2865     char *error;
2866     int ngenerate = 0, print = FALSE, px = 1, py = 1;
2867     int time_generation = FALSE, test_solve = FALSE, list_presets = FALSE;
2868     int soln = FALSE, colour = FALSE;
2869     float scale = 1.0F;
2870     float redo_proportion = 0.0F;
2871     char *savefile = NULL, *savesuffix = NULL;
2872     char *arg = NULL;
2873     int argtype = ARG_EITHER;
2874     char *screenshot_file = NULL;
2875     int doing_opts = TRUE;
2876     int ac = argc;
2877     char **av = argv;
2878     char errbuf[500];
2879
2880     /*
2881      * Command line parsing in this function is rather fiddly,
2882      * because GTK wants to have a go at argc/argv _first_ - and
2883      * yet we can't let it, because gtk_init() will bomb out if it
2884      * can't open an X display, whereas in fact we want to permit
2885      * our --generate and --print modes to run without an X
2886      * display.
2887      * 
2888      * So what we do is:
2889      *  - we parse the command line ourselves, without modifying
2890      *    argc/argv
2891      *  - if we encounter an error which might plausibly be the
2892      *    result of a GTK command line (i.e. not detailed errors in
2893      *    particular options of ours) we store the error message
2894      *    and terminate parsing.
2895      *  - if we got enough out of the command line to know it
2896      *    specifies a non-X mode of operation, we either display
2897      *    the stored error and return failure, or if there is no
2898      *    stored error we do the non-X operation and return
2899      *    success.
2900      *  - otherwise, we go straight to gtk_init().
2901      */
2902
2903     errbuf[0] = '\0';
2904     while (--ac > 0) {
2905         char *p = *++av;
2906         if (doing_opts && !strcmp(p, "--version")) {
2907             printf("%s, from Simon Tatham's Portable Puzzle Collection\n%s\n",
2908                    thegame.name, ver);
2909             return 0;
2910         } else if (doing_opts && !strcmp(p, "--generate")) {
2911             if (--ac > 0) {
2912                 ngenerate = atoi(*++av);
2913                 if (!ngenerate) {
2914                     fprintf(stderr, "%s: '--generate' expected a number\n",
2915                             pname);
2916                     return 1;
2917                 }
2918             } else
2919                 ngenerate = 1;
2920         } else if (doing_opts && !strcmp(p, "--time-generation")) {
2921             time_generation = TRUE;
2922         } else if (doing_opts && !strcmp(p, "--test-solve")) {
2923             test_solve = TRUE;
2924         } else if (doing_opts && !strcmp(p, "--list-presets")) {
2925             list_presets = TRUE;
2926         } else if (doing_opts && !strcmp(p, "--save")) {
2927             if (--ac > 0) {
2928                 savefile = *++av;
2929             } else {
2930                 fprintf(stderr, "%s: '--save' expected a filename\n",
2931                         pname);
2932                 return 1;
2933             }
2934         } else if (doing_opts && (!strcmp(p, "--save-suffix") ||
2935                                   !strcmp(p, "--savesuffix"))) {
2936             if (--ac > 0) {
2937                 savesuffix = *++av;
2938             } else {
2939                 fprintf(stderr, "%s: '--save-suffix' expected a filename\n",
2940                         pname);
2941                 return 1;
2942             }
2943         } else if (doing_opts && !strcmp(p, "--print")) {
2944             if (!thegame.can_print) {
2945                 fprintf(stderr, "%s: this game does not support printing\n",
2946                         pname);
2947                 return 1;
2948             }
2949             print = TRUE;
2950             if (--ac > 0) {
2951                 char *dim = *++av;
2952                 if (sscanf(dim, "%dx%d", &px, &py) != 2) {
2953                     fprintf(stderr, "%s: unable to parse argument '%s' to "
2954                             "'--print'\n", pname, dim);
2955                     return 1;
2956                 }
2957             } else {
2958                 px = py = 1;
2959             }
2960         } else if (doing_opts && !strcmp(p, "--scale")) {
2961             if (--ac > 0) {
2962                 scale = atof(*++av);
2963             } else {
2964                 fprintf(stderr, "%s: no argument supplied to '--scale'\n",
2965                         pname);
2966                 return 1;
2967             }
2968         } else if (doing_opts && !strcmp(p, "--redo")) {
2969             /*
2970              * This is an internal option which I don't expect
2971              * users to have any particular use for. The effect of
2972              * --redo is that once the game has been loaded and
2973              * initialised, the next move in the redo chain is
2974              * replayed, and the game screen is redrawn part way
2975              * through the making of the move. This is only
2976              * meaningful if there _is_ a next move in the redo
2977              * chain, which means in turn that this option is only
2978              * useful if you're also passing a save file on the
2979              * command line.
2980              *
2981              * This option is used by the script which generates
2982              * the puzzle icons and website screenshots, and I
2983              * don't imagine it's useful for anything else.
2984              * (Unless, I suppose, users don't like my screenshots
2985              * and want to generate their own in the same way for
2986              * some repackaged version of the puzzles.)
2987              */
2988             if (--ac > 0) {
2989                 redo_proportion = atof(*++av);
2990             } else {
2991                 fprintf(stderr, "%s: no argument supplied to '--redo'\n",
2992                         pname);
2993                 return 1;
2994             }
2995         } else if (doing_opts && !strcmp(p, "--screenshot")) {
2996             /*
2997              * Another internal option for the icon building
2998              * script. This causes a screenshot of the central
2999              * drawing area (i.e. not including the menu bar or
3000              * status bar) to be saved to a PNG file once the
3001              * window has been drawn, and then the application
3002              * quits immediately.
3003              */
3004             if (--ac > 0) {
3005                 screenshot_file = *++av;
3006             } else {
3007                 fprintf(stderr, "%s: no argument supplied to '--screenshot'\n",
3008                         pname);
3009                 return 1;
3010             }
3011         } else if (doing_opts && (!strcmp(p, "--with-solutions") ||
3012                                   !strcmp(p, "--with-solution") ||
3013                                   !strcmp(p, "--with-solns") ||
3014                                   !strcmp(p, "--with-soln") ||
3015                                   !strcmp(p, "--solutions") ||
3016                                   !strcmp(p, "--solution") ||
3017                                   !strcmp(p, "--solns") ||
3018                                   !strcmp(p, "--soln"))) {
3019             soln = TRUE;
3020         } else if (doing_opts && !strcmp(p, "--colour")) {
3021             if (!thegame.can_print_in_colour) {
3022                 fprintf(stderr, "%s: this game does not support colour"
3023                         " printing\n", pname);
3024                 return 1;
3025             }
3026             colour = TRUE;
3027         } else if (doing_opts && !strcmp(p, "--load")) {
3028             argtype = ARG_SAVE;
3029         } else if (doing_opts && !strcmp(p, "--game")) {
3030             argtype = ARG_ID;
3031         } else if (doing_opts && !strcmp(p, "--")) {
3032             doing_opts = FALSE;
3033         } else if (!doing_opts || p[0] != '-') {
3034             if (arg) {
3035                 fprintf(stderr, "%s: more than one argument supplied\n",
3036                         pname);
3037                 return 1;
3038             }
3039             arg = p;
3040         } else {
3041             sprintf(errbuf, "%.100s: unrecognised option '%.100s'\n",
3042                     pname, p);
3043             break;
3044         }
3045     }
3046
3047     /*
3048      * Special standalone mode for generating puzzle IDs on the
3049      * command line. Useful for generating puzzles to be printed
3050      * out and solved offline (for puzzles where that even makes
3051      * sense - Solo, for example, is a lot more pencil-and-paper
3052      * friendly than Twiddle!)
3053      * 
3054      * Usage:
3055      * 
3056      *   <puzzle-name> --generate [<n> [<params>]]
3057      * 
3058      * <n>, if present, is the number of puzzle IDs to generate.
3059      * <params>, if present, is the same type of parameter string
3060      * you would pass to the puzzle when running it in GUI mode,
3061      * including optional extras such as the expansion factor in
3062      * Rectangles and the difficulty level in Solo.
3063      * 
3064      * If you specify <params>, you must also specify <n> (although
3065      * you may specify it to be 1). Sorry; that was the
3066      * simplest-to-parse command-line syntax I came up with.
3067      */
3068     if (ngenerate > 0 || print || savefile || savesuffix) {
3069         int i, n = 1;
3070         midend *me;
3071         char *id;
3072         document *doc = NULL;
3073
3074         /*
3075          * If we're in this branch, we should display any pending
3076          * error message from the command line, since GTK isn't going
3077          * to take another crack at making sense of it.
3078          */
3079         if (*errbuf) {
3080             fputs(errbuf, stderr);
3081             return 1;
3082         }
3083
3084         n = ngenerate;
3085
3086         me = midend_new(NULL, &thegame, NULL, NULL);
3087         i = 0;
3088
3089         if (savefile && !savesuffix)
3090             savesuffix = "";
3091         if (!savefile && savesuffix)
3092             savefile = "";
3093
3094         if (print)
3095             doc = document_new(px, py, scale);
3096
3097         /*
3098          * In this loop, we either generate a game ID or read one
3099          * from stdin depending on whether we're in generate mode;
3100          * then we either write it to stdout or print it, depending
3101          * on whether we're in print mode. Thus, this loop handles
3102          * generate-to-stdout, print-from-stdin and generate-and-
3103          * immediately-print modes.
3104          * 
3105          * (It could also handle a copy-stdin-to-stdout mode,
3106          * although there's currently no combination of options
3107          * which will cause this loop to be activated in that mode.
3108          * It wouldn't be _entirely_ pointless, though, because
3109          * stdin could contain bare params strings or random-seed
3110          * IDs, and stdout would contain nothing but fully
3111          * generated descriptive game IDs.)
3112          */
3113         while (ngenerate == 0 || i < n) {
3114             char *pstr, *err, *seed;
3115             struct rusage before, after;
3116
3117             if (ngenerate == 0) {
3118                 pstr = fgetline(stdin);
3119                 if (!pstr)
3120                     break;
3121                 pstr[strcspn(pstr, "\r\n")] = '\0';
3122             } else {
3123                 if (arg) {
3124                     pstr = snewn(strlen(arg) + 40, char);
3125
3126                     strcpy(pstr, arg);
3127                     if (i > 0 && strchr(arg, '#'))
3128                         sprintf(pstr + strlen(pstr), "-%d", i);
3129                 } else
3130                     pstr = NULL;
3131             }
3132
3133             if (pstr) {
3134                 err = midend_game_id(me, pstr);
3135                 if (err) {
3136                     fprintf(stderr, "%s: error parsing '%s': %s\n",
3137                             pname, pstr, err);
3138                     return 1;
3139                 }
3140             }
3141
3142             if (time_generation)
3143                 getrusage(RUSAGE_SELF, &before);
3144
3145             midend_new_game(me);
3146
3147             seed = midend_get_random_seed(me);
3148
3149             if (time_generation) {
3150                 double elapsed;
3151
3152                 getrusage(RUSAGE_SELF, &after);
3153
3154                 elapsed = (after.ru_utime.tv_sec -
3155                            before.ru_utime.tv_sec);
3156                 elapsed += (after.ru_utime.tv_usec -
3157                             before.ru_utime.tv_usec) / 1000000.0;
3158
3159                 printf("%s %s: %.6f\n", thegame.name, seed, elapsed);
3160             }
3161
3162             if (test_solve && thegame.can_solve) {
3163                 /*
3164                  * Now destroy the aux_info in the midend, by means of
3165                  * re-entering the same game id, and then try to solve
3166                  * it.
3167                  */
3168                 char *game_id, *err;
3169
3170                 game_id = midend_get_game_id(me);
3171                 err = midend_game_id(me, game_id);
3172                 if (err) {
3173                     fprintf(stderr, "%s %s: game id re-entry error: %s\n",
3174                             thegame.name, seed, err);
3175                     return 1;
3176                 }
3177                 midend_new_game(me);
3178                 sfree(game_id);
3179
3180                 err = midend_solve(me);
3181                 /*
3182                  * If the solve operation returned the error "Solution
3183                  * not known for this puzzle", that's OK, because that
3184                  * just means it's a puzzle for which we don't have an
3185                  * algorithmic solver and hence can't solve it without
3186                  * the aux_info, e.g. Netslide. Any other error is a
3187                  * problem, though.
3188                  */
3189                 if (err && strcmp(err, "Solution not known for this puzzle")) {
3190                     fprintf(stderr, "%s %s: solve error: %s\n",
3191                             thegame.name, seed, err);
3192                     return 1;
3193                 }
3194             }
3195
3196             sfree(pstr);
3197             sfree(seed);
3198
3199             if (doc) {
3200                 err = midend_print_puzzle(me, doc, soln);
3201                 if (err) {
3202                     fprintf(stderr, "%s: error in printing: %s\n", pname, err);
3203                     return 1;
3204                 }
3205             }
3206             if (savefile) {
3207                 struct savefile_write_ctx ctx;
3208                 char *realname = snewn(40 + strlen(savefile) +
3209                                        strlen(savesuffix), char);
3210                 sprintf(realname, "%s%d%s", savefile, i, savesuffix);
3211
3212                 if (soln) {
3213                     char *err = midend_solve(me);
3214                     if (err) {
3215                         fprintf(stderr, "%s: unable to show solution: %s\n",
3216                                 realname, err);
3217                         return 1;
3218                     }
3219                 }
3220
3221                 ctx.fp = fopen(realname, "w");
3222                 if (!ctx.fp) {
3223                     fprintf(stderr, "%s: open: %s\n", realname,
3224                             strerror(errno));
3225                     return 1;
3226                 }
3227                 ctx.error = 0;
3228                 midend_serialise(me, savefile_write, &ctx);
3229                 if (ctx.error) {
3230                     fprintf(stderr, "%s: write: %s\n", realname,
3231                             strerror(ctx.error));
3232                     return 1;
3233                 }
3234                 if (fclose(ctx.fp)) {
3235                     fprintf(stderr, "%s: close: %s\n", realname,
3236                             strerror(errno));
3237                     return 1;
3238                 }
3239                 sfree(realname);
3240             }
3241             if (!doc && !savefile && !time_generation) {
3242                 id = midend_get_game_id(me);
3243                 puts(id);
3244                 sfree(id);
3245             }
3246
3247             i++;
3248         }
3249
3250         if (doc) {
3251             psdata *ps = ps_init(stdout, colour);
3252             document_print(doc, ps_drawing_api(ps));
3253             document_free(doc);
3254             ps_free(ps);
3255         }
3256
3257         midend_free(me);
3258
3259         return 0;
3260     } else if (list_presets) {
3261         /*
3262          * Another specialist mode which causes the puzzle to list the
3263          * game_params strings for all its preset configurations.
3264          */
3265         midend *me;
3266         struct preset_menu *menu;
3267
3268         me = midend_new(NULL, &thegame, NULL, NULL);
3269         menu = midend_get_presets(me, NULL);
3270         list_presets_from_menu(menu);
3271         midend_free(me);
3272         return 0;
3273     } else {
3274         frontend *fe;
3275
3276         gtk_init(&argc, &argv);
3277
3278         fe = new_window(arg, argtype, &error);
3279
3280         if (!fe) {
3281             fprintf(stderr, "%s: %s\n", pname, error);
3282             return 1;
3283         }
3284
3285         if (screenshot_file) {
3286             /*
3287              * Some puzzles will not redraw their entire area if
3288              * given a partially completed animation, which means
3289              * we must redraw now and _then_ redraw again after
3290              * freezing the move timer.
3291              */
3292             midend_force_redraw(fe->me);
3293         }
3294
3295         if (redo_proportion) {
3296             /* Start a redo. */
3297             midend_process_key(fe->me, 0, 0, 'r');
3298             /* And freeze the timer at the specified position. */
3299             midend_freeze_timer(fe->me, redo_proportion);
3300         }
3301
3302         if (screenshot_file) {
3303             save_screenshot_png(fe, screenshot_file);
3304             exit(0);
3305         }
3306
3307         gtk_main();
3308     }
3309
3310     return 0;
3311 }