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