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)
44 /* #undef USE_CAIRO */
45 /* #define NO_THICK_LINE */
47 static FILE *debug_fp = NULL;
52 debug_fp = fopen("debug.log", "w");
63 void debug_printf(char *fmt, ...)
69 vsprintf(buf, fmt, ap);
75 /* ----------------------------------------------------------------------
76 * Error reporting functions used elsewhere.
79 void fatal(char *fmt, ...)
83 fprintf(stderr, "fatal error: ");
86 vfprintf(stderr, fmt, ap);
89 fprintf(stderr, "\n");
93 /* ----------------------------------------------------------------------
94 * GTK front end to puzzles.
97 static void changed_preset(frontend *fe);
101 PangoFontDescription *desc;
110 * This structure holds all the data relevant to a single window.
111 * In principle this would allow us to open multiple independent
112 * puzzle windows, although I can't currently see any real point in
113 * doing so. I'm just coding cleanly because there's no
114 * particularly good reason not to.
118 GtkAccelGroup *accelgroup;
120 GtkWidget *statusbar;
126 const float *colours;
128 cairo_surface_t *image;
130 GdkColor background; /* for painting outside puzzle area */
136 int backgroundindex; /* which of colours[] is background */
139 int bbox_l, bbox_r, bbox_u, bbox_d;
140 int timer_active, timer_id;
141 struct timeval last_time;
143 int nfonts, fontsize;
145 int cfg_which, cfgret;
149 int pw, ph; /* pixmap size (w, h are area size) */
150 int ox, oy; /* offset of pixmap in drawing area */
154 int drawing_area_shrink_pending;
155 GSList *preset_radio;
156 int n_preset_menu_items;
158 GtkWidget *preset_custom;
159 GtkWidget *copy_menu_item;
164 cairo_surface_t *image;
171 void get_random_seed(void **randseed, int *randseedsize)
173 struct timeval *tvp = snew(struct timeval);
174 gettimeofday(tvp, NULL);
175 *randseed = (void *)tvp;
176 *randseedsize = sizeof(struct timeval);
179 void frontend_default_colour(frontend *fe, float *output)
181 GdkColor col = fe->window->style->bg[GTK_STATE_NORMAL];
182 output[0] = col.red / 65535.0;
183 output[1] = col.green / 65535.0;
184 output[2] = col.blue / 65535.0;
187 void gtk_status_bar(void *handle, char *text)
189 frontend *fe = (frontend *)handle;
191 assert(fe->statusbar);
193 gtk_statusbar_pop(GTK_STATUSBAR(fe->statusbar), fe->statusctx);
194 gtk_statusbar_push(GTK_STATUSBAR(fe->statusbar), fe->statusctx, text);
197 /* ----------------------------------------------------------------------
198 * Cairo drawing functions.
203 static void setup_drawing(frontend *fe)
205 fe->cr = cairo_create(fe->image);
206 cairo_set_antialias(fe->cr, CAIRO_ANTIALIAS_GRAY);
207 cairo_set_line_width(fe->cr, 1.0);
208 cairo_set_line_cap(fe->cr, CAIRO_LINE_CAP_SQUARE);
209 cairo_set_line_join(fe->cr, CAIRO_LINE_JOIN_ROUND);
212 static void teardown_drawing(frontend *fe)
216 cairo_destroy(fe->cr);
219 cr = gdk_cairo_create(fe->pixmap);
220 cairo_set_source_surface(cr, fe->image, 0, 0);
224 fe->bbox_r - fe->bbox_l + 2,
225 fe->bbox_d - fe->bbox_u + 2);
230 static void snaffle_colours(frontend *fe)
232 fe->colours = midend_colours(fe->me, &fe->ncolours);
235 static void set_colour(frontend *fe, int colour)
237 cairo_set_source_rgb(fe->cr,
238 fe->colours[3*colour + 0],
239 fe->colours[3*colour + 1],
240 fe->colours[3*colour + 2]);
243 static void set_window_background(frontend *fe, int colour)
247 colmap = gdk_colormap_get_system();
248 fe->background.red = fe->colours[3*colour + 0] * 65535;
249 fe->background.green = fe->colours[3*colour + 1] * 65535;
250 fe->background.blue = fe->colours[3*colour + 2] * 65535;
251 if (!gdk_colormap_alloc_color(colmap, &fe->background, FALSE, FALSE)) {
252 g_error("couldn't allocate background (#%02x%02x%02x)\n",
253 fe->background.red >> 8, fe->background.green >> 8,
254 fe->background.blue >> 8);
256 gdk_window_set_background(fe->area->window, &fe->background);
257 gdk_window_set_background(fe->window->window, &fe->background);
260 static PangoLayout *make_pango_layout(frontend *fe)
262 return (pango_cairo_create_layout(fe->cr));
265 static void draw_pango_layout(frontend *fe, PangoLayout *layout,
268 cairo_move_to(fe->cr, x, y);
269 pango_cairo_show_layout(fe->cr, layout);
272 static void save_screenshot_png(frontend *fe, const char *screenshot_file)
274 cairo_surface_write_to_png(fe->image, screenshot_file);
277 static void do_clip(frontend *fe, int x, int y, int w, int h)
279 cairo_new_path(fe->cr);
280 cairo_rectangle(fe->cr, x, y, w, h);
284 static void do_unclip(frontend *fe)
286 cairo_reset_clip(fe->cr);
289 static void do_draw_rect(frontend *fe, int x, int y, int w, int h)
292 cairo_new_path(fe->cr);
293 cairo_set_antialias(fe->cr, CAIRO_ANTIALIAS_NONE);
294 cairo_rectangle(fe->cr, x, y, w, h);
296 cairo_restore(fe->cr);
299 static void do_draw_line(frontend *fe, int x1, int y1, int x2, int y2)
301 cairo_new_path(fe->cr);
302 cairo_move_to(fe->cr, x1 + 0.5, y1 + 0.5);
303 cairo_line_to(fe->cr, x2 + 0.5, y2 + 0.5);
304 cairo_stroke(fe->cr);
307 static void do_draw_thick_line(frontend *fe, float thickness,
308 float x1, float y1, float x2, float y2)
311 cairo_set_line_width(fe->cr, thickness);
312 cairo_new_path(fe->cr);
313 cairo_move_to(fe->cr, x1, y1);
314 cairo_line_to(fe->cr, x2, y2);
315 cairo_stroke(fe->cr);
316 cairo_restore(fe->cr);
319 static void do_draw_poly(frontend *fe, int *coords, int npoints,
320 int fillcolour, int outlinecolour)
324 cairo_new_path(fe->cr);
325 for (i = 0; i < npoints; i++)
326 cairo_line_to(fe->cr, coords[i*2] + 0.5, coords[i*2 + 1] + 0.5);
327 cairo_close_path(fe->cr);
328 if (fillcolour >= 0) {
329 set_colour(fe, fillcolour);
330 cairo_fill_preserve(fe->cr);
332 assert(outlinecolour >= 0);
333 set_colour(fe, outlinecolour);
334 cairo_stroke(fe->cr);
337 static void do_draw_circle(frontend *fe, int cx, int cy, int radius,
338 int fillcolour, int outlinecolour)
340 cairo_new_path(fe->cr);
341 cairo_arc(fe->cr, cx + 0.5, cy + 0.5, radius, 0, 2*PI);
342 cairo_close_path(fe->cr); /* Just in case... */
343 if (fillcolour >= 0) {
344 set_colour(fe, fillcolour);
345 cairo_fill_preserve(fe->cr);
347 assert(outlinecolour >= 0);
348 set_colour(fe, outlinecolour);
349 cairo_stroke(fe->cr);
352 static void setup_blitter(blitter *bl, int w, int h)
354 bl->image = cairo_image_surface_create(CAIRO_FORMAT_RGB24, w, h);
357 static void teardown_blitter(blitter *bl)
359 cairo_surface_destroy(bl->image);
362 static void do_blitter_save(frontend *fe, blitter *bl, int x, int y)
364 cairo_t *cr = cairo_create(bl->image);
366 cairo_set_source_surface(cr, fe->image, -x, -y);
371 static void do_blitter_load(frontend *fe, blitter *bl, int x, int y)
373 cairo_set_source_surface(fe->cr, bl->image, x, y);
377 static void clear_backing_store(frontend *fe)
382 static void setup_backing_store(frontend *fe)
387 fe->pixmap = gdk_pixmap_new(fe->area->window, fe->pw, fe->ph, -1);
388 fe->image = cairo_image_surface_create(CAIRO_FORMAT_RGB24,
391 for (i = 0; i < 3; i++) {
393 case 0: cr = cairo_create(fe->image); break;
394 case 1: cr = gdk_cairo_create(fe->pixmap); break;
395 case 2: cr = gdk_cairo_create(fe->area->window); break;
397 cairo_set_source_rgb(cr,
398 fe->colours[0], fe->colours[1], fe->colours[2]);
404 static int backing_store_ok(frontend *fe)
406 return (!!fe->image);
409 static void teardown_backing_store(frontend *fe)
411 cairo_surface_destroy(fe->image);
412 gdk_pixmap_unref(fe->pixmap);
418 /* ----------------------------------------------------------------------
419 * GDK drawing functions.
424 static void setup_drawing(frontend *fe)
426 fe->gc = gdk_gc_new(fe->area->window);
429 static void teardown_drawing(frontend *fe)
431 gdk_gc_unref(fe->gc);
435 static void snaffle_colours(frontend *fe)
441 fe->colmap = gdk_colormap_get_system();
442 colours = midend_colours(fe->me, &ncolours);
443 fe->ncolours = ncolours;
444 fe->colours = snewn(ncolours, GdkColor);
445 for (i = 0; i < ncolours; i++) {
446 fe->colours[i].red = colours[i*3] * 0xFFFF;
447 fe->colours[i].green = colours[i*3+1] * 0xFFFF;
448 fe->colours[i].blue = colours[i*3+2] * 0xFFFF;
450 success = snewn(ncolours, gboolean);
451 gdk_colormap_alloc_colors(fe->colmap, fe->colours, ncolours,
452 FALSE, FALSE, success);
453 for (i = 0; i < ncolours; i++) {
455 g_error("couldn't allocate colour %d (#%02x%02x%02x)\n",
456 i, fe->colours[i].red >> 8,
457 fe->colours[i].green >> 8,
458 fe->colours[i].blue >> 8);
463 static void set_window_background(frontend *fe, int colour)
465 fe->backgroundindex = colour;
466 gdk_window_set_background(fe->area->window, &fe->colours[colour]);
467 gdk_window_set_background(fe->window->window, &fe->colours[colour]);
470 static void set_colour(frontend *fe, int colour)
472 gdk_gc_set_foreground(fe->gc, &fe->colours[colour]);
476 static PangoLayout *make_pango_layout(frontend *fe)
478 return (pango_layout_new(gtk_widget_get_pango_context(fe->area)));
481 static void draw_pango_layout(frontend *fe, PangoLayout *layout,
484 gdk_draw_layout(fe->pixmap, fe->gc, x, y, layout);
488 static void save_screenshot_png(frontend *fe, const char *screenshot_file)
491 GError *gerror = NULL;
493 midend_redraw(fe->me);
495 pb = gdk_pixbuf_get_from_drawable(NULL, fe->pixmap,
496 NULL, 0, 0, 0, 0, -1, -1);
497 gdk_pixbuf_save(pb, screenshot_file, "png", &gerror, NULL);
500 static void do_clip(frontend *fe, int x, int y, int w, int h)
508 gdk_gc_set_clip_rectangle(fe->gc, &rect);
511 static void do_unclip(frontend *fe)
519 gdk_gc_set_clip_rectangle(fe->gc, &rect);
522 static void do_draw_rect(frontend *fe, int x, int y, int w, int h)
524 gdk_draw_rectangle(fe->pixmap, fe->gc, 1, x, y, w, h);
527 static void do_draw_line(frontend *fe, int x1, int y1, int x2, int y2)
529 gdk_draw_line(fe->pixmap, fe->gc, x1, y1, x2, y2);
532 static void do_draw_thick_line(frontend *fe, float thickness,
533 float x1, float y1, float x2, float y2)
537 gdk_gc_get_values(fe->gc, &save);
538 gdk_gc_set_line_attributes(fe->gc,
543 gdk_draw_line(fe->pixmap, fe->gc, x1, y1, x2, y2);
544 gdk_gc_set_line_attributes(fe->gc,
551 static void do_draw_poly(frontend *fe, int *coords, int npoints,
552 int fillcolour, int outlinecolour)
554 GdkPoint *points = snewn(npoints, GdkPoint);
557 for (i = 0; i < npoints; i++) {
558 points[i].x = coords[i*2];
559 points[i].y = coords[i*2+1];
562 if (fillcolour >= 0) {
563 set_colour(fe, fillcolour);
564 gdk_draw_polygon(fe->pixmap, fe->gc, TRUE, points, npoints);
566 assert(outlinecolour >= 0);
567 set_colour(fe, outlinecolour);
570 * In principle we ought to be able to use gdk_draw_polygon for
571 * the outline as well. In fact, it turns out to interact badly
572 * with a clipping region, for no terribly obvious reason, so I
573 * draw the outline as a sequence of lines instead.
575 for (i = 0; i < npoints; i++)
576 gdk_draw_line(fe->pixmap, fe->gc,
577 points[i].x, points[i].y,
578 points[(i+1)%npoints].x, points[(i+1)%npoints].y);
583 static void do_draw_circle(frontend *fe, int cx, int cy, int radius,
584 int fillcolour, int outlinecolour)
586 if (fillcolour >= 0) {
587 set_colour(fe, fillcolour);
588 gdk_draw_arc(fe->pixmap, fe->gc, TRUE,
589 cx - radius, cy - radius,
590 2 * radius, 2 * radius, 0, 360 * 64);
593 assert(outlinecolour >= 0);
594 set_colour(fe, outlinecolour);
595 gdk_draw_arc(fe->pixmap, fe->gc, FALSE,
596 cx - radius, cy - radius,
597 2 * radius, 2 * radius, 0, 360 * 64);
600 static void setup_blitter(blitter *bl, int w, int h)
603 * We can't create the pixmap right now, because fe->window
604 * might not yet exist. So we just cache w and h and create it
605 * during the firs call to blitter_save.
610 static void teardown_blitter(blitter *bl)
613 gdk_pixmap_unref(bl->pixmap);
616 static void do_blitter_save(frontend *fe, blitter *bl, int x, int y)
619 bl->pixmap = gdk_pixmap_new(fe->area->window, bl->w, bl->h, -1);
620 gdk_draw_pixmap(bl->pixmap,
621 fe->area->style->fg_gc[GTK_WIDGET_STATE(fe->area)],
623 x, y, 0, 0, bl->w, bl->h);
626 static void do_blitter_load(frontend *fe, blitter *bl, int x, int y)
629 gdk_draw_pixmap(fe->pixmap,
630 fe->area->style->fg_gc[GTK_WIDGET_STATE(fe->area)],
632 0, 0, x, y, bl->w, bl->h);
635 static void clear_backing_store(frontend *fe)
640 static void setup_backing_store(frontend *fe)
644 fe->pixmap = gdk_pixmap_new(fe->area->window, fe->pw, fe->ph, -1);
646 gc = gdk_gc_new(fe->area->window);
647 gdk_gc_set_foreground(gc, &fe->colours[0]);
648 gdk_draw_rectangle(fe->pixmap, gc, 1, 0, 0, fe->pw, fe->ph);
649 gdk_draw_rectangle(fe->area->window, gc, 1, 0, 0, fe->w, fe->h);
653 static int backing_store_ok(frontend *fe)
655 return (!!fe->pixmap);
658 static void teardown_backing_store(frontend *fe)
660 gdk_pixmap_unref(fe->pixmap);
666 static void repaint_rectangle(frontend *fe, GtkWidget *widget,
667 int x, int y, int w, int h)
669 GdkGC *gc = gdk_gc_new(widget->window);
671 gdk_gc_set_foreground(gc, &fe->background);
673 gdk_gc_set_foreground(gc, &fe->colours[fe->backgroundindex]);
676 gdk_draw_rectangle(widget->window, gc,
677 TRUE, x, y, fe->ox - x, h);
682 gdk_draw_rectangle(widget->window, gc,
683 TRUE, x, y, w, fe->oy - y);
688 gdk_draw_rectangle(widget->window, gc,
689 TRUE, x + fe->pw, y, w - fe->pw, h);
693 gdk_draw_rectangle(widget->window, gc,
694 TRUE, x, y + fe->ph, w, h - fe->ph);
697 gdk_draw_pixmap(widget->window, gc, fe->pixmap,
698 x - fe->ox, y - fe->oy, x, y, w, h);
702 /* ----------------------------------------------------------------------
703 * Pango font functions.
708 static void add_font(frontend *fe, int index, int fonttype, int fontsize)
711 * Use Pango to find the closest match to the requested
714 PangoFontDescription *fd;
716 fd = pango_font_description_new();
717 /* `Monospace' and `Sans' are meta-families guaranteed to exist */
718 pango_font_description_set_family(fd, fonttype == FONT_FIXED ?
719 "Monospace" : "Sans");
720 pango_font_description_set_weight(fd, PANGO_WEIGHT_BOLD);
722 * I found some online Pango documentation which
723 * described a function called
724 * pango_font_description_set_absolute_size(), which is
725 * _exactly_ what I want here. Unfortunately, none of
726 * my local Pango installations have it (presumably
727 * they're too old), so I'm going to have to hack round
728 * it by figuring out the point size myself. This
729 * limits me to X and probably also breaks in later
730 * Pango installations, so ideally I should add another
731 * CHECK_VERSION type ifdef and use set_absolute_size
732 * where available. All very annoying.
734 #ifdef HAVE_SENSIBLE_ABSOLUTE_SIZE_FUNCTION
735 pango_font_description_set_absolute_size(fd, PANGO_SCALE*fontsize);
738 Display *d = GDK_DISPLAY();
739 int s = DefaultScreen(d);
741 (PANGO_SCALE * 72.27 / 25.4) *
742 ((double) DisplayWidthMM(d, s) / DisplayWidth (d, s));
743 pango_font_description_set_size(fd, resolution * fontsize);
746 fe->fonts[index].desc = fd;
749 static void align_and_draw_text(frontend *fe,
750 int index, int align, int x, int y,
756 layout = make_pango_layout(fe);
761 pango_layout_set_font_description(layout, fe->fonts[index].desc);
762 pango_layout_set_text(layout, text, strlen(text));
763 pango_layout_get_pixel_extents(layout, NULL, &rect);
765 if (align & ALIGN_VCENTRE)
766 rect.y -= rect.height / 2;
768 rect.y -= rect.height;
770 if (align & ALIGN_HCENTRE)
771 rect.x -= rect.width / 2;
772 else if (align & ALIGN_HRIGHT)
773 rect.x -= rect.width;
775 draw_pango_layout(fe, layout, rect.x + x, rect.y + y);
777 g_object_unref(layout);
782 /* ----------------------------------------------------------------------
783 * Old-fashioned font functions.
788 static void add_font(int index, int fonttype, int fontsize)
791 * In GTK 1.2, I don't know of any plausible way to
792 * pick a suitable font, so I'm just going to be
795 fe->fonts[i].font = gdk_font_load(fonttype == FONT_FIXED ?
796 "fixed" : "variable");
799 static void align_and_draw_text(int index, int align, int x, int y,
802 int lb, rb, wid, asc, desc;
805 * Measure vertical string extents with respect to the same
808 gdk_string_extents(fe->fonts[i].font,
809 "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
810 &lb, &rb, &wid, &asc, &desc);
811 if (align & ALIGN_VCENTRE)
812 y += asc - (asc+desc)/2;
817 * ... but horizontal extents with respect to the provided
818 * string. This means that multiple pieces of text centred
819 * on the same y-coordinate don't have different baselines.
821 gdk_string_extents(fe->fonts[i].font, text,
822 &lb, &rb, &wid, &asc, &desc);
824 if (align & ALIGN_HCENTRE)
826 else if (align & ALIGN_HRIGHT)
830 * Actually draw the text.
832 gdk_draw_string(fe->pixmap, fe->fonts[i].font, fe->gc, x, y, text);
837 /* ----------------------------------------------------------------------
838 * The exported drawing functions.
841 void gtk_start_draw(void *handle)
843 frontend *fe = (frontend *)handle;
851 void gtk_clip(void *handle, int x, int y, int w, int h)
853 frontend *fe = (frontend *)handle;
854 do_clip(fe, x, y, w, h);
857 void gtk_unclip(void *handle)
859 frontend *fe = (frontend *)handle;
863 void gtk_draw_text(void *handle, int x, int y, int fonttype, int fontsize,
864 int align, int colour, char *text)
866 frontend *fe = (frontend *)handle;
870 * Find or create the font.
872 for (i = 0; i < fe->nfonts; i++)
873 if (fe->fonts[i].type == fonttype && fe->fonts[i].size == fontsize)
876 if (i == fe->nfonts) {
877 if (fe->fontsize <= fe->nfonts) {
878 fe->fontsize = fe->nfonts + 10;
879 fe->fonts = sresize(fe->fonts, fe->fontsize, struct font);
884 fe->fonts[i].type = fonttype;
885 fe->fonts[i].size = fontsize;
886 add_font(fe, i, fonttype, fontsize);
892 set_colour(fe, colour);
893 align_and_draw_text(fe, i, align, x, y, text);
896 void gtk_draw_rect(void *handle, int x, int y, int w, int h, int colour)
898 frontend *fe = (frontend *)handle;
899 set_colour(fe, colour);
900 do_draw_rect(fe, x, y, w, h);
903 void gtk_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
905 frontend *fe = (frontend *)handle;
906 set_colour(fe, colour);
907 do_draw_line(fe, x1, y1, x2, y2);
910 void gtk_draw_thick_line(void *handle, float thickness,
911 float x1, float y1, float x2, float y2, int colour)
913 frontend *fe = (frontend *)handle;
914 set_colour(fe, colour);
915 do_draw_thick_line(fe, thickness, x1, y1, x2, y2);
918 void gtk_draw_poly(void *handle, int *coords, int npoints,
919 int fillcolour, int outlinecolour)
921 frontend *fe = (frontend *)handle;
922 do_draw_poly(fe, coords, npoints, fillcolour, outlinecolour);
925 void gtk_draw_circle(void *handle, int cx, int cy, int radius,
926 int fillcolour, int outlinecolour)
928 frontend *fe = (frontend *)handle;
929 do_draw_circle(fe, cx, cy, radius, fillcolour, outlinecolour);
932 blitter *gtk_blitter_new(void *handle, int w, int h)
934 blitter *bl = snew(blitter);
935 setup_blitter(bl, w, h);
941 void gtk_blitter_free(void *handle, blitter *bl)
943 teardown_blitter(bl);
947 void gtk_blitter_save(void *handle, blitter *bl, int x, int y)
949 frontend *fe = (frontend *)handle;
950 do_blitter_save(fe, bl, x, y);
955 void gtk_blitter_load(void *handle, blitter *bl, int x, int y)
957 frontend *fe = (frontend *)handle;
958 if (x == BLITTER_FROMSAVED && y == BLITTER_FROMSAVED) {
962 do_blitter_load(fe, bl, x, y);
965 void gtk_draw_update(void *handle, int x, int y, int w, int h)
967 frontend *fe = (frontend *)handle;
968 if (fe->bbox_l > x ) fe->bbox_l = x ;
969 if (fe->bbox_r < x+w) fe->bbox_r = x+w;
970 if (fe->bbox_u > y ) fe->bbox_u = y ;
971 if (fe->bbox_d < y+h) fe->bbox_d = y+h;
974 void gtk_end_draw(void *handle)
976 frontend *fe = (frontend *)handle;
978 teardown_drawing(fe);
980 if (fe->bbox_l < fe->bbox_r && fe->bbox_u < fe->bbox_d) {
981 repaint_rectangle(fe, fe->area,
982 fe->bbox_l - 1 + fe->ox,
983 fe->bbox_u - 1 + fe->oy,
984 fe->bbox_r - fe->bbox_l + 2,
985 fe->bbox_d - fe->bbox_u + 2);
990 char *gtk_text_fallback(void *handle, const char *const *strings, int nstrings)
993 * We assume Pango can cope with any UTF-8 likely to be emitted
996 return dupstr(strings[0]);
1000 const struct drawing_api gtk_drawing = {
1016 NULL, NULL, NULL, NULL, NULL, NULL, /* {begin,end}_{doc,page,puzzle} */
1017 NULL, NULL, /* line_width, line_dotted */
1023 #ifdef NO_THICK_LINE
1026 gtk_draw_thick_line,
1030 static void destroy(GtkWidget *widget, gpointer data)
1032 frontend *fe = (frontend *)data;
1033 deactivate_timer(fe);
1034 midend_free(fe->me);
1038 static gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data)
1040 frontend *fe = (frontend *)data;
1042 int shift = (event->state & GDK_SHIFT_MASK) ? MOD_SHFT : 0;
1043 int ctrl = (event->state & GDK_CONTROL_MASK) ? MOD_CTRL : 0;
1045 if (!backing_store_ok(fe))
1048 #if !GTK_CHECK_VERSION(2,0,0)
1049 /* Gtk 1.2 passes a key event to this function even if it's also
1050 * defined as an accelerator.
1051 * Gtk 2 doesn't do this, and this function appears not to exist there. */
1052 if (fe->accelgroup &&
1053 gtk_accel_group_get_entry(fe->accelgroup,
1054 event->keyval, event->state))
1058 /* Handle mnemonics. */
1059 if (gtk_window_activate_key(GTK_WINDOW(fe->window), event))
1062 if (event->keyval == GDK_Up)
1063 keyval = shift | ctrl | CURSOR_UP;
1064 else if (event->keyval == GDK_KP_Up || event->keyval == GDK_KP_8)
1065 keyval = MOD_NUM_KEYPAD | '8';
1066 else if (event->keyval == GDK_Down)
1067 keyval = shift | ctrl | CURSOR_DOWN;
1068 else if (event->keyval == GDK_KP_Down || event->keyval == GDK_KP_2)
1069 keyval = MOD_NUM_KEYPAD | '2';
1070 else if (event->keyval == GDK_Left)
1071 keyval = shift | ctrl | CURSOR_LEFT;
1072 else if (event->keyval == GDK_KP_Left || event->keyval == GDK_KP_4)
1073 keyval = MOD_NUM_KEYPAD | '4';
1074 else if (event->keyval == GDK_Right)
1075 keyval = shift | ctrl | CURSOR_RIGHT;
1076 else if (event->keyval == GDK_KP_Right || event->keyval == GDK_KP_6)
1077 keyval = MOD_NUM_KEYPAD | '6';
1078 else if (event->keyval == GDK_KP_Home || event->keyval == GDK_KP_7)
1079 keyval = MOD_NUM_KEYPAD | '7';
1080 else if (event->keyval == GDK_KP_End || event->keyval == GDK_KP_1)
1081 keyval = MOD_NUM_KEYPAD | '1';
1082 else if (event->keyval == GDK_KP_Page_Up || event->keyval == GDK_KP_9)
1083 keyval = MOD_NUM_KEYPAD | '9';
1084 else if (event->keyval == GDK_KP_Page_Down || event->keyval == GDK_KP_3)
1085 keyval = MOD_NUM_KEYPAD | '3';
1086 else if (event->keyval == GDK_KP_Insert || event->keyval == GDK_KP_0)
1087 keyval = MOD_NUM_KEYPAD | '0';
1088 else if (event->keyval == GDK_KP_Begin || event->keyval == GDK_KP_5)
1089 keyval = MOD_NUM_KEYPAD | '5';
1090 else if (event->keyval == GDK_BackSpace ||
1091 event->keyval == GDK_Delete ||
1092 event->keyval == GDK_KP_Delete)
1094 else if (event->string[0] && !event->string[1])
1095 keyval = (unsigned char)event->string[0];
1100 !midend_process_key(fe->me, 0, 0, keyval))
1101 gtk_widget_destroy(fe->window);
1106 static gint button_event(GtkWidget *widget, GdkEventButton *event,
1109 frontend *fe = (frontend *)data;
1112 if (!backing_store_ok(fe))
1115 if (event->type != GDK_BUTTON_PRESS && event->type != GDK_BUTTON_RELEASE)
1118 if (event->button == 2 || (event->state & GDK_SHIFT_MASK))
1119 button = MIDDLE_BUTTON;
1120 else if (event->button == 3 || (event->state & GDK_MOD1_MASK))
1121 button = RIGHT_BUTTON;
1122 else if (event->button == 1)
1123 button = LEFT_BUTTON;
1125 return FALSE; /* don't even know what button! */
1127 if (event->type == GDK_BUTTON_RELEASE)
1128 button += LEFT_RELEASE - LEFT_BUTTON;
1130 if (!midend_process_key(fe->me, event->x - fe->ox,
1131 event->y - fe->oy, button))
1132 gtk_widget_destroy(fe->window);
1137 static gint motion_event(GtkWidget *widget, GdkEventMotion *event,
1140 frontend *fe = (frontend *)data;
1143 if (!backing_store_ok(fe))
1146 if (event->state & (GDK_BUTTON2_MASK | GDK_SHIFT_MASK))
1147 button = MIDDLE_DRAG;
1148 else if (event->state & GDK_BUTTON1_MASK)
1150 else if (event->state & GDK_BUTTON3_MASK)
1151 button = RIGHT_DRAG;
1153 return FALSE; /* don't even know what button! */
1155 if (!midend_process_key(fe->me, event->x - fe->ox,
1156 event->y - fe->oy, button))
1157 gtk_widget_destroy(fe->window);
1158 #if GTK_CHECK_VERSION(2,12,0)
1159 gdk_event_request_motions(event);
1161 gdk_window_get_pointer(widget->window, NULL, NULL, NULL);
1167 static gint expose_area(GtkWidget *widget, GdkEventExpose *event,
1170 frontend *fe = (frontend *)data;
1172 if (backing_store_ok(fe)) {
1173 repaint_rectangle(fe, widget,
1174 event->area.x, event->area.y,
1175 event->area.width, event->area.height);
1180 static gint map_window(GtkWidget *widget, GdkEvent *event,
1183 frontend *fe = (frontend *)data;
1186 * Apparently we need to do this because otherwise the status
1187 * bar will fail to update immediately. Annoying, but there we
1190 gtk_widget_queue_draw(fe->window);
1195 static gint configure_area(GtkWidget *widget,
1196 GdkEventConfigure *event, gpointer data)
1198 frontend *fe = (frontend *)data;
1201 if (backing_store_ok(fe))
1202 teardown_backing_store(fe);
1204 x = fe->w = event->width;
1205 y = fe->h = event->height;
1206 midend_size(fe->me, &x, &y, TRUE);
1209 fe->ox = (fe->w - fe->pw) / 2;
1210 fe->oy = (fe->h - fe->ph) / 2;
1212 setup_backing_store(fe);
1213 midend_force_redraw(fe->me);
1218 static gint timer_func(gpointer data)
1220 frontend *fe = (frontend *)data;
1222 if (fe->timer_active) {
1225 gettimeofday(&now, NULL);
1226 elapsed = ((now.tv_usec - fe->last_time.tv_usec) * 0.000001F +
1227 (now.tv_sec - fe->last_time.tv_sec));
1228 midend_timer(fe->me, elapsed); /* may clear timer_active */
1229 fe->last_time = now;
1232 return fe->timer_active;
1235 void deactivate_timer(frontend *fe)
1238 return; /* can happen due to --generate */
1239 if (fe->timer_active)
1240 gtk_timeout_remove(fe->timer_id);
1241 fe->timer_active = FALSE;
1244 void activate_timer(frontend *fe)
1247 return; /* can happen due to --generate */
1248 if (!fe->timer_active) {
1249 fe->timer_id = gtk_timeout_add(20, timer_func, fe);
1250 gettimeofday(&fe->last_time, NULL);
1252 fe->timer_active = TRUE;
1255 static void window_destroy(GtkWidget *widget, gpointer data)
1260 static void msgbox_button_clicked(GtkButton *button, gpointer data)
1262 GtkWidget *window = GTK_WIDGET(data);
1265 ip = (int *)gtk_object_get_data(GTK_OBJECT(window), "user-data");
1266 v = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(button), "user-data"));
1269 gtk_widget_destroy(GTK_WIDGET(data));
1272 static int win_key_press(GtkWidget *widget, GdkEventKey *event, gpointer data)
1274 GtkObject *cancelbutton = GTK_OBJECT(data);
1277 * `Escape' effectively clicks the cancel button
1279 if (event->keyval == GDK_Escape) {
1280 gtk_signal_emit_by_name(GTK_OBJECT(cancelbutton), "clicked");
1287 enum { MB_OK, MB_YESNO };
1289 int message_box(GtkWidget *parent, char *title, char *msg, int centre,
1292 GtkWidget *window, *hbox, *text, *button;
1296 window = gtk_dialog_new();
1297 text = gtk_label_new(msg);
1298 gtk_misc_set_alignment(GTK_MISC(text), 0.0, 0.0);
1299 hbox = gtk_hbox_new(FALSE, 0);
1300 gtk_box_pack_start(GTK_BOX(hbox), text, FALSE, FALSE, 20);
1301 gtk_box_pack_start(GTK_BOX(GTK_DIALOG(window)->vbox),
1302 hbox, FALSE, FALSE, 20);
1303 gtk_widget_show(text);
1304 gtk_widget_show(hbox);
1305 gtk_window_set_title(GTK_WINDOW(window), title);
1306 gtk_label_set_line_wrap(GTK_LABEL(text), TRUE);
1308 if (type == MB_OK) {
1309 titles = GTK_STOCK_OK "\0";
1312 assert(type == MB_YESNO);
1313 titles = GTK_STOCK_NO "\0" GTK_STOCK_YES "\0";
1320 button = gtk_button_new_from_stock(titles);
1321 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(window)->action_area),
1322 button, FALSE, FALSE, 0);
1323 gtk_widget_show(button);
1325 GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
1326 gtk_window_set_default(GTK_WINDOW(window), button);
1329 gtk_signal_connect(GTK_OBJECT(window), "key_press_event",
1330 GTK_SIGNAL_FUNC(win_key_press), button);
1332 gtk_signal_connect(GTK_OBJECT(button), "clicked",
1333 GTK_SIGNAL_FUNC(msgbox_button_clicked), window);
1334 gtk_object_set_data(GTK_OBJECT(button), "user-data",
1335 GINT_TO_POINTER(i));
1336 titles += strlen(titles)+1;
1339 gtk_object_set_data(GTK_OBJECT(window), "user-data", &i);
1340 gtk_signal_connect(GTK_OBJECT(window), "destroy",
1341 GTK_SIGNAL_FUNC(window_destroy), NULL);
1342 gtk_window_set_modal(GTK_WINDOW(window), TRUE);
1343 gtk_window_set_transient_for(GTK_WINDOW(window), GTK_WINDOW(parent));
1344 /* set_transient_window_pos(parent, window); */
1345 gtk_widget_show(window);
1348 return (type == MB_YESNO ? i == 1 : TRUE);
1351 void error_box(GtkWidget *parent, char *msg)
1353 message_box(parent, "Error", msg, FALSE, MB_OK);
1356 static void config_ok_button_clicked(GtkButton *button, gpointer data)
1358 frontend *fe = (frontend *)data;
1361 err = midend_set_config(fe->me, fe->cfg_which, fe->cfg);
1364 error_box(fe->cfgbox, err);
1367 gtk_widget_destroy(fe->cfgbox);
1372 static void config_cancel_button_clicked(GtkButton *button, gpointer data)
1374 frontend *fe = (frontend *)data;
1376 gtk_widget_destroy(fe->cfgbox);
1379 static int editbox_key(GtkWidget *widget, GdkEventKey *event, gpointer data)
1382 * GtkEntry has a nasty habit of eating the Return key, which
1383 * is unhelpful since it doesn't actually _do_ anything with it
1384 * (it calls gtk_widget_activate, but our edit boxes never need
1385 * activating). So I catch Return before GtkEntry sees it, and
1386 * pass it straight on to the parent widget. Effect: hitting
1387 * Return in an edit box will now activate the default button
1388 * in the dialog just like it will everywhere else.
1390 if (event->keyval == GDK_Return && widget->parent != NULL) {
1392 gtk_signal_emit_stop_by_name(GTK_OBJECT(widget), "key_press_event");
1393 gtk_signal_emit_by_name(GTK_OBJECT(widget->parent), "key_press_event",
1394 event, &return_val);
1400 static void editbox_changed(GtkEditable *ed, gpointer data)
1402 config_item *i = (config_item *)data;
1405 i->sval = dupstr(gtk_entry_get_text(GTK_ENTRY(ed)));
1408 static void button_toggled(GtkToggleButton *tb, gpointer data)
1410 config_item *i = (config_item *)data;
1412 i->ival = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(tb));
1415 static void droplist_sel(GtkMenuItem *item, gpointer data)
1417 config_item *i = (config_item *)data;
1419 i->ival = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(item),
1423 static int get_config(frontend *fe, int which)
1425 GtkWidget *w, *table, *cancel;
1430 fe->cfg = midend_get_config(fe->me, which, &title);
1431 fe->cfg_which = which;
1434 fe->cfgbox = gtk_dialog_new();
1435 gtk_window_set_title(GTK_WINDOW(fe->cfgbox), title);
1438 w = gtk_button_new_from_stock(GTK_STOCK_CANCEL);
1439 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(fe->cfgbox)->action_area),
1440 w, FALSE, FALSE, 0);
1442 gtk_signal_connect(GTK_OBJECT(w), "clicked",
1443 GTK_SIGNAL_FUNC(config_cancel_button_clicked), fe);
1446 w = gtk_button_new_from_stock(GTK_STOCK_OK);
1447 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(fe->cfgbox)->action_area),
1448 w, FALSE, FALSE, 0);
1450 GTK_WIDGET_SET_FLAGS(w, GTK_CAN_DEFAULT);
1451 gtk_window_set_default(GTK_WINDOW(fe->cfgbox), w);
1452 gtk_signal_connect(GTK_OBJECT(w), "clicked",
1453 GTK_SIGNAL_FUNC(config_ok_button_clicked), fe);
1455 table = gtk_table_new(1, 2, FALSE);
1457 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(fe->cfgbox)->vbox),
1458 table, FALSE, FALSE, 0);
1459 gtk_widget_show(table);
1461 for (i = fe->cfg; i->type != C_END; i++) {
1462 gtk_table_resize(GTK_TABLE(table), y+1, 2);
1467 * Edit box with a label beside it.
1470 w = gtk_label_new(i->name);
1471 gtk_misc_set_alignment(GTK_MISC(w), 0.0, 0.5);
1472 gtk_table_attach(GTK_TABLE(table), w, 0, 1, y, y+1,
1473 GTK_SHRINK | GTK_FILL,
1474 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1478 w = gtk_entry_new();
1479 gtk_table_attach(GTK_TABLE(table), w, 1, 2, y, y+1,
1480 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1481 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1483 gtk_entry_set_text(GTK_ENTRY(w), i->sval);
1484 gtk_signal_connect(GTK_OBJECT(w), "changed",
1485 GTK_SIGNAL_FUNC(editbox_changed), i);
1486 gtk_signal_connect(GTK_OBJECT(w), "key_press_event",
1487 GTK_SIGNAL_FUNC(editbox_key), NULL);
1496 w = gtk_check_button_new_with_label(i->name);
1497 gtk_signal_connect(GTK_OBJECT(w), "toggled",
1498 GTK_SIGNAL_FUNC(button_toggled), i);
1499 gtk_table_attach(GTK_TABLE(table), w, 0, 2, y, y+1,
1500 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1501 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1503 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(w), i->ival);
1509 * Drop-down list (GtkOptionMenu).
1512 w = gtk_label_new(i->name);
1513 gtk_misc_set_alignment(GTK_MISC(w), 0.0, 0.5);
1514 gtk_table_attach(GTK_TABLE(table), w, 0, 1, y, y+1,
1515 GTK_SHRINK | GTK_FILL,
1516 GTK_EXPAND | GTK_SHRINK | GTK_FILL ,
1520 w = gtk_option_menu_new();
1521 gtk_table_attach(GTK_TABLE(table), w, 1, 2, y, y+1,
1522 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1523 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1530 GtkWidget *menuitem;
1531 GtkWidget *menu = gtk_menu_new();
1533 gtk_option_menu_set_menu(GTK_OPTION_MENU(w), menu);
1541 while (*q && *q != c)
1544 name = snewn(q-p+1, char);
1545 strncpy(name, p, q-p);
1548 if (*q) q++; /* eat delimiter */
1550 menuitem = gtk_menu_item_new_with_label(name);
1551 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1552 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1553 GINT_TO_POINTER(val));
1554 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1555 GTK_SIGNAL_FUNC(droplist_sel), i);
1556 gtk_widget_show(menuitem);
1563 gtk_option_menu_set_history(GTK_OPTION_MENU(w), i->ival);
1572 gtk_signal_connect(GTK_OBJECT(fe->cfgbox), "destroy",
1573 GTK_SIGNAL_FUNC(window_destroy), NULL);
1574 gtk_signal_connect(GTK_OBJECT(fe->cfgbox), "key_press_event",
1575 GTK_SIGNAL_FUNC(win_key_press), cancel);
1576 gtk_window_set_modal(GTK_WINDOW(fe->cfgbox), TRUE);
1577 gtk_window_set_transient_for(GTK_WINDOW(fe->cfgbox),
1578 GTK_WINDOW(fe->window));
1579 /* set_transient_window_pos(fe->window, fe->cfgbox); */
1580 gtk_widget_show(fe->cfgbox);
1588 static void menu_key_event(GtkMenuItem *menuitem, gpointer data)
1590 frontend *fe = (frontend *)data;
1591 int key = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(menuitem),
1593 if (!midend_process_key(fe->me, 0, 0, key))
1594 gtk_widget_destroy(fe->window);
1597 static void get_size(frontend *fe, int *px, int *py)
1602 * Currently I don't want to make the GTK port scale large
1603 * puzzles to fit on the screen. This is because X does permit
1604 * extremely large windows and many window managers provide a
1605 * means of navigating round them, and the users I consulted
1606 * before deciding said that they'd rather have enormous puzzle
1607 * windows spanning multiple screen pages than have them
1608 * shrunk. I could change my mind later or introduce
1609 * configurability; this would be the place to do so, by
1610 * replacing the initial values of x and y with the screen
1615 midend_size(fe->me, &x, &y, FALSE);
1620 #if !GTK_CHECK_VERSION(2,0,0)
1621 #define gtk_window_resize(win, x, y) \
1622 gdk_window_resize(GTK_WIDGET(win)->window, x, y)
1626 * Called when any other code in this file has changed the
1627 * selected game parameters.
1629 static void changed_preset(frontend *fe)
1631 int n = midend_which_preset(fe->me);
1633 fe->preset_threaded = TRUE;
1634 if (n < 0 && fe->preset_custom) {
1635 gtk_check_menu_item_set_active(
1636 GTK_CHECK_MENU_ITEM(fe->preset_custom),
1639 GSList *gs = fe->preset_radio;
1640 int i = fe->n_preset_menu_items - 1 - n;
1641 if (fe->preset_custom)
1648 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(gs->data),
1650 } else for (gs = fe->preset_radio; gs; gs = gs->next) {
1651 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(gs->data),
1655 fe->preset_threaded = FALSE;
1658 * Update the greying on the Copy menu option.
1660 if (fe->copy_menu_item) {
1661 int enabled = midend_can_format_as_text_now(fe->me);
1662 gtk_widget_set_sensitive(fe->copy_menu_item, enabled);
1666 static gboolean not_size_allocated_yet(GtkWidget *w)
1669 * This function tests whether a widget has not yet taken up space
1670 * on the screen which it will occupy in future. (Therefore, it
1671 * returns true only if the widget does exist but does not have a
1672 * size allocation. A null widget is already taking up all the
1673 * space it ever will.)
1676 return FALSE; /* nonexistent widgets aren't a problem */
1678 #if GTK_CHECK_VERSION(2,18,0) /* skip if no gtk_widget_get_allocation */
1681 gtk_widget_get_allocation(w, &a);
1682 if (a.height == 0 || a.width == 0)
1683 return TRUE; /* widget exists but has no size yet */
1690 static void try_shrink_drawing_area(frontend *fe)
1692 if (fe->drawing_area_shrink_pending &&
1693 !not_size_allocated_yet(fe->menubar) &&
1694 !not_size_allocated_yet(fe->statusbar)) {
1696 * In order to permit the user to resize the window smaller as
1697 * well as bigger, we call this function after the window size
1698 * has ended up where we want it. This shouldn't shrink the
1699 * window immediately; it just arranges that the next time the
1700 * user tries to shrink it, they can.
1702 * However, at puzzle creation time, we defer the first of
1703 * these operations until after the menu bar and status bar
1704 * are actually visible. On Ubuntu 12.04 I've found that these
1705 * can take a while to be displayed, and that it's a mistake
1706 * to reduce the drawing area's size allocation before they've
1707 * turned up or else the drawing area makes room for them by
1708 * shrinking to less than the size we intended.
1710 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), 1, 1);
1711 fe->drawing_area_shrink_pending = FALSE;
1715 static gint configure_window(GtkWidget *widget,
1716 GdkEventConfigure *event, gpointer data)
1718 frontend *fe = (frontend *)data;
1720 * When the main puzzle window changes size, it might be because
1721 * the menu bar or status bar has turned up after starting off
1722 * absent, in which case we should have another go at enacting a
1723 * pending shrink of the drawing area.
1725 try_shrink_drawing_area(fe);
1729 static void resize_fe(frontend *fe)
1733 get_size(fe, &x, &y);
1736 fe->drawing_area_shrink_pending = FALSE;
1737 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
1740 gtk_widget_size_request(GTK_WIDGET(fe->window), &req);
1741 gtk_window_resize(GTK_WINDOW(fe->window), req.width, req.height);
1743 fe->drawing_area_shrink_pending = TRUE;
1744 try_shrink_drawing_area(fe);
1747 static void menu_preset_event(GtkMenuItem *menuitem, gpointer data)
1749 frontend *fe = (frontend *)data;
1750 game_params *params =
1751 (game_params *)gtk_object_get_data(GTK_OBJECT(menuitem), "user-data");
1753 if (fe->preset_threaded ||
1754 (GTK_IS_CHECK_MENU_ITEM(menuitem) &&
1755 !gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(menuitem))))
1757 midend_set_params(fe->me, params);
1758 midend_new_game(fe->me);
1763 GdkAtom compound_text_atom, utf8_string_atom;
1764 int paste_initialised = FALSE;
1766 static void set_selection(frontend *fe, GdkAtom selection)
1768 if (!paste_initialised) {
1769 compound_text_atom = gdk_atom_intern("COMPOUND_TEXT", FALSE);
1770 utf8_string_atom = gdk_atom_intern("UTF8_STRING", FALSE);
1771 paste_initialised = TRUE;
1775 * For this simple application we can safely assume that the
1776 * data passed to this function is pure ASCII, which means we
1777 * can return precisely the same stuff for types STRING,
1778 * COMPOUND_TEXT or UTF8_STRING.
1781 if (gtk_selection_owner_set(fe->area, selection, CurrentTime)) {
1782 gtk_selection_clear_targets(fe->area, selection);
1783 gtk_selection_add_target(fe->area, selection,
1784 GDK_SELECTION_TYPE_STRING, 1);
1785 gtk_selection_add_target(fe->area, selection, compound_text_atom, 1);
1786 gtk_selection_add_target(fe->area, selection, utf8_string_atom, 1);
1790 void write_clip(frontend *fe, char *data)
1793 sfree(fe->paste_data);
1795 fe->paste_data = data;
1796 fe->paste_data_len = strlen(data);
1798 set_selection(fe, GDK_SELECTION_PRIMARY);
1799 set_selection(fe, GDK_SELECTION_CLIPBOARD);
1802 void selection_get(GtkWidget *widget, GtkSelectionData *seldata,
1803 guint info, guint time_stamp, gpointer data)
1805 frontend *fe = (frontend *)data;
1806 gtk_selection_data_set(seldata, seldata->target, 8,
1807 fe->paste_data, fe->paste_data_len);
1810 gint selection_clear(GtkWidget *widget, GdkEventSelection *seldata,
1813 frontend *fe = (frontend *)data;
1816 sfree(fe->paste_data);
1817 fe->paste_data = NULL;
1818 fe->paste_data_len = 0;
1822 static void menu_copy_event(GtkMenuItem *menuitem, gpointer data)
1824 frontend *fe = (frontend *)data;
1827 text = midend_text_format(fe->me);
1830 write_clip(fe, text);
1838 static void filesel_ok(GtkButton *button, gpointer data)
1840 frontend *fe = (frontend *)data;
1842 gpointer filesel = gtk_object_get_data(GTK_OBJECT(button), "user-data");
1845 gtk_file_selection_get_filename(GTK_FILE_SELECTION(filesel));
1847 fe->filesel_name = dupstr(name);
1850 static char *file_selector(frontend *fe, char *title, int save)
1852 GtkWidget *filesel =
1853 gtk_file_selection_new(title);
1855 fe->filesel_name = NULL;
1857 gtk_window_set_modal(GTK_WINDOW(filesel), TRUE);
1859 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "user-data",
1862 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "clicked",
1863 GTK_SIGNAL_FUNC(filesel_ok), fe);
1864 gtk_signal_connect_object
1865 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "clicked",
1866 GTK_SIGNAL_FUNC(gtk_widget_destroy), (gpointer)filesel);
1867 gtk_signal_connect_object
1868 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->cancel_button), "clicked",
1869 GTK_SIGNAL_FUNC(gtk_widget_destroy), (gpointer)filesel);
1870 gtk_signal_connect(GTK_OBJECT(filesel), "destroy",
1871 GTK_SIGNAL_FUNC(window_destroy), NULL);
1872 gtk_widget_show(filesel);
1873 gtk_window_set_transient_for(GTK_WINDOW(filesel), GTK_WINDOW(fe->window));
1876 return fe->filesel_name;
1881 static char *file_selector(frontend *fe, char *title, int save)
1883 char *filesel_name = NULL;
1885 GtkWidget *filesel =
1886 gtk_file_chooser_dialog_new(title,
1887 GTK_WINDOW(fe->window),
1888 save ? GTK_FILE_CHOOSER_ACTION_SAVE :
1889 GTK_FILE_CHOOSER_ACTION_OPEN,
1890 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
1891 save ? GTK_STOCK_SAVE : GTK_STOCK_OPEN,
1892 GTK_RESPONSE_ACCEPT,
1895 if (gtk_dialog_run(GTK_DIALOG(filesel)) == GTK_RESPONSE_ACCEPT) {
1896 const char *name = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(filesel));
1897 filesel_name = dupstr(name);
1900 gtk_widget_destroy(filesel);
1902 return filesel_name;
1907 struct savefile_write_ctx {
1912 static void savefile_write(void *wctx, void *buf, int len)
1914 struct savefile_write_ctx *ctx = (struct savefile_write_ctx *)wctx;
1915 if (fwrite(buf, 1, len, ctx->fp) < len)
1919 static int savefile_read(void *wctx, void *buf, int len)
1921 FILE *fp = (FILE *)wctx;
1924 ret = fread(buf, 1, len, fp);
1925 return (ret == len);
1928 static void menu_save_event(GtkMenuItem *menuitem, gpointer data)
1930 frontend *fe = (frontend *)data;
1933 name = file_selector(fe, "Enter name of game file to save", TRUE);
1938 if ((fp = fopen(name, "r")) != NULL) {
1939 char buf[256 + FILENAME_MAX];
1943 sprintf(buf, "Are you sure you want to overwrite the"
1945 FILENAME_MAX, name);
1946 if (!message_box(fe->window, "Question", buf, TRUE, MB_YESNO))
1950 fp = fopen(name, "w");
1954 error_box(fe->window, "Unable to open save file");
1959 struct savefile_write_ctx ctx;
1962 midend_serialise(fe->me, savefile_write, &ctx);
1966 sprintf(boxmsg, "Error writing save file: %.400s",
1968 error_box(fe->window, boxmsg);
1976 static void menu_load_event(GtkMenuItem *menuitem, gpointer data)
1978 frontend *fe = (frontend *)data;
1981 name = file_selector(fe, "Enter name of saved game file to load", FALSE);
1984 FILE *fp = fopen(name, "r");
1988 error_box(fe->window, "Unable to open saved game file");
1992 err = midend_deserialise(fe->me, savefile_read, fp);
1997 error_box(fe->window, err);
2006 static void menu_solve_event(GtkMenuItem *menuitem, gpointer data)
2008 frontend *fe = (frontend *)data;
2011 msg = midend_solve(fe->me);
2014 error_box(fe->window, msg);
2017 static void menu_restart_event(GtkMenuItem *menuitem, gpointer data)
2019 frontend *fe = (frontend *)data;
2021 midend_restart_game(fe->me);
2024 static void menu_config_event(GtkMenuItem *menuitem, gpointer data)
2026 frontend *fe = (frontend *)data;
2027 int which = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(menuitem),
2030 if (fe->preset_threaded ||
2031 (GTK_IS_CHECK_MENU_ITEM(menuitem) &&
2032 !gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(menuitem))))
2034 changed_preset(fe); /* Put the old preset back! */
2035 if (!get_config(fe, which))
2038 midend_new_game(fe->me);
2042 static void menu_about_event(GtkMenuItem *menuitem, gpointer data)
2044 frontend *fe = (frontend *)data;
2048 sprintf(titlebuf, "About %.200s", thegame.name);
2051 "from Simon Tatham's Portable Puzzle Collection\n\n"
2052 "%.500s", thegame.name, ver);
2054 message_box(fe->window, titlebuf, textbuf, TRUE, MB_OK);
2057 static GtkWidget *add_menu_item_with_key(frontend *fe, GtkContainer *cont,
2058 char *text, int key)
2060 GtkWidget *menuitem = gtk_menu_item_new_with_label(text);
2062 gtk_container_add(cont, menuitem);
2063 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
2064 GINT_TO_POINTER(key));
2065 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2066 GTK_SIGNAL_FUNC(menu_key_event), fe);
2067 switch (key & ~0x1F) {
2070 keyqual = GDK_CONTROL_MASK;
2074 keyqual = GDK_SHIFT_MASK;
2080 gtk_widget_add_accelerator(menuitem,
2081 "activate", fe->accelgroup,
2084 gtk_widget_show(menuitem);
2088 static void add_menu_separator(GtkContainer *cont)
2090 GtkWidget *menuitem = gtk_menu_item_new();
2091 gtk_container_add(cont, menuitem);
2092 gtk_widget_show(menuitem);
2095 enum { ARG_EITHER, ARG_SAVE, ARG_ID }; /* for argtype */
2097 static frontend *new_window(char *arg, int argtype, char **error)
2100 GtkBox *vbox, *hbox;
2101 GtkWidget *menu, *menuitem;
2106 extern char *const *const xpm_icons[];
2107 extern const int n_xpm_icons;
2109 fe = snew(frontend);
2111 fe->timer_active = FALSE;
2114 fe->me = midend_new(fe, &thegame, >k_drawing, fe);
2124 err = midend_game_id(fe->me, arg);
2126 midend_new_game(fe->me);
2128 sprintf(errbuf, "Invalid game ID: %.800s", err);
2131 fp = fopen(arg, "r");
2133 sprintf(errbuf, "Error opening file: %.800s", strerror(errno));
2135 err = midend_deserialise(fe->me, savefile_read, fp);
2137 sprintf(errbuf, "Invalid save file: %.800s", err);
2141 default /*case ARG_EITHER*/:
2143 * First try treating the argument as a game ID.
2145 err = midend_game_id(fe->me, arg);
2148 * It's a valid game ID.
2150 midend_new_game(fe->me);
2152 FILE *fp = fopen(arg, "r");
2154 sprintf(errbuf, "Supplied argument is neither a game ID (%.400s)"
2155 " nor a save file (%.400s)", err, strerror(errno));
2157 err = midend_deserialise(fe->me, savefile_read, fp);
2159 sprintf(errbuf, "%.800s", err);
2166 *error = dupstr(errbuf);
2167 midend_free(fe->me);
2173 midend_new_game(fe->me);
2176 fe->window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
2177 gtk_window_set_title(GTK_WINDOW(fe->window), thegame.name);
2179 vbox = GTK_BOX(gtk_vbox_new(FALSE, 0));
2180 gtk_container_add(GTK_CONTAINER(fe->window), GTK_WIDGET(vbox));
2181 gtk_widget_show(GTK_WIDGET(vbox));
2183 fe->accelgroup = gtk_accel_group_new();
2184 gtk_window_add_accel_group(GTK_WINDOW(fe->window), fe->accelgroup);
2186 hbox = GTK_BOX(gtk_hbox_new(FALSE, 0));
2187 gtk_box_pack_start(vbox, GTK_WIDGET(hbox), FALSE, FALSE, 0);
2188 gtk_widget_show(GTK_WIDGET(hbox));
2190 fe->menubar = gtk_menu_bar_new();
2191 gtk_box_pack_start(hbox, fe->menubar, TRUE, TRUE, 0);
2192 gtk_widget_show(fe->menubar);
2194 menuitem = gtk_menu_item_new_with_mnemonic("_Game");
2195 gtk_container_add(GTK_CONTAINER(fe->menubar), menuitem);
2196 gtk_widget_show(menuitem);
2198 menu = gtk_menu_new();
2199 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
2201 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "New", 'n');
2203 menuitem = gtk_menu_item_new_with_label("Restart");
2204 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2205 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2206 GTK_SIGNAL_FUNC(menu_restart_event), fe);
2207 gtk_widget_show(menuitem);
2209 menuitem = gtk_menu_item_new_with_label("Specific...");
2210 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
2211 GINT_TO_POINTER(CFG_DESC));
2212 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2213 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2214 GTK_SIGNAL_FUNC(menu_config_event), fe);
2215 gtk_widget_show(menuitem);
2217 menuitem = gtk_menu_item_new_with_label("Random Seed...");
2218 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
2219 GINT_TO_POINTER(CFG_SEED));
2220 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2221 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2222 GTK_SIGNAL_FUNC(menu_config_event), fe);
2223 gtk_widget_show(menuitem);
2225 fe->preset_radio = NULL;
2226 fe->preset_custom = NULL;
2227 fe->n_preset_menu_items = 0;
2228 fe->preset_threaded = FALSE;
2229 if ((n = midend_num_presets(fe->me)) > 0 || thegame.can_configure) {
2233 menuitem = gtk_menu_item_new_with_mnemonic("_Type");
2234 gtk_container_add(GTK_CONTAINER(fe->menubar), menuitem);
2235 gtk_widget_show(menuitem);
2237 submenu = gtk_menu_new();
2238 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), submenu);
2240 for (i = 0; i < n; i++) {
2242 game_params *params;
2244 midend_fetch_preset(fe->me, i, &name, ¶ms);
2247 gtk_radio_menu_item_new_with_label(fe->preset_radio, name);
2249 gtk_radio_menu_item_group(GTK_RADIO_MENU_ITEM(menuitem));
2250 fe->n_preset_menu_items++;
2251 gtk_container_add(GTK_CONTAINER(submenu), menuitem);
2252 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data", params);
2253 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2254 GTK_SIGNAL_FUNC(menu_preset_event), fe);
2255 gtk_widget_show(menuitem);
2258 if (thegame.can_configure) {
2259 menuitem = fe->preset_custom =
2260 gtk_radio_menu_item_new_with_label(fe->preset_radio,
2263 gtk_radio_menu_item_group(GTK_RADIO_MENU_ITEM(menuitem));
2264 gtk_container_add(GTK_CONTAINER(submenu), menuitem);
2265 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
2266 GINT_TO_POINTER(CFG_SETTINGS));
2267 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2268 GTK_SIGNAL_FUNC(menu_config_event), fe);
2269 gtk_widget_show(menuitem);
2274 add_menu_separator(GTK_CONTAINER(menu));
2275 menuitem = gtk_menu_item_new_with_label("Load...");
2276 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2277 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2278 GTK_SIGNAL_FUNC(menu_load_event), fe);
2279 gtk_widget_show(menuitem);
2280 menuitem = gtk_menu_item_new_with_label("Save...");
2281 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2282 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2283 GTK_SIGNAL_FUNC(menu_save_event), fe);
2284 gtk_widget_show(menuitem);
2285 #ifndef STYLUS_BASED
2286 add_menu_separator(GTK_CONTAINER(menu));
2287 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Undo", 'u');
2288 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Redo", 'r');
2290 if (thegame.can_format_as_text_ever) {
2291 add_menu_separator(GTK_CONTAINER(menu));
2292 menuitem = gtk_menu_item_new_with_label("Copy");
2293 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2294 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2295 GTK_SIGNAL_FUNC(menu_copy_event), fe);
2296 gtk_widget_show(menuitem);
2297 fe->copy_menu_item = menuitem;
2299 fe->copy_menu_item = NULL;
2301 if (thegame.can_solve) {
2302 add_menu_separator(GTK_CONTAINER(menu));
2303 menuitem = gtk_menu_item_new_with_label("Solve");
2304 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2305 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2306 GTK_SIGNAL_FUNC(menu_solve_event), fe);
2307 gtk_widget_show(menuitem);
2309 add_menu_separator(GTK_CONTAINER(menu));
2310 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Exit", 'q');
2312 menuitem = gtk_menu_item_new_with_mnemonic("_Help");
2313 gtk_container_add(GTK_CONTAINER(fe->menubar), menuitem);
2314 gtk_widget_show(menuitem);
2316 menu = gtk_menu_new();
2317 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
2319 menuitem = gtk_menu_item_new_with_label("About");
2320 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2321 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2322 GTK_SIGNAL_FUNC(menu_about_event), fe);
2323 gtk_widget_show(menuitem);
2326 menuitem=gtk_button_new_with_mnemonic("_Redo");
2327 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
2328 GINT_TO_POINTER((int)('r')));
2329 gtk_signal_connect(GTK_OBJECT(menuitem), "clicked",
2330 GTK_SIGNAL_FUNC(menu_key_event), fe);
2331 gtk_box_pack_end(hbox, menuitem, FALSE, FALSE, 0);
2332 gtk_widget_show(menuitem);
2334 menuitem=gtk_button_new_with_mnemonic("_Undo");
2335 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
2336 GINT_TO_POINTER((int)('u')));
2337 gtk_signal_connect(GTK_OBJECT(menuitem), "clicked",
2338 GTK_SIGNAL_FUNC(menu_key_event), fe);
2339 gtk_box_pack_end(hbox, menuitem, FALSE, FALSE, 0);
2340 gtk_widget_show(menuitem);
2342 if (thegame.flags & REQUIRE_NUMPAD) {
2343 hbox = GTK_BOX(gtk_hbox_new(FALSE, 0));
2344 gtk_box_pack_start(vbox, GTK_WIDGET(hbox), FALSE, FALSE, 0);
2345 gtk_widget_show(GTK_WIDGET(hbox));
2349 for(errbuf[0]='0';errbuf[0]<='9';errbuf[0]++) {
2350 menuitem=gtk_button_new_with_label(errbuf);
2351 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
2352 GINT_TO_POINTER((int)(errbuf[0])));
2353 gtk_signal_connect(GTK_OBJECT(menuitem), "clicked",
2354 GTK_SIGNAL_FUNC(menu_key_event), fe);
2355 gtk_box_pack_start(hbox, menuitem, TRUE, TRUE, 0);
2356 gtk_widget_show(menuitem);
2359 #endif /* STYLUS_BASED */
2363 snaffle_colours(fe);
2365 if (midend_wants_statusbar(fe->me)) {
2366 GtkWidget *viewport;
2369 viewport = gtk_viewport_new(NULL, NULL);
2370 gtk_viewport_set_shadow_type(GTK_VIEWPORT(viewport), GTK_SHADOW_NONE);
2371 fe->statusbar = gtk_statusbar_new();
2372 gtk_container_add(GTK_CONTAINER(viewport), fe->statusbar);
2373 gtk_widget_show(viewport);
2374 gtk_box_pack_end(vbox, viewport, FALSE, FALSE, 0);
2375 gtk_widget_show(fe->statusbar);
2376 fe->statusctx = gtk_statusbar_get_context_id
2377 (GTK_STATUSBAR(fe->statusbar), "game");
2378 gtk_statusbar_push(GTK_STATUSBAR(fe->statusbar), fe->statusctx,
2380 gtk_widget_size_request(fe->statusbar, &req);
2382 /* For GTK 2.0, should we be using gtk_widget_set_size_request? */
2384 gtk_widget_set_usize(viewport, -1, req.height);
2386 fe->statusbar = NULL;
2388 fe->area = gtk_drawing_area_new();
2389 #if GTK_CHECK_VERSION(2,0,0)
2390 GTK_WIDGET_UNSET_FLAGS(fe->area, GTK_DOUBLE_BUFFERED);
2392 get_size(fe, &x, &y);
2393 fe->drawing_area_shrink_pending = FALSE;
2394 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
2398 gtk_box_pack_end(vbox, fe->area, TRUE, TRUE, 0);
2400 clear_backing_store(fe);
2402 fe->nfonts = fe->fontsize = 0;
2404 fe->paste_data = NULL;
2405 fe->paste_data_len = 0;
2407 gtk_signal_connect(GTK_OBJECT(fe->window), "destroy",
2408 GTK_SIGNAL_FUNC(destroy), fe);
2409 gtk_signal_connect(GTK_OBJECT(fe->window), "key_press_event",
2410 GTK_SIGNAL_FUNC(key_event), fe);
2411 gtk_signal_connect(GTK_OBJECT(fe->area), "button_press_event",
2412 GTK_SIGNAL_FUNC(button_event), fe);
2413 gtk_signal_connect(GTK_OBJECT(fe->area), "button_release_event",
2414 GTK_SIGNAL_FUNC(button_event), fe);
2415 gtk_signal_connect(GTK_OBJECT(fe->area), "motion_notify_event",
2416 GTK_SIGNAL_FUNC(motion_event), fe);
2417 gtk_signal_connect(GTK_OBJECT(fe->area), "selection_get",
2418 GTK_SIGNAL_FUNC(selection_get), fe);
2419 gtk_signal_connect(GTK_OBJECT(fe->area), "selection_clear_event",
2420 GTK_SIGNAL_FUNC(selection_clear), fe);
2421 gtk_signal_connect(GTK_OBJECT(fe->area), "expose_event",
2422 GTK_SIGNAL_FUNC(expose_area), fe);
2423 gtk_signal_connect(GTK_OBJECT(fe->window), "map_event",
2424 GTK_SIGNAL_FUNC(map_window), fe);
2425 gtk_signal_connect(GTK_OBJECT(fe->area), "configure_event",
2426 GTK_SIGNAL_FUNC(configure_area), fe);
2427 gtk_signal_connect(GTK_OBJECT(fe->window), "configure_event",
2428 GTK_SIGNAL_FUNC(configure_window), fe);
2430 gtk_widget_add_events(GTK_WIDGET(fe->area),
2431 GDK_BUTTON_PRESS_MASK |
2432 GDK_BUTTON_RELEASE_MASK |
2433 GDK_BUTTON_MOTION_MASK |
2434 GDK_POINTER_MOTION_HINT_MASK);
2437 gtk_widget_realize(fe->window);
2438 iconpm = gdk_pixmap_create_from_xpm_d(fe->window->window, NULL,
2439 NULL, (gchar **)xpm_icons[0]);
2440 gdk_window_set_icon(fe->window->window, NULL, iconpm, NULL);
2442 for (n = 0; n < n_xpm_icons; n++) {
2444 g_list_append(iconlist,
2445 gdk_pixbuf_new_from_xpm_data((const gchar **)
2448 gdk_window_set_icon_list(fe->window->window, iconlist);
2451 gtk_widget_show(fe->area);
2452 gtk_widget_show(fe->window);
2454 fe->drawing_area_shrink_pending = TRUE;
2455 try_shrink_drawing_area(fe);
2456 set_window_background(fe, 0);
2461 char *fgetline(FILE *fp)
2463 char *ret = snewn(512, char);
2464 int size = 512, len = 0;
2465 while (fgets(ret + len, size - len, fp)) {
2466 len += strlen(ret + len);
2467 if (ret[len-1] == '\n')
2468 break; /* got a newline, we're done */
2470 ret = sresize(ret, size, char);
2472 if (len == 0) { /* first fgets returned NULL */
2480 int main(int argc, char **argv)
2482 char *pname = argv[0];
2484 int ngenerate = 0, print = FALSE, px = 1, py = 1;
2485 int time_generation = FALSE, test_solve = FALSE, list_presets = FALSE;
2486 int soln = FALSE, colour = FALSE;
2488 float redo_proportion = 0.0F;
2489 char *savefile = NULL, *savesuffix = NULL;
2491 int argtype = ARG_EITHER;
2492 char *screenshot_file = NULL;
2493 int doing_opts = TRUE;
2499 * Command line parsing in this function is rather fiddly,
2500 * because GTK wants to have a go at argc/argv _first_ - and
2501 * yet we can't let it, because gtk_init() will bomb out if it
2502 * can't open an X display, whereas in fact we want to permit
2503 * our --generate and --print modes to run without an X
2507 * - we parse the command line ourselves, without modifying
2509 * - if we encounter an error which might plausibly be the
2510 * result of a GTK command line (i.e. not detailed errors in
2511 * particular options of ours) we store the error message
2512 * and terminate parsing.
2513 * - if we got enough out of the command line to know it
2514 * specifies a non-X mode of operation, we either display
2515 * the stored error and return failure, or if there is no
2516 * stored error we do the non-X operation and return
2518 * - otherwise, we go straight to gtk_init().
2524 if (doing_opts && !strcmp(p, "--version")) {
2525 printf("%s, from Simon Tatham's Portable Puzzle Collection\n%s\n",
2528 } else if (doing_opts && !strcmp(p, "--generate")) {
2530 ngenerate = atoi(*++av);
2532 fprintf(stderr, "%s: '--generate' expected a number\n",
2538 } else if (doing_opts && !strcmp(p, "--time-generation")) {
2539 time_generation = TRUE;
2540 } else if (doing_opts && !strcmp(p, "--test-solve")) {
2542 } else if (doing_opts && !strcmp(p, "--list-presets")) {
2543 list_presets = TRUE;
2544 } else if (doing_opts && !strcmp(p, "--save")) {
2548 fprintf(stderr, "%s: '--save' expected a filename\n",
2552 } else if (doing_opts && (!strcmp(p, "--save-suffix") ||
2553 !strcmp(p, "--savesuffix"))) {
2557 fprintf(stderr, "%s: '--save-suffix' expected a filename\n",
2561 } else if (doing_opts && !strcmp(p, "--print")) {
2562 if (!thegame.can_print) {
2563 fprintf(stderr, "%s: this game does not support printing\n",
2570 if (sscanf(dim, "%dx%d", &px, &py) != 2) {
2571 fprintf(stderr, "%s: unable to parse argument '%s' to "
2572 "'--print'\n", pname, dim);
2578 } else if (doing_opts && !strcmp(p, "--scale")) {
2580 scale = atof(*++av);
2582 fprintf(stderr, "%s: no argument supplied to '--scale'\n",
2586 } else if (doing_opts && !strcmp(p, "--redo")) {
2588 * This is an internal option which I don't expect
2589 * users to have any particular use for. The effect of
2590 * --redo is that once the game has been loaded and
2591 * initialised, the next move in the redo chain is
2592 * replayed, and the game screen is redrawn part way
2593 * through the making of the move. This is only
2594 * meaningful if there _is_ a next move in the redo
2595 * chain, which means in turn that this option is only
2596 * useful if you're also passing a save file on the
2599 * This option is used by the script which generates
2600 * the puzzle icons and website screenshots, and I
2601 * don't imagine it's useful for anything else.
2602 * (Unless, I suppose, users don't like my screenshots
2603 * and want to generate their own in the same way for
2604 * some repackaged version of the puzzles.)
2607 redo_proportion = atof(*++av);
2609 fprintf(stderr, "%s: no argument supplied to '--redo'\n",
2613 } else if (doing_opts && !strcmp(p, "--screenshot")) {
2615 * Another internal option for the icon building
2616 * script. This causes a screenshot of the central
2617 * drawing area (i.e. not including the menu bar or
2618 * status bar) to be saved to a PNG file once the
2619 * window has been drawn, and then the application
2620 * quits immediately.
2623 screenshot_file = *++av;
2625 fprintf(stderr, "%s: no argument supplied to '--screenshot'\n",
2629 } else if (doing_opts && (!strcmp(p, "--with-solutions") ||
2630 !strcmp(p, "--with-solution") ||
2631 !strcmp(p, "--with-solns") ||
2632 !strcmp(p, "--with-soln") ||
2633 !strcmp(p, "--solutions") ||
2634 !strcmp(p, "--solution") ||
2635 !strcmp(p, "--solns") ||
2636 !strcmp(p, "--soln"))) {
2638 } else if (doing_opts && !strcmp(p, "--colour")) {
2639 if (!thegame.can_print_in_colour) {
2640 fprintf(stderr, "%s: this game does not support colour"
2641 " printing\n", pname);
2645 } else if (doing_opts && !strcmp(p, "--load")) {
2647 } else if (doing_opts && !strcmp(p, "--game")) {
2649 } else if (doing_opts && !strcmp(p, "--")) {
2651 } else if (!doing_opts || p[0] != '-') {
2653 fprintf(stderr, "%s: more than one argument supplied\n",
2659 sprintf(errbuf, "%.100s: unrecognised option '%.100s'\n",
2666 * Special standalone mode for generating puzzle IDs on the
2667 * command line. Useful for generating puzzles to be printed
2668 * out and solved offline (for puzzles where that even makes
2669 * sense - Solo, for example, is a lot more pencil-and-paper
2670 * friendly than Twiddle!)
2674 * <puzzle-name> --generate [<n> [<params>]]
2676 * <n>, if present, is the number of puzzle IDs to generate.
2677 * <params>, if present, is the same type of parameter string
2678 * you would pass to the puzzle when running it in GUI mode,
2679 * including optional extras such as the expansion factor in
2680 * Rectangles and the difficulty level in Solo.
2682 * If you specify <params>, you must also specify <n> (although
2683 * you may specify it to be 1). Sorry; that was the
2684 * simplest-to-parse command-line syntax I came up with.
2686 if (ngenerate > 0 || print || savefile || savesuffix) {
2690 document *doc = NULL;
2693 * If we're in this branch, we should display any pending
2694 * error message from the command line, since GTK isn't going
2695 * to take another crack at making sense of it.
2698 fputs(errbuf, stderr);
2704 me = midend_new(NULL, &thegame, NULL, NULL);
2707 if (savefile && !savesuffix)
2709 if (!savefile && savesuffix)
2713 doc = document_new(px, py, scale);
2716 * In this loop, we either generate a game ID or read one
2717 * from stdin depending on whether we're in generate mode;
2718 * then we either write it to stdout or print it, depending
2719 * on whether we're in print mode. Thus, this loop handles
2720 * generate-to-stdout, print-from-stdin and generate-and-
2721 * immediately-print modes.
2723 * (It could also handle a copy-stdin-to-stdout mode,
2724 * although there's currently no combination of options
2725 * which will cause this loop to be activated in that mode.
2726 * It wouldn't be _entirely_ pointless, though, because
2727 * stdin could contain bare params strings or random-seed
2728 * IDs, and stdout would contain nothing but fully
2729 * generated descriptive game IDs.)
2731 while (ngenerate == 0 || i < n) {
2732 char *pstr, *err, *seed;
2733 struct rusage before, after;
2735 if (ngenerate == 0) {
2736 pstr = fgetline(stdin);
2739 pstr[strcspn(pstr, "\r\n")] = '\0';
2742 pstr = snewn(strlen(arg) + 40, char);
2745 if (i > 0 && strchr(arg, '#'))
2746 sprintf(pstr + strlen(pstr), "-%d", i);
2752 err = midend_game_id(me, pstr);
2754 fprintf(stderr, "%s: error parsing '%s': %s\n",
2760 if (time_generation)
2761 getrusage(RUSAGE_SELF, &before);
2763 midend_new_game(me);
2765 seed = midend_get_random_seed(me);
2767 if (time_generation) {
2770 getrusage(RUSAGE_SELF, &after);
2772 elapsed = (after.ru_utime.tv_sec -
2773 before.ru_utime.tv_sec);
2774 elapsed += (after.ru_utime.tv_usec -
2775 before.ru_utime.tv_usec) / 1000000.0;
2777 printf("%s %s: %.6f\n", thegame.name, seed, elapsed);
2780 if (test_solve && thegame.can_solve) {
2782 * Now destroy the aux_info in the midend, by means of
2783 * re-entering the same game id, and then try to solve
2786 char *game_id, *err;
2788 game_id = midend_get_game_id(me);
2789 err = midend_game_id(me, game_id);
2791 fprintf(stderr, "%s %s: game id re-entry error: %s\n",
2792 thegame.name, seed, err);
2795 midend_new_game(me);
2798 err = midend_solve(me);
2800 * If the solve operation returned the error "Solution
2801 * not known for this puzzle", that's OK, because that
2802 * just means it's a puzzle for which we don't have an
2803 * algorithmic solver and hence can't solve it without
2804 * the aux_info, e.g. Netslide. Any other error is a
2807 if (err && strcmp(err, "Solution not known for this puzzle")) {
2808 fprintf(stderr, "%s %s: solve error: %s\n",
2809 thegame.name, seed, err);
2818 err = midend_print_puzzle(me, doc, soln);
2820 fprintf(stderr, "%s: error in printing: %s\n", pname, err);
2825 struct savefile_write_ctx ctx;
2826 char *realname = snewn(40 + strlen(savefile) +
2827 strlen(savesuffix), char);
2828 sprintf(realname, "%s%d%s", savefile, i, savesuffix);
2831 char *err = midend_solve(me);
2833 fprintf(stderr, "%s: unable to show solution: %s\n",
2839 ctx.fp = fopen(realname, "w");
2841 fprintf(stderr, "%s: open: %s\n", realname,
2846 midend_serialise(me, savefile_write, &ctx);
2848 fprintf(stderr, "%s: write: %s\n", realname,
2849 strerror(ctx.error));
2852 if (fclose(ctx.fp)) {
2853 fprintf(stderr, "%s: close: %s\n", realname,
2859 if (!doc && !savefile && !time_generation) {
2860 id = midend_get_game_id(me);
2869 psdata *ps = ps_init(stdout, colour);
2870 document_print(doc, ps_drawing_api(ps));
2878 } else if (list_presets) {
2880 * Another specialist mode which causes the puzzle to list the
2881 * game_params strings for all its preset configurations.
2886 me = midend_new(NULL, &thegame, NULL, NULL);
2887 npresets = midend_num_presets(me);
2889 for (i = 0; i < npresets; i++) {
2890 game_params *params;
2891 char *name, *paramstr;
2893 midend_fetch_preset(me, i, &name, ¶ms);
2894 paramstr = thegame.encode_params(params, TRUE);
2896 printf("%s %s\n", paramstr, name);
2905 gtk_init(&argc, &argv);
2907 fe = new_window(arg, argtype, &error);
2910 fprintf(stderr, "%s: %s\n", pname, error);
2914 if (screenshot_file) {
2916 * Some puzzles will not redraw their entire area if
2917 * given a partially completed animation, which means
2918 * we must redraw now and _then_ redraw again after
2919 * freezing the move timer.
2921 midend_force_redraw(fe->me);
2924 if (redo_proportion) {
2926 midend_process_key(fe->me, 0, 0, 'r');
2927 /* And freeze the timer at the specified position. */
2928 midend_freeze_timer(fe->me, redo_proportion);
2931 if (screenshot_file) {
2932 save_screenshot_png(fe, screenshot_file);