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