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