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