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