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