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;
160 int menubar_is_local;
165 cairo_surface_t *image;
172 void get_random_seed(void **randseed, int *randseedsize)
174 struct timeval *tvp = snew(struct timeval);
175 gettimeofday(tvp, NULL);
176 *randseed = (void *)tvp;
177 *randseedsize = sizeof(struct timeval);
180 void frontend_default_colour(frontend *fe, float *output)
182 GdkColor col = fe->window->style->bg[GTK_STATE_NORMAL];
183 output[0] = col.red / 65535.0;
184 output[1] = col.green / 65535.0;
185 output[2] = col.blue / 65535.0;
188 void gtk_status_bar(void *handle, char *text)
190 frontend *fe = (frontend *)handle;
192 assert(fe->statusbar);
194 gtk_statusbar_pop(GTK_STATUSBAR(fe->statusbar), fe->statusctx);
195 gtk_statusbar_push(GTK_STATUSBAR(fe->statusbar), fe->statusctx, text);
198 /* ----------------------------------------------------------------------
199 * Cairo drawing functions.
204 static void setup_drawing(frontend *fe)
206 fe->cr = cairo_create(fe->image);
207 cairo_set_antialias(fe->cr, CAIRO_ANTIALIAS_GRAY);
208 cairo_set_line_width(fe->cr, 1.0);
209 cairo_set_line_cap(fe->cr, CAIRO_LINE_CAP_SQUARE);
210 cairo_set_line_join(fe->cr, CAIRO_LINE_JOIN_ROUND);
213 static void teardown_drawing(frontend *fe)
217 cairo_destroy(fe->cr);
220 cr = gdk_cairo_create(fe->pixmap);
221 cairo_set_source_surface(cr, fe->image, 0, 0);
225 fe->bbox_r - fe->bbox_l + 2,
226 fe->bbox_d - fe->bbox_u + 2);
231 static void snaffle_colours(frontend *fe)
233 fe->colours = midend_colours(fe->me, &fe->ncolours);
236 static void set_colour(frontend *fe, int colour)
238 cairo_set_source_rgb(fe->cr,
239 fe->colours[3*colour + 0],
240 fe->colours[3*colour + 1],
241 fe->colours[3*colour + 2]);
244 static void set_window_background(frontend *fe, int colour)
248 colmap = gdk_colormap_get_system();
249 fe->background.red = fe->colours[3*colour + 0] * 65535;
250 fe->background.green = fe->colours[3*colour + 1] * 65535;
251 fe->background.blue = fe->colours[3*colour + 2] * 65535;
252 if (!gdk_colormap_alloc_color(colmap, &fe->background, FALSE, FALSE)) {
253 g_error("couldn't allocate background (#%02x%02x%02x)\n",
254 fe->background.red >> 8, fe->background.green >> 8,
255 fe->background.blue >> 8);
257 gdk_window_set_background(fe->area->window, &fe->background);
258 gdk_window_set_background(fe->window->window, &fe->background);
261 static PangoLayout *make_pango_layout(frontend *fe)
263 return (pango_cairo_create_layout(fe->cr));
266 static void draw_pango_layout(frontend *fe, PangoLayout *layout,
269 cairo_move_to(fe->cr, x, y);
270 pango_cairo_show_layout(fe->cr, layout);
273 static void save_screenshot_png(frontend *fe, const char *screenshot_file)
275 cairo_surface_write_to_png(fe->image, screenshot_file);
278 static void do_clip(frontend *fe, int x, int y, int w, int h)
280 cairo_new_path(fe->cr);
281 cairo_rectangle(fe->cr, x, y, w, h);
285 static void do_unclip(frontend *fe)
287 cairo_reset_clip(fe->cr);
290 static void do_draw_rect(frontend *fe, int x, int y, int w, int h)
293 cairo_new_path(fe->cr);
294 cairo_set_antialias(fe->cr, CAIRO_ANTIALIAS_NONE);
295 cairo_rectangle(fe->cr, x, y, w, h);
297 cairo_restore(fe->cr);
300 static void do_draw_line(frontend *fe, int x1, int y1, int x2, int y2)
302 cairo_new_path(fe->cr);
303 cairo_move_to(fe->cr, x1 + 0.5, y1 + 0.5);
304 cairo_line_to(fe->cr, x2 + 0.5, y2 + 0.5);
305 cairo_stroke(fe->cr);
308 static void do_draw_thick_line(frontend *fe, float thickness,
309 float x1, float y1, float x2, float y2)
312 cairo_set_line_width(fe->cr, thickness);
313 cairo_new_path(fe->cr);
314 cairo_move_to(fe->cr, x1, y1);
315 cairo_line_to(fe->cr, x2, y2);
316 cairo_stroke(fe->cr);
317 cairo_restore(fe->cr);
320 static void do_draw_poly(frontend *fe, int *coords, int npoints,
321 int fillcolour, int outlinecolour)
325 cairo_new_path(fe->cr);
326 for (i = 0; i < npoints; i++)
327 cairo_line_to(fe->cr, coords[i*2] + 0.5, coords[i*2 + 1] + 0.5);
328 cairo_close_path(fe->cr);
329 if (fillcolour >= 0) {
330 set_colour(fe, fillcolour);
331 cairo_fill_preserve(fe->cr);
333 assert(outlinecolour >= 0);
334 set_colour(fe, outlinecolour);
335 cairo_stroke(fe->cr);
338 static void do_draw_circle(frontend *fe, int cx, int cy, int radius,
339 int fillcolour, int outlinecolour)
341 cairo_new_path(fe->cr);
342 cairo_arc(fe->cr, cx + 0.5, cy + 0.5, radius, 0, 2*PI);
343 cairo_close_path(fe->cr); /* Just in case... */
344 if (fillcolour >= 0) {
345 set_colour(fe, fillcolour);
346 cairo_fill_preserve(fe->cr);
348 assert(outlinecolour >= 0);
349 set_colour(fe, outlinecolour);
350 cairo_stroke(fe->cr);
353 static void setup_blitter(blitter *bl, int w, int h)
355 bl->image = cairo_image_surface_create(CAIRO_FORMAT_RGB24, w, h);
358 static void teardown_blitter(blitter *bl)
360 cairo_surface_destroy(bl->image);
363 static void do_blitter_save(frontend *fe, blitter *bl, int x, int y)
365 cairo_t *cr = cairo_create(bl->image);
367 cairo_set_source_surface(cr, fe->image, -x, -y);
372 static void do_blitter_load(frontend *fe, blitter *bl, int x, int y)
374 cairo_set_source_surface(fe->cr, bl->image, x, y);
378 static void clear_backing_store(frontend *fe)
383 static void setup_backing_store(frontend *fe)
388 fe->pixmap = gdk_pixmap_new(fe->area->window, fe->pw, fe->ph, -1);
389 fe->image = cairo_image_surface_create(CAIRO_FORMAT_RGB24,
392 for (i = 0; i < 3; i++) {
394 case 0: cr = cairo_create(fe->image); break;
395 case 1: cr = gdk_cairo_create(fe->pixmap); break;
396 case 2: cr = gdk_cairo_create(fe->area->window); break;
398 cairo_set_source_rgb(cr,
399 fe->colours[0], fe->colours[1], fe->colours[2]);
405 static int backing_store_ok(frontend *fe)
407 return (!!fe->image);
410 static void teardown_backing_store(frontend *fe)
412 cairo_surface_destroy(fe->image);
413 gdk_pixmap_unref(fe->pixmap);
419 /* ----------------------------------------------------------------------
420 * GDK drawing functions.
425 static void setup_drawing(frontend *fe)
427 fe->gc = gdk_gc_new(fe->area->window);
430 static void teardown_drawing(frontend *fe)
432 gdk_gc_unref(fe->gc);
436 static void snaffle_colours(frontend *fe)
442 fe->colmap = gdk_colormap_get_system();
443 colours = midend_colours(fe->me, &ncolours);
444 fe->ncolours = ncolours;
445 fe->colours = snewn(ncolours, GdkColor);
446 for (i = 0; i < ncolours; i++) {
447 fe->colours[i].red = colours[i*3] * 0xFFFF;
448 fe->colours[i].green = colours[i*3+1] * 0xFFFF;
449 fe->colours[i].blue = colours[i*3+2] * 0xFFFF;
451 success = snewn(ncolours, gboolean);
452 gdk_colormap_alloc_colors(fe->colmap, fe->colours, ncolours,
453 FALSE, FALSE, success);
454 for (i = 0; i < ncolours; i++) {
456 g_error("couldn't allocate colour %d (#%02x%02x%02x)\n",
457 i, fe->colours[i].red >> 8,
458 fe->colours[i].green >> 8,
459 fe->colours[i].blue >> 8);
464 static void set_window_background(frontend *fe, int colour)
466 fe->backgroundindex = colour;
467 gdk_window_set_background(fe->area->window, &fe->colours[colour]);
468 gdk_window_set_background(fe->window->window, &fe->colours[colour]);
471 static void set_colour(frontend *fe, int colour)
473 gdk_gc_set_foreground(fe->gc, &fe->colours[colour]);
477 static PangoLayout *make_pango_layout(frontend *fe)
479 return (pango_layout_new(gtk_widget_get_pango_context(fe->area)));
482 static void draw_pango_layout(frontend *fe, PangoLayout *layout,
485 gdk_draw_layout(fe->pixmap, fe->gc, x, y, layout);
489 static void save_screenshot_png(frontend *fe, const char *screenshot_file)
492 GError *gerror = NULL;
494 midend_redraw(fe->me);
496 pb = gdk_pixbuf_get_from_drawable(NULL, fe->pixmap,
497 NULL, 0, 0, 0, 0, -1, -1);
498 gdk_pixbuf_save(pb, screenshot_file, "png", &gerror, NULL);
501 static void do_clip(frontend *fe, int x, int y, int w, int h)
509 gdk_gc_set_clip_rectangle(fe->gc, &rect);
512 static void do_unclip(frontend *fe)
520 gdk_gc_set_clip_rectangle(fe->gc, &rect);
523 static void do_draw_rect(frontend *fe, int x, int y, int w, int h)
525 gdk_draw_rectangle(fe->pixmap, fe->gc, 1, x, y, w, h);
528 static void do_draw_line(frontend *fe, int x1, int y1, int x2, int y2)
530 gdk_draw_line(fe->pixmap, fe->gc, x1, y1, x2, y2);
533 static void do_draw_thick_line(frontend *fe, float thickness,
534 float x1, float y1, float x2, float y2)
538 gdk_gc_get_values(fe->gc, &save);
539 gdk_gc_set_line_attributes(fe->gc,
544 gdk_draw_line(fe->pixmap, fe->gc, x1, y1, x2, y2);
545 gdk_gc_set_line_attributes(fe->gc,
552 static void do_draw_poly(frontend *fe, int *coords, int npoints,
553 int fillcolour, int outlinecolour)
555 GdkPoint *points = snewn(npoints, GdkPoint);
558 for (i = 0; i < npoints; i++) {
559 points[i].x = coords[i*2];
560 points[i].y = coords[i*2+1];
563 if (fillcolour >= 0) {
564 set_colour(fe, fillcolour);
565 gdk_draw_polygon(fe->pixmap, fe->gc, TRUE, points, npoints);
567 assert(outlinecolour >= 0);
568 set_colour(fe, outlinecolour);
571 * In principle we ought to be able to use gdk_draw_polygon for
572 * the outline as well. In fact, it turns out to interact badly
573 * with a clipping region, for no terribly obvious reason, so I
574 * draw the outline as a sequence of lines instead.
576 for (i = 0; i < npoints; i++)
577 gdk_draw_line(fe->pixmap, fe->gc,
578 points[i].x, points[i].y,
579 points[(i+1)%npoints].x, points[(i+1)%npoints].y);
584 static void do_draw_circle(frontend *fe, int cx, int cy, int radius,
585 int fillcolour, int outlinecolour)
587 if (fillcolour >= 0) {
588 set_colour(fe, fillcolour);
589 gdk_draw_arc(fe->pixmap, fe->gc, TRUE,
590 cx - radius, cy - radius,
591 2 * radius, 2 * radius, 0, 360 * 64);
594 assert(outlinecolour >= 0);
595 set_colour(fe, outlinecolour);
596 gdk_draw_arc(fe->pixmap, fe->gc, FALSE,
597 cx - radius, cy - radius,
598 2 * radius, 2 * radius, 0, 360 * 64);
601 static void setup_blitter(blitter *bl, int w, int h)
604 * We can't create the pixmap right now, because fe->window
605 * might not yet exist. So we just cache w and h and create it
606 * during the firs call to blitter_save.
611 static void teardown_blitter(blitter *bl)
614 gdk_pixmap_unref(bl->pixmap);
617 static void do_blitter_save(frontend *fe, blitter *bl, int x, int y)
620 bl->pixmap = gdk_pixmap_new(fe->area->window, bl->w, bl->h, -1);
621 gdk_draw_pixmap(bl->pixmap,
622 fe->area->style->fg_gc[GTK_WIDGET_STATE(fe->area)],
624 x, y, 0, 0, bl->w, bl->h);
627 static void do_blitter_load(frontend *fe, blitter *bl, int x, int y)
630 gdk_draw_pixmap(fe->pixmap,
631 fe->area->style->fg_gc[GTK_WIDGET_STATE(fe->area)],
633 0, 0, x, y, bl->w, bl->h);
636 static void clear_backing_store(frontend *fe)
641 static void setup_backing_store(frontend *fe)
645 fe->pixmap = gdk_pixmap_new(fe->area->window, fe->pw, fe->ph, -1);
647 gc = gdk_gc_new(fe->area->window);
648 gdk_gc_set_foreground(gc, &fe->colours[0]);
649 gdk_draw_rectangle(fe->pixmap, gc, 1, 0, 0, fe->pw, fe->ph);
650 gdk_draw_rectangle(fe->area->window, gc, 1, 0, 0, fe->w, fe->h);
654 static int backing_store_ok(frontend *fe)
656 return (!!fe->pixmap);
659 static void teardown_backing_store(frontend *fe)
661 gdk_pixmap_unref(fe->pixmap);
667 static void repaint_rectangle(frontend *fe, GtkWidget *widget,
668 int x, int y, int w, int h)
670 GdkGC *gc = gdk_gc_new(widget->window);
672 gdk_gc_set_foreground(gc, &fe->background);
674 gdk_gc_set_foreground(gc, &fe->colours[fe->backgroundindex]);
677 gdk_draw_rectangle(widget->window, gc,
678 TRUE, x, y, fe->ox - x, h);
683 gdk_draw_rectangle(widget->window, gc,
684 TRUE, x, y, w, fe->oy - y);
689 gdk_draw_rectangle(widget->window, gc,
690 TRUE, x + fe->pw, y, w - fe->pw, h);
694 gdk_draw_rectangle(widget->window, gc,
695 TRUE, x, y + fe->ph, w, h - fe->ph);
698 gdk_draw_pixmap(widget->window, gc, fe->pixmap,
699 x - fe->ox, y - fe->oy, x, y, w, h);
703 /* ----------------------------------------------------------------------
704 * Pango font functions.
709 static void add_font(frontend *fe, int index, int fonttype, int fontsize)
712 * Use Pango to find the closest match to the requested
715 PangoFontDescription *fd;
717 fd = pango_font_description_new();
718 /* `Monospace' and `Sans' are meta-families guaranteed to exist */
719 pango_font_description_set_family(fd, fonttype == FONT_FIXED ?
720 "Monospace" : "Sans");
721 pango_font_description_set_weight(fd, PANGO_WEIGHT_BOLD);
723 * I found some online Pango documentation which
724 * described a function called
725 * pango_font_description_set_absolute_size(), which is
726 * _exactly_ what I want here. Unfortunately, none of
727 * my local Pango installations have it (presumably
728 * they're too old), so I'm going to have to hack round
729 * it by figuring out the point size myself. This
730 * limits me to X and probably also breaks in later
731 * Pango installations, so ideally I should add another
732 * CHECK_VERSION type ifdef and use set_absolute_size
733 * where available. All very annoying.
735 #ifdef HAVE_SENSIBLE_ABSOLUTE_SIZE_FUNCTION
736 pango_font_description_set_absolute_size(fd, PANGO_SCALE*fontsize);
739 Display *d = GDK_DISPLAY();
740 int s = DefaultScreen(d);
742 (PANGO_SCALE * 72.27 / 25.4) *
743 ((double) DisplayWidthMM(d, s) / DisplayWidth (d, s));
744 pango_font_description_set_size(fd, resolution * fontsize);
747 fe->fonts[index].desc = fd;
750 static void align_and_draw_text(frontend *fe,
751 int index, int align, int x, int y,
757 layout = make_pango_layout(fe);
762 pango_layout_set_font_description(layout, fe->fonts[index].desc);
763 pango_layout_set_text(layout, text, strlen(text));
764 pango_layout_get_pixel_extents(layout, NULL, &rect);
766 if (align & ALIGN_VCENTRE)
767 rect.y -= rect.height / 2;
769 rect.y -= rect.height;
771 if (align & ALIGN_HCENTRE)
772 rect.x -= rect.width / 2;
773 else if (align & ALIGN_HRIGHT)
774 rect.x -= rect.width;
776 draw_pango_layout(fe, layout, rect.x + x, rect.y + y);
778 g_object_unref(layout);
783 /* ----------------------------------------------------------------------
784 * Old-fashioned font functions.
789 static void add_font(int index, int fonttype, int fontsize)
792 * In GTK 1.2, I don't know of any plausible way to
793 * pick a suitable font, so I'm just going to be
796 fe->fonts[i].font = gdk_font_load(fonttype == FONT_FIXED ?
797 "fixed" : "variable");
800 static void align_and_draw_text(int index, int align, int x, int y,
803 int lb, rb, wid, asc, desc;
806 * Measure vertical string extents with respect to the same
809 gdk_string_extents(fe->fonts[i].font,
810 "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
811 &lb, &rb, &wid, &asc, &desc);
812 if (align & ALIGN_VCENTRE)
813 y += asc - (asc+desc)/2;
818 * ... but horizontal extents with respect to the provided
819 * string. This means that multiple pieces of text centred
820 * on the same y-coordinate don't have different baselines.
822 gdk_string_extents(fe->fonts[i].font, text,
823 &lb, &rb, &wid, &asc, &desc);
825 if (align & ALIGN_HCENTRE)
827 else if (align & ALIGN_HRIGHT)
831 * Actually draw the text.
833 gdk_draw_string(fe->pixmap, fe->fonts[i].font, fe->gc, x, y, text);
838 /* ----------------------------------------------------------------------
839 * The exported drawing functions.
842 void gtk_start_draw(void *handle)
844 frontend *fe = (frontend *)handle;
852 void gtk_clip(void *handle, int x, int y, int w, int h)
854 frontend *fe = (frontend *)handle;
855 do_clip(fe, x, y, w, h);
858 void gtk_unclip(void *handle)
860 frontend *fe = (frontend *)handle;
864 void gtk_draw_text(void *handle, int x, int y, int fonttype, int fontsize,
865 int align, int colour, char *text)
867 frontend *fe = (frontend *)handle;
871 * Find or create the font.
873 for (i = 0; i < fe->nfonts; i++)
874 if (fe->fonts[i].type == fonttype && fe->fonts[i].size == fontsize)
877 if (i == fe->nfonts) {
878 if (fe->fontsize <= fe->nfonts) {
879 fe->fontsize = fe->nfonts + 10;
880 fe->fonts = sresize(fe->fonts, fe->fontsize, struct font);
885 fe->fonts[i].type = fonttype;
886 fe->fonts[i].size = fontsize;
887 add_font(fe, i, fonttype, fontsize);
893 set_colour(fe, colour);
894 align_and_draw_text(fe, i, align, x, y, text);
897 void gtk_draw_rect(void *handle, int x, int y, int w, int h, int colour)
899 frontend *fe = (frontend *)handle;
900 set_colour(fe, colour);
901 do_draw_rect(fe, x, y, w, h);
904 void gtk_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
906 frontend *fe = (frontend *)handle;
907 set_colour(fe, colour);
908 do_draw_line(fe, x1, y1, x2, y2);
911 void gtk_draw_thick_line(void *handle, float thickness,
912 float x1, float y1, float x2, float y2, int colour)
914 frontend *fe = (frontend *)handle;
915 set_colour(fe, colour);
916 do_draw_thick_line(fe, thickness, x1, y1, x2, y2);
919 void gtk_draw_poly(void *handle, int *coords, int npoints,
920 int fillcolour, int outlinecolour)
922 frontend *fe = (frontend *)handle;
923 do_draw_poly(fe, coords, npoints, fillcolour, outlinecolour);
926 void gtk_draw_circle(void *handle, int cx, int cy, int radius,
927 int fillcolour, int outlinecolour)
929 frontend *fe = (frontend *)handle;
930 do_draw_circle(fe, cx, cy, radius, fillcolour, outlinecolour);
933 blitter *gtk_blitter_new(void *handle, int w, int h)
935 blitter *bl = snew(blitter);
936 setup_blitter(bl, w, h);
942 void gtk_blitter_free(void *handle, blitter *bl)
944 teardown_blitter(bl);
948 void gtk_blitter_save(void *handle, blitter *bl, int x, int y)
950 frontend *fe = (frontend *)handle;
951 do_blitter_save(fe, bl, x, y);
956 void gtk_blitter_load(void *handle, blitter *bl, int x, int y)
958 frontend *fe = (frontend *)handle;
959 if (x == BLITTER_FROMSAVED && y == BLITTER_FROMSAVED) {
963 do_blitter_load(fe, bl, x, y);
966 void gtk_draw_update(void *handle, int x, int y, int w, int h)
968 frontend *fe = (frontend *)handle;
969 if (fe->bbox_l > x ) fe->bbox_l = x ;
970 if (fe->bbox_r < x+w) fe->bbox_r = x+w;
971 if (fe->bbox_u > y ) fe->bbox_u = y ;
972 if (fe->bbox_d < y+h) fe->bbox_d = y+h;
975 void gtk_end_draw(void *handle)
977 frontend *fe = (frontend *)handle;
979 teardown_drawing(fe);
981 if (fe->bbox_l < fe->bbox_r && fe->bbox_u < fe->bbox_d) {
982 repaint_rectangle(fe, fe->area,
983 fe->bbox_l - 1 + fe->ox,
984 fe->bbox_u - 1 + fe->oy,
985 fe->bbox_r - fe->bbox_l + 2,
986 fe->bbox_d - fe->bbox_u + 2);
991 char *gtk_text_fallback(void *handle, const char *const *strings, int nstrings)
994 * We assume Pango can cope with any UTF-8 likely to be emitted
997 return dupstr(strings[0]);
1001 const struct drawing_api gtk_drawing = {
1017 NULL, NULL, NULL, NULL, NULL, NULL, /* {begin,end}_{doc,page,puzzle} */
1018 NULL, NULL, /* line_width, line_dotted */
1024 #ifdef NO_THICK_LINE
1027 gtk_draw_thick_line,
1031 static void destroy(GtkWidget *widget, gpointer data)
1033 frontend *fe = (frontend *)data;
1034 deactivate_timer(fe);
1035 midend_free(fe->me);
1039 static gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data)
1041 frontend *fe = (frontend *)data;
1043 int shift = (event->state & GDK_SHIFT_MASK) ? MOD_SHFT : 0;
1044 int ctrl = (event->state & GDK_CONTROL_MASK) ? MOD_CTRL : 0;
1046 if (!backing_store_ok(fe))
1049 #if !GTK_CHECK_VERSION(2,0,0)
1050 /* Gtk 1.2 passes a key event to this function even if it's also
1051 * defined as an accelerator.
1052 * Gtk 2 doesn't do this, and this function appears not to exist there. */
1053 if (fe->accelgroup &&
1054 gtk_accel_group_get_entry(fe->accelgroup,
1055 event->keyval, event->state))
1059 /* Handle mnemonics. */
1060 if (gtk_window_activate_key(GTK_WINDOW(fe->window), event))
1063 if (event->keyval == GDK_Up)
1064 keyval = shift | ctrl | CURSOR_UP;
1065 else if (event->keyval == GDK_KP_Up || event->keyval == GDK_KP_8)
1066 keyval = MOD_NUM_KEYPAD | '8';
1067 else if (event->keyval == GDK_Down)
1068 keyval = shift | ctrl | CURSOR_DOWN;
1069 else if (event->keyval == GDK_KP_Down || event->keyval == GDK_KP_2)
1070 keyval = MOD_NUM_KEYPAD | '2';
1071 else if (event->keyval == GDK_Left)
1072 keyval = shift | ctrl | CURSOR_LEFT;
1073 else if (event->keyval == GDK_KP_Left || event->keyval == GDK_KP_4)
1074 keyval = MOD_NUM_KEYPAD | '4';
1075 else if (event->keyval == GDK_Right)
1076 keyval = shift | ctrl | CURSOR_RIGHT;
1077 else if (event->keyval == GDK_KP_Right || event->keyval == GDK_KP_6)
1078 keyval = MOD_NUM_KEYPAD | '6';
1079 else if (event->keyval == GDK_KP_Home || event->keyval == GDK_KP_7)
1080 keyval = MOD_NUM_KEYPAD | '7';
1081 else if (event->keyval == GDK_KP_End || event->keyval == GDK_KP_1)
1082 keyval = MOD_NUM_KEYPAD | '1';
1083 else if (event->keyval == GDK_KP_Page_Up || event->keyval == GDK_KP_9)
1084 keyval = MOD_NUM_KEYPAD | '9';
1085 else if (event->keyval == GDK_KP_Page_Down || event->keyval == GDK_KP_3)
1086 keyval = MOD_NUM_KEYPAD | '3';
1087 else if (event->keyval == GDK_KP_Insert || event->keyval == GDK_KP_0)
1088 keyval = MOD_NUM_KEYPAD | '0';
1089 else if (event->keyval == GDK_KP_Begin || event->keyval == GDK_KP_5)
1090 keyval = MOD_NUM_KEYPAD | '5';
1091 else if (event->keyval == GDK_BackSpace ||
1092 event->keyval == GDK_Delete ||
1093 event->keyval == GDK_KP_Delete)
1095 else if (event->string[0] && !event->string[1])
1096 keyval = (unsigned char)event->string[0];
1101 !midend_process_key(fe->me, 0, 0, keyval))
1102 gtk_widget_destroy(fe->window);
1107 static gint button_event(GtkWidget *widget, GdkEventButton *event,
1110 frontend *fe = (frontend *)data;
1113 if (!backing_store_ok(fe))
1116 if (event->type != GDK_BUTTON_PRESS && event->type != GDK_BUTTON_RELEASE)
1119 if (event->button == 2 || (event->state & GDK_SHIFT_MASK))
1120 button = MIDDLE_BUTTON;
1121 else if (event->button == 3 || (event->state & GDK_MOD1_MASK))
1122 button = RIGHT_BUTTON;
1123 else if (event->button == 1)
1124 button = LEFT_BUTTON;
1126 return FALSE; /* don't even know what button! */
1128 if (event->type == GDK_BUTTON_RELEASE)
1129 button += LEFT_RELEASE - LEFT_BUTTON;
1131 if (!midend_process_key(fe->me, event->x - fe->ox,
1132 event->y - fe->oy, button))
1133 gtk_widget_destroy(fe->window);
1138 static gint motion_event(GtkWidget *widget, GdkEventMotion *event,
1141 frontend *fe = (frontend *)data;
1144 if (!backing_store_ok(fe))
1147 if (event->state & (GDK_BUTTON2_MASK | GDK_SHIFT_MASK))
1148 button = MIDDLE_DRAG;
1149 else if (event->state & GDK_BUTTON1_MASK)
1151 else if (event->state & GDK_BUTTON3_MASK)
1152 button = RIGHT_DRAG;
1154 return FALSE; /* don't even know what button! */
1156 if (!midend_process_key(fe->me, event->x - fe->ox,
1157 event->y - fe->oy, button))
1158 gtk_widget_destroy(fe->window);
1159 #if GTK_CHECK_VERSION(2,12,0)
1160 gdk_event_request_motions(event);
1162 gdk_window_get_pointer(widget->window, NULL, NULL, NULL);
1168 static gint expose_area(GtkWidget *widget, GdkEventExpose *event,
1171 frontend *fe = (frontend *)data;
1173 if (backing_store_ok(fe)) {
1174 repaint_rectangle(fe, widget,
1175 event->area.x, event->area.y,
1176 event->area.width, event->area.height);
1181 static gint map_window(GtkWidget *widget, GdkEvent *event,
1184 frontend *fe = (frontend *)data;
1187 * Apparently we need to do this because otherwise the status
1188 * bar will fail to update immediately. Annoying, but there we
1191 gtk_widget_queue_draw(fe->window);
1196 static gint configure_area(GtkWidget *widget,
1197 GdkEventConfigure *event, gpointer data)
1199 frontend *fe = (frontend *)data;
1202 if (backing_store_ok(fe))
1203 teardown_backing_store(fe);
1205 x = fe->w = event->width;
1206 y = fe->h = event->height;
1207 midend_size(fe->me, &x, &y, TRUE);
1210 fe->ox = (fe->w - fe->pw) / 2;
1211 fe->oy = (fe->h - fe->ph) / 2;
1213 setup_backing_store(fe);
1214 midend_force_redraw(fe->me);
1219 static gint timer_func(gpointer data)
1221 frontend *fe = (frontend *)data;
1223 if (fe->timer_active) {
1226 gettimeofday(&now, NULL);
1227 elapsed = ((now.tv_usec - fe->last_time.tv_usec) * 0.000001F +
1228 (now.tv_sec - fe->last_time.tv_sec));
1229 midend_timer(fe->me, elapsed); /* may clear timer_active */
1230 fe->last_time = now;
1233 return fe->timer_active;
1236 void deactivate_timer(frontend *fe)
1239 return; /* can happen due to --generate */
1240 if (fe->timer_active)
1241 gtk_timeout_remove(fe->timer_id);
1242 fe->timer_active = FALSE;
1245 void activate_timer(frontend *fe)
1248 return; /* can happen due to --generate */
1249 if (!fe->timer_active) {
1250 fe->timer_id = gtk_timeout_add(20, timer_func, fe);
1251 gettimeofday(&fe->last_time, NULL);
1253 fe->timer_active = TRUE;
1256 static void window_destroy(GtkWidget *widget, gpointer data)
1261 static void msgbox_button_clicked(GtkButton *button, gpointer data)
1263 GtkWidget *window = GTK_WIDGET(data);
1266 ip = (int *)gtk_object_get_data(GTK_OBJECT(window), "user-data");
1267 v = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(button), "user-data"));
1270 gtk_widget_destroy(GTK_WIDGET(data));
1273 static int win_key_press(GtkWidget *widget, GdkEventKey *event, gpointer data)
1275 GtkObject *cancelbutton = GTK_OBJECT(data);
1278 * `Escape' effectively clicks the cancel button
1280 if (event->keyval == GDK_Escape) {
1281 gtk_signal_emit_by_name(GTK_OBJECT(cancelbutton), "clicked");
1288 enum { MB_OK, MB_YESNO };
1290 int message_box(GtkWidget *parent, char *title, char *msg, int centre,
1293 GtkWidget *window, *hbox, *text, *button;
1297 window = gtk_dialog_new();
1298 text = gtk_label_new(msg);
1299 gtk_misc_set_alignment(GTK_MISC(text), 0.0, 0.0);
1300 hbox = gtk_hbox_new(FALSE, 0);
1301 gtk_box_pack_start(GTK_BOX(hbox), text, FALSE, FALSE, 20);
1302 gtk_box_pack_start(GTK_BOX(GTK_DIALOG(window)->vbox),
1303 hbox, FALSE, FALSE, 20);
1304 gtk_widget_show(text);
1305 gtk_widget_show(hbox);
1306 gtk_window_set_title(GTK_WINDOW(window), title);
1307 gtk_label_set_line_wrap(GTK_LABEL(text), TRUE);
1309 if (type == MB_OK) {
1310 titles = GTK_STOCK_OK "\0";
1313 assert(type == MB_YESNO);
1314 titles = GTK_STOCK_NO "\0" GTK_STOCK_YES "\0";
1321 button = gtk_button_new_from_stock(titles);
1322 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(window)->action_area),
1323 button, FALSE, FALSE, 0);
1324 gtk_widget_show(button);
1326 GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
1327 gtk_window_set_default(GTK_WINDOW(window), button);
1330 gtk_signal_connect(GTK_OBJECT(window), "key_press_event",
1331 GTK_SIGNAL_FUNC(win_key_press), button);
1333 gtk_signal_connect(GTK_OBJECT(button), "clicked",
1334 GTK_SIGNAL_FUNC(msgbox_button_clicked), window);
1335 gtk_object_set_data(GTK_OBJECT(button), "user-data",
1336 GINT_TO_POINTER(i));
1337 titles += strlen(titles)+1;
1340 gtk_object_set_data(GTK_OBJECT(window), "user-data", &i);
1341 gtk_signal_connect(GTK_OBJECT(window), "destroy",
1342 GTK_SIGNAL_FUNC(window_destroy), NULL);
1343 gtk_window_set_modal(GTK_WINDOW(window), TRUE);
1344 gtk_window_set_transient_for(GTK_WINDOW(window), GTK_WINDOW(parent));
1345 /* set_transient_window_pos(parent, window); */
1346 gtk_widget_show(window);
1349 return (type == MB_YESNO ? i == 1 : TRUE);
1352 void error_box(GtkWidget *parent, char *msg)
1354 message_box(parent, "Error", msg, FALSE, MB_OK);
1357 static void config_ok_button_clicked(GtkButton *button, gpointer data)
1359 frontend *fe = (frontend *)data;
1362 err = midend_set_config(fe->me, fe->cfg_which, fe->cfg);
1365 error_box(fe->cfgbox, err);
1368 gtk_widget_destroy(fe->cfgbox);
1373 static void config_cancel_button_clicked(GtkButton *button, gpointer data)
1375 frontend *fe = (frontend *)data;
1377 gtk_widget_destroy(fe->cfgbox);
1380 static int editbox_key(GtkWidget *widget, GdkEventKey *event, gpointer data)
1383 * GtkEntry has a nasty habit of eating the Return key, which
1384 * is unhelpful since it doesn't actually _do_ anything with it
1385 * (it calls gtk_widget_activate, but our edit boxes never need
1386 * activating). So I catch Return before GtkEntry sees it, and
1387 * pass it straight on to the parent widget. Effect: hitting
1388 * Return in an edit box will now activate the default button
1389 * in the dialog just like it will everywhere else.
1391 if (event->keyval == GDK_Return && widget->parent != NULL) {
1393 gtk_signal_emit_stop_by_name(GTK_OBJECT(widget), "key_press_event");
1394 gtk_signal_emit_by_name(GTK_OBJECT(widget->parent), "key_press_event",
1395 event, &return_val);
1401 static void editbox_changed(GtkEditable *ed, gpointer data)
1403 config_item *i = (config_item *)data;
1406 i->sval = dupstr(gtk_entry_get_text(GTK_ENTRY(ed)));
1409 static void button_toggled(GtkToggleButton *tb, gpointer data)
1411 config_item *i = (config_item *)data;
1413 i->ival = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(tb));
1416 static void droplist_sel(GtkMenuItem *item, gpointer data)
1418 config_item *i = (config_item *)data;
1420 i->ival = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(item),
1424 static int get_config(frontend *fe, int which)
1426 GtkWidget *w, *table, *cancel;
1431 fe->cfg = midend_get_config(fe->me, which, &title);
1432 fe->cfg_which = which;
1435 fe->cfgbox = gtk_dialog_new();
1436 gtk_window_set_title(GTK_WINDOW(fe->cfgbox), title);
1439 w = gtk_button_new_from_stock(GTK_STOCK_CANCEL);
1440 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(fe->cfgbox)->action_area),
1441 w, FALSE, FALSE, 0);
1443 gtk_signal_connect(GTK_OBJECT(w), "clicked",
1444 GTK_SIGNAL_FUNC(config_cancel_button_clicked), fe);
1447 w = gtk_button_new_from_stock(GTK_STOCK_OK);
1448 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(fe->cfgbox)->action_area),
1449 w, FALSE, FALSE, 0);
1451 GTK_WIDGET_SET_FLAGS(w, GTK_CAN_DEFAULT);
1452 gtk_window_set_default(GTK_WINDOW(fe->cfgbox), w);
1453 gtk_signal_connect(GTK_OBJECT(w), "clicked",
1454 GTK_SIGNAL_FUNC(config_ok_button_clicked), fe);
1456 table = gtk_table_new(1, 2, FALSE);
1458 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(fe->cfgbox)->vbox),
1459 table, FALSE, FALSE, 0);
1460 gtk_widget_show(table);
1462 for (i = fe->cfg; i->type != C_END; i++) {
1463 gtk_table_resize(GTK_TABLE(table), y+1, 2);
1468 * Edit box with a label beside it.
1471 w = gtk_label_new(i->name);
1472 gtk_misc_set_alignment(GTK_MISC(w), 0.0, 0.5);
1473 gtk_table_attach(GTK_TABLE(table), w, 0, 1, y, y+1,
1474 GTK_SHRINK | GTK_FILL,
1475 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1479 w = gtk_entry_new();
1480 gtk_table_attach(GTK_TABLE(table), w, 1, 2, y, y+1,
1481 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1482 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1484 gtk_entry_set_text(GTK_ENTRY(w), i->sval);
1485 gtk_signal_connect(GTK_OBJECT(w), "changed",
1486 GTK_SIGNAL_FUNC(editbox_changed), i);
1487 gtk_signal_connect(GTK_OBJECT(w), "key_press_event",
1488 GTK_SIGNAL_FUNC(editbox_key), NULL);
1497 w = gtk_check_button_new_with_label(i->name);
1498 gtk_signal_connect(GTK_OBJECT(w), "toggled",
1499 GTK_SIGNAL_FUNC(button_toggled), i);
1500 gtk_table_attach(GTK_TABLE(table), w, 0, 2, y, y+1,
1501 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1502 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1504 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(w), i->ival);
1510 * Drop-down list (GtkOptionMenu).
1513 w = gtk_label_new(i->name);
1514 gtk_misc_set_alignment(GTK_MISC(w), 0.0, 0.5);
1515 gtk_table_attach(GTK_TABLE(table), w, 0, 1, y, y+1,
1516 GTK_SHRINK | GTK_FILL,
1517 GTK_EXPAND | GTK_SHRINK | GTK_FILL ,
1521 w = gtk_option_menu_new();
1522 gtk_table_attach(GTK_TABLE(table), w, 1, 2, y, y+1,
1523 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1524 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1531 GtkWidget *menuitem;
1532 GtkWidget *menu = gtk_menu_new();
1534 gtk_option_menu_set_menu(GTK_OPTION_MENU(w), menu);
1542 while (*q && *q != c)
1545 name = snewn(q-p+1, char);
1546 strncpy(name, p, q-p);
1549 if (*q) q++; /* eat delimiter */
1551 menuitem = gtk_menu_item_new_with_label(name);
1552 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1553 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1554 GINT_TO_POINTER(val));
1555 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1556 GTK_SIGNAL_FUNC(droplist_sel), i);
1557 gtk_widget_show(menuitem);
1564 gtk_option_menu_set_history(GTK_OPTION_MENU(w), i->ival);
1573 gtk_signal_connect(GTK_OBJECT(fe->cfgbox), "destroy",
1574 GTK_SIGNAL_FUNC(window_destroy), NULL);
1575 gtk_signal_connect(GTK_OBJECT(fe->cfgbox), "key_press_event",
1576 GTK_SIGNAL_FUNC(win_key_press), cancel);
1577 gtk_window_set_modal(GTK_WINDOW(fe->cfgbox), TRUE);
1578 gtk_window_set_transient_for(GTK_WINDOW(fe->cfgbox),
1579 GTK_WINDOW(fe->window));
1580 /* set_transient_window_pos(fe->window, fe->cfgbox); */
1581 gtk_widget_show(fe->cfgbox);
1589 static void menu_key_event(GtkMenuItem *menuitem, gpointer data)
1591 frontend *fe = (frontend *)data;
1592 int key = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(menuitem),
1594 if (!midend_process_key(fe->me, 0, 0, key))
1595 gtk_widget_destroy(fe->window);
1598 static void get_size(frontend *fe, int *px, int *py)
1603 * Currently I don't want to make the GTK port scale large
1604 * puzzles to fit on the screen. This is because X does permit
1605 * extremely large windows and many window managers provide a
1606 * means of navigating round them, and the users I consulted
1607 * before deciding said that they'd rather have enormous puzzle
1608 * windows spanning multiple screen pages than have them
1609 * shrunk. I could change my mind later or introduce
1610 * configurability; this would be the place to do so, by
1611 * replacing the initial values of x and y with the screen
1616 midend_size(fe->me, &x, &y, FALSE);
1621 #if !GTK_CHECK_VERSION(2,0,0)
1622 #define gtk_window_resize(win, x, y) \
1623 gdk_window_resize(GTK_WIDGET(win)->window, x, y)
1627 * Called when any other code in this file has changed the
1628 * selected game parameters.
1630 static void changed_preset(frontend *fe)
1632 int n = midend_which_preset(fe->me);
1634 fe->preset_threaded = TRUE;
1635 if (n < 0 && fe->preset_custom) {
1636 gtk_check_menu_item_set_active(
1637 GTK_CHECK_MENU_ITEM(fe->preset_custom),
1640 GSList *gs = fe->preset_radio;
1641 int i = fe->n_preset_menu_items - 1 - n;
1642 if (fe->preset_custom)
1649 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(gs->data),
1651 } else for (gs = fe->preset_radio; gs; gs = gs->next) {
1652 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(gs->data),
1656 fe->preset_threaded = FALSE;
1659 * Update the greying on the Copy menu option.
1661 if (fe->copy_menu_item) {
1662 int enabled = midend_can_format_as_text_now(fe->me);
1663 gtk_widget_set_sensitive(fe->copy_menu_item, enabled);
1667 static gboolean not_size_allocated_yet(GtkWidget *w)
1670 * This function tests whether a widget has not yet taken up space
1671 * on the screen which it will occupy in future. (Therefore, it
1672 * returns true only if the widget does exist but does not have a
1673 * size allocation. A null widget is already taking up all the
1674 * space it ever will.)
1677 return FALSE; /* nonexistent widgets aren't a problem */
1679 #if GTK_CHECK_VERSION(2,18,0) /* skip if no gtk_widget_get_allocation */
1682 gtk_widget_get_allocation(w, &a);
1683 if (a.height == 0 || a.width == 0)
1684 return TRUE; /* widget exists but has no size yet */
1691 static void try_shrink_drawing_area(frontend *fe)
1693 if (fe->drawing_area_shrink_pending &&
1694 (!fe->menubar_is_local || !not_size_allocated_yet(fe->menubar)) &&
1695 !not_size_allocated_yet(fe->statusbar)) {
1697 * In order to permit the user to resize the window smaller as
1698 * well as bigger, we call this function after the window size
1699 * has ended up where we want it. This shouldn't shrink the
1700 * window immediately; it just arranges that the next time the
1701 * user tries to shrink it, they can.
1703 * However, at puzzle creation time, we defer the first of
1704 * these operations until after the menu bar and status bar
1705 * are actually visible. On Ubuntu 12.04 I've found that these
1706 * can take a while to be displayed, and that it's a mistake
1707 * to reduce the drawing area's size allocation before they've
1708 * turned up or else the drawing area makes room for them by
1709 * shrinking to less than the size we intended.
1711 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), 1, 1);
1712 fe->drawing_area_shrink_pending = FALSE;
1716 static gint configure_window(GtkWidget *widget,
1717 GdkEventConfigure *event, gpointer data)
1719 frontend *fe = (frontend *)data;
1721 * When the main puzzle window changes size, it might be because
1722 * the menu bar or status bar has turned up after starting off
1723 * absent, in which case we should have another go at enacting a
1724 * pending shrink of the drawing area.
1726 try_shrink_drawing_area(fe);
1730 static void resize_fe(frontend *fe)
1734 get_size(fe, &x, &y);
1737 fe->drawing_area_shrink_pending = FALSE;
1738 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
1741 gtk_widget_size_request(GTK_WIDGET(fe->window), &req);
1742 gtk_window_resize(GTK_WINDOW(fe->window), req.width, req.height);
1744 fe->drawing_area_shrink_pending = TRUE;
1745 try_shrink_drawing_area(fe);
1748 static void menu_preset_event(GtkMenuItem *menuitem, gpointer data)
1750 frontend *fe = (frontend *)data;
1751 game_params *params =
1752 (game_params *)gtk_object_get_data(GTK_OBJECT(menuitem), "user-data");
1754 if (fe->preset_threaded ||
1755 (GTK_IS_CHECK_MENU_ITEM(menuitem) &&
1756 !gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(menuitem))))
1758 midend_set_params(fe->me, params);
1759 midend_new_game(fe->me);
1764 GdkAtom compound_text_atom, utf8_string_atom;
1765 int paste_initialised = FALSE;
1767 static void set_selection(frontend *fe, GdkAtom selection)
1769 if (!paste_initialised) {
1770 compound_text_atom = gdk_atom_intern("COMPOUND_TEXT", FALSE);
1771 utf8_string_atom = gdk_atom_intern("UTF8_STRING", FALSE);
1772 paste_initialised = TRUE;
1776 * For this simple application we can safely assume that the
1777 * data passed to this function is pure ASCII, which means we
1778 * can return precisely the same stuff for types STRING,
1779 * COMPOUND_TEXT or UTF8_STRING.
1782 if (gtk_selection_owner_set(fe->area, selection, CurrentTime)) {
1783 gtk_selection_clear_targets(fe->area, selection);
1784 gtk_selection_add_target(fe->area, selection,
1785 GDK_SELECTION_TYPE_STRING, 1);
1786 gtk_selection_add_target(fe->area, selection, compound_text_atom, 1);
1787 gtk_selection_add_target(fe->area, selection, utf8_string_atom, 1);
1791 void write_clip(frontend *fe, char *data)
1794 sfree(fe->paste_data);
1796 fe->paste_data = data;
1797 fe->paste_data_len = strlen(data);
1799 set_selection(fe, GDK_SELECTION_PRIMARY);
1800 set_selection(fe, GDK_SELECTION_CLIPBOARD);
1803 void selection_get(GtkWidget *widget, GtkSelectionData *seldata,
1804 guint info, guint time_stamp, gpointer data)
1806 frontend *fe = (frontend *)data;
1807 gtk_selection_data_set(seldata, seldata->target, 8,
1808 fe->paste_data, fe->paste_data_len);
1811 gint selection_clear(GtkWidget *widget, GdkEventSelection *seldata,
1814 frontend *fe = (frontend *)data;
1817 sfree(fe->paste_data);
1818 fe->paste_data = NULL;
1819 fe->paste_data_len = 0;
1823 static void menu_copy_event(GtkMenuItem *menuitem, gpointer data)
1825 frontend *fe = (frontend *)data;
1828 text = midend_text_format(fe->me);
1831 write_clip(fe, text);
1839 static void filesel_ok(GtkButton *button, gpointer data)
1841 frontend *fe = (frontend *)data;
1843 gpointer filesel = gtk_object_get_data(GTK_OBJECT(button), "user-data");
1846 gtk_file_selection_get_filename(GTK_FILE_SELECTION(filesel));
1848 fe->filesel_name = dupstr(name);
1851 static char *file_selector(frontend *fe, char *title, int save)
1853 GtkWidget *filesel =
1854 gtk_file_selection_new(title);
1856 fe->filesel_name = NULL;
1858 gtk_window_set_modal(GTK_WINDOW(filesel), TRUE);
1860 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "user-data",
1863 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "clicked",
1864 GTK_SIGNAL_FUNC(filesel_ok), fe);
1865 gtk_signal_connect_object
1866 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "clicked",
1867 GTK_SIGNAL_FUNC(gtk_widget_destroy), (gpointer)filesel);
1868 gtk_signal_connect_object
1869 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->cancel_button), "clicked",
1870 GTK_SIGNAL_FUNC(gtk_widget_destroy), (gpointer)filesel);
1871 gtk_signal_connect(GTK_OBJECT(filesel), "destroy",
1872 GTK_SIGNAL_FUNC(window_destroy), NULL);
1873 gtk_widget_show(filesel);
1874 gtk_window_set_transient_for(GTK_WINDOW(filesel), GTK_WINDOW(fe->window));
1877 return fe->filesel_name;
1882 static char *file_selector(frontend *fe, char *title, int save)
1884 char *filesel_name = NULL;
1886 GtkWidget *filesel =
1887 gtk_file_chooser_dialog_new(title,
1888 GTK_WINDOW(fe->window),
1889 save ? GTK_FILE_CHOOSER_ACTION_SAVE :
1890 GTK_FILE_CHOOSER_ACTION_OPEN,
1891 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
1892 save ? GTK_STOCK_SAVE : GTK_STOCK_OPEN,
1893 GTK_RESPONSE_ACCEPT,
1896 if (gtk_dialog_run(GTK_DIALOG(filesel)) == GTK_RESPONSE_ACCEPT) {
1897 const char *name = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(filesel));
1898 filesel_name = dupstr(name);
1901 gtk_widget_destroy(filesel);
1903 return filesel_name;
1908 struct savefile_write_ctx {
1913 static void savefile_write(void *wctx, void *buf, int len)
1915 struct savefile_write_ctx *ctx = (struct savefile_write_ctx *)wctx;
1916 if (fwrite(buf, 1, len, ctx->fp) < len)
1920 static int savefile_read(void *wctx, void *buf, int len)
1922 FILE *fp = (FILE *)wctx;
1925 ret = fread(buf, 1, len, fp);
1926 return (ret == len);
1929 static void menu_save_event(GtkMenuItem *menuitem, gpointer data)
1931 frontend *fe = (frontend *)data;
1934 name = file_selector(fe, "Enter name of game file to save", TRUE);
1939 if ((fp = fopen(name, "r")) != NULL) {
1940 char buf[256 + FILENAME_MAX];
1944 sprintf(buf, "Are you sure you want to overwrite the"
1946 FILENAME_MAX, name);
1947 if (!message_box(fe->window, "Question", buf, TRUE, MB_YESNO))
1951 fp = fopen(name, "w");
1955 error_box(fe->window, "Unable to open save file");
1960 struct savefile_write_ctx ctx;
1963 midend_serialise(fe->me, savefile_write, &ctx);
1967 sprintf(boxmsg, "Error writing save file: %.400s",
1969 error_box(fe->window, boxmsg);
1977 static void menu_load_event(GtkMenuItem *menuitem, gpointer data)
1979 frontend *fe = (frontend *)data;
1982 name = file_selector(fe, "Enter name of saved game file to load", FALSE);
1985 FILE *fp = fopen(name, "r");
1989 error_box(fe->window, "Unable to open saved game file");
1993 err = midend_deserialise(fe->me, savefile_read, fp);
1998 error_box(fe->window, err);
2007 static void menu_solve_event(GtkMenuItem *menuitem, gpointer data)
2009 frontend *fe = (frontend *)data;
2012 msg = midend_solve(fe->me);
2015 error_box(fe->window, msg);
2018 static void menu_restart_event(GtkMenuItem *menuitem, gpointer data)
2020 frontend *fe = (frontend *)data;
2022 midend_restart_game(fe->me);
2025 static void menu_config_event(GtkMenuItem *menuitem, gpointer data)
2027 frontend *fe = (frontend *)data;
2028 int which = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(menuitem),
2031 if (fe->preset_threaded ||
2032 (GTK_IS_CHECK_MENU_ITEM(menuitem) &&
2033 !gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(menuitem))))
2035 changed_preset(fe); /* Put the old preset back! */
2036 if (!get_config(fe, which))
2039 midend_new_game(fe->me);
2043 static void menu_about_event(GtkMenuItem *menuitem, gpointer data)
2045 frontend *fe = (frontend *)data;
2049 sprintf(titlebuf, "About %.200s", thegame.name);
2052 "from Simon Tatham's Portable Puzzle Collection\n\n"
2053 "%.500s", thegame.name, ver);
2055 message_box(fe->window, titlebuf, textbuf, TRUE, MB_OK);
2058 static GtkWidget *add_menu_item_with_key(frontend *fe, GtkContainer *cont,
2059 char *text, int key)
2061 GtkWidget *menuitem = gtk_menu_item_new_with_label(text);
2063 gtk_container_add(cont, menuitem);
2064 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
2065 GINT_TO_POINTER(key));
2066 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2067 GTK_SIGNAL_FUNC(menu_key_event), fe);
2068 switch (key & ~0x1F) {
2071 keyqual = GDK_CONTROL_MASK;
2075 keyqual = GDK_SHIFT_MASK;
2081 gtk_widget_add_accelerator(menuitem,
2082 "activate", fe->accelgroup,
2085 gtk_widget_show(menuitem);
2089 static void add_menu_separator(GtkContainer *cont)
2091 GtkWidget *menuitem = gtk_menu_item_new();
2092 gtk_container_add(cont, menuitem);
2093 gtk_widget_show(menuitem);
2096 enum { ARG_EITHER, ARG_SAVE, ARG_ID }; /* for argtype */
2098 static frontend *new_window(char *arg, int argtype, char **error)
2101 GtkBox *vbox, *hbox;
2102 GtkWidget *menu, *menuitem;
2107 extern char *const *const xpm_icons[];
2108 extern const int n_xpm_icons;
2110 fe = snew(frontend);
2112 fe->timer_active = FALSE;
2115 fe->me = midend_new(fe, &thegame, >k_drawing, fe);
2125 err = midend_game_id(fe->me, arg);
2127 midend_new_game(fe->me);
2129 sprintf(errbuf, "Invalid game ID: %.800s", err);
2132 fp = fopen(arg, "r");
2134 sprintf(errbuf, "Error opening file: %.800s", strerror(errno));
2136 err = midend_deserialise(fe->me, savefile_read, fp);
2138 sprintf(errbuf, "Invalid save file: %.800s", err);
2142 default /*case ARG_EITHER*/:
2144 * First try treating the argument as a game ID.
2146 err = midend_game_id(fe->me, arg);
2149 * It's a valid game ID.
2151 midend_new_game(fe->me);
2153 FILE *fp = fopen(arg, "r");
2155 sprintf(errbuf, "Supplied argument is neither a game ID (%.400s)"
2156 " nor a save file (%.400s)", err, strerror(errno));
2158 err = midend_deserialise(fe->me, savefile_read, fp);
2160 sprintf(errbuf, "%.800s", err);
2167 *error = dupstr(errbuf);
2168 midend_free(fe->me);
2174 midend_new_game(fe->me);
2179 * try_shrink_drawing_area() will do some fiddling with the
2180 * window size request (see comment in that function) after
2181 * all the bits and pieces such as the menu bar and status bar
2182 * have appeared in the puzzle window.
2184 * However, on Unity systems, the menu bar _doesn't_ appear in
2185 * the puzzle window, because the Unity shell hijacks it into
2186 * the menu bar at the very top of the screen. We therefore
2187 * try to detect that situation here, so that we don't sit
2188 * here forever waiting for a menu bar.
2190 const char prop[] = "gtk-shell-shows-menubar";
2191 GtkSettings *settings = gtk_settings_get_default();
2192 if (!g_object_class_find_property(G_OBJECT_GET_CLASS(settings),
2194 fe->menubar_is_local = TRUE;
2197 g_object_get(gtk_settings_get_default(),
2199 (const gchar *)NULL);
2200 fe->menubar_is_local = !unity_mode;
2204 fe->window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
2205 gtk_window_set_title(GTK_WINDOW(fe->window), thegame.name);
2207 vbox = GTK_BOX(gtk_vbox_new(FALSE, 0));
2208 gtk_container_add(GTK_CONTAINER(fe->window), GTK_WIDGET(vbox));
2209 gtk_widget_show(GTK_WIDGET(vbox));
2211 fe->accelgroup = gtk_accel_group_new();
2212 gtk_window_add_accel_group(GTK_WINDOW(fe->window), fe->accelgroup);
2214 hbox = GTK_BOX(gtk_hbox_new(FALSE, 0));
2215 gtk_box_pack_start(vbox, GTK_WIDGET(hbox), FALSE, FALSE, 0);
2216 gtk_widget_show(GTK_WIDGET(hbox));
2218 fe->menubar = gtk_menu_bar_new();
2219 gtk_box_pack_start(hbox, fe->menubar, TRUE, TRUE, 0);
2220 gtk_widget_show(fe->menubar);
2222 menuitem = gtk_menu_item_new_with_mnemonic("_Game");
2223 gtk_container_add(GTK_CONTAINER(fe->menubar), menuitem);
2224 gtk_widget_show(menuitem);
2226 menu = gtk_menu_new();
2227 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
2229 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "New", 'n');
2231 menuitem = gtk_menu_item_new_with_label("Restart");
2232 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2233 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2234 GTK_SIGNAL_FUNC(menu_restart_event), fe);
2235 gtk_widget_show(menuitem);
2237 menuitem = gtk_menu_item_new_with_label("Specific...");
2238 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
2239 GINT_TO_POINTER(CFG_DESC));
2240 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2241 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2242 GTK_SIGNAL_FUNC(menu_config_event), fe);
2243 gtk_widget_show(menuitem);
2245 menuitem = gtk_menu_item_new_with_label("Random Seed...");
2246 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
2247 GINT_TO_POINTER(CFG_SEED));
2248 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2249 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2250 GTK_SIGNAL_FUNC(menu_config_event), fe);
2251 gtk_widget_show(menuitem);
2253 fe->preset_radio = NULL;
2254 fe->preset_custom = NULL;
2255 fe->n_preset_menu_items = 0;
2256 fe->preset_threaded = FALSE;
2257 if ((n = midend_num_presets(fe->me)) > 0 || thegame.can_configure) {
2261 menuitem = gtk_menu_item_new_with_mnemonic("_Type");
2262 gtk_container_add(GTK_CONTAINER(fe->menubar), menuitem);
2263 gtk_widget_show(menuitem);
2265 submenu = gtk_menu_new();
2266 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), submenu);
2268 for (i = 0; i < n; i++) {
2270 game_params *params;
2272 midend_fetch_preset(fe->me, i, &name, ¶ms);
2275 gtk_radio_menu_item_new_with_label(fe->preset_radio, name);
2277 gtk_radio_menu_item_group(GTK_RADIO_MENU_ITEM(menuitem));
2278 fe->n_preset_menu_items++;
2279 gtk_container_add(GTK_CONTAINER(submenu), menuitem);
2280 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data", params);
2281 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2282 GTK_SIGNAL_FUNC(menu_preset_event), fe);
2283 gtk_widget_show(menuitem);
2286 if (thegame.can_configure) {
2287 menuitem = fe->preset_custom =
2288 gtk_radio_menu_item_new_with_label(fe->preset_radio,
2291 gtk_radio_menu_item_group(GTK_RADIO_MENU_ITEM(menuitem));
2292 gtk_container_add(GTK_CONTAINER(submenu), menuitem);
2293 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
2294 GINT_TO_POINTER(CFG_SETTINGS));
2295 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2296 GTK_SIGNAL_FUNC(menu_config_event), fe);
2297 gtk_widget_show(menuitem);
2302 add_menu_separator(GTK_CONTAINER(menu));
2303 menuitem = gtk_menu_item_new_with_label("Load...");
2304 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2305 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2306 GTK_SIGNAL_FUNC(menu_load_event), fe);
2307 gtk_widget_show(menuitem);
2308 menuitem = gtk_menu_item_new_with_label("Save...");
2309 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2310 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2311 GTK_SIGNAL_FUNC(menu_save_event), fe);
2312 gtk_widget_show(menuitem);
2313 #ifndef STYLUS_BASED
2314 add_menu_separator(GTK_CONTAINER(menu));
2315 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Undo", 'u');
2316 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Redo", 'r');
2318 if (thegame.can_format_as_text_ever) {
2319 add_menu_separator(GTK_CONTAINER(menu));
2320 menuitem = gtk_menu_item_new_with_label("Copy");
2321 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2322 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2323 GTK_SIGNAL_FUNC(menu_copy_event), fe);
2324 gtk_widget_show(menuitem);
2325 fe->copy_menu_item = menuitem;
2327 fe->copy_menu_item = NULL;
2329 if (thegame.can_solve) {
2330 add_menu_separator(GTK_CONTAINER(menu));
2331 menuitem = gtk_menu_item_new_with_label("Solve");
2332 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2333 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2334 GTK_SIGNAL_FUNC(menu_solve_event), fe);
2335 gtk_widget_show(menuitem);
2337 add_menu_separator(GTK_CONTAINER(menu));
2338 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Exit", 'q');
2340 menuitem = gtk_menu_item_new_with_mnemonic("_Help");
2341 gtk_container_add(GTK_CONTAINER(fe->menubar), menuitem);
2342 gtk_widget_show(menuitem);
2344 menu = gtk_menu_new();
2345 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
2347 menuitem = gtk_menu_item_new_with_label("About");
2348 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2349 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2350 GTK_SIGNAL_FUNC(menu_about_event), fe);
2351 gtk_widget_show(menuitem);
2354 menuitem=gtk_button_new_with_mnemonic("_Redo");
2355 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
2356 GINT_TO_POINTER((int)('r')));
2357 gtk_signal_connect(GTK_OBJECT(menuitem), "clicked",
2358 GTK_SIGNAL_FUNC(menu_key_event), fe);
2359 gtk_box_pack_end(hbox, menuitem, FALSE, FALSE, 0);
2360 gtk_widget_show(menuitem);
2362 menuitem=gtk_button_new_with_mnemonic("_Undo");
2363 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
2364 GINT_TO_POINTER((int)('u')));
2365 gtk_signal_connect(GTK_OBJECT(menuitem), "clicked",
2366 GTK_SIGNAL_FUNC(menu_key_event), fe);
2367 gtk_box_pack_end(hbox, menuitem, FALSE, FALSE, 0);
2368 gtk_widget_show(menuitem);
2370 if (thegame.flags & REQUIRE_NUMPAD) {
2371 hbox = GTK_BOX(gtk_hbox_new(FALSE, 0));
2372 gtk_box_pack_start(vbox, GTK_WIDGET(hbox), FALSE, FALSE, 0);
2373 gtk_widget_show(GTK_WIDGET(hbox));
2377 for(errbuf[0]='0';errbuf[0]<='9';errbuf[0]++) {
2378 menuitem=gtk_button_new_with_label(errbuf);
2379 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
2380 GINT_TO_POINTER((int)(errbuf[0])));
2381 gtk_signal_connect(GTK_OBJECT(menuitem), "clicked",
2382 GTK_SIGNAL_FUNC(menu_key_event), fe);
2383 gtk_box_pack_start(hbox, menuitem, TRUE, TRUE, 0);
2384 gtk_widget_show(menuitem);
2387 #endif /* STYLUS_BASED */
2391 snaffle_colours(fe);
2393 if (midend_wants_statusbar(fe->me)) {
2394 GtkWidget *viewport;
2397 viewport = gtk_viewport_new(NULL, NULL);
2398 gtk_viewport_set_shadow_type(GTK_VIEWPORT(viewport), GTK_SHADOW_NONE);
2399 fe->statusbar = gtk_statusbar_new();
2400 gtk_container_add(GTK_CONTAINER(viewport), fe->statusbar);
2401 gtk_widget_show(viewport);
2402 gtk_box_pack_end(vbox, viewport, FALSE, FALSE, 0);
2403 gtk_widget_show(fe->statusbar);
2404 fe->statusctx = gtk_statusbar_get_context_id
2405 (GTK_STATUSBAR(fe->statusbar), "game");
2406 gtk_statusbar_push(GTK_STATUSBAR(fe->statusbar), fe->statusctx,
2408 gtk_widget_size_request(fe->statusbar, &req);
2410 /* For GTK 2.0, should we be using gtk_widget_set_size_request? */
2412 gtk_widget_set_usize(viewport, -1, req.height);
2414 fe->statusbar = NULL;
2416 fe->area = gtk_drawing_area_new();
2417 #if GTK_CHECK_VERSION(2,0,0)
2418 GTK_WIDGET_UNSET_FLAGS(fe->area, GTK_DOUBLE_BUFFERED);
2420 get_size(fe, &x, &y);
2421 fe->drawing_area_shrink_pending = FALSE;
2422 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
2426 gtk_box_pack_end(vbox, fe->area, TRUE, TRUE, 0);
2428 clear_backing_store(fe);
2430 fe->nfonts = fe->fontsize = 0;
2432 fe->paste_data = NULL;
2433 fe->paste_data_len = 0;
2435 gtk_signal_connect(GTK_OBJECT(fe->window), "destroy",
2436 GTK_SIGNAL_FUNC(destroy), fe);
2437 gtk_signal_connect(GTK_OBJECT(fe->window), "key_press_event",
2438 GTK_SIGNAL_FUNC(key_event), fe);
2439 gtk_signal_connect(GTK_OBJECT(fe->area), "button_press_event",
2440 GTK_SIGNAL_FUNC(button_event), fe);
2441 gtk_signal_connect(GTK_OBJECT(fe->area), "button_release_event",
2442 GTK_SIGNAL_FUNC(button_event), fe);
2443 gtk_signal_connect(GTK_OBJECT(fe->area), "motion_notify_event",
2444 GTK_SIGNAL_FUNC(motion_event), fe);
2445 gtk_signal_connect(GTK_OBJECT(fe->area), "selection_get",
2446 GTK_SIGNAL_FUNC(selection_get), fe);
2447 gtk_signal_connect(GTK_OBJECT(fe->area), "selection_clear_event",
2448 GTK_SIGNAL_FUNC(selection_clear), fe);
2449 gtk_signal_connect(GTK_OBJECT(fe->area), "expose_event",
2450 GTK_SIGNAL_FUNC(expose_area), fe);
2451 gtk_signal_connect(GTK_OBJECT(fe->window), "map_event",
2452 GTK_SIGNAL_FUNC(map_window), fe);
2453 gtk_signal_connect(GTK_OBJECT(fe->area), "configure_event",
2454 GTK_SIGNAL_FUNC(configure_area), fe);
2455 gtk_signal_connect(GTK_OBJECT(fe->window), "configure_event",
2456 GTK_SIGNAL_FUNC(configure_window), fe);
2458 gtk_widget_add_events(GTK_WIDGET(fe->area),
2459 GDK_BUTTON_PRESS_MASK |
2460 GDK_BUTTON_RELEASE_MASK |
2461 GDK_BUTTON_MOTION_MASK |
2462 GDK_POINTER_MOTION_HINT_MASK);
2465 gtk_widget_realize(fe->window);
2466 iconpm = gdk_pixmap_create_from_xpm_d(fe->window->window, NULL,
2467 NULL, (gchar **)xpm_icons[0]);
2468 gdk_window_set_icon(fe->window->window, NULL, iconpm, NULL);
2470 for (n = 0; n < n_xpm_icons; n++) {
2472 g_list_append(iconlist,
2473 gdk_pixbuf_new_from_xpm_data((const gchar **)
2476 gdk_window_set_icon_list(fe->window->window, iconlist);
2479 gtk_widget_show(fe->area);
2480 gtk_widget_show(fe->window);
2482 fe->drawing_area_shrink_pending = TRUE;
2483 try_shrink_drawing_area(fe);
2484 set_window_background(fe, 0);
2489 char *fgetline(FILE *fp)
2491 char *ret = snewn(512, char);
2492 int size = 512, len = 0;
2493 while (fgets(ret + len, size - len, fp)) {
2494 len += strlen(ret + len);
2495 if (ret[len-1] == '\n')
2496 break; /* got a newline, we're done */
2498 ret = sresize(ret, size, char);
2500 if (len == 0) { /* first fgets returned NULL */
2508 int main(int argc, char **argv)
2510 char *pname = argv[0];
2512 int ngenerate = 0, print = FALSE, px = 1, py = 1;
2513 int time_generation = FALSE, test_solve = FALSE, list_presets = FALSE;
2514 int soln = FALSE, colour = FALSE;
2516 float redo_proportion = 0.0F;
2517 char *savefile = NULL, *savesuffix = NULL;
2519 int argtype = ARG_EITHER;
2520 char *screenshot_file = NULL;
2521 int doing_opts = TRUE;
2527 * Command line parsing in this function is rather fiddly,
2528 * because GTK wants to have a go at argc/argv _first_ - and
2529 * yet we can't let it, because gtk_init() will bomb out if it
2530 * can't open an X display, whereas in fact we want to permit
2531 * our --generate and --print modes to run without an X
2535 * - we parse the command line ourselves, without modifying
2537 * - if we encounter an error which might plausibly be the
2538 * result of a GTK command line (i.e. not detailed errors in
2539 * particular options of ours) we store the error message
2540 * and terminate parsing.
2541 * - if we got enough out of the command line to know it
2542 * specifies a non-X mode of operation, we either display
2543 * the stored error and return failure, or if there is no
2544 * stored error we do the non-X operation and return
2546 * - otherwise, we go straight to gtk_init().
2552 if (doing_opts && !strcmp(p, "--version")) {
2553 printf("%s, from Simon Tatham's Portable Puzzle Collection\n%s\n",
2556 } else if (doing_opts && !strcmp(p, "--generate")) {
2558 ngenerate = atoi(*++av);
2560 fprintf(stderr, "%s: '--generate' expected a number\n",
2566 } else if (doing_opts && !strcmp(p, "--time-generation")) {
2567 time_generation = TRUE;
2568 } else if (doing_opts && !strcmp(p, "--test-solve")) {
2570 } else if (doing_opts && !strcmp(p, "--list-presets")) {
2571 list_presets = TRUE;
2572 } else if (doing_opts && !strcmp(p, "--save")) {
2576 fprintf(stderr, "%s: '--save' expected a filename\n",
2580 } else if (doing_opts && (!strcmp(p, "--save-suffix") ||
2581 !strcmp(p, "--savesuffix"))) {
2585 fprintf(stderr, "%s: '--save-suffix' expected a filename\n",
2589 } else if (doing_opts && !strcmp(p, "--print")) {
2590 if (!thegame.can_print) {
2591 fprintf(stderr, "%s: this game does not support printing\n",
2598 if (sscanf(dim, "%dx%d", &px, &py) != 2) {
2599 fprintf(stderr, "%s: unable to parse argument '%s' to "
2600 "'--print'\n", pname, dim);
2606 } else if (doing_opts && !strcmp(p, "--scale")) {
2608 scale = atof(*++av);
2610 fprintf(stderr, "%s: no argument supplied to '--scale'\n",
2614 } else if (doing_opts && !strcmp(p, "--redo")) {
2616 * This is an internal option which I don't expect
2617 * users to have any particular use for. The effect of
2618 * --redo is that once the game has been loaded and
2619 * initialised, the next move in the redo chain is
2620 * replayed, and the game screen is redrawn part way
2621 * through the making of the move. This is only
2622 * meaningful if there _is_ a next move in the redo
2623 * chain, which means in turn that this option is only
2624 * useful if you're also passing a save file on the
2627 * This option is used by the script which generates
2628 * the puzzle icons and website screenshots, and I
2629 * don't imagine it's useful for anything else.
2630 * (Unless, I suppose, users don't like my screenshots
2631 * and want to generate their own in the same way for
2632 * some repackaged version of the puzzles.)
2635 redo_proportion = atof(*++av);
2637 fprintf(stderr, "%s: no argument supplied to '--redo'\n",
2641 } else if (doing_opts && !strcmp(p, "--screenshot")) {
2643 * Another internal option for the icon building
2644 * script. This causes a screenshot of the central
2645 * drawing area (i.e. not including the menu bar or
2646 * status bar) to be saved to a PNG file once the
2647 * window has been drawn, and then the application
2648 * quits immediately.
2651 screenshot_file = *++av;
2653 fprintf(stderr, "%s: no argument supplied to '--screenshot'\n",
2657 } else if (doing_opts && (!strcmp(p, "--with-solutions") ||
2658 !strcmp(p, "--with-solution") ||
2659 !strcmp(p, "--with-solns") ||
2660 !strcmp(p, "--with-soln") ||
2661 !strcmp(p, "--solutions") ||
2662 !strcmp(p, "--solution") ||
2663 !strcmp(p, "--solns") ||
2664 !strcmp(p, "--soln"))) {
2666 } else if (doing_opts && !strcmp(p, "--colour")) {
2667 if (!thegame.can_print_in_colour) {
2668 fprintf(stderr, "%s: this game does not support colour"
2669 " printing\n", pname);
2673 } else if (doing_opts && !strcmp(p, "--load")) {
2675 } else if (doing_opts && !strcmp(p, "--game")) {
2677 } else if (doing_opts && !strcmp(p, "--")) {
2679 } else if (!doing_opts || p[0] != '-') {
2681 fprintf(stderr, "%s: more than one argument supplied\n",
2687 sprintf(errbuf, "%.100s: unrecognised option '%.100s'\n",
2694 * Special standalone mode for generating puzzle IDs on the
2695 * command line. Useful for generating puzzles to be printed
2696 * out and solved offline (for puzzles where that even makes
2697 * sense - Solo, for example, is a lot more pencil-and-paper
2698 * friendly than Twiddle!)
2702 * <puzzle-name> --generate [<n> [<params>]]
2704 * <n>, if present, is the number of puzzle IDs to generate.
2705 * <params>, if present, is the same type of parameter string
2706 * you would pass to the puzzle when running it in GUI mode,
2707 * including optional extras such as the expansion factor in
2708 * Rectangles and the difficulty level in Solo.
2710 * If you specify <params>, you must also specify <n> (although
2711 * you may specify it to be 1). Sorry; that was the
2712 * simplest-to-parse command-line syntax I came up with.
2714 if (ngenerate > 0 || print || savefile || savesuffix) {
2718 document *doc = NULL;
2721 * If we're in this branch, we should display any pending
2722 * error message from the command line, since GTK isn't going
2723 * to take another crack at making sense of it.
2726 fputs(errbuf, stderr);
2732 me = midend_new(NULL, &thegame, NULL, NULL);
2735 if (savefile && !savesuffix)
2737 if (!savefile && savesuffix)
2741 doc = document_new(px, py, scale);
2744 * In this loop, we either generate a game ID or read one
2745 * from stdin depending on whether we're in generate mode;
2746 * then we either write it to stdout or print it, depending
2747 * on whether we're in print mode. Thus, this loop handles
2748 * generate-to-stdout, print-from-stdin and generate-and-
2749 * immediately-print modes.
2751 * (It could also handle a copy-stdin-to-stdout mode,
2752 * although there's currently no combination of options
2753 * which will cause this loop to be activated in that mode.
2754 * It wouldn't be _entirely_ pointless, though, because
2755 * stdin could contain bare params strings or random-seed
2756 * IDs, and stdout would contain nothing but fully
2757 * generated descriptive game IDs.)
2759 while (ngenerate == 0 || i < n) {
2760 char *pstr, *err, *seed;
2761 struct rusage before, after;
2763 if (ngenerate == 0) {
2764 pstr = fgetline(stdin);
2767 pstr[strcspn(pstr, "\r\n")] = '\0';
2770 pstr = snewn(strlen(arg) + 40, char);
2773 if (i > 0 && strchr(arg, '#'))
2774 sprintf(pstr + strlen(pstr), "-%d", i);
2780 err = midend_game_id(me, pstr);
2782 fprintf(stderr, "%s: error parsing '%s': %s\n",
2788 if (time_generation)
2789 getrusage(RUSAGE_SELF, &before);
2791 midend_new_game(me);
2793 seed = midend_get_random_seed(me);
2795 if (time_generation) {
2798 getrusage(RUSAGE_SELF, &after);
2800 elapsed = (after.ru_utime.tv_sec -
2801 before.ru_utime.tv_sec);
2802 elapsed += (after.ru_utime.tv_usec -
2803 before.ru_utime.tv_usec) / 1000000.0;
2805 printf("%s %s: %.6f\n", thegame.name, seed, elapsed);
2808 if (test_solve && thegame.can_solve) {
2810 * Now destroy the aux_info in the midend, by means of
2811 * re-entering the same game id, and then try to solve
2814 char *game_id, *err;
2816 game_id = midend_get_game_id(me);
2817 err = midend_game_id(me, game_id);
2819 fprintf(stderr, "%s %s: game id re-entry error: %s\n",
2820 thegame.name, seed, err);
2823 midend_new_game(me);
2826 err = midend_solve(me);
2828 * If the solve operation returned the error "Solution
2829 * not known for this puzzle", that's OK, because that
2830 * just means it's a puzzle for which we don't have an
2831 * algorithmic solver and hence can't solve it without
2832 * the aux_info, e.g. Netslide. Any other error is a
2835 if (err && strcmp(err, "Solution not known for this puzzle")) {
2836 fprintf(stderr, "%s %s: solve error: %s\n",
2837 thegame.name, seed, err);
2846 err = midend_print_puzzle(me, doc, soln);
2848 fprintf(stderr, "%s: error in printing: %s\n", pname, err);
2853 struct savefile_write_ctx ctx;
2854 char *realname = snewn(40 + strlen(savefile) +
2855 strlen(savesuffix), char);
2856 sprintf(realname, "%s%d%s", savefile, i, savesuffix);
2859 char *err = midend_solve(me);
2861 fprintf(stderr, "%s: unable to show solution: %s\n",
2867 ctx.fp = fopen(realname, "w");
2869 fprintf(stderr, "%s: open: %s\n", realname,
2874 midend_serialise(me, savefile_write, &ctx);
2876 fprintf(stderr, "%s: write: %s\n", realname,
2877 strerror(ctx.error));
2880 if (fclose(ctx.fp)) {
2881 fprintf(stderr, "%s: close: %s\n", realname,
2887 if (!doc && !savefile && !time_generation) {
2888 id = midend_get_game_id(me);
2897 psdata *ps = ps_init(stdout, colour);
2898 document_print(doc, ps_drawing_api(ps));
2906 } else if (list_presets) {
2908 * Another specialist mode which causes the puzzle to list the
2909 * game_params strings for all its preset configurations.
2914 me = midend_new(NULL, &thegame, NULL, NULL);
2915 npresets = midend_num_presets(me);
2917 for (i = 0; i < npresets; i++) {
2918 game_params *params;
2919 char *name, *paramstr;
2921 midend_fetch_preset(me, i, &name, ¶ms);
2922 paramstr = thegame.encode_params(params, TRUE);
2924 printf("%s %s\n", paramstr, name);
2933 gtk_init(&argc, &argv);
2935 fe = new_window(arg, argtype, &error);
2938 fprintf(stderr, "%s: %s\n", pname, error);
2942 if (screenshot_file) {
2944 * Some puzzles will not redraw their entire area if
2945 * given a partially completed animation, which means
2946 * we must redraw now and _then_ redraw again after
2947 * freezing the move timer.
2949 midend_force_redraw(fe->me);
2952 if (redo_proportion) {
2954 midend_process_key(fe->me, 0, 0, 'r');
2955 /* And freeze the timer at the specified position. */
2956 midend_freeze_timer(fe->me, redo_proportion);
2959 if (screenshot_file) {
2960 save_screenshot_png(fe, screenshot_file);