chiark / gitweb /
Patch from Mark Wooding: use gdk_event_request_motions() where
[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 #if GTK_CHECK_VERSION(2,12,0)
650     gdk_event_request_motions(event);
651 #else
652     gdk_window_get_pointer(widget->window, NULL, NULL, NULL);
653 #endif
654
655     return TRUE;
656 }
657
658 static gint expose_area(GtkWidget *widget, GdkEventExpose *event,
659                         gpointer data)
660 {
661     frontend *fe = (frontend *)data;
662
663     if (fe->pixmap) {
664         gdk_draw_pixmap(widget->window,
665                         widget->style->fg_gc[GTK_WIDGET_STATE(widget)],
666                         fe->pixmap,
667                         event->area.x - fe->ox, event->area.y - fe->oy,
668                         event->area.x, event->area.y,
669                         event->area.width, event->area.height);
670     }
671     return TRUE;
672 }
673
674 static gint map_window(GtkWidget *widget, GdkEvent *event,
675                        gpointer data)
676 {
677     frontend *fe = (frontend *)data;
678
679     /*
680      * Apparently we need to do this because otherwise the status
681      * bar will fail to update immediately. Annoying, but there we
682      * go.
683      */
684     gtk_widget_queue_draw(fe->window);
685
686     return TRUE;
687 }
688
689 static gint configure_area(GtkWidget *widget,
690                            GdkEventConfigure *event, gpointer data)
691 {
692     frontend *fe = (frontend *)data;
693     GdkGC *gc;
694     int x, y;
695
696     if (fe->pixmap)
697         gdk_pixmap_unref(fe->pixmap);
698
699     x = fe->w = event->width;
700     y = fe->h = event->height;
701     midend_size(fe->me, &x, &y, TRUE);
702     fe->pw = x;
703     fe->ph = y;
704     fe->ox = (fe->w - fe->pw) / 2;
705     fe->oy = (fe->h - fe->ph) / 2;
706
707     fe->pixmap = gdk_pixmap_new(widget->window, fe->pw, fe->ph, -1);
708
709     gc = gdk_gc_new(fe->area->window);
710     gdk_gc_set_foreground(gc, &fe->colours[0]);
711     gdk_draw_rectangle(fe->pixmap, gc, 1, 0, 0, fe->pw, fe->ph);
712     gdk_draw_rectangle(widget->window, gc, 1, 0, 0,
713                        event->width, event->height);
714     gdk_gc_unref(gc);
715
716     midend_force_redraw(fe->me);
717
718     return TRUE;
719 }
720
721 static gint timer_func(gpointer data)
722 {
723     frontend *fe = (frontend *)data;
724
725     if (fe->timer_active) {
726         struct timeval now;
727         float elapsed;
728         gettimeofday(&now, NULL);
729         elapsed = ((now.tv_usec - fe->last_time.tv_usec) * 0.000001F +
730                    (now.tv_sec - fe->last_time.tv_sec));
731         midend_timer(fe->me, elapsed);  /* may clear timer_active */
732         fe->last_time = now;
733     }
734
735     return fe->timer_active;
736 }
737
738 void deactivate_timer(frontend *fe)
739 {
740     if (!fe)
741         return;                        /* can happen due to --generate */
742     if (fe->timer_active)
743         gtk_timeout_remove(fe->timer_id);
744     fe->timer_active = FALSE;
745 }
746
747 void activate_timer(frontend *fe)
748 {
749     if (!fe)
750         return;                        /* can happen due to --generate */
751     if (!fe->timer_active) {
752         fe->timer_id = gtk_timeout_add(20, timer_func, fe);
753         gettimeofday(&fe->last_time, NULL);
754     }
755     fe->timer_active = TRUE;
756 }
757
758 static void window_destroy(GtkWidget *widget, gpointer data)
759 {
760     gtk_main_quit();
761 }
762
763 static void msgbox_button_clicked(GtkButton *button, gpointer data)
764 {
765     GtkWidget *window = GTK_WIDGET(data);
766     int v, *ip;
767
768     ip = (int *)gtk_object_get_data(GTK_OBJECT(window), "user-data");
769     v = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(button), "user-data"));
770     *ip = v;
771
772     gtk_widget_destroy(GTK_WIDGET(data));
773 }
774
775 static int win_key_press(GtkWidget *widget, GdkEventKey *event, gpointer data)
776 {
777     GtkObject *cancelbutton = GTK_OBJECT(data);
778
779     /*
780      * `Escape' effectively clicks the cancel button
781      */
782     if (event->keyval == GDK_Escape) {
783         gtk_signal_emit_by_name(GTK_OBJECT(cancelbutton), "clicked");
784         return TRUE;
785     }
786
787     return FALSE;
788 }
789
790 enum { MB_OK, MB_YESNO };
791
792 int message_box(GtkWidget *parent, char *title, char *msg, int centre,
793                 int type)
794 {
795     GtkWidget *window, *hbox, *text, *button;
796     char *titles;
797     int i, def, cancel;
798
799     window = gtk_dialog_new();
800     text = gtk_label_new(msg);
801     gtk_misc_set_alignment(GTK_MISC(text), 0.0, 0.0);
802     hbox = gtk_hbox_new(FALSE, 0);
803     gtk_box_pack_start(GTK_BOX(hbox), text, FALSE, FALSE, 20);
804     gtk_box_pack_start(GTK_BOX(GTK_DIALOG(window)->vbox),
805                        hbox, FALSE, FALSE, 20);
806     gtk_widget_show(text);
807     gtk_widget_show(hbox);
808     gtk_window_set_title(GTK_WINDOW(window), title);
809     gtk_label_set_line_wrap(GTK_LABEL(text), TRUE);
810
811     if (type == MB_OK) {
812         titles = "OK\0";
813         def = cancel = 0;
814     } else {
815         assert(type == MB_YESNO);
816         titles = "Yes\0No\0";
817         def = 0;
818         cancel = 1;
819     }
820     i = 0;
821     
822     while (*titles) {
823         button = gtk_button_new_with_label(titles);
824         gtk_box_pack_end(GTK_BOX(GTK_DIALOG(window)->action_area),
825                          button, FALSE, FALSE, 0);
826         gtk_widget_show(button);
827         if (i == def) {
828             GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
829             gtk_window_set_default(GTK_WINDOW(window), button);
830         }
831         if (i == cancel) {
832             gtk_signal_connect(GTK_OBJECT(window), "key_press_event",
833                                GTK_SIGNAL_FUNC(win_key_press), button);
834         }
835         gtk_signal_connect(GTK_OBJECT(button), "clicked",
836                            GTK_SIGNAL_FUNC(msgbox_button_clicked), window);
837         gtk_object_set_data(GTK_OBJECT(button), "user-data",
838                             GINT_TO_POINTER(i));
839         titles += strlen(titles)+1;
840         i++;
841     }
842     gtk_object_set_data(GTK_OBJECT(window), "user-data",
843                         GINT_TO_POINTER(&i));
844     gtk_signal_connect(GTK_OBJECT(window), "destroy",
845                        GTK_SIGNAL_FUNC(window_destroy), NULL);
846     gtk_window_set_modal(GTK_WINDOW(window), TRUE);
847     gtk_window_set_transient_for(GTK_WINDOW(window), GTK_WINDOW(parent));
848     /* set_transient_window_pos(parent, window); */
849     gtk_widget_show(window);
850     i = -1;
851     gtk_main();
852     return (type == MB_YESNO ? i == 0 : TRUE);
853 }
854
855 void error_box(GtkWidget *parent, char *msg)
856 {
857     message_box(parent, "Error", msg, FALSE, MB_OK);
858 }
859
860 static void config_ok_button_clicked(GtkButton *button, gpointer data)
861 {
862     frontend *fe = (frontend *)data;
863     char *err;
864
865     err = midend_set_config(fe->me, fe->cfg_which, fe->cfg);
866
867     if (err)
868         error_box(fe->cfgbox, err);
869     else {
870         fe->cfgret = TRUE;
871         gtk_widget_destroy(fe->cfgbox);
872         changed_preset(fe);
873     }
874 }
875
876 static void config_cancel_button_clicked(GtkButton *button, gpointer data)
877 {
878     frontend *fe = (frontend *)data;
879
880     gtk_widget_destroy(fe->cfgbox);
881 }
882
883 static int editbox_key(GtkWidget *widget, GdkEventKey *event, gpointer data)
884 {
885     /*
886      * GtkEntry has a nasty habit of eating the Return key, which
887      * is unhelpful since it doesn't actually _do_ anything with it
888      * (it calls gtk_widget_activate, but our edit boxes never need
889      * activating). So I catch Return before GtkEntry sees it, and
890      * pass it straight on to the parent widget. Effect: hitting
891      * Return in an edit box will now activate the default button
892      * in the dialog just like it will everywhere else.
893      */
894     if (event->keyval == GDK_Return && widget->parent != NULL) {
895         gint return_val;
896         gtk_signal_emit_stop_by_name(GTK_OBJECT(widget), "key_press_event");
897         gtk_signal_emit_by_name(GTK_OBJECT(widget->parent), "key_press_event",
898                                 event, &return_val);
899         return return_val;
900     }
901     return FALSE;
902 }
903
904 static void editbox_changed(GtkEditable *ed, gpointer data)
905 {
906     config_item *i = (config_item *)data;
907
908     sfree(i->sval);
909     i->sval = dupstr(gtk_entry_get_text(GTK_ENTRY(ed)));
910 }
911
912 static void button_toggled(GtkToggleButton *tb, gpointer data)
913 {
914     config_item *i = (config_item *)data;
915
916     i->ival = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(tb));
917 }
918
919 static void droplist_sel(GtkMenuItem *item, gpointer data)
920 {
921     config_item *i = (config_item *)data;
922
923     i->ival = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(item),
924                                                   "user-data"));
925 }
926
927 static int get_config(frontend *fe, int which)
928 {
929     GtkWidget *w, *table, *cancel;
930     char *title;
931     config_item *i;
932     int y;
933
934     fe->cfg = midend_get_config(fe->me, which, &title);
935     fe->cfg_which = which;
936     fe->cfgret = FALSE;
937
938     fe->cfgbox = gtk_dialog_new();
939     gtk_window_set_title(GTK_WINDOW(fe->cfgbox), title);
940     sfree(title);
941
942     w = gtk_button_new_with_label("OK");
943     gtk_box_pack_end(GTK_BOX(GTK_DIALOG(fe->cfgbox)->action_area),
944                      w, FALSE, FALSE, 0);
945     gtk_widget_show(w);
946     GTK_WIDGET_SET_FLAGS(w, GTK_CAN_DEFAULT);
947     gtk_window_set_default(GTK_WINDOW(fe->cfgbox), w);
948     gtk_signal_connect(GTK_OBJECT(w), "clicked",
949                        GTK_SIGNAL_FUNC(config_ok_button_clicked), fe);
950
951     w = gtk_button_new_with_label("Cancel");
952     gtk_box_pack_end(GTK_BOX(GTK_DIALOG(fe->cfgbox)->action_area),
953                      w, FALSE, FALSE, 0);
954     gtk_widget_show(w);
955     gtk_signal_connect(GTK_OBJECT(w), "clicked",
956                        GTK_SIGNAL_FUNC(config_cancel_button_clicked), fe);
957     cancel = w;
958
959     table = gtk_table_new(1, 2, FALSE);
960     y = 0;
961     gtk_box_pack_end(GTK_BOX(GTK_DIALOG(fe->cfgbox)->vbox),
962                      table, FALSE, FALSE, 0);
963     gtk_widget_show(table);
964
965     for (i = fe->cfg; i->type != C_END; i++) {
966         gtk_table_resize(GTK_TABLE(table), y+1, 2);
967
968         switch (i->type) {
969           case C_STRING:
970             /*
971              * Edit box with a label beside it.
972              */
973
974             w = gtk_label_new(i->name);
975             gtk_misc_set_alignment(GTK_MISC(w), 0.0, 0.5);
976             gtk_table_attach(GTK_TABLE(table), w, 0, 1, y, y+1,
977                              GTK_SHRINK | GTK_FILL,
978                              GTK_EXPAND | GTK_SHRINK | GTK_FILL,
979                              3, 3);
980             gtk_widget_show(w);
981
982             w = gtk_entry_new();
983             gtk_table_attach(GTK_TABLE(table), w, 1, 2, y, y+1,
984                              GTK_EXPAND | GTK_SHRINK | GTK_FILL,
985                              GTK_EXPAND | GTK_SHRINK | GTK_FILL,
986                              3, 3);
987             gtk_entry_set_text(GTK_ENTRY(w), i->sval);
988             gtk_signal_connect(GTK_OBJECT(w), "changed",
989                                GTK_SIGNAL_FUNC(editbox_changed), i);
990             gtk_signal_connect(GTK_OBJECT(w), "key_press_event",
991                                GTK_SIGNAL_FUNC(editbox_key), NULL);
992             gtk_widget_show(w);
993
994             break;
995
996           case C_BOOLEAN:
997             /*
998              * Simple checkbox.
999              */
1000             w = gtk_check_button_new_with_label(i->name);
1001             gtk_signal_connect(GTK_OBJECT(w), "toggled",
1002                                GTK_SIGNAL_FUNC(button_toggled), i);
1003             gtk_table_attach(GTK_TABLE(table), w, 0, 2, y, y+1,
1004                              GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1005                              GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1006                              3, 3);
1007             gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(w), i->ival);
1008             gtk_widget_show(w);
1009             break;
1010
1011           case C_CHOICES:
1012             /*
1013              * Drop-down list (GtkOptionMenu).
1014              */
1015
1016             w = gtk_label_new(i->name);
1017             gtk_misc_set_alignment(GTK_MISC(w), 0.0, 0.5);
1018             gtk_table_attach(GTK_TABLE(table), w, 0, 1, y, y+1,
1019                              GTK_SHRINK | GTK_FILL,
1020                              GTK_EXPAND | GTK_SHRINK | GTK_FILL ,
1021                              3, 3);
1022             gtk_widget_show(w);
1023
1024             w = gtk_option_menu_new();
1025             gtk_table_attach(GTK_TABLE(table), w, 1, 2, y, y+1,
1026                              GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1027                              GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1028                              3, 3);
1029             gtk_widget_show(w);
1030
1031             {
1032                 int c, val;
1033                 char *p, *q, *name;
1034                 GtkWidget *menuitem;
1035                 GtkWidget *menu = gtk_menu_new();
1036
1037                 gtk_option_menu_set_menu(GTK_OPTION_MENU(w), menu);
1038
1039                 c = *i->sval;
1040                 p = i->sval+1;
1041                 val = 0;
1042
1043                 while (*p) {
1044                     q = p;
1045                     while (*q && *q != c)
1046                         q++;
1047
1048                     name = snewn(q-p+1, char);
1049                     strncpy(name, p, q-p);
1050                     name[q-p] = '\0';
1051
1052                     if (*q) q++;       /* eat delimiter */
1053
1054                     menuitem = gtk_menu_item_new_with_label(name);
1055                     gtk_container_add(GTK_CONTAINER(menu), menuitem);
1056                     gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1057                                         GINT_TO_POINTER(val));
1058                     gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1059                                        GTK_SIGNAL_FUNC(droplist_sel), i);
1060                     gtk_widget_show(menuitem);
1061
1062                     val++;
1063
1064                     p = q;
1065                 }
1066
1067                 gtk_option_menu_set_history(GTK_OPTION_MENU(w), i->ival);
1068             }
1069
1070             break;
1071         }
1072
1073         y++;
1074     }
1075
1076     gtk_signal_connect(GTK_OBJECT(fe->cfgbox), "destroy",
1077                        GTK_SIGNAL_FUNC(window_destroy), NULL);
1078     gtk_signal_connect(GTK_OBJECT(fe->cfgbox), "key_press_event",
1079                        GTK_SIGNAL_FUNC(win_key_press), cancel);
1080     gtk_window_set_modal(GTK_WINDOW(fe->cfgbox), TRUE);
1081     gtk_window_set_transient_for(GTK_WINDOW(fe->cfgbox),
1082                                  GTK_WINDOW(fe->window));
1083     /* set_transient_window_pos(fe->window, fe->cfgbox); */
1084     gtk_widget_show(fe->cfgbox);
1085     gtk_main();
1086
1087     free_cfg(fe->cfg);
1088
1089     return fe->cfgret;
1090 }
1091
1092 static void menu_key_event(GtkMenuItem *menuitem, gpointer data)
1093 {
1094     frontend *fe = (frontend *)data;
1095     int key = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(menuitem),
1096                                                   "user-data"));
1097     if (!midend_process_key(fe->me, 0, 0, key))
1098         gtk_widget_destroy(fe->window);
1099 }
1100
1101 static void get_size(frontend *fe, int *px, int *py)
1102 {
1103     int x, y;
1104
1105     /*
1106      * Currently I don't want to make the GTK port scale large
1107      * puzzles to fit on the screen. This is because X does permit
1108      * extremely large windows and many window managers provide a
1109      * means of navigating round them, and the users I consulted
1110      * before deciding said that they'd rather have enormous puzzle
1111      * windows spanning multiple screen pages than have them
1112      * shrunk. I could change my mind later or introduce
1113      * configurability; this would be the place to do so, by
1114      * replacing the initial values of x and y with the screen
1115      * dimensions.
1116      */
1117     x = INT_MAX;
1118     y = INT_MAX;
1119     midend_size(fe->me, &x, &y, FALSE);
1120     *px = x;
1121     *py = y;
1122 }
1123
1124 #if !GTK_CHECK_VERSION(2,0,0)
1125 #define gtk_window_resize(win, x, y) \
1126         gdk_window_resize(GTK_WIDGET(win)->window, x, y)
1127 #endif
1128
1129 static void update_menuitem_bullet(GtkWidget *label, int visible)
1130 {
1131     if (visible) {
1132         gtk_label_set_text(GTK_LABEL(label), "\xE2\x80\xA2");
1133     } else {
1134         gtk_label_set_text(GTK_LABEL(label), "");
1135     }
1136 }
1137
1138 /*
1139  * Called when any other code in this file has changed the
1140  * selected game parameters.
1141  */
1142 static void changed_preset(frontend *fe)
1143 {
1144     int n = midend_which_preset(fe->me);
1145     int i;
1146
1147     /*
1148      * Update the tick mark in the Type menu.
1149      */
1150     if (fe->preset_bullets) {
1151         for (i = 0; i < fe->npresets; i++)
1152             update_menuitem_bullet(fe->preset_bullets[i], n == i);
1153     }
1154     if (fe->preset_custom_bullet) {
1155         update_menuitem_bullet(fe->preset_custom_bullet, n < 0);
1156     }
1157
1158     /*
1159      * Update the greying on the Copy menu option.
1160      */
1161     if (fe->copy_menu_item) {
1162         int enabled = midend_can_format_as_text_now(fe->me);
1163         gtk_widget_set_sensitive(fe->copy_menu_item, enabled);
1164     }
1165 }
1166
1167 static void resize_fe(frontend *fe)
1168 {
1169     int x, y;
1170
1171     get_size(fe, &x, &y);
1172     fe->w = x;
1173     fe->h = y;
1174     gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
1175     {
1176         GtkRequisition req;
1177         gtk_widget_size_request(GTK_WIDGET(fe->window), &req);
1178         gtk_window_resize(GTK_WINDOW(fe->window), req.width, req.height);
1179     }
1180     /*
1181      * Now that we've established the preferred size of the window,
1182      * reduce the drawing area's size request so the user can shrink
1183      * the window.
1184      */
1185     gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), 1, 1);
1186 }
1187
1188 static void menu_preset_event(GtkMenuItem *menuitem, gpointer data)
1189 {
1190     frontend *fe = (frontend *)data;
1191     game_params *params =
1192         (game_params *)gtk_object_get_data(GTK_OBJECT(menuitem), "user-data");
1193
1194     midend_set_params(fe->me, params);
1195     midend_new_game(fe->me);
1196     changed_preset(fe);
1197     resize_fe(fe);
1198 }
1199
1200 GdkAtom compound_text_atom, utf8_string_atom;
1201 int paste_initialised = FALSE;
1202
1203 void init_paste()
1204 {
1205     unsigned char empty[] = { 0 };
1206
1207     if (paste_initialised)
1208         return;
1209
1210     if (!compound_text_atom)
1211         compound_text_atom = gdk_atom_intern("COMPOUND_TEXT", FALSE);
1212     if (!utf8_string_atom)
1213         utf8_string_atom = gdk_atom_intern("UTF8_STRING", FALSE);
1214
1215     /*
1216      * Ensure that all the cut buffers exist - according to the
1217      * ICCCM, we must do this before we start using cut buffers.
1218      */
1219     XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1220                     XA_CUT_BUFFER0, XA_STRING, 8, PropModeAppend, empty, 0);
1221     XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1222                     XA_CUT_BUFFER1, XA_STRING, 8, PropModeAppend, empty, 0);
1223     XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1224                     XA_CUT_BUFFER2, XA_STRING, 8, PropModeAppend, empty, 0);
1225     XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1226                     XA_CUT_BUFFER3, XA_STRING, 8, PropModeAppend, empty, 0);
1227     XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1228                     XA_CUT_BUFFER4, XA_STRING, 8, PropModeAppend, empty, 0);
1229     XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1230                     XA_CUT_BUFFER5, XA_STRING, 8, PropModeAppend, empty, 0);
1231     XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1232                     XA_CUT_BUFFER6, XA_STRING, 8, PropModeAppend, empty, 0);
1233     XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1234                     XA_CUT_BUFFER7, XA_STRING, 8, PropModeAppend, empty, 0);
1235 }
1236
1237 /* Store data in a cut-buffer. */
1238 void store_cutbuffer(char *ptr, int len)
1239 {
1240     /* ICCCM says we must rotate the buffers before storing to buffer 0. */
1241     XRotateBuffers(GDK_DISPLAY(), 1);
1242     XStoreBytes(GDK_DISPLAY(), ptr, len);
1243 }
1244
1245 void write_clip(frontend *fe, char *data)
1246 {
1247     init_paste();
1248
1249     if (fe->paste_data)
1250         sfree(fe->paste_data);
1251
1252     /*
1253      * For this simple application we can safely assume that the
1254      * data passed to this function is pure ASCII, which means we
1255      * can return precisely the same stuff for types STRING,
1256      * COMPOUND_TEXT or UTF8_STRING.
1257      */
1258
1259     fe->paste_data = data;
1260     fe->paste_data_len = strlen(data);
1261
1262     store_cutbuffer(fe->paste_data, fe->paste_data_len);
1263
1264     if (gtk_selection_owner_set(fe->area, GDK_SELECTION_PRIMARY,
1265                                 CurrentTime)) {
1266         gtk_selection_clear_targets(fe->area, GDK_SELECTION_PRIMARY);
1267         gtk_selection_add_target(fe->area, GDK_SELECTION_PRIMARY,
1268                                  GDK_SELECTION_TYPE_STRING, 1);
1269         gtk_selection_add_target(fe->area, GDK_SELECTION_PRIMARY,
1270                                  compound_text_atom, 1);
1271         gtk_selection_add_target(fe->area, GDK_SELECTION_PRIMARY,
1272                                  utf8_string_atom, 1);
1273     }
1274 }
1275
1276 void selection_get(GtkWidget *widget, GtkSelectionData *seldata,
1277                    guint info, guint time_stamp, gpointer data)
1278 {
1279     frontend *fe = (frontend *)data;
1280     gtk_selection_data_set(seldata, seldata->target, 8,
1281                            fe->paste_data, fe->paste_data_len);
1282 }
1283
1284 gint selection_clear(GtkWidget *widget, GdkEventSelection *seldata,
1285                      gpointer data)
1286 {
1287     frontend *fe = (frontend *)data;
1288
1289     if (fe->paste_data)
1290         sfree(fe->paste_data);
1291     fe->paste_data = NULL;
1292     fe->paste_data_len = 0;
1293     return TRUE;
1294 }
1295
1296 static void menu_copy_event(GtkMenuItem *menuitem, gpointer data)
1297 {
1298     frontend *fe = (frontend *)data;
1299     char *text;
1300
1301     text = midend_text_format(fe->me);
1302
1303     if (text) {
1304         write_clip(fe, text);
1305     } else {
1306         gdk_beep();
1307     }
1308 }
1309
1310 #ifdef OLD_FILESEL
1311
1312 static void filesel_ok(GtkButton *button, gpointer data)
1313 {
1314     frontend *fe = (frontend *)data;
1315
1316     gpointer filesel = gtk_object_get_data(GTK_OBJECT(button), "user-data");
1317
1318     const char *name =
1319         gtk_file_selection_get_filename(GTK_FILE_SELECTION(filesel));
1320
1321     fe->filesel_name = dupstr(name);
1322 }
1323
1324 static char *file_selector(frontend *fe, char *title, int save)
1325 {
1326     GtkWidget *filesel =
1327         gtk_file_selection_new(title);
1328
1329     fe->filesel_name = NULL;
1330
1331     gtk_window_set_modal(GTK_WINDOW(filesel), TRUE);
1332     gtk_object_set_data
1333         (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "user-data",
1334          (gpointer)filesel);
1335     gtk_signal_connect
1336         (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "clicked",
1337          GTK_SIGNAL_FUNC(filesel_ok), fe);
1338     gtk_signal_connect_object
1339         (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "clicked",
1340          GTK_SIGNAL_FUNC(gtk_widget_destroy), (gpointer)filesel);
1341     gtk_signal_connect_object
1342         (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->cancel_button), "clicked",
1343          GTK_SIGNAL_FUNC(gtk_widget_destroy), (gpointer)filesel);
1344     gtk_signal_connect(GTK_OBJECT(filesel), "destroy",
1345                        GTK_SIGNAL_FUNC(window_destroy), NULL);
1346     gtk_widget_show(filesel);
1347     gtk_window_set_transient_for(GTK_WINDOW(filesel), GTK_WINDOW(fe->window));
1348     gtk_main();
1349
1350     return fe->filesel_name;
1351 }
1352
1353 #else
1354
1355 static char *file_selector(frontend *fe, char *title, int save)
1356 {
1357     char *filesel_name = NULL;
1358
1359     GtkWidget *filesel =
1360         gtk_file_chooser_dialog_new(title,
1361                                     GTK_WINDOW(fe->window),
1362                                     save ? GTK_FILE_CHOOSER_ACTION_SAVE :
1363                                     GTK_FILE_CHOOSER_ACTION_OPEN,
1364                                     GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
1365                                     save ? GTK_STOCK_SAVE : GTK_STOCK_OPEN,
1366                                     GTK_RESPONSE_ACCEPT,
1367                                     NULL);
1368
1369     if (gtk_dialog_run(GTK_DIALOG(filesel)) == GTK_RESPONSE_ACCEPT) {
1370         const char *name = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(filesel));
1371         filesel_name = dupstr(name);
1372     }
1373
1374     gtk_widget_destroy(filesel);
1375
1376     return filesel_name;
1377 }
1378
1379 #endif
1380
1381 struct savefile_write_ctx {
1382     FILE *fp;
1383     int error;
1384 };
1385
1386 static void savefile_write(void *wctx, void *buf, int len)
1387 {
1388     struct savefile_write_ctx *ctx = (struct savefile_write_ctx *)wctx;
1389     if (fwrite(buf, 1, len, ctx->fp) < len)
1390         ctx->error = errno;
1391 }
1392
1393 static int savefile_read(void *wctx, void *buf, int len)
1394 {
1395     FILE *fp = (FILE *)wctx;
1396     int ret;
1397
1398     ret = fread(buf, 1, len, fp);
1399     return (ret == len);
1400 }
1401
1402 static void menu_save_event(GtkMenuItem *menuitem, gpointer data)
1403 {
1404     frontend *fe = (frontend *)data;
1405     char *name;
1406
1407     name = file_selector(fe, "Enter name of game file to save", TRUE);
1408
1409     if (name) {
1410         FILE *fp;
1411
1412         if ((fp = fopen(name, "r")) != NULL) {
1413             char buf[256 + FILENAME_MAX];
1414             fclose(fp);
1415             /* file exists */
1416
1417             sprintf(buf, "Are you sure you want to overwrite the"
1418                     " file \"%.*s\"?",
1419                     FILENAME_MAX, name);
1420             if (!message_box(fe->window, "Question", buf, TRUE, MB_YESNO))
1421                 return;
1422         }
1423
1424         fp = fopen(name, "w");
1425         sfree(name);
1426
1427         if (!fp) {
1428             error_box(fe->window, "Unable to open save file");
1429             return;
1430         }
1431
1432         {
1433             struct savefile_write_ctx ctx;
1434             ctx.fp = fp;
1435             ctx.error = 0;
1436             midend_serialise(fe->me, savefile_write, &ctx);
1437             fclose(fp);
1438             if (ctx.error) {
1439                 char boxmsg[512];
1440                 sprintf(boxmsg, "Error writing save file: %.400s",
1441                         strerror(errno));
1442                 error_box(fe->window, boxmsg);
1443                 return;
1444             }
1445         }
1446
1447     }
1448 }
1449
1450 static void menu_load_event(GtkMenuItem *menuitem, gpointer data)
1451 {
1452     frontend *fe = (frontend *)data;
1453     char *name, *err;
1454
1455     name = file_selector(fe, "Enter name of saved game file to load", FALSE);
1456
1457     if (name) {
1458         FILE *fp = fopen(name, "r");
1459         sfree(name);
1460
1461         if (!fp) {
1462             error_box(fe->window, "Unable to open saved game file");
1463             return;
1464         }
1465
1466         err = midend_deserialise(fe->me, savefile_read, fp);
1467
1468         fclose(fp);
1469
1470         if (err) {
1471             error_box(fe->window, err);
1472             return;
1473         }
1474
1475         changed_preset(fe);
1476         resize_fe(fe);
1477     }
1478 }
1479
1480 static void menu_solve_event(GtkMenuItem *menuitem, gpointer data)
1481 {
1482     frontend *fe = (frontend *)data;
1483     char *msg;
1484
1485     msg = midend_solve(fe->me);
1486
1487     if (msg)
1488         error_box(fe->window, msg);
1489 }
1490
1491 static void menu_restart_event(GtkMenuItem *menuitem, gpointer data)
1492 {
1493     frontend *fe = (frontend *)data;
1494
1495     midend_restart_game(fe->me);
1496 }
1497
1498 static void menu_config_event(GtkMenuItem *menuitem, gpointer data)
1499 {
1500     frontend *fe = (frontend *)data;
1501     int which = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(menuitem),
1502                                                     "user-data"));
1503
1504     if (!get_config(fe, which))
1505         return;
1506
1507     midend_new_game(fe->me);
1508     resize_fe(fe);
1509 }
1510
1511 static void menu_about_event(GtkMenuItem *menuitem, gpointer data)
1512 {
1513     frontend *fe = (frontend *)data;
1514     char titlebuf[256];
1515     char textbuf[1024];
1516
1517     sprintf(titlebuf, "About %.200s", thegame.name);
1518     sprintf(textbuf,
1519             "%.200s\n\n"
1520             "from Simon Tatham's Portable Puzzle Collection\n\n"
1521             "%.500s", thegame.name, ver);
1522
1523     message_box(fe->window, titlebuf, textbuf, TRUE, MB_OK);
1524 }
1525
1526 static GtkWidget *add_menu_item_with_key(frontend *fe, GtkContainer *cont,
1527                                          char *text, int key)
1528 {
1529     GtkWidget *menuitem = gtk_menu_item_new_with_label(text);
1530     int keyqual;
1531     gtk_container_add(cont, menuitem);
1532     gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1533                         GINT_TO_POINTER(key));
1534     gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1535                        GTK_SIGNAL_FUNC(menu_key_event), fe);
1536     switch (key & ~0x1F) {
1537       case 0x00:
1538         key += 0x60;
1539         keyqual = GDK_CONTROL_MASK;
1540         break;
1541       case 0x40:
1542         key += 0x20;
1543         keyqual = GDK_SHIFT_MASK;
1544         break;
1545       default:
1546         keyqual = 0;
1547         break;
1548     }
1549     gtk_widget_add_accelerator(menuitem,
1550                                "activate", fe->accelgroup,
1551                                key, keyqual,
1552                                GTK_ACCEL_VISIBLE);
1553     gtk_widget_show(menuitem);
1554     return menuitem;
1555 }
1556
1557 static void add_menu_separator(GtkContainer *cont)
1558 {
1559     GtkWidget *menuitem = gtk_menu_item_new();
1560     gtk_container_add(cont, menuitem);
1561     gtk_widget_show(menuitem);
1562 }
1563
1564 enum { ARG_EITHER, ARG_SAVE, ARG_ID }; /* for argtype */
1565
1566 static GtkWidget *make_preset_menuitem(GtkWidget **bulletlabel,
1567                                        const char *name)
1568 {
1569     GtkWidget *hbox, *lab1, *lab2, *menuitem;
1570     GtkRequisition req;
1571
1572     hbox = gtk_hbox_new(FALSE, 0);
1573     gtk_widget_show(hbox);
1574     lab1 = gtk_label_new("\xE2\x80\xA2 ");
1575     gtk_widget_show(lab1);
1576     gtk_box_pack_start(GTK_BOX(hbox), lab1, FALSE, FALSE, 0);
1577     gtk_misc_set_alignment(GTK_MISC(lab1), 0.0, 0.0);
1578     lab2 = gtk_label_new(name);
1579     gtk_widget_show(lab2);
1580     gtk_box_pack_start(GTK_BOX(hbox), lab2, TRUE, TRUE, 0);
1581     gtk_misc_set_alignment(GTK_MISC(lab2), 0.0, 0.0);
1582
1583     gtk_widget_size_request(lab1, &req);
1584     gtk_widget_set_usize(lab1, req.width, -1);
1585     gtk_label_set_text(GTK_LABEL(lab1), "");
1586
1587     menuitem = gtk_menu_item_new();
1588     gtk_container_add(GTK_CONTAINER(menuitem), hbox);
1589
1590     *bulletlabel = lab1;
1591     return menuitem;
1592 }
1593
1594 static frontend *new_window(char *arg, int argtype, char **error)
1595 {
1596     frontend *fe;
1597     GtkBox *vbox;
1598     GtkWidget *menubar, *menu, *menuitem;
1599     GdkPixmap *iconpm;
1600     GList *iconlist;
1601     int x, y, n;
1602     char errbuf[1024];
1603     extern char *const *const xpm_icons[];
1604     extern const int n_xpm_icons;
1605
1606     fe = snew(frontend);
1607
1608     fe->timer_active = FALSE;
1609     fe->timer_id = -1;
1610
1611     fe->me = midend_new(fe, &thegame, &gtk_drawing, fe);
1612
1613     if (arg) {
1614         char *err;
1615         FILE *fp;
1616
1617         errbuf[0] = '\0';
1618
1619         switch (argtype) {
1620           case ARG_ID:
1621             err = midend_game_id(fe->me, arg);
1622             if (!err)
1623                 midend_new_game(fe->me);
1624             else
1625                 sprintf(errbuf, "Invalid game ID: %.800s", err);
1626             break;
1627           case ARG_SAVE:
1628             fp = fopen(arg, "r");
1629             if (!fp) {
1630                 sprintf(errbuf, "Error opening file: %.800s", strerror(errno));
1631             } else {
1632                 err = midend_deserialise(fe->me, savefile_read, fp);
1633                 if (err)
1634                     sprintf(errbuf, "Invalid save file: %.800s", err);
1635                 fclose(fp);
1636             }
1637             break;
1638           default /*case ARG_EITHER*/:
1639             /*
1640              * First try treating the argument as a game ID.
1641              */
1642             err = midend_game_id(fe->me, arg);
1643             if (!err) {
1644                 /*
1645                  * It's a valid game ID.
1646                  */
1647                 midend_new_game(fe->me);
1648             } else {
1649                 FILE *fp = fopen(arg, "r");
1650                 if (!fp) {
1651                     sprintf(errbuf, "Supplied argument is neither a game ID (%.400s)"
1652                             " nor a save file (%.400s)", err, strerror(errno));
1653                 } else {
1654                     err = midend_deserialise(fe->me, savefile_read, fp);
1655                     if (err)
1656                         sprintf(errbuf, "%.800s", err);
1657                     fclose(fp);
1658                 }
1659             }
1660             break;
1661         }
1662         if (*errbuf) {
1663             *error = dupstr(errbuf);
1664             midend_free(fe->me);
1665             sfree(fe);
1666             return NULL;
1667         }
1668
1669     } else {
1670         midend_new_game(fe->me);
1671     }
1672
1673     fe->window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1674     gtk_window_set_title(GTK_WINDOW(fe->window), thegame.name);
1675
1676     vbox = GTK_BOX(gtk_vbox_new(FALSE, 0));
1677     gtk_container_add(GTK_CONTAINER(fe->window), GTK_WIDGET(vbox));
1678     gtk_widget_show(GTK_WIDGET(vbox));
1679
1680     fe->accelgroup = gtk_accel_group_new();
1681     gtk_window_add_accel_group(GTK_WINDOW(fe->window), fe->accelgroup);
1682
1683     menubar = gtk_menu_bar_new();
1684     gtk_box_pack_start(vbox, menubar, FALSE, FALSE, 0);
1685     gtk_widget_show(menubar);
1686
1687     menuitem = gtk_menu_item_new_with_mnemonic("_Game");
1688     gtk_container_add(GTK_CONTAINER(menubar), menuitem);
1689     gtk_widget_show(menuitem);
1690
1691     menu = gtk_menu_new();
1692     gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
1693
1694     add_menu_item_with_key(fe, GTK_CONTAINER(menu), "New", 'n');
1695
1696     menuitem = gtk_menu_item_new_with_label("Restart");
1697     gtk_container_add(GTK_CONTAINER(menu), menuitem);
1698     gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1699                        GTK_SIGNAL_FUNC(menu_restart_event), fe);
1700     gtk_widget_show(menuitem);
1701
1702     menuitem = gtk_menu_item_new_with_label("Specific...");
1703     gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1704                         GINT_TO_POINTER(CFG_DESC));
1705     gtk_container_add(GTK_CONTAINER(menu), menuitem);
1706     gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1707                        GTK_SIGNAL_FUNC(menu_config_event), fe);
1708     gtk_widget_show(menuitem);
1709
1710     menuitem = gtk_menu_item_new_with_label("Random Seed...");
1711     gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1712                         GINT_TO_POINTER(CFG_SEED));
1713     gtk_container_add(GTK_CONTAINER(menu), menuitem);
1714     gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1715                        GTK_SIGNAL_FUNC(menu_config_event), fe);
1716     gtk_widget_show(menuitem);
1717
1718     if ((n = midend_num_presets(fe->me)) > 0 || thegame.can_configure) {
1719         GtkWidget *submenu;
1720         int i;
1721
1722         menuitem = gtk_menu_item_new_with_mnemonic("_Type");
1723         gtk_container_add(GTK_CONTAINER(menubar), menuitem);
1724         gtk_widget_show(menuitem);
1725
1726         submenu = gtk_menu_new();
1727         gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), submenu);
1728
1729         fe->npresets = n;
1730         fe->preset_bullets = snewn(n, GtkWidget *);
1731
1732         for (i = 0; i < n; i++) {
1733             char *name;
1734             game_params *params;
1735
1736             midend_fetch_preset(fe->me, i, &name, &params);
1737
1738             menuitem = make_preset_menuitem(&fe->preset_bullets[i], name);
1739
1740             gtk_container_add(GTK_CONTAINER(submenu), menuitem);
1741             gtk_object_set_data(GTK_OBJECT(menuitem), "user-data", params);
1742             gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1743                                GTK_SIGNAL_FUNC(menu_preset_event), fe);
1744             gtk_widget_show(menuitem);
1745         }
1746
1747         if (thegame.can_configure) {
1748             menuitem = make_preset_menuitem(&fe->preset_custom_bullet,
1749                                             "Custom...");
1750
1751             gtk_container_add(GTK_CONTAINER(submenu), menuitem);
1752             gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1753                                 GPOINTER_TO_INT(CFG_SETTINGS));
1754             gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1755                                GTK_SIGNAL_FUNC(menu_config_event), fe);
1756             gtk_widget_show(menuitem);
1757         } else
1758             fe->preset_custom_bullet = NULL;
1759
1760     } else {
1761         fe->npresets = 0;
1762         fe->preset_bullets = NULL;
1763         fe->preset_custom_bullet = NULL;
1764     }
1765
1766     add_menu_separator(GTK_CONTAINER(menu));
1767     menuitem = gtk_menu_item_new_with_label("Load...");
1768     gtk_container_add(GTK_CONTAINER(menu), menuitem);
1769     gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1770                        GTK_SIGNAL_FUNC(menu_load_event), fe);
1771     gtk_widget_show(menuitem);
1772     menuitem = gtk_menu_item_new_with_label("Save...");
1773     gtk_container_add(GTK_CONTAINER(menu), menuitem);
1774     gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1775                        GTK_SIGNAL_FUNC(menu_save_event), fe);
1776     gtk_widget_show(menuitem);
1777     add_menu_separator(GTK_CONTAINER(menu));
1778     add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Undo", 'u');
1779     add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Redo", 'r');
1780     if (thegame.can_format_as_text_ever) {
1781         add_menu_separator(GTK_CONTAINER(menu));
1782         menuitem = gtk_menu_item_new_with_label("Copy");
1783         gtk_container_add(GTK_CONTAINER(menu), menuitem);
1784         gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1785                            GTK_SIGNAL_FUNC(menu_copy_event), fe);
1786         gtk_widget_show(menuitem);
1787         fe->copy_menu_item = menuitem;
1788     } else {
1789         fe->copy_menu_item = NULL;
1790     }
1791     if (thegame.can_solve) {
1792         add_menu_separator(GTK_CONTAINER(menu));
1793         menuitem = gtk_menu_item_new_with_label("Solve");
1794         gtk_container_add(GTK_CONTAINER(menu), menuitem);
1795         gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1796                            GTK_SIGNAL_FUNC(menu_solve_event), fe);
1797         gtk_widget_show(menuitem);
1798     }
1799     add_menu_separator(GTK_CONTAINER(menu));
1800     add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Exit", 'q');
1801
1802     menuitem = gtk_menu_item_new_with_mnemonic("_Help");
1803     gtk_container_add(GTK_CONTAINER(menubar), menuitem);
1804     gtk_widget_show(menuitem);
1805
1806     menu = gtk_menu_new();
1807     gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
1808
1809     menuitem = gtk_menu_item_new_with_label("About");
1810     gtk_container_add(GTK_CONTAINER(menu), menuitem);
1811     gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1812                        GTK_SIGNAL_FUNC(menu_about_event), fe);
1813     gtk_widget_show(menuitem);
1814
1815     changed_preset(fe);
1816
1817     {
1818         int i, ncolours;
1819         float *colours;
1820         gboolean *success;
1821
1822         fe->colmap = gdk_colormap_get_system();
1823         colours = midend_colours(fe->me, &ncolours);
1824         fe->ncolours = ncolours;
1825         fe->colours = snewn(ncolours, GdkColor);
1826         for (i = 0; i < ncolours; i++) {
1827             fe->colours[i].red = colours[i*3] * 0xFFFF;
1828             fe->colours[i].green = colours[i*3+1] * 0xFFFF;
1829             fe->colours[i].blue = colours[i*3+2] * 0xFFFF;
1830         }
1831         success = snewn(ncolours, gboolean);
1832         gdk_colormap_alloc_colors(fe->colmap, fe->colours, ncolours,
1833                                   FALSE, FALSE, success);
1834         for (i = 0; i < ncolours; i++) {
1835             if (!success[i]) {
1836                 g_error("couldn't allocate colour %d (#%02x%02x%02x)\n",
1837                         i, fe->colours[i].red >> 8,
1838                         fe->colours[i].green >> 8,
1839                         fe->colours[i].blue >> 8);
1840             }
1841         }
1842     }
1843
1844     if (midend_wants_statusbar(fe->me)) {
1845         GtkWidget *viewport;
1846         GtkRequisition req;
1847
1848         viewport = gtk_viewport_new(NULL, NULL);
1849         gtk_viewport_set_shadow_type(GTK_VIEWPORT(viewport), GTK_SHADOW_NONE);
1850         fe->statusbar = gtk_statusbar_new();
1851         gtk_container_add(GTK_CONTAINER(viewport), fe->statusbar);
1852         gtk_widget_show(viewport);
1853         gtk_box_pack_end(vbox, viewport, FALSE, FALSE, 0);
1854         gtk_widget_show(fe->statusbar);
1855         fe->statusctx = gtk_statusbar_get_context_id
1856             (GTK_STATUSBAR(fe->statusbar), "game");
1857         gtk_statusbar_push(GTK_STATUSBAR(fe->statusbar), fe->statusctx,
1858                            "test");
1859         gtk_widget_size_request(fe->statusbar, &req);
1860 #if 0
1861         /* For GTK 2.0, should we be using gtk_widget_set_size_request? */
1862 #endif
1863         gtk_widget_set_usize(viewport, -1, req.height);
1864     } else
1865         fe->statusbar = NULL;
1866
1867     fe->area = gtk_drawing_area_new();
1868     get_size(fe, &x, &y);
1869     gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
1870     fe->w = x;
1871     fe->h = y;
1872
1873     gtk_box_pack_end(vbox, fe->area, TRUE, TRUE, 0);
1874
1875     fe->pixmap = NULL;
1876     fe->fonts = NULL;
1877     fe->nfonts = fe->fontsize = 0;
1878
1879     fe->paste_data = NULL;
1880     fe->paste_data_len = 0;
1881
1882     gtk_signal_connect(GTK_OBJECT(fe->window), "destroy",
1883                        GTK_SIGNAL_FUNC(destroy), fe);
1884     gtk_signal_connect(GTK_OBJECT(fe->window), "key_press_event",
1885                        GTK_SIGNAL_FUNC(key_event), fe);
1886     gtk_signal_connect(GTK_OBJECT(fe->area), "button_press_event",
1887                        GTK_SIGNAL_FUNC(button_event), fe);
1888     gtk_signal_connect(GTK_OBJECT(fe->area), "button_release_event",
1889                        GTK_SIGNAL_FUNC(button_event), fe);
1890     gtk_signal_connect(GTK_OBJECT(fe->area), "motion_notify_event",
1891                        GTK_SIGNAL_FUNC(motion_event), fe);
1892     gtk_signal_connect(GTK_OBJECT(fe->area), "selection_get",
1893                        GTK_SIGNAL_FUNC(selection_get), fe);
1894     gtk_signal_connect(GTK_OBJECT(fe->area), "selection_clear_event",
1895                        GTK_SIGNAL_FUNC(selection_clear), fe);
1896     gtk_signal_connect(GTK_OBJECT(fe->area), "expose_event",
1897                        GTK_SIGNAL_FUNC(expose_area), fe);
1898     gtk_signal_connect(GTK_OBJECT(fe->window), "map_event",
1899                        GTK_SIGNAL_FUNC(map_window), fe);
1900     gtk_signal_connect(GTK_OBJECT(fe->area), "configure_event",
1901                        GTK_SIGNAL_FUNC(configure_area), fe);
1902
1903     gtk_widget_add_events(GTK_WIDGET(fe->area),
1904                           GDK_BUTTON_PRESS_MASK |
1905                           GDK_BUTTON_RELEASE_MASK |
1906                           GDK_BUTTON_MOTION_MASK |
1907                           GDK_POINTER_MOTION_HINT_MASK);
1908
1909     if (n_xpm_icons) {
1910         gtk_widget_realize(fe->window);
1911         iconpm = gdk_pixmap_create_from_xpm_d(fe->window->window, NULL,
1912                                               NULL, (gchar **)xpm_icons[0]);
1913         gdk_window_set_icon(fe->window->window, NULL, iconpm, NULL);
1914         iconlist = NULL;
1915         for (n = 0; n < n_xpm_icons; n++) {
1916             iconlist =
1917                 g_list_append(iconlist,
1918                               gdk_pixbuf_new_from_xpm_data((const gchar **)
1919                                                            xpm_icons[n]));
1920         }
1921         gdk_window_set_icon_list(fe->window->window, iconlist);
1922     }
1923
1924     gtk_widget_show(fe->area);
1925     gtk_widget_show(fe->window);
1926
1927     /*
1928      * Now that we've established the preferred size of the window,
1929      * reduce the drawing area's size request so the user can shrink
1930      * the window.
1931      */
1932     gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), 1, 1);
1933
1934     gdk_window_set_background(fe->area->window, &fe->colours[0]);
1935     gdk_window_set_background(fe->window->window, &fe->colours[0]);
1936
1937     return fe;
1938 }
1939
1940 char *fgetline(FILE *fp)
1941 {
1942     char *ret = snewn(512, char);
1943     int size = 512, len = 0;
1944     while (fgets(ret + len, size - len, fp)) {
1945         len += strlen(ret + len);
1946         if (ret[len-1] == '\n')
1947             break;                     /* got a newline, we're done */
1948         size = len + 512;
1949         ret = sresize(ret, size, char);
1950     }
1951     if (len == 0) {                    /* first fgets returned NULL */
1952         sfree(ret);
1953         return NULL;
1954     }
1955     ret[len] = '\0';
1956     return ret;
1957 }
1958
1959 int main(int argc, char **argv)
1960 {
1961     char *pname = argv[0];
1962     char *error;
1963     int ngenerate = 0, print = FALSE, px = 1, py = 1;
1964     int soln = FALSE, colour = FALSE;
1965     float scale = 1.0F;
1966     float redo_proportion = 0.0F;
1967     char *savefile = NULL, *savesuffix = NULL;
1968     char *arg = NULL;
1969     int argtype = ARG_EITHER;
1970     char *screenshot_file = NULL;
1971     int doing_opts = TRUE;
1972     int ac = argc;
1973     char **av = argv;
1974     char errbuf[500];
1975
1976     /*
1977      * Command line parsing in this function is rather fiddly,
1978      * because GTK wants to have a go at argc/argv _first_ - and
1979      * yet we can't let it, because gtk_init() will bomb out if it
1980      * can't open an X display, whereas in fact we want to permit
1981      * our --generate and --print modes to run without an X
1982      * display.
1983      * 
1984      * So what we do is:
1985      *  - we parse the command line ourselves, without modifying
1986      *    argc/argv
1987      *  - if we encounter an error which might plausibly be the
1988      *    result of a GTK command line (i.e. not detailed errors in
1989      *    particular options of ours) we store the error message
1990      *    and terminate parsing.
1991      *  - if we got enough out of the command line to know it
1992      *    specifies a non-X mode of operation, we either display
1993      *    the stored error and return failure, or if there is no
1994      *    stored error we do the non-X operation and return
1995      *    success.
1996      *  - otherwise, we go straight to gtk_init().
1997      */
1998
1999     errbuf[0] = '\0';
2000     while (--ac > 0) {
2001         char *p = *++av;
2002         if (doing_opts && !strcmp(p, "--version")) {
2003             printf("%s, from Simon Tatham's Portable Puzzle Collection\n%s\n",
2004                    thegame.name, ver);
2005             return 0;
2006         } else if (doing_opts && !strcmp(p, "--generate")) {
2007             if (--ac > 0) {
2008                 ngenerate = atoi(*++av);
2009                 if (!ngenerate) {
2010                     fprintf(stderr, "%s: '--generate' expected a number\n",
2011                             pname);
2012                     return 1;
2013                 }
2014             } else
2015                 ngenerate = 1;
2016         } else if (doing_opts && !strcmp(p, "--save")) {
2017             if (--ac > 0) {
2018                 savefile = *++av;
2019             } else {
2020                 fprintf(stderr, "%s: '--save' expected a filename\n",
2021                         pname);
2022                 return 1;
2023             }
2024         } else if (doing_opts && (!strcmp(p, "--save-suffix") ||
2025                                   !strcmp(p, "--savesuffix"))) {
2026             if (--ac > 0) {
2027                 savesuffix = *++av;
2028             } else {
2029                 fprintf(stderr, "%s: '--save-suffix' expected a filename\n",
2030                         pname);
2031                 return 1;
2032             }
2033         } else if (doing_opts && !strcmp(p, "--print")) {
2034             if (!thegame.can_print) {
2035                 fprintf(stderr, "%s: this game does not support printing\n",
2036                         pname);
2037                 return 1;
2038             }
2039             print = TRUE;
2040             if (--ac > 0) {
2041                 char *dim = *++av;
2042                 if (sscanf(dim, "%dx%d", &px, &py) != 2) {
2043                     fprintf(stderr, "%s: unable to parse argument '%s' to "
2044                             "'--print'\n", pname, dim);
2045                     return 1;
2046                 }
2047             } else {
2048                 px = py = 1;
2049             }
2050         } else if (doing_opts && !strcmp(p, "--scale")) {
2051             if (--ac > 0) {
2052                 scale = atof(*++av);
2053             } else {
2054                 fprintf(stderr, "%s: no argument supplied to '--scale'\n",
2055                         pname);
2056                 return 1;
2057             }
2058         } else if (doing_opts && !strcmp(p, "--redo")) {
2059             /*
2060              * This is an internal option which I don't expect
2061              * users to have any particular use for. The effect of
2062              * --redo is that once the game has been loaded and
2063              * initialised, the next move in the redo chain is
2064              * replayed, and the game screen is redrawn part way
2065              * through the making of the move. This is only
2066              * meaningful if there _is_ a next move in the redo
2067              * chain, which means in turn that this option is only
2068              * useful if you're also passing a save file on the
2069              * command line.
2070              *
2071              * This option is used by the script which generates
2072              * the puzzle icons and website screenshots, and I
2073              * don't imagine it's useful for anything else.
2074              * (Unless, I suppose, users don't like my screenshots
2075              * and want to generate their own in the same way for
2076              * some repackaged version of the puzzles.)
2077              */
2078             if (--ac > 0) {
2079                 redo_proportion = atof(*++av);
2080             } else {
2081                 fprintf(stderr, "%s: no argument supplied to '--redo'\n",
2082                         pname);
2083                 return 1;
2084             }
2085         } else if (doing_opts && !strcmp(p, "--screenshot")) {
2086             /*
2087              * Another internal option for the icon building
2088              * script. This causes a screenshot of the central
2089              * drawing area (i.e. not including the menu bar or
2090              * status bar) to be saved to a PNG file once the
2091              * window has been drawn, and then the application
2092              * quits immediately.
2093              */
2094             if (--ac > 0) {
2095                 screenshot_file = *++av;
2096             } else {
2097                 fprintf(stderr, "%s: no argument supplied to '--screenshot'\n",
2098                         pname);
2099                 return 1;
2100             }
2101         } else if (doing_opts && (!strcmp(p, "--with-solutions") ||
2102                                   !strcmp(p, "--with-solution") ||
2103                                   !strcmp(p, "--with-solns") ||
2104                                   !strcmp(p, "--with-soln") ||
2105                                   !strcmp(p, "--solutions") ||
2106                                   !strcmp(p, "--solution") ||
2107                                   !strcmp(p, "--solns") ||
2108                                   !strcmp(p, "--soln"))) {
2109             soln = TRUE;
2110         } else if (doing_opts && !strcmp(p, "--colour")) {
2111             if (!thegame.can_print_in_colour) {
2112                 fprintf(stderr, "%s: this game does not support colour"
2113                         " printing\n", pname);
2114                 return 1;
2115             }
2116             colour = TRUE;
2117         } else if (doing_opts && !strcmp(p, "--load")) {
2118             argtype = ARG_SAVE;
2119         } else if (doing_opts && !strcmp(p, "--game")) {
2120             argtype = ARG_ID;
2121         } else if (doing_opts && !strcmp(p, "--")) {
2122             doing_opts = FALSE;
2123         } else if (!doing_opts || p[0] != '-') {
2124             if (arg) {
2125                 fprintf(stderr, "%s: more than one argument supplied\n",
2126                         pname);
2127                 return 1;
2128             }
2129             arg = p;
2130         } else {
2131             sprintf(errbuf, "%.100s: unrecognised option '%.100s'\n",
2132                     pname, p);
2133             break;
2134         }
2135     }
2136
2137     if (*errbuf) {
2138         fputs(errbuf, stderr);
2139         return 1;
2140     }
2141
2142     /*
2143      * Special standalone mode for generating puzzle IDs on the
2144      * command line. Useful for generating puzzles to be printed
2145      * out and solved offline (for puzzles where that even makes
2146      * sense - Solo, for example, is a lot more pencil-and-paper
2147      * friendly than Twiddle!)
2148      * 
2149      * Usage:
2150      * 
2151      *   <puzzle-name> --generate [<n> [<params>]]
2152      * 
2153      * <n>, if present, is the number of puzzle IDs to generate.
2154      * <params>, if present, is the same type of parameter string
2155      * you would pass to the puzzle when running it in GUI mode,
2156      * including optional extras such as the expansion factor in
2157      * Rectangles and the difficulty level in Solo.
2158      * 
2159      * If you specify <params>, you must also specify <n> (although
2160      * you may specify it to be 1). Sorry; that was the
2161      * simplest-to-parse command-line syntax I came up with.
2162      */
2163     if (ngenerate > 0 || print || savefile || savesuffix) {
2164         int i, n = 1;
2165         midend *me;
2166         char *id;
2167         document *doc = NULL;
2168
2169         n = ngenerate;
2170
2171         me = midend_new(NULL, &thegame, NULL, NULL);
2172         i = 0;
2173
2174         if (savefile && !savesuffix)
2175             savesuffix = "";
2176         if (!savefile && savesuffix)
2177             savefile = "";
2178
2179         if (print)
2180             doc = document_new(px, py, scale);
2181
2182         /*
2183          * In this loop, we either generate a game ID or read one
2184          * from stdin depending on whether we're in generate mode;
2185          * then we either write it to stdout or print it, depending
2186          * on whether we're in print mode. Thus, this loop handles
2187          * generate-to-stdout, print-from-stdin and generate-and-
2188          * immediately-print modes.
2189          * 
2190          * (It could also handle a copy-stdin-to-stdout mode,
2191          * although there's currently no combination of options
2192          * which will cause this loop to be activated in that mode.
2193          * It wouldn't be _entirely_ pointless, though, because
2194          * stdin could contain bare params strings or random-seed
2195          * IDs, and stdout would contain nothing but fully
2196          * generated descriptive game IDs.)
2197          */
2198         while (ngenerate == 0 || i < n) {
2199             char *pstr, *err;
2200
2201             if (ngenerate == 0) {
2202                 pstr = fgetline(stdin);
2203                 if (!pstr)
2204                     break;
2205                 pstr[strcspn(pstr, "\r\n")] = '\0';
2206             } else {
2207                 if (arg) {
2208                     pstr = snewn(strlen(arg) + 40, char);
2209
2210                     strcpy(pstr, arg);
2211                     if (i > 0 && strchr(arg, '#'))
2212                         sprintf(pstr + strlen(pstr), "-%d", i);
2213                 } else
2214                     pstr = NULL;
2215             }
2216
2217             if (pstr) {
2218                 err = midend_game_id(me, pstr);
2219                 if (err) {
2220                     fprintf(stderr, "%s: error parsing '%s': %s\n",
2221                             pname, pstr, err);
2222                     return 1;
2223                 }
2224             }
2225             sfree(pstr);
2226
2227             midend_new_game(me);
2228
2229             if (doc) {
2230                 err = midend_print_puzzle(me, doc, soln);
2231                 if (err) {
2232                     fprintf(stderr, "%s: error in printing: %s\n", pname, err);
2233                     return 1;
2234                 }
2235             }
2236             if (savefile) {
2237                 struct savefile_write_ctx ctx;
2238                 char *realname = snewn(40 + strlen(savefile) +
2239                                        strlen(savesuffix), char);
2240                 sprintf(realname, "%s%d%s", savefile, i, savesuffix);
2241                 ctx.fp = fopen(realname, "w");
2242                 if (!ctx.fp) {
2243                     fprintf(stderr, "%s: open: %s\n", realname,
2244                             strerror(errno));
2245                     return 1;
2246                 }
2247                 sfree(realname);
2248                 midend_serialise(me, savefile_write, &ctx);
2249                 if (ctx.error) {
2250                     fprintf(stderr, "%s: write: %s\n", realname,
2251                             strerror(ctx.error));
2252                     return 1;
2253                 }
2254                 if (fclose(ctx.fp)) {
2255                     fprintf(stderr, "%s: close: %s\n", realname,
2256                             strerror(errno));
2257                     return 1;
2258                 }
2259             }
2260             if (!doc && !savefile) {
2261                 id = midend_get_game_id(me);
2262                 puts(id);
2263                 sfree(id);
2264             }
2265
2266             i++;
2267         }
2268
2269         if (doc) {
2270             psdata *ps = ps_init(stdout, colour);
2271             document_print(doc, ps_drawing_api(ps));
2272             document_free(doc);
2273             ps_free(ps);
2274         }
2275
2276         midend_free(me);
2277
2278         return 0;
2279     } else {
2280         frontend *fe;
2281
2282         gtk_init(&argc, &argv);
2283
2284         fe = new_window(arg, argtype, &error);
2285
2286         if (!fe) {
2287             fprintf(stderr, "%s: %s\n", pname, error);
2288             return 1;
2289         }
2290
2291         if (screenshot_file) {
2292             /*
2293              * Some puzzles will not redraw their entire area if
2294              * given a partially completed animation, which means
2295              * we must redraw now and _then_ redraw again after
2296              * freezing the move timer.
2297              */
2298             midend_force_redraw(fe->me);
2299         }
2300
2301         if (redo_proportion) {
2302             /* Start a redo. */
2303             midend_process_key(fe->me, 0, 0, 'r');
2304             /* And freeze the timer at the specified position. */
2305             midend_freeze_timer(fe->me, redo_proportion);
2306         }
2307
2308         if (screenshot_file) {
2309             GdkPixbuf *pb;
2310             GError *gerror = NULL;
2311
2312             midend_redraw(fe->me);
2313
2314             pb = gdk_pixbuf_get_from_drawable(NULL, fe->pixmap,
2315                                               NULL, 0, 0, 0, 0, -1, -1);
2316             gdk_pixbuf_save(pb, screenshot_file, "png", &gerror, NULL);
2317
2318             exit(0);
2319         }
2320
2321         gtk_main();
2322     }
2323
2324     return 0;
2325 }