2 * gtk.c: GTK front end for my puzzle collection.
15 #include <sys/resource.h>
18 #include <gdk/gdkkeysyms.h>
20 #include <gdk-pixbuf/gdk-pixbuf.h>
24 #include <X11/Xutil.h>
25 #include <X11/Xatom.h>
29 #if GTK_CHECK_VERSION(2,0,0)
31 # ifdef PANGO_VERSION_CHECK
32 # if PANGO_VERSION_CHECK(1,8,0)
33 # define HAVE_SENSIBLE_ABSOLUTE_SIZE_FUNCTION
37 #if !GTK_CHECK_VERSION(2,4,0)
40 #if GTK_CHECK_VERSION(2,8,0)
42 # if GTK_CHECK_VERSION(3,0,0) || defined(GDK_DISABLE_DEPRECATED)
43 # define USE_CAIRO_WITHOUT_PIXMAP
47 #if GTK_CHECK_VERSION(3,0,0)
48 /* The old names are still more concise! */
49 #define gtk_hbox_new(x,y) gtk_box_new(GTK_ORIENTATION_HORIZONTAL,y)
50 #define gtk_vbox_new(x,y) gtk_box_new(GTK_ORIENTATION_VERTICAL,y)
51 /* GTK 3 has retired stock button labels */
52 #define LABEL_OK "_OK"
53 #define LABEL_CANCEL "_Cancel"
54 #define LABEL_NO "_No"
55 #define LABEL_YES "_Yes"
56 #define LABEL_SAVE "_Save"
57 #define LABEL_OPEN "_Open"
58 #define gtk_button_new_with_our_label gtk_button_new_with_mnemonic
60 #define LABEL_OK GTK_STOCK_OK
61 #define LABEL_CANCEL GTK_STOCK_CANCEL
62 #define LABEL_NO GTK_STOCK_NO
63 #define LABEL_YES GTK_STOCK_YES
64 #define LABEL_SAVE GTK_STOCK_SAVE
65 #define LABEL_OPEN GTK_STOCK_OPEN
66 #define gtk_button_new_with_our_label gtk_button_new_from_stock
69 /* #undef USE_CAIRO */
70 /* #define NO_THICK_LINE */
72 static FILE *debug_fp = NULL;
74 void dputs(const char *buf)
77 debug_fp = fopen("debug.log", "w");
88 void debug_printf(const char *fmt, ...)
94 vsprintf(buf, fmt, ap);
100 /* ----------------------------------------------------------------------
101 * Error reporting functions used elsewhere.
104 void fatal(const char *fmt, ...)
108 fprintf(stderr, "fatal error: ");
111 vfprintf(stderr, fmt, ap);
114 fprintf(stderr, "\n");
118 /* ----------------------------------------------------------------------
119 * GTK front end to puzzles.
122 static void changed_preset(frontend *fe);
126 PangoFontDescription *desc;
135 * This structure holds all the data relevant to a single window.
136 * In principle this would allow us to open multiple independent
137 * puzzle windows, although I can't currently see any real point in
138 * doing so. I'm just coding cleanly because there's no
139 * particularly good reason not to.
143 GtkAccelGroup *dummy_accelgroup;
145 GtkWidget *statusbar;
147 #if GTK_CHECK_VERSION(3,20,0)
148 GtkCssProvider *css_provider;
154 const float *colours;
156 cairo_surface_t *image;
157 #ifndef USE_CAIRO_WITHOUT_PIXMAP
160 GdkColor background; /* for painting outside puzzle area */
166 int backgroundindex; /* which of colours[] is background */
169 int bbox_l, bbox_r, bbox_u, bbox_d;
170 int timer_active, timer_id;
171 struct timeval last_time;
173 int nfonts, fontsize;
175 int cfg_which, cfgret;
179 int pw, ph; /* pixmap size (w, h are area size) */
180 int ox, oy; /* offset of pixmap in drawing area */
184 GSList *preset_radio;
186 GtkWidget *preset_custom;
187 GtkWidget *copy_menu_item;
188 #if !GTK_CHECK_VERSION(3,0,0)
189 int drawing_area_shrink_pending;
190 int menubar_is_local;
192 #if GTK_CHECK_VERSION(3,0,0)
194 * This is used to get round an annoying lack of GTK notification
195 * message. If we request a window resize with
196 * gtk_window_resize(), we normally get back a "configure" event
197 * on the window and on its drawing area, and we respond to the
198 * latter by doing an appropriate resize of the puzzle. If the
199 * window is maximised, so that gtk_window_resize() _doesn't_
200 * change its size, then that configure event never shows up. But
201 * if we requested the resize in response to a change of puzzle
202 * parameters (say, the user selected a differently-sized preset
203 * from the menu), then we would still like to be _notified_ that
204 * the window size was staying the same, so that we can respond by
205 * choosing an appropriate tile size for the new puzzle preset in
206 * the existing window size.
208 * Fortunately, in GTK 3, we may not get a "configure" event on
209 * the drawing area in this situation, but we still get a
210 * "size_allocate" event on the whole window (which, in other
211 * situations when we _do_ get a "configure" on the area, turns up
212 * second). So we treat _that_ event as indicating that if the
213 * "configure" event hasn't already shown up then it's not going
216 * This flag is where we bookkeep this system. On
217 * gtk_window_resize we set this flag to true; the area's
218 * configure handler sets it back to false; then if that doesn't
219 * happen, the window's size_allocate handler does a fallback
220 * puzzle resize when it sees this flag still set to true.
222 int awaiting_resize_ack;
228 cairo_surface_t *image;
235 void get_random_seed(void **randseed, int *randseedsize)
237 struct timeval *tvp = snew(struct timeval);
238 gettimeofday(tvp, NULL);
239 *randseed = (void *)tvp;
240 *randseedsize = sizeof(struct timeval);
243 void frontend_default_colour(frontend *fe, float *output)
245 #if !GTK_CHECK_VERSION(3,0,0)
247 * Use the widget style's default background colour as the
248 * background for the puzzle drawing area.
250 GdkColor col = gtk_widget_get_style(fe->window)->bg[GTK_STATE_NORMAL];
251 output[0] = col.red / 65535.0;
252 output[1] = col.green / 65535.0;
253 output[2] = col.blue / 65535.0;
256 * GTK 3 has decided that there's no such thing as a 'default
257 * background colour' any more, because widget styles might set
258 * the background to something more complicated like a background
259 * image. We don't want to get into overlaying our entire puzzle
260 * on an arbitrary background image, so we'll just make up a
261 * reasonable shade of grey.
263 output[0] = output[1] = output[2] = 0.9F;
267 void gtk_status_bar(void *handle, const char *text)
269 frontend *fe = (frontend *)handle;
271 assert(fe->statusbar);
273 gtk_statusbar_pop(GTK_STATUSBAR(fe->statusbar), fe->statusctx);
274 gtk_statusbar_push(GTK_STATUSBAR(fe->statusbar), fe->statusctx, text);
277 /* ----------------------------------------------------------------------
278 * Cairo drawing functions.
283 static void setup_drawing(frontend *fe)
285 fe->cr = cairo_create(fe->image);
286 cairo_set_antialias(fe->cr, CAIRO_ANTIALIAS_GRAY);
287 cairo_set_line_width(fe->cr, 1.0);
288 cairo_set_line_cap(fe->cr, CAIRO_LINE_CAP_SQUARE);
289 cairo_set_line_join(fe->cr, CAIRO_LINE_JOIN_ROUND);
292 static void teardown_drawing(frontend *fe)
294 cairo_destroy(fe->cr);
297 #ifndef USE_CAIRO_WITHOUT_PIXMAP
299 cairo_t *cr = gdk_cairo_create(fe->pixmap);
300 cairo_set_source_surface(cr, fe->image, 0, 0);
304 fe->bbox_r - fe->bbox_l + 2,
305 fe->bbox_d - fe->bbox_u + 2);
312 static void snaffle_colours(frontend *fe)
314 fe->colours = midend_colours(fe->me, &fe->ncolours);
317 static void set_colour(frontend *fe, int colour)
319 cairo_set_source_rgb(fe->cr,
320 fe->colours[3*colour + 0],
321 fe->colours[3*colour + 1],
322 fe->colours[3*colour + 2]);
325 static void set_window_background(frontend *fe, int colour)
327 #if GTK_CHECK_VERSION(3,20,0)
329 sprintf(css_buf, ".background { "
330 "background-color: #%02x%02x%02x; }",
331 (unsigned)(fe->colours[3*colour + 0] * 255),
332 (unsigned)(fe->colours[3*colour + 1] * 255),
333 (unsigned)(fe->colours[3*colour + 2] * 255));
334 if (!fe->css_provider)
335 fe->css_provider = gtk_css_provider_new();
336 if (!gtk_css_provider_load_from_data(
337 GTK_CSS_PROVIDER(fe->css_provider), css_buf, -1, NULL))
338 assert(0 && "Couldn't load CSS");
339 gtk_style_context_add_provider(
340 gtk_widget_get_style_context(fe->window),
341 GTK_STYLE_PROVIDER(fe->css_provider),
342 GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
343 gtk_style_context_add_provider(
344 gtk_widget_get_style_context(fe->area),
345 GTK_STYLE_PROVIDER(fe->css_provider),
346 GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
347 #elif GTK_CHECK_VERSION(3,0,0)
349 rgba.red = fe->colours[3*colour + 0];
350 rgba.green = fe->colours[3*colour + 1];
351 rgba.blue = fe->colours[3*colour + 2];
353 gdk_window_set_background_rgba(gtk_widget_get_window(fe->area), &rgba);
354 gdk_window_set_background_rgba(gtk_widget_get_window(fe->window), &rgba);
358 colmap = gdk_colormap_get_system();
359 fe->background.red = fe->colours[3*colour + 0] * 65535;
360 fe->background.green = fe->colours[3*colour + 1] * 65535;
361 fe->background.blue = fe->colours[3*colour + 2] * 65535;
362 if (!gdk_colormap_alloc_color(colmap, &fe->background, FALSE, FALSE)) {
363 g_error("couldn't allocate background (#%02x%02x%02x)\n",
364 fe->background.red >> 8, fe->background.green >> 8,
365 fe->background.blue >> 8);
367 gdk_window_set_background(gtk_widget_get_window(fe->area),
369 gdk_window_set_background(gtk_widget_get_window(fe->window),
374 static PangoLayout *make_pango_layout(frontend *fe)
376 return (pango_cairo_create_layout(fe->cr));
379 static void draw_pango_layout(frontend *fe, PangoLayout *layout,
382 cairo_move_to(fe->cr, x, y);
383 pango_cairo_show_layout(fe->cr, layout);
386 static void save_screenshot_png(frontend *fe, const char *screenshot_file)
388 cairo_surface_write_to_png(fe->image, screenshot_file);
391 static void do_clip(frontend *fe, int x, int y, int w, int h)
393 cairo_new_path(fe->cr);
394 cairo_rectangle(fe->cr, x, y, w, h);
398 static void do_unclip(frontend *fe)
400 cairo_reset_clip(fe->cr);
403 static void do_draw_rect(frontend *fe, int x, int y, int w, int h)
406 cairo_new_path(fe->cr);
407 cairo_set_antialias(fe->cr, CAIRO_ANTIALIAS_NONE);
408 cairo_rectangle(fe->cr, x, y, w, h);
410 cairo_restore(fe->cr);
413 static void do_draw_line(frontend *fe, int x1, int y1, int x2, int y2)
415 cairo_new_path(fe->cr);
416 cairo_move_to(fe->cr, x1 + 0.5, y1 + 0.5);
417 cairo_line_to(fe->cr, x2 + 0.5, y2 + 0.5);
418 cairo_stroke(fe->cr);
421 static void do_draw_thick_line(frontend *fe, float thickness,
422 float x1, float y1, float x2, float y2)
425 cairo_set_line_width(fe->cr, thickness);
426 cairo_new_path(fe->cr);
427 cairo_move_to(fe->cr, x1, y1);
428 cairo_line_to(fe->cr, x2, y2);
429 cairo_stroke(fe->cr);
430 cairo_restore(fe->cr);
433 static void do_draw_poly(frontend *fe, int *coords, int npoints,
434 int fillcolour, int outlinecolour)
438 cairo_new_path(fe->cr);
439 for (i = 0; i < npoints; i++)
440 cairo_line_to(fe->cr, coords[i*2] + 0.5, coords[i*2 + 1] + 0.5);
441 cairo_close_path(fe->cr);
442 if (fillcolour >= 0) {
443 set_colour(fe, fillcolour);
444 cairo_fill_preserve(fe->cr);
446 assert(outlinecolour >= 0);
447 set_colour(fe, outlinecolour);
448 cairo_stroke(fe->cr);
451 static void do_draw_circle(frontend *fe, int cx, int cy, int radius,
452 int fillcolour, int outlinecolour)
454 cairo_new_path(fe->cr);
455 cairo_arc(fe->cr, cx + 0.5, cy + 0.5, radius, 0, 2*PI);
456 cairo_close_path(fe->cr); /* Just in case... */
457 if (fillcolour >= 0) {
458 set_colour(fe, fillcolour);
459 cairo_fill_preserve(fe->cr);
461 assert(outlinecolour >= 0);
462 set_colour(fe, outlinecolour);
463 cairo_stroke(fe->cr);
466 static void setup_blitter(blitter *bl, int w, int h)
468 bl->image = cairo_image_surface_create(CAIRO_FORMAT_RGB24, w, h);
471 static void teardown_blitter(blitter *bl)
473 cairo_surface_destroy(bl->image);
476 static void do_blitter_save(frontend *fe, blitter *bl, int x, int y)
478 cairo_t *cr = cairo_create(bl->image);
480 cairo_set_source_surface(cr, fe->image, -x, -y);
485 static void do_blitter_load(frontend *fe, blitter *bl, int x, int y)
487 cairo_set_source_surface(fe->cr, bl->image, x, y);
491 static void clear_backing_store(frontend *fe)
496 static void wipe_and_maybe_destroy_cairo(frontend *fe, cairo_t *cr,
499 cairo_set_source_rgb(cr, fe->colours[0], fe->colours[1], fe->colours[2]);
505 static void setup_backing_store(frontend *fe)
507 #ifndef USE_CAIRO_WITHOUT_PIXMAP
508 fe->pixmap = gdk_pixmap_new(gtk_widget_get_window(fe->area),
511 fe->image = cairo_image_surface_create(CAIRO_FORMAT_RGB24,
514 wipe_and_maybe_destroy_cairo(fe, cairo_create(fe->image), TRUE);
515 #ifndef USE_CAIRO_WITHOUT_PIXMAP
516 wipe_and_maybe_destroy_cairo(fe, gdk_cairo_create(fe->pixmap), TRUE);
518 #if GTK_CHECK_VERSION(3,22,0)
521 cairo_region_t *region;
522 GdkDrawingContext *drawctx;
525 gdkwin = gtk_widget_get_window(fe->area);
526 region = gdk_window_get_clip_region(gdkwin);
527 drawctx = gdk_window_begin_draw_frame(gdkwin, region);
528 cr = gdk_drawing_context_get_cairo_context(drawctx);
529 wipe_and_maybe_destroy_cairo(fe, cr, FALSE);
530 gdk_window_end_draw_frame(gdkwin, drawctx);
531 cairo_region_destroy(region);
534 wipe_and_maybe_destroy_cairo(
535 fe, gdk_cairo_create(gtk_widget_get_window(fe->area)), TRUE);
539 static int backing_store_ok(frontend *fe)
541 return (!!fe->image);
544 static void teardown_backing_store(frontend *fe)
546 cairo_surface_destroy(fe->image);
547 #ifndef USE_CAIRO_WITHOUT_PIXMAP
548 gdk_pixmap_unref(fe->pixmap);
555 /* ----------------------------------------------------------------------
556 * GDK drawing functions.
561 static void setup_drawing(frontend *fe)
563 fe->gc = gdk_gc_new(fe->area->window);
566 static void teardown_drawing(frontend *fe)
568 gdk_gc_unref(fe->gc);
572 static void snaffle_colours(frontend *fe)
578 fe->colmap = gdk_colormap_get_system();
579 colours = midend_colours(fe->me, &ncolours);
580 fe->ncolours = ncolours;
581 fe->colours = snewn(ncolours, GdkColor);
582 for (i = 0; i < ncolours; i++) {
583 fe->colours[i].red = colours[i*3] * 0xFFFF;
584 fe->colours[i].green = colours[i*3+1] * 0xFFFF;
585 fe->colours[i].blue = colours[i*3+2] * 0xFFFF;
587 success = snewn(ncolours, gboolean);
588 gdk_colormap_alloc_colors(fe->colmap, fe->colours, ncolours,
589 FALSE, FALSE, success);
590 for (i = 0; i < ncolours; i++) {
592 g_error("couldn't allocate colour %d (#%02x%02x%02x)\n",
593 i, fe->colours[i].red >> 8,
594 fe->colours[i].green >> 8,
595 fe->colours[i].blue >> 8);
600 static void set_window_background(frontend *fe, int colour)
602 fe->backgroundindex = colour;
603 gdk_window_set_background(fe->area->window, &fe->colours[colour]);
604 gdk_window_set_background(fe->window->window, &fe->colours[colour]);
607 static void set_colour(frontend *fe, int colour)
609 gdk_gc_set_foreground(fe->gc, &fe->colours[colour]);
613 static PangoLayout *make_pango_layout(frontend *fe)
615 return (pango_layout_new(gtk_widget_get_pango_context(fe->area)));
618 static void draw_pango_layout(frontend *fe, PangoLayout *layout,
621 gdk_draw_layout(fe->pixmap, fe->gc, x, y, layout);
625 static void save_screenshot_png(frontend *fe, const char *screenshot_file)
628 GError *gerror = NULL;
630 midend_redraw(fe->me);
632 pb = gdk_pixbuf_get_from_drawable(NULL, fe->pixmap,
633 NULL, 0, 0, 0, 0, -1, -1);
634 gdk_pixbuf_save(pb, screenshot_file, "png", &gerror, NULL);
637 static void do_clip(frontend *fe, int x, int y, int w, int h)
645 gdk_gc_set_clip_rectangle(fe->gc, &rect);
648 static void do_unclip(frontend *fe)
656 gdk_gc_set_clip_rectangle(fe->gc, &rect);
659 static void do_draw_rect(frontend *fe, int x, int y, int w, int h)
661 gdk_draw_rectangle(fe->pixmap, fe->gc, 1, x, y, w, h);
664 static void do_draw_line(frontend *fe, int x1, int y1, int x2, int y2)
666 gdk_draw_line(fe->pixmap, fe->gc, x1, y1, x2, y2);
669 static void do_draw_thick_line(frontend *fe, float thickness,
670 float x1, float y1, float x2, float y2)
674 gdk_gc_get_values(fe->gc, &save);
675 gdk_gc_set_line_attributes(fe->gc,
680 gdk_draw_line(fe->pixmap, fe->gc, x1, y1, x2, y2);
681 gdk_gc_set_line_attributes(fe->gc,
688 static void do_draw_poly(frontend *fe, int *coords, int npoints,
689 int fillcolour, int outlinecolour)
691 GdkPoint *points = snewn(npoints, GdkPoint);
694 for (i = 0; i < npoints; i++) {
695 points[i].x = coords[i*2];
696 points[i].y = coords[i*2+1];
699 if (fillcolour >= 0) {
700 set_colour(fe, fillcolour);
701 gdk_draw_polygon(fe->pixmap, fe->gc, TRUE, points, npoints);
703 assert(outlinecolour >= 0);
704 set_colour(fe, outlinecolour);
707 * In principle we ought to be able to use gdk_draw_polygon for
708 * the outline as well. In fact, it turns out to interact badly
709 * with a clipping region, for no terribly obvious reason, so I
710 * draw the outline as a sequence of lines instead.
712 for (i = 0; i < npoints; i++)
713 gdk_draw_line(fe->pixmap, fe->gc,
714 points[i].x, points[i].y,
715 points[(i+1)%npoints].x, points[(i+1)%npoints].y);
720 static void do_draw_circle(frontend *fe, int cx, int cy, int radius,
721 int fillcolour, int outlinecolour)
723 if (fillcolour >= 0) {
724 set_colour(fe, fillcolour);
725 gdk_draw_arc(fe->pixmap, fe->gc, TRUE,
726 cx - radius, cy - radius,
727 2 * radius, 2 * radius, 0, 360 * 64);
730 assert(outlinecolour >= 0);
731 set_colour(fe, outlinecolour);
732 gdk_draw_arc(fe->pixmap, fe->gc, FALSE,
733 cx - radius, cy - radius,
734 2 * radius, 2 * radius, 0, 360 * 64);
737 static void setup_blitter(blitter *bl, int w, int h)
740 * We can't create the pixmap right now, because fe->window
741 * might not yet exist. So we just cache w and h and create it
742 * during the firs call to blitter_save.
747 static void teardown_blitter(blitter *bl)
750 gdk_pixmap_unref(bl->pixmap);
753 static void do_blitter_save(frontend *fe, blitter *bl, int x, int y)
756 bl->pixmap = gdk_pixmap_new(fe->area->window, bl->w, bl->h, -1);
757 gdk_draw_pixmap(bl->pixmap,
758 fe->area->style->fg_gc[GTK_WIDGET_STATE(fe->area)],
760 x, y, 0, 0, bl->w, bl->h);
763 static void do_blitter_load(frontend *fe, blitter *bl, int x, int y)
766 gdk_draw_pixmap(fe->pixmap,
767 fe->area->style->fg_gc[GTK_WIDGET_STATE(fe->area)],
769 0, 0, x, y, bl->w, bl->h);
772 static void clear_backing_store(frontend *fe)
777 static void setup_backing_store(frontend *fe)
781 fe->pixmap = gdk_pixmap_new(fe->area->window, fe->pw, fe->ph, -1);
783 gc = gdk_gc_new(fe->area->window);
784 gdk_gc_set_foreground(gc, &fe->colours[0]);
785 gdk_draw_rectangle(fe->pixmap, gc, 1, 0, 0, fe->pw, fe->ph);
786 gdk_draw_rectangle(fe->area->window, gc, 1, 0, 0, fe->w, fe->h);
790 static int backing_store_ok(frontend *fe)
792 return (!!fe->pixmap);
795 static void teardown_backing_store(frontend *fe)
797 gdk_pixmap_unref(fe->pixmap);
803 #ifndef USE_CAIRO_WITHOUT_PIXMAP
804 static void repaint_rectangle(frontend *fe, GtkWidget *widget,
805 int x, int y, int w, int h)
807 GdkGC *gc = gdk_gc_new(gtk_widget_get_window(widget));
809 gdk_gc_set_foreground(gc, &fe->background);
811 gdk_gc_set_foreground(gc, &fe->colours[fe->backgroundindex]);
814 gdk_draw_rectangle(gtk_widget_get_window(widget), gc,
815 TRUE, x, y, fe->ox - x, h);
820 gdk_draw_rectangle(gtk_widget_get_window(widget), gc,
821 TRUE, x, y, w, fe->oy - y);
826 gdk_draw_rectangle(gtk_widget_get_window(widget), gc,
827 TRUE, x + fe->pw, y, w - fe->pw, h);
831 gdk_draw_rectangle(gtk_widget_get_window(widget), gc,
832 TRUE, x, y + fe->ph, w, h - fe->ph);
835 gdk_draw_pixmap(gtk_widget_get_window(widget), gc, fe->pixmap,
836 x - fe->ox, y - fe->oy, x, y, w, h);
841 /* ----------------------------------------------------------------------
842 * Pango font functions.
847 static void add_font(frontend *fe, int index, int fonttype, int fontsize)
850 * Use Pango to find the closest match to the requested
853 PangoFontDescription *fd;
855 fd = pango_font_description_new();
856 /* `Monospace' and `Sans' are meta-families guaranteed to exist */
857 pango_font_description_set_family(fd, fonttype == FONT_FIXED ?
858 "Monospace" : "Sans");
859 pango_font_description_set_weight(fd, PANGO_WEIGHT_BOLD);
861 * I found some online Pango documentation which
862 * described a function called
863 * pango_font_description_set_absolute_size(), which is
864 * _exactly_ what I want here. Unfortunately, none of
865 * my local Pango installations have it (presumably
866 * they're too old), so I'm going to have to hack round
867 * it by figuring out the point size myself. This
868 * limits me to X and probably also breaks in later
869 * Pango installations, so ideally I should add another
870 * CHECK_VERSION type ifdef and use set_absolute_size
871 * where available. All very annoying.
873 #ifdef HAVE_SENSIBLE_ABSOLUTE_SIZE_FUNCTION
874 pango_font_description_set_absolute_size(fd, PANGO_SCALE*fontsize);
877 Display *d = GDK_DISPLAY();
878 int s = DefaultScreen(d);
880 (PANGO_SCALE * 72.27 / 25.4) *
881 ((double) DisplayWidthMM(d, s) / DisplayWidth (d, s));
882 pango_font_description_set_size(fd, resolution * fontsize);
885 fe->fonts[index].desc = fd;
888 static void align_and_draw_text(frontend *fe,
889 int index, int align, int x, int y,
895 layout = make_pango_layout(fe);
900 pango_layout_set_font_description(layout, fe->fonts[index].desc);
901 pango_layout_set_text(layout, text, strlen(text));
902 pango_layout_get_pixel_extents(layout, NULL, &rect);
904 if (align & ALIGN_VCENTRE)
905 rect.y -= rect.height / 2;
907 rect.y -= rect.height;
909 if (align & ALIGN_HCENTRE)
910 rect.x -= rect.width / 2;
911 else if (align & ALIGN_HRIGHT)
912 rect.x -= rect.width;
914 draw_pango_layout(fe, layout, rect.x + x, rect.y + y);
916 g_object_unref(layout);
921 /* ----------------------------------------------------------------------
922 * Old-fashioned font functions.
927 static void add_font(int index, int fonttype, int fontsize)
930 * In GTK 1.2, I don't know of any plausible way to
931 * pick a suitable font, so I'm just going to be
934 fe->fonts[i].font = gdk_font_load(fonttype == FONT_FIXED ?
935 "fixed" : "variable");
938 static void align_and_draw_text(int index, int align, int x, int y,
941 int lb, rb, wid, asc, desc;
944 * Measure vertical string extents with respect to the same
947 gdk_string_extents(fe->fonts[i].font,
948 "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
949 &lb, &rb, &wid, &asc, &desc);
950 if (align & ALIGN_VCENTRE)
951 y += asc - (asc+desc)/2;
956 * ... but horizontal extents with respect to the provided
957 * string. This means that multiple pieces of text centred
958 * on the same y-coordinate don't have different baselines.
960 gdk_string_extents(fe->fonts[i].font, text,
961 &lb, &rb, &wid, &asc, &desc);
963 if (align & ALIGN_HCENTRE)
965 else if (align & ALIGN_HRIGHT)
969 * Actually draw the text.
971 gdk_draw_string(fe->pixmap, fe->fonts[i].font, fe->gc, x, y, text);
976 /* ----------------------------------------------------------------------
977 * The exported drawing functions.
980 void gtk_start_draw(void *handle)
982 frontend *fe = (frontend *)handle;
990 void gtk_clip(void *handle, int x, int y, int w, int h)
992 frontend *fe = (frontend *)handle;
993 do_clip(fe, x, y, w, h);
996 void gtk_unclip(void *handle)
998 frontend *fe = (frontend *)handle;
1002 void gtk_draw_text(void *handle, int x, int y, int fonttype, int fontsize,
1003 int align, int colour, const char *text)
1005 frontend *fe = (frontend *)handle;
1009 * Find or create the font.
1011 for (i = 0; i < fe->nfonts; i++)
1012 if (fe->fonts[i].type == fonttype && fe->fonts[i].size == fontsize)
1015 if (i == fe->nfonts) {
1016 if (fe->fontsize <= fe->nfonts) {
1017 fe->fontsize = fe->nfonts + 10;
1018 fe->fonts = sresize(fe->fonts, fe->fontsize, struct font);
1023 fe->fonts[i].type = fonttype;
1024 fe->fonts[i].size = fontsize;
1025 add_font(fe, i, fonttype, fontsize);
1031 set_colour(fe, colour);
1032 align_and_draw_text(fe, i, align, x, y, text);
1035 void gtk_draw_rect(void *handle, int x, int y, int w, int h, int colour)
1037 frontend *fe = (frontend *)handle;
1038 set_colour(fe, colour);
1039 do_draw_rect(fe, x, y, w, h);
1042 void gtk_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
1044 frontend *fe = (frontend *)handle;
1045 set_colour(fe, colour);
1046 do_draw_line(fe, x1, y1, x2, y2);
1049 void gtk_draw_thick_line(void *handle, float thickness,
1050 float x1, float y1, float x2, float y2, int colour)
1052 frontend *fe = (frontend *)handle;
1053 set_colour(fe, colour);
1054 do_draw_thick_line(fe, thickness, x1, y1, x2, y2);
1057 void gtk_draw_poly(void *handle, int *coords, int npoints,
1058 int fillcolour, int outlinecolour)
1060 frontend *fe = (frontend *)handle;
1061 do_draw_poly(fe, coords, npoints, fillcolour, outlinecolour);
1064 void gtk_draw_circle(void *handle, int cx, int cy, int radius,
1065 int fillcolour, int outlinecolour)
1067 frontend *fe = (frontend *)handle;
1068 do_draw_circle(fe, cx, cy, radius, fillcolour, outlinecolour);
1071 blitter *gtk_blitter_new(void *handle, int w, int h)
1073 blitter *bl = snew(blitter);
1074 setup_blitter(bl, w, h);
1080 void gtk_blitter_free(void *handle, blitter *bl)
1082 teardown_blitter(bl);
1086 void gtk_blitter_save(void *handle, blitter *bl, int x, int y)
1088 frontend *fe = (frontend *)handle;
1089 do_blitter_save(fe, bl, x, y);
1094 void gtk_blitter_load(void *handle, blitter *bl, int x, int y)
1096 frontend *fe = (frontend *)handle;
1097 if (x == BLITTER_FROMSAVED && y == BLITTER_FROMSAVED) {
1101 do_blitter_load(fe, bl, x, y);
1104 void gtk_draw_update(void *handle, int x, int y, int w, int h)
1106 frontend *fe = (frontend *)handle;
1107 if (fe->bbox_l > x ) fe->bbox_l = x ;
1108 if (fe->bbox_r < x+w) fe->bbox_r = x+w;
1109 if (fe->bbox_u > y ) fe->bbox_u = y ;
1110 if (fe->bbox_d < y+h) fe->bbox_d = y+h;
1113 void gtk_end_draw(void *handle)
1115 frontend *fe = (frontend *)handle;
1117 teardown_drawing(fe);
1119 if (fe->bbox_l < fe->bbox_r && fe->bbox_u < fe->bbox_d) {
1120 #ifdef USE_CAIRO_WITHOUT_PIXMAP
1121 gtk_widget_queue_draw_area(fe->area,
1122 fe->bbox_l - 1 + fe->ox,
1123 fe->bbox_u - 1 + fe->oy,
1124 fe->bbox_r - fe->bbox_l + 2,
1125 fe->bbox_d - fe->bbox_u + 2);
1127 repaint_rectangle(fe, fe->area,
1128 fe->bbox_l - 1 + fe->ox,
1129 fe->bbox_u - 1 + fe->oy,
1130 fe->bbox_r - fe->bbox_l + 2,
1131 fe->bbox_d - fe->bbox_u + 2);
1137 char *gtk_text_fallback(void *handle, const char *const *strings, int nstrings)
1140 * We assume Pango can cope with any UTF-8 likely to be emitted
1143 return dupstr(strings[0]);
1147 const struct drawing_api gtk_drawing = {
1163 NULL, NULL, NULL, NULL, NULL, NULL, /* {begin,end}_{doc,page,puzzle} */
1164 NULL, NULL, /* line_width, line_dotted */
1170 #ifdef NO_THICK_LINE
1173 gtk_draw_thick_line,
1177 static void destroy(GtkWidget *widget, gpointer data)
1179 frontend *fe = (frontend *)data;
1180 deactivate_timer(fe);
1181 midend_free(fe->me);
1185 static gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data)
1187 frontend *fe = (frontend *)data;
1189 int shift = (event->state & GDK_SHIFT_MASK) ? MOD_SHFT : 0;
1190 int ctrl = (event->state & GDK_CONTROL_MASK) ? MOD_CTRL : 0;
1192 if (!backing_store_ok(fe))
1195 /* Handle mnemonics. */
1196 if (gtk_window_activate_key(GTK_WINDOW(fe->window), event))
1199 if (event->keyval == GDK_KEY_Up)
1200 keyval = shift | ctrl | CURSOR_UP;
1201 else if (event->keyval == GDK_KEY_KP_Up ||
1202 event->keyval == GDK_KEY_KP_8)
1203 keyval = MOD_NUM_KEYPAD | '8';
1204 else if (event->keyval == GDK_KEY_Down)
1205 keyval = shift | ctrl | CURSOR_DOWN;
1206 else if (event->keyval == GDK_KEY_KP_Down ||
1207 event->keyval == GDK_KEY_KP_2)
1208 keyval = MOD_NUM_KEYPAD | '2';
1209 else if (event->keyval == GDK_KEY_Left)
1210 keyval = shift | ctrl | CURSOR_LEFT;
1211 else if (event->keyval == GDK_KEY_KP_Left ||
1212 event->keyval == GDK_KEY_KP_4)
1213 keyval = MOD_NUM_KEYPAD | '4';
1214 else if (event->keyval == GDK_KEY_Right)
1215 keyval = shift | ctrl | CURSOR_RIGHT;
1216 else if (event->keyval == GDK_KEY_KP_Right ||
1217 event->keyval == GDK_KEY_KP_6)
1218 keyval = MOD_NUM_KEYPAD | '6';
1219 else if (event->keyval == GDK_KEY_KP_Home ||
1220 event->keyval == GDK_KEY_KP_7)
1221 keyval = MOD_NUM_KEYPAD | '7';
1222 else if (event->keyval == GDK_KEY_KP_End ||
1223 event->keyval == GDK_KEY_KP_1)
1224 keyval = MOD_NUM_KEYPAD | '1';
1225 else if (event->keyval == GDK_KEY_KP_Page_Up ||
1226 event->keyval == GDK_KEY_KP_9)
1227 keyval = MOD_NUM_KEYPAD | '9';
1228 else if (event->keyval == GDK_KEY_KP_Page_Down ||
1229 event->keyval == GDK_KEY_KP_3)
1230 keyval = MOD_NUM_KEYPAD | '3';
1231 else if (event->keyval == GDK_KEY_KP_Insert ||
1232 event->keyval == GDK_KEY_KP_0)
1233 keyval = MOD_NUM_KEYPAD | '0';
1234 else if (event->keyval == GDK_KEY_KP_Begin ||
1235 event->keyval == GDK_KEY_KP_5)
1236 keyval = MOD_NUM_KEYPAD | '5';
1237 else if (event->keyval == GDK_KEY_BackSpace ||
1238 event->keyval == GDK_KEY_Delete ||
1239 event->keyval == GDK_KEY_KP_Delete)
1241 else if ((event->keyval == 'z' || event->keyval == 'Z') && shift && ctrl)
1243 else if (event->string[0] && !event->string[1])
1244 keyval = (unsigned char)event->string[0];
1249 !midend_process_key(fe->me, 0, 0, keyval))
1250 gtk_widget_destroy(fe->window);
1255 static gint button_event(GtkWidget *widget, GdkEventButton *event,
1258 frontend *fe = (frontend *)data;
1261 if (!backing_store_ok(fe))
1264 if (event->type != GDK_BUTTON_PRESS && event->type != GDK_BUTTON_RELEASE)
1267 if (event->button == 2 || (event->state & GDK_SHIFT_MASK))
1268 button = MIDDLE_BUTTON;
1269 else if (event->button == 3 || (event->state & GDK_MOD1_MASK))
1270 button = RIGHT_BUTTON;
1271 else if (event->button == 1)
1272 button = LEFT_BUTTON;
1273 else if (event->button == 8 && event->type == GDK_BUTTON_PRESS)
1275 else if (event->button == 9 && event->type == GDK_BUTTON_PRESS)
1278 return FALSE; /* don't even know what button! */
1280 if (event->type == GDK_BUTTON_RELEASE && button >= LEFT_BUTTON)
1281 button += LEFT_RELEASE - LEFT_BUTTON;
1283 if (!midend_process_key(fe->me, event->x - fe->ox,
1284 event->y - fe->oy, button))
1285 gtk_widget_destroy(fe->window);
1290 static gint motion_event(GtkWidget *widget, GdkEventMotion *event,
1293 frontend *fe = (frontend *)data;
1296 if (!backing_store_ok(fe))
1299 if (event->state & (GDK_BUTTON2_MASK | GDK_SHIFT_MASK))
1300 button = MIDDLE_DRAG;
1301 else if (event->state & GDK_BUTTON1_MASK)
1303 else if (event->state & GDK_BUTTON3_MASK)
1304 button = RIGHT_DRAG;
1306 return FALSE; /* don't even know what button! */
1308 if (!midend_process_key(fe->me, event->x - fe->ox,
1309 event->y - fe->oy, button))
1310 gtk_widget_destroy(fe->window);
1311 #if GTK_CHECK_VERSION(2,12,0)
1312 gdk_event_request_motions(event);
1314 gdk_window_get_pointer(gtk_widget_get_window(widget), NULL, NULL, NULL);
1320 #if GTK_CHECK_VERSION(3,0,0)
1321 static gint draw_area(GtkWidget *widget, cairo_t *cr, gpointer data)
1323 frontend *fe = (frontend *)data;
1324 GdkRectangle dirtyrect;
1326 gdk_cairo_get_clip_rectangle(cr, &dirtyrect);
1327 cairo_set_source_surface(cr, fe->image, fe->ox, fe->oy);
1328 cairo_rectangle(cr, dirtyrect.x, dirtyrect.y,
1329 dirtyrect.width, dirtyrect.height);
1335 static gint expose_area(GtkWidget *widget, GdkEventExpose *event,
1338 frontend *fe = (frontend *)data;
1340 if (backing_store_ok(fe)) {
1341 #ifdef USE_CAIRO_WITHOUT_PIXMAP
1342 cairo_t *cr = gdk_cairo_create(gtk_widget_get_window(widget));
1343 cairo_set_source_surface(cr, fe->image, fe->ox, fe->oy);
1344 cairo_rectangle(cr, event->area.x, event->area.y,
1345 event->area.width, event->area.height);
1349 repaint_rectangle(fe, widget,
1350 event->area.x, event->area.y,
1351 event->area.width, event->area.height);
1358 static gint map_window(GtkWidget *widget, GdkEvent *event,
1361 frontend *fe = (frontend *)data;
1364 * Apparently we need to do this because otherwise the status
1365 * bar will fail to update immediately. Annoying, but there we
1368 gtk_widget_queue_draw(fe->window);
1373 static void resize_puzzle_to_area(frontend *fe, int x, int y)
1375 int oldw = fe->w, oldpw = fe->pw, oldh = fe->h, oldph = fe->ph;
1379 midend_size(fe->me, &x, &y, TRUE);
1382 fe->ox = (fe->w - fe->pw) / 2;
1383 fe->oy = (fe->h - fe->ph) / 2;
1385 if (oldw != fe->w || oldpw != fe->pw ||
1386 oldh != fe->h || oldph != fe->ph || !backing_store_ok(fe)) {
1387 if (backing_store_ok(fe))
1388 teardown_backing_store(fe);
1389 setup_backing_store(fe);
1392 midend_force_redraw(fe->me);
1395 static gint configure_area(GtkWidget *widget,
1396 GdkEventConfigure *event, gpointer data)
1398 frontend *fe = (frontend *)data;
1399 resize_puzzle_to_area(fe, event->width, event->height);
1400 fe->awaiting_resize_ack = FALSE;
1404 #if GTK_CHECK_VERSION(3,0,0)
1405 static void window_size_alloc(GtkWidget *widget, GtkAllocation *allocation,
1408 frontend *fe = (frontend *)data;
1409 if (fe->awaiting_resize_ack) {
1411 gtk_widget_get_allocation(fe->area, &a);
1412 resize_puzzle_to_area(fe, a.width, a.height);
1413 fe->awaiting_resize_ack = FALSE;
1418 static gint timer_func(gpointer data)
1420 frontend *fe = (frontend *)data;
1422 if (fe->timer_active) {
1425 gettimeofday(&now, NULL);
1426 elapsed = ((now.tv_usec - fe->last_time.tv_usec) * 0.000001F +
1427 (now.tv_sec - fe->last_time.tv_sec));
1428 midend_timer(fe->me, elapsed); /* may clear timer_active */
1429 fe->last_time = now;
1432 return fe->timer_active;
1435 void deactivate_timer(frontend *fe)
1438 return; /* can happen due to --generate */
1439 if (fe->timer_active)
1440 g_source_remove(fe->timer_id);
1441 fe->timer_active = FALSE;
1444 void activate_timer(frontend *fe)
1447 return; /* can happen due to --generate */
1448 if (!fe->timer_active) {
1449 fe->timer_id = g_timeout_add(20, timer_func, fe);
1450 gettimeofday(&fe->last_time, NULL);
1452 fe->timer_active = TRUE;
1455 static void window_destroy(GtkWidget *widget, gpointer data)
1460 static int win_key_press(GtkWidget *widget, GdkEventKey *event, gpointer data)
1462 GObject *cancelbutton = G_OBJECT(data);
1465 * `Escape' effectively clicks the cancel button
1467 if (event->keyval == GDK_KEY_Escape) {
1468 g_signal_emit_by_name(cancelbutton, "clicked");
1475 enum { MB_OK, MB_YESNO };
1477 static void align_label(GtkLabel *label, double x, double y)
1479 #if GTK_CHECK_VERSION(3,16,0)
1480 gtk_label_set_xalign(label, x);
1481 gtk_label_set_yalign(label, y);
1482 #elif GTK_CHECK_VERSION(3,14,0)
1483 gtk_widget_set_halign(GTK_WIDGET(label),
1484 x == 0 ? GTK_ALIGN_START :
1485 x == 1 ? GTK_ALIGN_END : GTK_ALIGN_CENTER);
1486 gtk_widget_set_valign(GTK_WIDGET(label),
1487 y == 0 ? GTK_ALIGN_START :
1488 y == 1 ? GTK_ALIGN_END : GTK_ALIGN_CENTER);
1490 gtk_misc_set_alignment(GTK_MISC(label), x, y);
1494 #if GTK_CHECK_VERSION(3,0,0)
1495 int message_box(GtkWidget *parent, const char *title, const char *msg,
1496 int centre, int type)
1501 window = gtk_message_dialog_new
1502 (GTK_WINDOW(parent),
1503 (GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT),
1504 (type == MB_OK ? GTK_MESSAGE_INFO : GTK_MESSAGE_QUESTION),
1505 (type == MB_OK ? GTK_BUTTONS_OK : GTK_BUTTONS_YES_NO),
1507 gtk_window_set_title(GTK_WINDOW(window), title);
1508 ret = gtk_dialog_run(GTK_DIALOG(window));
1509 gtk_widget_destroy(window);
1510 return (type == MB_OK ? TRUE : (ret == GTK_RESPONSE_YES));
1512 #else /* GTK_CHECK_VERSION(3,0,0) */
1513 static void msgbox_button_clicked(GtkButton *button, gpointer data)
1515 GtkWidget *window = GTK_WIDGET(data);
1518 ip = (int *)g_object_get_data(G_OBJECT(window), "user-data");
1519 v = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(button), "user-data"));
1522 gtk_widget_destroy(GTK_WIDGET(data));
1525 int message_box(GtkWidget *parent, char *title, char *msg, int centre,
1528 GtkWidget *window, *hbox, *text, *button;
1532 window = gtk_dialog_new();
1533 text = gtk_label_new(msg);
1534 align_label(GTK_LABEL(text), 0.0, 0.0);
1535 hbox = gtk_hbox_new(FALSE, 0);
1536 gtk_box_pack_start(GTK_BOX(hbox), text, FALSE, FALSE, 20);
1538 (GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(window))),
1539 hbox, FALSE, FALSE, 20);
1540 gtk_widget_show(text);
1541 gtk_widget_show(hbox);
1542 gtk_window_set_title(GTK_WINDOW(window), title);
1543 gtk_label_set_line_wrap(GTK_LABEL(text), TRUE);
1545 if (type == MB_OK) {
1546 titles = LABEL_OK "\0";
1549 assert(type == MB_YESNO);
1550 titles = LABEL_NO "\0" LABEL_YES "\0";
1557 button = gtk_button_new_with_our_label(titles);
1559 (GTK_BOX(gtk_dialog_get_action_area(GTK_DIALOG(window))),
1560 button, FALSE, FALSE, 0);
1561 gtk_widget_show(button);
1563 gtk_widget_set_can_default(button, TRUE);
1564 gtk_window_set_default(GTK_WINDOW(window), button);
1567 g_signal_connect(G_OBJECT(window), "key_press_event",
1568 G_CALLBACK(win_key_press), button);
1570 g_signal_connect(G_OBJECT(button), "clicked",
1571 G_CALLBACK(msgbox_button_clicked), window);
1572 g_object_set_data(G_OBJECT(button), "user-data",
1573 GINT_TO_POINTER(i));
1574 titles += strlen(titles)+1;
1577 g_object_set_data(G_OBJECT(window), "user-data", &i);
1578 g_signal_connect(G_OBJECT(window), "destroy",
1579 G_CALLBACK(window_destroy), NULL);
1580 gtk_window_set_modal(GTK_WINDOW(window), TRUE);
1581 gtk_window_set_transient_for(GTK_WINDOW(window), GTK_WINDOW(parent));
1582 /* set_transient_window_pos(parent, window); */
1583 gtk_widget_show(window);
1586 return (type == MB_YESNO ? i == 1 : TRUE);
1588 #endif /* GTK_CHECK_VERSION(3,0,0) */
1590 void error_box(GtkWidget *parent, const char *msg)
1592 message_box(parent, "Error", msg, FALSE, MB_OK);
1595 static void config_ok_button_clicked(GtkButton *button, gpointer data)
1597 frontend *fe = (frontend *)data;
1600 err = midend_set_config(fe->me, fe->cfg_which, fe->cfg);
1603 error_box(fe->cfgbox, err);
1606 gtk_widget_destroy(fe->cfgbox);
1611 static void config_cancel_button_clicked(GtkButton *button, gpointer data)
1613 frontend *fe = (frontend *)data;
1615 gtk_widget_destroy(fe->cfgbox);
1618 static int editbox_key(GtkWidget *widget, GdkEventKey *event, gpointer data)
1621 * GtkEntry has a nasty habit of eating the Return key, which
1622 * is unhelpful since it doesn't actually _do_ anything with it
1623 * (it calls gtk_widget_activate, but our edit boxes never need
1624 * activating). So I catch Return before GtkEntry sees it, and
1625 * pass it straight on to the parent widget. Effect: hitting
1626 * Return in an edit box will now activate the default button
1627 * in the dialog just like it will everywhere else.
1629 if (event->keyval == GDK_KEY_Return &&
1630 gtk_widget_get_parent(widget) != NULL) {
1632 g_signal_stop_emission_by_name(G_OBJECT(widget), "key_press_event");
1633 g_signal_emit_by_name(G_OBJECT(gtk_widget_get_parent(widget)),
1634 "key_press_event", event, &return_val);
1640 static void editbox_changed(GtkEditable *ed, gpointer data)
1642 config_item *i = (config_item *)data;
1644 assert(i->type == C_STRING);
1645 sfree(i->u.string.sval);
1646 i->u.string.sval = dupstr(gtk_entry_get_text(GTK_ENTRY(ed)));
1649 static void button_toggled(GtkToggleButton *tb, gpointer data)
1651 config_item *i = (config_item *)data;
1653 assert(i->type == C_BOOLEAN);
1654 i->u.boolean.bval = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(tb));
1657 static void droplist_sel(GtkComboBox *combo, gpointer data)
1659 config_item *i = (config_item *)data;
1661 assert(i->type == C_CHOICES);
1662 i->u.choices.selected = gtk_combo_box_get_active(combo);
1665 static int get_config(frontend *fe, int which)
1667 GtkWidget *w, *table, *cancel;
1668 GtkBox *content_box, *button_box;
1673 fe->cfg = midend_get_config(fe->me, which, &title);
1674 fe->cfg_which = which;
1677 #if GTK_CHECK_VERSION(3,0,0)
1678 /* GtkDialog isn't quite flexible enough */
1679 fe->cfgbox = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1680 content_box = GTK_BOX(gtk_vbox_new(FALSE, 8));
1681 g_object_set(G_OBJECT(content_box), "margin", 8, (const char *)NULL);
1682 gtk_widget_show(GTK_WIDGET(content_box));
1683 gtk_container_add(GTK_CONTAINER(fe->cfgbox), GTK_WIDGET(content_box));
1684 button_box = GTK_BOX(gtk_hbox_new(FALSE, 8));
1685 gtk_widget_show(GTK_WIDGET(button_box));
1686 gtk_box_pack_end(content_box, GTK_WIDGET(button_box), FALSE, FALSE, 0);
1688 GtkWidget *sep = gtk_separator_new(GTK_ORIENTATION_HORIZONTAL);
1689 gtk_widget_show(sep);
1690 gtk_box_pack_end(content_box, sep, FALSE, FALSE, 0);
1693 fe->cfgbox = gtk_dialog_new();
1694 content_box = GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(fe->cfgbox)));
1695 button_box = GTK_BOX(gtk_dialog_get_action_area(GTK_DIALOG(fe->cfgbox)));
1697 gtk_window_set_title(GTK_WINDOW(fe->cfgbox), title);
1700 w = gtk_button_new_with_our_label(LABEL_CANCEL);
1701 gtk_box_pack_end(button_box, w, FALSE, FALSE, 0);
1703 g_signal_connect(G_OBJECT(w), "clicked",
1704 G_CALLBACK(config_cancel_button_clicked), fe);
1707 w = gtk_button_new_with_our_label(LABEL_OK);
1708 gtk_box_pack_end(button_box, w, FALSE, FALSE, 0);
1710 gtk_widget_set_can_default(w, TRUE);
1711 gtk_window_set_default(GTK_WINDOW(fe->cfgbox), w);
1712 g_signal_connect(G_OBJECT(w), "clicked",
1713 G_CALLBACK(config_ok_button_clicked), fe);
1715 #if GTK_CHECK_VERSION(3,0,0)
1716 table = gtk_grid_new();
1718 table = gtk_table_new(1, 2, FALSE);
1721 gtk_box_pack_start(content_box, table, FALSE, FALSE, 0);
1722 gtk_widget_show(table);
1724 for (i = fe->cfg; i->type != C_END; i++) {
1725 #if !GTK_CHECK_VERSION(3,0,0)
1726 gtk_table_resize(GTK_TABLE(table), y+1, 2);
1732 * Edit box with a label beside it.
1735 w = gtk_label_new(i->name);
1736 align_label(GTK_LABEL(w), 0.0, 0.5);
1737 #if GTK_CHECK_VERSION(3,0,0)
1738 gtk_grid_attach(GTK_GRID(table), w, 0, y, 1, 1);
1740 gtk_table_attach(GTK_TABLE(table), w, 0, 1, y, y+1,
1741 GTK_SHRINK | GTK_FILL,
1742 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1747 w = gtk_entry_new();
1748 #if GTK_CHECK_VERSION(3,0,0)
1749 gtk_grid_attach(GTK_GRID(table), w, 1, y, 1, 1);
1750 g_object_set(G_OBJECT(w), "hexpand", TRUE, (const char *)NULL);
1752 gtk_table_attach(GTK_TABLE(table), w, 1, 2, y, y+1,
1753 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1754 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1757 gtk_entry_set_text(GTK_ENTRY(w), i->u.string.sval);
1758 g_signal_connect(G_OBJECT(w), "changed",
1759 G_CALLBACK(editbox_changed), i);
1760 g_signal_connect(G_OBJECT(w), "key_press_event",
1761 G_CALLBACK(editbox_key), NULL);
1770 w = gtk_check_button_new_with_label(i->name);
1771 g_signal_connect(G_OBJECT(w), "toggled",
1772 G_CALLBACK(button_toggled), i);
1773 #if GTK_CHECK_VERSION(3,0,0)
1774 gtk_grid_attach(GTK_GRID(table), w, 0, y, 2, 1);
1775 g_object_set(G_OBJECT(w), "hexpand", TRUE, (const char *)NULL);
1777 gtk_table_attach(GTK_TABLE(table), w, 0, 2, y, y+1,
1778 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1779 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1782 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(w),
1789 * Drop-down list (GtkComboBox).
1792 w = gtk_label_new(i->name);
1793 align_label(GTK_LABEL(w), 0.0, 0.5);
1794 #if GTK_CHECK_VERSION(3,0,0)
1795 gtk_grid_attach(GTK_GRID(table), w, 0, y, 1, 1);
1797 gtk_table_attach(GTK_TABLE(table), w, 0, 1, y, y+1,
1798 GTK_SHRINK | GTK_FILL,
1799 GTK_EXPAND | GTK_SHRINK | GTK_FILL ,
1808 GtkListStore *model;
1809 GtkCellRenderer *cr;
1812 model = gtk_list_store_new(1, G_TYPE_STRING);
1814 c = *i->u.choices.choicenames;
1815 p = i->u.choices.choicenames+1;
1819 while (*q && *q != c)
1822 name = snewn(q-p+1, char);
1823 strncpy(name, p, q-p);
1826 if (*q) q++; /* eat delimiter */
1828 gtk_list_store_append(model, &iter);
1829 gtk_list_store_set(model, &iter, 0, name, -1);
1834 w = gtk_combo_box_new_with_model(GTK_TREE_MODEL(model));
1836 gtk_combo_box_set_active(GTK_COMBO_BOX(w),
1837 i->u.choices.selected);
1839 cr = gtk_cell_renderer_text_new();
1840 gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(w), cr, TRUE);
1841 gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(w), cr,
1844 g_signal_connect(G_OBJECT(w), "changed",
1845 G_CALLBACK(droplist_sel), i);
1848 #if GTK_CHECK_VERSION(3,0,0)
1849 gtk_grid_attach(GTK_GRID(table), w, 1, y, 1, 1);
1850 g_object_set(G_OBJECT(w), "hexpand", TRUE, (const char *)NULL);
1852 gtk_table_attach(GTK_TABLE(table), w, 1, 2, y, y+1,
1853 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1854 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1864 g_signal_connect(G_OBJECT(fe->cfgbox), "destroy",
1865 G_CALLBACK(window_destroy), NULL);
1866 g_signal_connect(G_OBJECT(fe->cfgbox), "key_press_event",
1867 G_CALLBACK(win_key_press), cancel);
1868 gtk_window_set_modal(GTK_WINDOW(fe->cfgbox), TRUE);
1869 gtk_window_set_transient_for(GTK_WINDOW(fe->cfgbox),
1870 GTK_WINDOW(fe->window));
1871 /* set_transient_window_pos(fe->window, fe->cfgbox); */
1872 gtk_widget_show(fe->cfgbox);
1880 static void menu_key_event(GtkMenuItem *menuitem, gpointer data)
1882 frontend *fe = (frontend *)data;
1883 int key = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(menuitem),
1885 if (!midend_process_key(fe->me, 0, 0, key))
1886 gtk_widget_destroy(fe->window);
1889 static void get_size(frontend *fe, int *px, int *py)
1894 * Currently I don't want to make the GTK port scale large
1895 * puzzles to fit on the screen. This is because X does permit
1896 * extremely large windows and many window managers provide a
1897 * means of navigating round them, and the users I consulted
1898 * before deciding said that they'd rather have enormous puzzle
1899 * windows spanning multiple screen pages than have them
1900 * shrunk. I could change my mind later or introduce
1901 * configurability; this would be the place to do so, by
1902 * replacing the initial values of x and y with the screen
1907 midend_size(fe->me, &x, &y, FALSE);
1912 #if !GTK_CHECK_VERSION(2,0,0)
1913 #define gtk_window_resize(win, x, y) \
1914 gdk_window_resize(GTK_WIDGET(win)->window, x, y)
1918 * Called when any other code in this file has changed the
1919 * selected game parameters.
1921 static void changed_preset(frontend *fe)
1923 int n = midend_which_preset(fe->me);
1925 fe->preset_threaded = TRUE;
1926 if (n < 0 && fe->preset_custom) {
1927 gtk_check_menu_item_set_active(
1928 GTK_CHECK_MENU_ITEM(fe->preset_custom),
1931 GSList *gs = fe->preset_radio;
1932 GSList *found = NULL;
1934 for (gs = fe->preset_radio; gs; gs = gs->next) {
1935 struct preset_menu_entry *entry =
1936 (struct preset_menu_entry *)g_object_get_data(
1937 G_OBJECT(gs->data), "user-data");
1938 if (!entry || entry->id != n)
1939 gtk_check_menu_item_set_active(
1940 GTK_CHECK_MENU_ITEM(gs->data), FALSE);
1945 gtk_check_menu_item_set_active(
1946 GTK_CHECK_MENU_ITEM(found->data), TRUE);
1948 fe->preset_threaded = FALSE;
1951 * Update the greying on the Copy menu option.
1953 if (fe->copy_menu_item) {
1954 int enabled = midend_can_format_as_text_now(fe->me);
1955 gtk_widget_set_sensitive(fe->copy_menu_item, enabled);
1959 #if !GTK_CHECK_VERSION(3,0,0)
1960 static gboolean not_size_allocated_yet(GtkWidget *w)
1963 * This function tests whether a widget has not yet taken up space
1964 * on the screen which it will occupy in future. (Therefore, it
1965 * returns true only if the widget does exist but does not have a
1966 * size allocation. A null widget is already taking up all the
1967 * space it ever will.)
1970 return FALSE; /* nonexistent widgets aren't a problem */
1972 #if GTK_CHECK_VERSION(2,18,0) /* skip if no gtk_widget_get_allocation */
1975 gtk_widget_get_allocation(w, &a);
1976 if (a.height == 0 || a.width == 0)
1977 return TRUE; /* widget exists but has no size yet */
1984 static void try_shrink_drawing_area(frontend *fe)
1986 if (fe->drawing_area_shrink_pending &&
1987 (!fe->menubar_is_local || !not_size_allocated_yet(fe->menubar)) &&
1988 !not_size_allocated_yet(fe->statusbar)) {
1990 * In order to permit the user to resize the window smaller as
1991 * well as bigger, we call this function after the window size
1992 * has ended up where we want it. This shouldn't shrink the
1993 * window immediately; it just arranges that the next time the
1994 * user tries to shrink it, they can.
1996 * However, at puzzle creation time, we defer the first of
1997 * these operations until after the menu bar and status bar
1998 * are actually visible. On Ubuntu 12.04 I've found that these
1999 * can take a while to be displayed, and that it's a mistake
2000 * to reduce the drawing area's size allocation before they've
2001 * turned up or else the drawing area makes room for them by
2002 * shrinking to less than the size we intended.
2004 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), 1, 1);
2005 fe->drawing_area_shrink_pending = FALSE;
2008 #endif /* !GTK_CHECK_VERSION(3,0,0) */
2010 static gint configure_window(GtkWidget *widget,
2011 GdkEventConfigure *event, gpointer data)
2013 #if !GTK_CHECK_VERSION(3,0,0)
2015 * When the main puzzle window changes size, it might be because
2016 * the menu bar or status bar has turned up after starting off
2017 * absent, in which case we should have another go at enacting a
2018 * pending shrink of the drawing area.
2020 frontend *fe = (frontend *)data;
2021 try_shrink_drawing_area(fe);
2026 #if GTK_CHECK_VERSION(3,0,0)
2027 static int window_extra_height(frontend *fe)
2032 gtk_widget_get_preferred_size(fe->menubar, &req, NULL);
2035 if (fe->statusbar) {
2037 gtk_widget_get_preferred_size(fe->statusbar, &req, NULL);
2044 static void resize_fe(frontend *fe)
2048 get_size(fe, &x, &y);
2050 #if GTK_CHECK_VERSION(3,0,0)
2051 gtk_window_resize(GTK_WINDOW(fe->window), x, y + window_extra_height(fe));
2052 fe->awaiting_resize_ack = TRUE;
2054 fe->drawing_area_shrink_pending = FALSE;
2055 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
2058 gtk_widget_size_request(GTK_WIDGET(fe->window), &req);
2059 gtk_window_resize(GTK_WINDOW(fe->window), req.width, req.height);
2061 fe->drawing_area_shrink_pending = TRUE;
2062 try_shrink_drawing_area(fe);
2066 static void menu_preset_event(GtkMenuItem *menuitem, gpointer data)
2068 frontend *fe = (frontend *)data;
2069 struct preset_menu_entry *entry =
2070 (struct preset_menu_entry *)g_object_get_data(
2071 G_OBJECT(menuitem), "user-data");
2073 if (fe->preset_threaded ||
2074 (GTK_IS_CHECK_MENU_ITEM(menuitem) &&
2075 !gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(menuitem))))
2077 midend_set_params(fe->me, entry->params);
2078 midend_new_game(fe->me);
2081 midend_redraw(fe->me);
2084 GdkAtom compound_text_atom, utf8_string_atom;
2085 int paste_initialised = FALSE;
2087 static void set_selection(frontend *fe, GdkAtom selection)
2089 if (!paste_initialised) {
2090 compound_text_atom = gdk_atom_intern("COMPOUND_TEXT", FALSE);
2091 utf8_string_atom = gdk_atom_intern("UTF8_STRING", FALSE);
2092 paste_initialised = TRUE;
2096 * For this simple application we can safely assume that the
2097 * data passed to this function is pure ASCII, which means we
2098 * can return precisely the same stuff for types STRING,
2099 * COMPOUND_TEXT or UTF8_STRING.
2102 if (gtk_selection_owner_set(fe->area, selection, CurrentTime)) {
2103 gtk_selection_clear_targets(fe->area, selection);
2104 gtk_selection_add_target(fe->area, selection,
2105 GDK_SELECTION_TYPE_STRING, 1);
2106 gtk_selection_add_target(fe->area, selection, compound_text_atom, 1);
2107 gtk_selection_add_target(fe->area, selection, utf8_string_atom, 1);
2111 void write_clip(frontend *fe, char *data)
2114 sfree(fe->paste_data);
2116 fe->paste_data = data;
2117 fe->paste_data_len = strlen(data);
2119 set_selection(fe, GDK_SELECTION_PRIMARY);
2120 set_selection(fe, GDK_SELECTION_CLIPBOARD);
2123 void selection_get(GtkWidget *widget, GtkSelectionData *seldata,
2124 guint info, guint time_stamp, gpointer data)
2126 frontend *fe = (frontend *)data;
2127 gtk_selection_data_set(seldata, gtk_selection_data_get_target(seldata), 8,
2128 fe->paste_data, fe->paste_data_len);
2131 gint selection_clear(GtkWidget *widget, GdkEventSelection *seldata,
2134 frontend *fe = (frontend *)data;
2137 sfree(fe->paste_data);
2138 fe->paste_data = NULL;
2139 fe->paste_data_len = 0;
2143 static void menu_copy_event(GtkMenuItem *menuitem, gpointer data)
2145 frontend *fe = (frontend *)data;
2148 text = midend_text_format(fe->me);
2151 write_clip(fe, text);
2159 static void filesel_ok(GtkButton *button, gpointer data)
2161 frontend *fe = (frontend *)data;
2163 gpointer filesel = g_object_get_data(G_OBJECT(button), "user-data");
2166 gtk_file_selection_get_filename(GTK_FILE_SELECTION(filesel));
2168 fe->filesel_name = dupstr(name);
2171 static char *file_selector(frontend *fe, char *title, int save)
2173 GtkWidget *filesel =
2174 gtk_file_selection_new(title);
2176 fe->filesel_name = NULL;
2178 gtk_window_set_modal(GTK_WINDOW(filesel), TRUE);
2180 (G_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "user-data",
2183 (G_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "clicked",
2184 G_CALLBACK(filesel_ok), fe);
2185 g_signal_connect_swapped
2186 (G_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "clicked",
2187 G_CALLBACK(gtk_widget_destroy), (gpointer)filesel);
2188 g_signal_connect_object
2189 (G_OBJECT(GTK_FILE_SELECTION(filesel)->cancel_button), "clicked",
2190 G_CALLBACK(gtk_widget_destroy), (gpointer)filesel);
2191 g_signal_connect(G_OBJECT(filesel), "destroy",
2192 G_CALLBACK(window_destroy), NULL);
2193 gtk_widget_show(filesel);
2194 gtk_window_set_transient_for(GTK_WINDOW(filesel), GTK_WINDOW(fe->window));
2197 return fe->filesel_name;
2202 static char *file_selector(frontend *fe, char *title, int save)
2204 char *filesel_name = NULL;
2206 GtkWidget *filesel =
2207 gtk_file_chooser_dialog_new(title,
2208 GTK_WINDOW(fe->window),
2209 save ? GTK_FILE_CHOOSER_ACTION_SAVE :
2210 GTK_FILE_CHOOSER_ACTION_OPEN,
2211 LABEL_CANCEL, GTK_RESPONSE_CANCEL,
2212 save ? LABEL_SAVE : LABEL_OPEN,
2213 GTK_RESPONSE_ACCEPT,
2216 if (gtk_dialog_run(GTK_DIALOG(filesel)) == GTK_RESPONSE_ACCEPT) {
2217 char *name = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(filesel));
2218 filesel_name = dupstr(name);
2222 gtk_widget_destroy(filesel);
2224 return filesel_name;
2229 struct savefile_write_ctx {
2234 static void savefile_write(void *wctx, void *buf, int len)
2236 struct savefile_write_ctx *ctx = (struct savefile_write_ctx *)wctx;
2237 if (fwrite(buf, 1, len, ctx->fp) < len)
2241 static int savefile_read(void *wctx, void *buf, int len)
2243 FILE *fp = (FILE *)wctx;
2246 ret = fread(buf, 1, len, fp);
2247 return (ret == len);
2250 static void menu_save_event(GtkMenuItem *menuitem, gpointer data)
2252 frontend *fe = (frontend *)data;
2255 name = file_selector(fe, "Enter name of game file to save", TRUE);
2260 if ((fp = fopen(name, "r")) != NULL) {
2261 char buf[256 + FILENAME_MAX];
2265 sprintf(buf, "Are you sure you want to overwrite the"
2267 FILENAME_MAX, name);
2268 if (!message_box(fe->window, "Question", buf, TRUE, MB_YESNO))
2269 goto free_and_return;
2272 fp = fopen(name, "w");
2275 error_box(fe->window, "Unable to open save file");
2276 goto free_and_return;
2280 struct savefile_write_ctx ctx;
2283 midend_serialise(fe->me, savefile_write, &ctx);
2287 sprintf(boxmsg, "Error writing save file: %.400s",
2289 error_box(fe->window, boxmsg);
2290 goto free_and_return;
2298 static void menu_load_event(GtkMenuItem *menuitem, gpointer data)
2300 frontend *fe = (frontend *)data;
2304 name = file_selector(fe, "Enter name of saved game file to load", FALSE);
2307 FILE *fp = fopen(name, "r");
2311 error_box(fe->window, "Unable to open saved game file");
2315 err = midend_deserialise(fe->me, savefile_read, fp);
2320 error_box(fe->window, err);
2326 midend_redraw(fe->me);
2330 static void menu_solve_event(GtkMenuItem *menuitem, gpointer data)
2332 frontend *fe = (frontend *)data;
2335 msg = midend_solve(fe->me);
2338 error_box(fe->window, msg);
2341 static void menu_restart_event(GtkMenuItem *menuitem, gpointer data)
2343 frontend *fe = (frontend *)data;
2345 midend_restart_game(fe->me);
2348 static void menu_config_event(GtkMenuItem *menuitem, gpointer data)
2350 frontend *fe = (frontend *)data;
2351 int which = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(menuitem),
2354 if (fe->preset_threaded ||
2355 (GTK_IS_CHECK_MENU_ITEM(menuitem) &&
2356 !gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(menuitem))))
2358 changed_preset(fe); /* Put the old preset back! */
2359 if (!get_config(fe, which))
2362 midend_new_game(fe->me);
2364 midend_redraw(fe->me);
2367 static void menu_about_event(GtkMenuItem *menuitem, gpointer data)
2369 frontend *fe = (frontend *)data;
2371 #if GTK_CHECK_VERSION(3,0,0)
2372 extern char *const *const xpm_icons[];
2373 extern const int n_xpm_icons;
2374 GdkPixbuf *icon = gdk_pixbuf_new_from_xpm_data
2375 ((const gchar **)xpm_icons[n_xpm_icons-1]);
2376 gtk_show_about_dialog
2377 (GTK_WINDOW(fe->window),
2378 "program-name", thegame.name,
2380 "comments", "Part of Simon Tatham's Portable Puzzle Collection",
2382 (const gchar *)NULL);
2383 g_object_unref(G_OBJECT(icon));
2388 sprintf(titlebuf, "About %.200s", thegame.name);
2391 "from Simon Tatham's Portable Puzzle Collection\n\n"
2392 "%.500s", thegame.name, ver);
2394 message_box(fe->window, titlebuf, textbuf, TRUE, MB_OK);
2398 static GtkWidget *add_menu_ui_item(
2399 frontend *fe, GtkContainer *cont, char *text, int action,
2400 int accel_key, int accel_keyqual)
2402 GtkWidget *menuitem = gtk_menu_item_new_with_label(text);
2403 gtk_container_add(cont, menuitem);
2404 g_object_set_data(G_OBJECT(menuitem), "user-data",
2405 GINT_TO_POINTER(action));
2406 g_signal_connect(G_OBJECT(menuitem), "activate",
2407 G_CALLBACK(menu_key_event), fe);
2411 * Display a keyboard accelerator alongside this menu item.
2412 * Actually this won't be processed via the usual GTK
2413 * accelerator system, because we add it to a dummy
2414 * accelerator group which is never actually activated on the
2415 * main window; this permits back ends to override special
2416 * keys like 'n' and 'r' and 'u' in some UI states. So
2417 * whatever keystroke we display here will still go to
2418 * key_event and be handled in the normal way.
2420 gtk_widget_add_accelerator(menuitem,
2421 "activate", fe->dummy_accelgroup,
2422 accel_key, accel_keyqual,
2423 GTK_ACCEL_VISIBLE | GTK_ACCEL_LOCKED);
2426 gtk_widget_show(menuitem);
2430 static void add_menu_separator(GtkContainer *cont)
2432 GtkWidget *menuitem = gtk_menu_item_new();
2433 gtk_container_add(cont, menuitem);
2434 gtk_widget_show(menuitem);
2437 static void populate_gtk_preset_menu(frontend *fe, struct preset_menu *menu,
2442 for (i = 0; i < menu->n_entries; i++) {
2443 struct preset_menu_entry *entry = &menu->entries[i];
2444 GtkWidget *menuitem;
2446 if (entry->params) {
2447 menuitem = gtk_radio_menu_item_new_with_label(
2448 fe->preset_radio, entry->title);
2449 fe->preset_radio = gtk_radio_menu_item_get_group(
2450 GTK_RADIO_MENU_ITEM(menuitem));
2451 g_object_set_data(G_OBJECT(menuitem), "user-data", entry);
2452 g_signal_connect(G_OBJECT(menuitem), "activate",
2453 G_CALLBACK(menu_preset_event), fe);
2456 menuitem = gtk_menu_item_new_with_label(entry->title);
2457 submenu = gtk_menu_new();
2458 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), submenu);
2459 populate_gtk_preset_menu(fe, entry->submenu, submenu);
2462 gtk_container_add(GTK_CONTAINER(gtkmenu), menuitem);
2463 gtk_widget_show(menuitem);
2467 enum { ARG_EITHER, ARG_SAVE, ARG_ID }; /* for argtype */
2469 static frontend *new_window(char *arg, int argtype, char **error)
2472 GtkBox *vbox, *hbox;
2473 GtkWidget *menu, *menuitem;
2477 extern char *const *const xpm_icons[];
2478 extern const int n_xpm_icons;
2479 struct preset_menu *preset_menu;
2481 fe = snew(frontend);
2482 #if GTK_CHECK_VERSION(3,20,0)
2483 fe->css_provider = NULL;
2486 fe->timer_active = FALSE;
2489 fe->me = midend_new(fe, &thegame, >k_drawing, fe);
2499 err = midend_game_id(fe->me, arg);
2501 midend_new_game(fe->me);
2503 sprintf(errbuf, "Invalid game ID: %.800s", err);
2506 fp = fopen(arg, "r");
2508 sprintf(errbuf, "Error opening file: %.800s", strerror(errno));
2510 err = midend_deserialise(fe->me, savefile_read, fp);
2512 sprintf(errbuf, "Invalid save file: %.800s", err);
2516 default /*case ARG_EITHER*/:
2518 * First try treating the argument as a game ID.
2520 err = midend_game_id(fe->me, arg);
2523 * It's a valid game ID.
2525 midend_new_game(fe->me);
2527 FILE *fp = fopen(arg, "r");
2529 sprintf(errbuf, "Supplied argument is neither a game ID (%.400s)"
2530 " nor a save file (%.400s)", err, strerror(errno));
2532 err = midend_deserialise(fe->me, savefile_read, fp);
2534 sprintf(errbuf, "%.800s", err);
2541 *error = dupstr(errbuf);
2542 midend_free(fe->me);
2548 midend_new_game(fe->me);
2551 #if !GTK_CHECK_VERSION(3,0,0)
2554 * try_shrink_drawing_area() will do some fiddling with the
2555 * window size request (see comment in that function) after
2556 * all the bits and pieces such as the menu bar and status bar
2557 * have appeared in the puzzle window.
2559 * However, on Unity systems, the menu bar _doesn't_ appear in
2560 * the puzzle window, because the Unity shell hijacks it into
2561 * the menu bar at the very top of the screen. We therefore
2562 * try to detect that situation here, so that we don't sit
2563 * here forever waiting for a menu bar.
2565 const char prop[] = "gtk-shell-shows-menubar";
2566 GtkSettings *settings = gtk_settings_get_default();
2567 if (!g_object_class_find_property(G_OBJECT_GET_CLASS(settings),
2569 fe->menubar_is_local = TRUE;
2572 g_object_get(gtk_settings_get_default(),
2574 (const gchar *)NULL);
2575 fe->menubar_is_local = !unity_mode;
2580 #if GTK_CHECK_VERSION(3,0,0)
2581 fe->awaiting_resize_ack = FALSE;
2584 fe->window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
2585 gtk_window_set_title(GTK_WINDOW(fe->window), thegame.name);
2587 vbox = GTK_BOX(gtk_vbox_new(FALSE, 0));
2588 gtk_container_add(GTK_CONTAINER(fe->window), GTK_WIDGET(vbox));
2589 gtk_widget_show(GTK_WIDGET(vbox));
2591 fe->dummy_accelgroup = gtk_accel_group_new();
2593 * Intentionally _not_ added to the window via
2594 * gtk_window_add_accel_group; see menu_key_event
2597 hbox = GTK_BOX(gtk_hbox_new(FALSE, 0));
2598 gtk_box_pack_start(vbox, GTK_WIDGET(hbox), FALSE, FALSE, 0);
2599 gtk_widget_show(GTK_WIDGET(hbox));
2601 fe->menubar = gtk_menu_bar_new();
2602 gtk_box_pack_start(hbox, fe->menubar, TRUE, TRUE, 0);
2603 gtk_widget_show(fe->menubar);
2605 menuitem = gtk_menu_item_new_with_mnemonic("_Game");
2606 gtk_container_add(GTK_CONTAINER(fe->menubar), menuitem);
2607 gtk_widget_show(menuitem);
2609 menu = gtk_menu_new();
2610 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
2612 add_menu_ui_item(fe, GTK_CONTAINER(menu), "New", UI_NEWGAME, 'n', 0);
2614 menuitem = gtk_menu_item_new_with_label("Restart");
2615 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2616 g_signal_connect(G_OBJECT(menuitem), "activate",
2617 G_CALLBACK(menu_restart_event), fe);
2618 gtk_widget_show(menuitem);
2620 menuitem = gtk_menu_item_new_with_label("Specific...");
2621 g_object_set_data(G_OBJECT(menuitem), "user-data",
2622 GINT_TO_POINTER(CFG_DESC));
2623 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2624 g_signal_connect(G_OBJECT(menuitem), "activate",
2625 G_CALLBACK(menu_config_event), fe);
2626 gtk_widget_show(menuitem);
2628 menuitem = gtk_menu_item_new_with_label("Random Seed...");
2629 g_object_set_data(G_OBJECT(menuitem), "user-data",
2630 GINT_TO_POINTER(CFG_SEED));
2631 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2632 g_signal_connect(G_OBJECT(menuitem), "activate",
2633 G_CALLBACK(menu_config_event), fe);
2634 gtk_widget_show(menuitem);
2636 fe->preset_radio = NULL;
2637 fe->preset_custom = NULL;
2638 fe->preset_threaded = FALSE;
2640 preset_menu = midend_get_presets(fe->me, NULL);
2641 if (preset_menu->n_entries > 0 || thegame.can_configure) {
2644 menuitem = gtk_menu_item_new_with_mnemonic("_Type");
2645 gtk_container_add(GTK_CONTAINER(fe->menubar), menuitem);
2646 gtk_widget_show(menuitem);
2648 submenu = gtk_menu_new();
2649 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), submenu);
2651 populate_gtk_preset_menu(fe, preset_menu, submenu);
2653 if (thegame.can_configure) {
2654 menuitem = fe->preset_custom =
2655 gtk_radio_menu_item_new_with_label(fe->preset_radio,
2658 gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(menuitem));
2659 gtk_container_add(GTK_CONTAINER(submenu), menuitem);
2660 g_object_set_data(G_OBJECT(menuitem), "user-data",
2661 GINT_TO_POINTER(CFG_SETTINGS));
2662 g_signal_connect(G_OBJECT(menuitem), "activate",
2663 G_CALLBACK(menu_config_event), fe);
2664 gtk_widget_show(menuitem);
2669 add_menu_separator(GTK_CONTAINER(menu));
2670 menuitem = gtk_menu_item_new_with_label("Load...");
2671 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2672 g_signal_connect(G_OBJECT(menuitem), "activate",
2673 G_CALLBACK(menu_load_event), fe);
2674 gtk_widget_show(menuitem);
2675 menuitem = gtk_menu_item_new_with_label("Save...");
2676 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2677 g_signal_connect(G_OBJECT(menuitem), "activate",
2678 G_CALLBACK(menu_save_event), fe);
2679 gtk_widget_show(menuitem);
2680 #ifndef STYLUS_BASED
2681 add_menu_separator(GTK_CONTAINER(menu));
2682 add_menu_ui_item(fe, GTK_CONTAINER(menu), "Undo", UI_UNDO, 'u', 0);
2683 add_menu_ui_item(fe, GTK_CONTAINER(menu), "Redo", UI_REDO, 'r', 0);
2685 if (thegame.can_format_as_text_ever) {
2686 add_menu_separator(GTK_CONTAINER(menu));
2687 menuitem = gtk_menu_item_new_with_label("Copy");
2688 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2689 g_signal_connect(G_OBJECT(menuitem), "activate",
2690 G_CALLBACK(menu_copy_event), fe);
2691 gtk_widget_show(menuitem);
2692 fe->copy_menu_item = menuitem;
2694 fe->copy_menu_item = NULL;
2696 if (thegame.can_solve) {
2697 add_menu_separator(GTK_CONTAINER(menu));
2698 menuitem = gtk_menu_item_new_with_label("Solve");
2699 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2700 g_signal_connect(G_OBJECT(menuitem), "activate",
2701 G_CALLBACK(menu_solve_event), fe);
2702 gtk_widget_show(menuitem);
2704 add_menu_separator(GTK_CONTAINER(menu));
2705 add_menu_ui_item(fe, GTK_CONTAINER(menu), "Exit", UI_QUIT, 'q', 0);
2707 menuitem = gtk_menu_item_new_with_mnemonic("_Help");
2708 gtk_container_add(GTK_CONTAINER(fe->menubar), menuitem);
2709 gtk_widget_show(menuitem);
2711 menu = gtk_menu_new();
2712 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
2714 menuitem = gtk_menu_item_new_with_label("About");
2715 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2716 g_signal_connect(G_OBJECT(menuitem), "activate",
2717 G_CALLBACK(menu_about_event), fe);
2718 gtk_widget_show(menuitem);
2721 menuitem=gtk_button_new_with_mnemonic("_Redo");
2722 g_object_set_data(G_OBJECT(menuitem), "user-data",
2723 GINT_TO_POINTER(UI_REDO));
2724 g_signal_connect(G_OBJECT(menuitem), "clicked",
2725 G_CALLBACK(menu_key_event), fe);
2726 gtk_box_pack_end(hbox, menuitem, FALSE, FALSE, 0);
2727 gtk_widget_show(menuitem);
2729 menuitem=gtk_button_new_with_mnemonic("_Undo");
2730 g_object_set_data(G_OBJECT(menuitem), "user-data",
2731 GINT_TO_POINTER(UI_UNDO));
2732 g_signal_connect(G_OBJECT(menuitem), "clicked",
2733 G_CALLBACK(menu_key_event), fe);
2734 gtk_box_pack_end(hbox, menuitem, FALSE, FALSE, 0);
2735 gtk_widget_show(menuitem);
2737 if (thegame.flags & REQUIRE_NUMPAD) {
2738 hbox = GTK_BOX(gtk_hbox_new(FALSE, 0));
2739 gtk_box_pack_start(vbox, GTK_WIDGET(hbox), FALSE, FALSE, 0);
2740 gtk_widget_show(GTK_WIDGET(hbox));
2744 for(errbuf[0]='0';errbuf[0]<='9';errbuf[0]++) {
2745 menuitem=gtk_button_new_with_label(errbuf);
2746 g_object_set_data(G_OBJECT(menuitem), "user-data",
2747 GINT_TO_POINTER((int)(errbuf[0])));
2748 g_signal_connect(G_OBJECT(menuitem), "clicked",
2749 G_CALLBACK(menu_key_event), fe);
2750 gtk_box_pack_start(hbox, menuitem, TRUE, TRUE, 0);
2751 gtk_widget_show(menuitem);
2754 #endif /* STYLUS_BASED */
2758 snaffle_colours(fe);
2760 if (midend_wants_statusbar(fe->me)) {
2761 GtkWidget *viewport;
2764 viewport = gtk_viewport_new(NULL, NULL);
2765 gtk_viewport_set_shadow_type(GTK_VIEWPORT(viewport), GTK_SHADOW_NONE);
2766 fe->statusbar = gtk_statusbar_new();
2767 gtk_container_add(GTK_CONTAINER(viewport), fe->statusbar);
2768 gtk_widget_show(viewport);
2769 gtk_box_pack_end(vbox, viewport, FALSE, FALSE, 0);
2770 gtk_widget_show(fe->statusbar);
2771 fe->statusctx = gtk_statusbar_get_context_id
2772 (GTK_STATUSBAR(fe->statusbar), "game");
2773 gtk_statusbar_push(GTK_STATUSBAR(fe->statusbar), fe->statusctx,
2774 DEFAULT_STATUSBAR_TEXT);
2775 #if GTK_CHECK_VERSION(3,0,0)
2776 gtk_widget_get_preferred_size(fe->statusbar, &req, NULL);
2778 gtk_widget_size_request(fe->statusbar, &req);
2780 gtk_widget_set_size_request(viewport, -1, req.height);
2782 fe->statusbar = NULL;
2784 fe->area = gtk_drawing_area_new();
2785 #if GTK_CHECK_VERSION(2,0,0) && !GTK_CHECK_VERSION(3,0,0)
2786 gtk_widget_set_double_buffered(fe->area, FALSE);
2790 geom.base_width = 0;
2791 #if GTK_CHECK_VERSION(3,0,0)
2792 geom.base_height = window_extra_height(fe);
2793 gtk_window_set_geometry_hints(GTK_WINDOW(fe->window), NULL,
2794 &geom, GDK_HINT_BASE_SIZE);
2796 geom.base_height = 0;
2797 gtk_window_set_geometry_hints(GTK_WINDOW(fe->window), fe->area,
2798 &geom, GDK_HINT_BASE_SIZE);
2803 get_size(fe, &x, &y);
2804 #if GTK_CHECK_VERSION(3,0,0)
2805 gtk_window_set_default_size(GTK_WINDOW(fe->window),
2806 x, y + window_extra_height(fe));
2808 fe->drawing_area_shrink_pending = FALSE;
2809 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
2812 gtk_box_pack_end(vbox, fe->area, TRUE, TRUE, 0);
2814 clear_backing_store(fe);
2816 fe->nfonts = fe->fontsize = 0;
2818 fe->paste_data = NULL;
2819 fe->paste_data_len = 0;
2821 g_signal_connect(G_OBJECT(fe->window), "destroy",
2822 G_CALLBACK(destroy), fe);
2823 g_signal_connect(G_OBJECT(fe->window), "key_press_event",
2824 G_CALLBACK(key_event), fe);
2825 g_signal_connect(G_OBJECT(fe->area), "button_press_event",
2826 G_CALLBACK(button_event), fe);
2827 g_signal_connect(G_OBJECT(fe->area), "button_release_event",
2828 G_CALLBACK(button_event), fe);
2829 g_signal_connect(G_OBJECT(fe->area), "motion_notify_event",
2830 G_CALLBACK(motion_event), fe);
2831 g_signal_connect(G_OBJECT(fe->area), "selection_get",
2832 G_CALLBACK(selection_get), fe);
2833 g_signal_connect(G_OBJECT(fe->area), "selection_clear_event",
2834 G_CALLBACK(selection_clear), fe);
2835 #if GTK_CHECK_VERSION(3,0,0)
2836 g_signal_connect(G_OBJECT(fe->area), "draw",
2837 G_CALLBACK(draw_area), fe);
2839 g_signal_connect(G_OBJECT(fe->area), "expose_event",
2840 G_CALLBACK(expose_area), fe);
2842 g_signal_connect(G_OBJECT(fe->window), "map_event",
2843 G_CALLBACK(map_window), fe);
2844 g_signal_connect(G_OBJECT(fe->area), "configure_event",
2845 G_CALLBACK(configure_area), fe);
2846 g_signal_connect(G_OBJECT(fe->window), "configure_event",
2847 G_CALLBACK(configure_window), fe);
2848 #if GTK_CHECK_VERSION(3,0,0)
2849 g_signal_connect(G_OBJECT(fe->window), "size_allocate",
2850 G_CALLBACK(window_size_alloc), fe);
2853 gtk_widget_add_events(GTK_WIDGET(fe->area),
2854 GDK_BUTTON_PRESS_MASK |
2855 GDK_BUTTON_RELEASE_MASK |
2856 GDK_BUTTON_MOTION_MASK |
2857 GDK_POINTER_MOTION_HINT_MASK);
2860 gtk_window_set_icon(GTK_WINDOW(fe->window),
2861 gdk_pixbuf_new_from_xpm_data
2862 ((const gchar **)xpm_icons[0]));
2865 for (n = 0; n < n_xpm_icons; n++) {
2867 g_list_append(iconlist,
2868 gdk_pixbuf_new_from_xpm_data((const gchar **)
2871 gtk_window_set_icon_list(GTK_WINDOW(fe->window), iconlist);
2874 gtk_widget_show(fe->area);
2875 gtk_widget_show(fe->window);
2877 #if !GTK_CHECK_VERSION(3,0,0)
2878 fe->drawing_area_shrink_pending = TRUE;
2879 try_shrink_drawing_area(fe);
2882 set_window_background(fe, 0);
2887 char *fgetline(FILE *fp)
2889 char *ret = snewn(512, char);
2890 int size = 512, len = 0;
2891 while (fgets(ret + len, size - len, fp)) {
2892 len += strlen(ret + len);
2893 if (ret[len-1] == '\n')
2894 break; /* got a newline, we're done */
2896 ret = sresize(ret, size, char);
2898 if (len == 0) { /* first fgets returned NULL */
2906 static void list_presets_from_menu(struct preset_menu *menu)
2910 for (i = 0; i < menu->n_entries; i++) {
2911 if (menu->entries[i].params) {
2912 char *paramstr = thegame.encode_params(
2913 menu->entries[i].params, TRUE);
2914 printf("%s %s\n", paramstr, menu->entries[i].title);
2917 list_presets_from_menu(menu->entries[i].submenu);
2922 int main(int argc, char **argv)
2924 char *pname = argv[0];
2926 int ngenerate = 0, print = FALSE, px = 1, py = 1;
2927 int time_generation = FALSE, test_solve = FALSE, list_presets = FALSE;
2928 int soln = FALSE, colour = FALSE;
2930 float redo_proportion = 0.0F;
2931 char *savefile = NULL, *savesuffix = NULL;
2933 int argtype = ARG_EITHER;
2934 char *screenshot_file = NULL;
2935 int doing_opts = TRUE;
2941 * Command line parsing in this function is rather fiddly,
2942 * because GTK wants to have a go at argc/argv _first_ - and
2943 * yet we can't let it, because gtk_init() will bomb out if it
2944 * can't open an X display, whereas in fact we want to permit
2945 * our --generate and --print modes to run without an X
2949 * - we parse the command line ourselves, without modifying
2951 * - if we encounter an error which might plausibly be the
2952 * result of a GTK command line (i.e. not detailed errors in
2953 * particular options of ours) we store the error message
2954 * and terminate parsing.
2955 * - if we got enough out of the command line to know it
2956 * specifies a non-X mode of operation, we either display
2957 * the stored error and return failure, or if there is no
2958 * stored error we do the non-X operation and return
2960 * - otherwise, we go straight to gtk_init().
2966 if (doing_opts && !strcmp(p, "--version")) {
2967 printf("%s, from Simon Tatham's Portable Puzzle Collection\n%s\n",
2970 } else if (doing_opts && !strcmp(p, "--generate")) {
2972 ngenerate = atoi(*++av);
2974 fprintf(stderr, "%s: '--generate' expected a number\n",
2980 } else if (doing_opts && !strcmp(p, "--time-generation")) {
2981 time_generation = TRUE;
2982 } else if (doing_opts && !strcmp(p, "--test-solve")) {
2984 } else if (doing_opts && !strcmp(p, "--list-presets")) {
2985 list_presets = TRUE;
2986 } else if (doing_opts && !strcmp(p, "--save")) {
2990 fprintf(stderr, "%s: '--save' expected a filename\n",
2994 } else if (doing_opts && (!strcmp(p, "--save-suffix") ||
2995 !strcmp(p, "--savesuffix"))) {
2999 fprintf(stderr, "%s: '--save-suffix' expected a filename\n",
3003 } else if (doing_opts && !strcmp(p, "--print")) {
3004 if (!thegame.can_print) {
3005 fprintf(stderr, "%s: this game does not support printing\n",
3012 if (sscanf(dim, "%dx%d", &px, &py) != 2) {
3013 fprintf(stderr, "%s: unable to parse argument '%s' to "
3014 "'--print'\n", pname, dim);
3020 } else if (doing_opts && !strcmp(p, "--scale")) {
3022 scale = atof(*++av);
3024 fprintf(stderr, "%s: no argument supplied to '--scale'\n",
3028 } else if (doing_opts && !strcmp(p, "--redo")) {
3030 * This is an internal option which I don't expect
3031 * users to have any particular use for. The effect of
3032 * --redo is that once the game has been loaded and
3033 * initialised, the next move in the redo chain is
3034 * replayed, and the game screen is redrawn part way
3035 * through the making of the move. This is only
3036 * meaningful if there _is_ a next move in the redo
3037 * chain, which means in turn that this option is only
3038 * useful if you're also passing a save file on the
3041 * This option is used by the script which generates
3042 * the puzzle icons and website screenshots, and I
3043 * don't imagine it's useful for anything else.
3044 * (Unless, I suppose, users don't like my screenshots
3045 * and want to generate their own in the same way for
3046 * some repackaged version of the puzzles.)
3049 redo_proportion = atof(*++av);
3051 fprintf(stderr, "%s: no argument supplied to '--redo'\n",
3055 } else if (doing_opts && !strcmp(p, "--screenshot")) {
3057 * Another internal option for the icon building
3058 * script. This causes a screenshot of the central
3059 * drawing area (i.e. not including the menu bar or
3060 * status bar) to be saved to a PNG file once the
3061 * window has been drawn, and then the application
3062 * quits immediately.
3065 screenshot_file = *++av;
3067 fprintf(stderr, "%s: no argument supplied to '--screenshot'\n",
3071 } else if (doing_opts && (!strcmp(p, "--with-solutions") ||
3072 !strcmp(p, "--with-solution") ||
3073 !strcmp(p, "--with-solns") ||
3074 !strcmp(p, "--with-soln") ||
3075 !strcmp(p, "--solutions") ||
3076 !strcmp(p, "--solution") ||
3077 !strcmp(p, "--solns") ||
3078 !strcmp(p, "--soln"))) {
3080 } else if (doing_opts && !strcmp(p, "--colour")) {
3081 if (!thegame.can_print_in_colour) {
3082 fprintf(stderr, "%s: this game does not support colour"
3083 " printing\n", pname);
3087 } else if (doing_opts && !strcmp(p, "--load")) {
3089 } else if (doing_opts && !strcmp(p, "--game")) {
3091 } else if (doing_opts && !strcmp(p, "--")) {
3093 } else if (!doing_opts || p[0] != '-') {
3095 fprintf(stderr, "%s: more than one argument supplied\n",
3101 sprintf(errbuf, "%.100s: unrecognised option '%.100s'\n",
3108 * Special standalone mode for generating puzzle IDs on the
3109 * command line. Useful for generating puzzles to be printed
3110 * out and solved offline (for puzzles where that even makes
3111 * sense - Solo, for example, is a lot more pencil-and-paper
3112 * friendly than Twiddle!)
3116 * <puzzle-name> --generate [<n> [<params>]]
3118 * <n>, if present, is the number of puzzle IDs to generate.
3119 * <params>, if present, is the same type of parameter string
3120 * you would pass to the puzzle when running it in GUI mode,
3121 * including optional extras such as the expansion factor in
3122 * Rectangles and the difficulty level in Solo.
3124 * If you specify <params>, you must also specify <n> (although
3125 * you may specify it to be 1). Sorry; that was the
3126 * simplest-to-parse command-line syntax I came up with.
3128 if (ngenerate > 0 || print || savefile || savesuffix) {
3132 document *doc = NULL;
3135 * If we're in this branch, we should display any pending
3136 * error message from the command line, since GTK isn't going
3137 * to take another crack at making sense of it.
3140 fputs(errbuf, stderr);
3146 me = midend_new(NULL, &thegame, NULL, NULL);
3149 if (savefile && !savesuffix)
3151 if (!savefile && savesuffix)
3155 doc = document_new(px, py, scale);
3158 * In this loop, we either generate a game ID or read one
3159 * from stdin depending on whether we're in generate mode;
3160 * then we either write it to stdout or print it, depending
3161 * on whether we're in print mode. Thus, this loop handles
3162 * generate-to-stdout, print-from-stdin and generate-and-
3163 * immediately-print modes.
3165 * (It could also handle a copy-stdin-to-stdout mode,
3166 * although there's currently no combination of options
3167 * which will cause this loop to be activated in that mode.
3168 * It wouldn't be _entirely_ pointless, though, because
3169 * stdin could contain bare params strings or random-seed
3170 * IDs, and stdout would contain nothing but fully
3171 * generated descriptive game IDs.)
3173 while (ngenerate == 0 || i < n) {
3176 struct rusage before, after;
3178 if (ngenerate == 0) {
3179 pstr = fgetline(stdin);
3182 pstr[strcspn(pstr, "\r\n")] = '\0';
3185 pstr = snewn(strlen(arg) + 40, char);
3188 if (i > 0 && strchr(arg, '#'))
3189 sprintf(pstr + strlen(pstr), "-%d", i);
3195 err = midend_game_id(me, pstr);
3197 fprintf(stderr, "%s: error parsing '%s': %s\n",
3203 if (time_generation)
3204 getrusage(RUSAGE_SELF, &before);
3206 midend_new_game(me);
3208 seed = midend_get_random_seed(me);
3210 if (time_generation) {
3213 getrusage(RUSAGE_SELF, &after);
3215 elapsed = (after.ru_utime.tv_sec -
3216 before.ru_utime.tv_sec);
3217 elapsed += (after.ru_utime.tv_usec -
3218 before.ru_utime.tv_usec) / 1000000.0;
3220 printf("%s %s: %.6f\n", thegame.name, seed, elapsed);
3223 if (test_solve && thegame.can_solve) {
3225 * Now destroy the aux_info in the midend, by means of
3226 * re-entering the same game id, and then try to solve
3231 game_id = midend_get_game_id(me);
3232 err = midend_game_id(me, game_id);
3234 fprintf(stderr, "%s %s: game id re-entry error: %s\n",
3235 thegame.name, seed, err);
3238 midend_new_game(me);
3241 err = midend_solve(me);
3243 * If the solve operation returned the error "Solution
3244 * not known for this puzzle", that's OK, because that
3245 * just means it's a puzzle for which we don't have an
3246 * algorithmic solver and hence can't solve it without
3247 * the aux_info, e.g. Netslide. Any other error is a
3250 if (err && strcmp(err, "Solution not known for this puzzle")) {
3251 fprintf(stderr, "%s %s: solve error: %s\n",
3252 thegame.name, seed, err);
3261 err = midend_print_puzzle(me, doc, soln);
3263 fprintf(stderr, "%s: error in printing: %s\n", pname, err);
3268 struct savefile_write_ctx ctx;
3269 char *realname = snewn(40 + strlen(savefile) +
3270 strlen(savesuffix), char);
3271 sprintf(realname, "%s%d%s", savefile, i, savesuffix);
3274 const char *err = midend_solve(me);
3276 fprintf(stderr, "%s: unable to show solution: %s\n",
3282 ctx.fp = fopen(realname, "w");
3284 fprintf(stderr, "%s: open: %s\n", realname,
3289 midend_serialise(me, savefile_write, &ctx);
3291 fprintf(stderr, "%s: write: %s\n", realname,
3292 strerror(ctx.error));
3295 if (fclose(ctx.fp)) {
3296 fprintf(stderr, "%s: close: %s\n", realname,
3302 if (!doc && !savefile && !time_generation) {
3303 id = midend_get_game_id(me);
3312 psdata *ps = ps_init(stdout, colour);
3313 document_print(doc, ps_drawing_api(ps));
3321 } else if (list_presets) {
3323 * Another specialist mode which causes the puzzle to list the
3324 * game_params strings for all its preset configurations.
3327 struct preset_menu *menu;
3329 me = midend_new(NULL, &thegame, NULL, NULL);
3330 menu = midend_get_presets(me, NULL);
3331 list_presets_from_menu(menu);
3337 gtk_init(&argc, &argv);
3339 fe = new_window(arg, argtype, &error);
3342 fprintf(stderr, "%s: %s\n", pname, error);
3346 if (screenshot_file) {
3348 * Some puzzles will not redraw their entire area if
3349 * given a partially completed animation, which means
3350 * we must redraw now and _then_ redraw again after
3351 * freezing the move timer.
3353 midend_force_redraw(fe->me);
3356 if (redo_proportion) {
3358 midend_process_key(fe->me, 0, 0, 'r');
3359 /* And freeze the timer at the specified position. */
3360 midend_freeze_timer(fe->me, redo_proportion);
3363 if (screenshot_file) {
3364 save_screenshot_png(fe, screenshot_file);