Release version 9306-1
[sgt-puzzles/ydirson.git] / gtk.c
blob1af877c24d1831fc667dfdcb21f5ddae398f66fb
1 /*
2 * gtk.c: GTK front end for my puzzle collection.
3 */
5 #include <stdio.h>
6 #include <assert.h>
7 #include <stdlib.h>
8 #include <time.h>
9 #include <stdarg.h>
10 #include <string.h>
11 #include <errno.h>
12 #include <math.h>
14 #include <sys/time.h>
16 #include <gtk/gtk.h>
17 #include <gdk/gdkkeysyms.h>
19 #include <gdk-pixbuf/gdk-pixbuf.h>
21 #include <gdk/gdkx.h>
22 #include <X11/Xlib.h>
23 #include <X11/Xutil.h>
24 #include <X11/Xatom.h>
26 #include "puzzles.h"
28 #if GTK_CHECK_VERSION(2,0,0)
29 # define USE_PANGO
30 # ifdef PANGO_VERSION_CHECK
31 # if PANGO_VERSION_CHECK(1,8,0)
32 # define HAVE_SENSIBLE_ABSOLUTE_SIZE_FUNCTION
33 # endif
34 # endif
35 #endif
36 #if !GTK_CHECK_VERSION(2,4,0)
37 # define OLD_FILESEL
38 #endif
39 #if GTK_CHECK_VERSION(2,8,0)
40 # define USE_CAIRO
41 #endif
43 /* #undef USE_CAIRO */
44 /* #define NO_THICK_LINE */
45 #ifdef DEBUGGING
46 static FILE *debug_fp = NULL;
48 void dputs(char *buf)
50 if (!debug_fp) {
51 debug_fp = fopen("debug.log", "w");
54 fputs(buf, stderr);
56 if (debug_fp) {
57 fputs(buf, debug_fp);
58 fflush(debug_fp);
62 void debug_printf(char *fmt, ...)
64 char buf[4096];
65 va_list ap;
67 va_start(ap, fmt);
68 vsprintf(buf, fmt, ap);
69 dputs(buf);
70 va_end(ap);
72 #endif
74 /* ----------------------------------------------------------------------
75 * Error reporting functions used elsewhere.
78 void fatal(char *fmt, ...)
80 va_list ap;
82 fprintf(stderr, "fatal error: ");
84 va_start(ap, fmt);
85 vfprintf(stderr, fmt, ap);
86 va_end(ap);
88 fprintf(stderr, "\n");
89 exit(1);
92 /* ----------------------------------------------------------------------
93 * GTK front end to puzzles.
96 static void changed_preset(frontend *fe);
98 struct font {
99 #ifdef USE_PANGO
100 PangoFontDescription *desc;
101 #else
102 GdkFont *font;
103 #endif
104 int type;
105 int size;
109 * This structure holds all the data relevant to a single window.
110 * In principle this would allow us to open multiple independent
111 * puzzle windows, although I can't currently see any real point in
112 * doing so. I'm just coding cleanly because there's no
113 * particularly good reason not to.
115 struct frontend {
116 GtkWidget *window;
117 GtkAccelGroup *accelgroup;
118 GtkWidget *area;
119 GtkWidget *statusbar;
120 guint statusctx;
121 int w, h;
122 midend *me;
123 #ifdef USE_CAIRO
124 const float *colours;
125 cairo_t *cr;
126 cairo_surface_t *image;
127 GdkPixmap *pixmap;
128 GdkColor background; /* for painting outside puzzle area */
129 #else
130 GdkPixmap *pixmap;
131 GdkGC *gc;
132 GdkColor *colours;
133 GdkColormap *colmap;
134 int backgroundindex; /* which of colours[] is background */
135 #endif
136 int ncolours;
137 int bbox_l, bbox_r, bbox_u, bbox_d;
138 int timer_active, timer_id;
139 struct timeval last_time;
140 struct font *fonts;
141 int nfonts, fontsize;
142 config_item *cfg;
143 int cfg_which, cfgret;
144 GtkWidget *cfgbox;
145 void *paste_data;
146 int paste_data_len;
147 int pw, ph; /* pixmap size (w, h are area size) */
148 int ox, oy; /* offset of pixmap in drawing area */
149 #ifdef OLD_FILESEL
150 char *filesel_name;
151 #endif
152 GSList *preset_radio;
153 int n_preset_menu_items;
154 int preset_threaded;
155 GtkWidget *preset_custom;
156 GtkWidget *copy_menu_item;
159 struct blitter {
160 #ifdef USE_CAIRO
161 cairo_surface_t *image;
162 #else
163 GdkPixmap *pixmap;
164 #endif
165 int w, h, x, y;
168 void get_random_seed(void **randseed, int *randseedsize)
170 struct timeval *tvp = snew(struct timeval);
171 gettimeofday(tvp, NULL);
172 *randseed = (void *)tvp;
173 *randseedsize = sizeof(struct timeval);
176 void frontend_default_colour(frontend *fe, float *output)
178 GdkColor col = fe->window->style->bg[GTK_STATE_NORMAL];
179 output[0] = col.red / 65535.0;
180 output[1] = col.green / 65535.0;
181 output[2] = col.blue / 65535.0;
184 void gtk_status_bar(void *handle, char *text)
186 frontend *fe = (frontend *)handle;
188 assert(fe->statusbar);
190 gtk_statusbar_pop(GTK_STATUSBAR(fe->statusbar), fe->statusctx);
191 gtk_statusbar_push(GTK_STATUSBAR(fe->statusbar), fe->statusctx, text);
194 /* ----------------------------------------------------------------------
195 * Cairo drawing functions.
198 #ifdef USE_CAIRO
200 static void setup_drawing(frontend *fe)
202 fe->cr = cairo_create(fe->image);
203 cairo_set_antialias(fe->cr, CAIRO_ANTIALIAS_GRAY);
204 cairo_set_line_width(fe->cr, 1.0);
205 cairo_set_line_cap(fe->cr, CAIRO_LINE_CAP_SQUARE);
206 cairo_set_line_join(fe->cr, CAIRO_LINE_JOIN_ROUND);
209 static void teardown_drawing(frontend *fe)
211 cairo_t *cr;
213 cairo_destroy(fe->cr);
214 fe->cr = NULL;
216 cr = gdk_cairo_create(fe->pixmap);
217 cairo_set_source_surface(cr, fe->image, 0, 0);
218 cairo_rectangle(cr,
219 fe->bbox_l - 1,
220 fe->bbox_u - 1,
221 fe->bbox_r - fe->bbox_l + 2,
222 fe->bbox_d - fe->bbox_u + 2);
223 cairo_fill(cr);
224 cairo_destroy(cr);
227 static void snaffle_colours(frontend *fe)
229 fe->colours = midend_colours(fe->me, &fe->ncolours);
232 static void set_colour(frontend *fe, int colour)
234 cairo_set_source_rgb(fe->cr,
235 fe->colours[3*colour + 0],
236 fe->colours[3*colour + 1],
237 fe->colours[3*colour + 2]);
240 static void set_window_background(frontend *fe, int colour)
242 GdkColormap *colmap;
244 colmap = gdk_colormap_get_system();
245 fe->background.red = fe->colours[3*colour + 0] * 65535;
246 fe->background.green = fe->colours[3*colour + 1] * 65535;
247 fe->background.blue = fe->colours[3*colour + 2] * 65535;
248 if (!gdk_colormap_alloc_color(colmap, &fe->background, FALSE, FALSE)) {
249 g_error("couldn't allocate background (#%02x%02x%02x)\n",
250 fe->background.red >> 8, fe->background.green >> 8,
251 fe->background.blue >> 8);
253 gdk_window_set_background(fe->area->window, &fe->background);
254 gdk_window_set_background(fe->window->window, &fe->background);
257 static PangoLayout *make_pango_layout(frontend *fe)
259 return (pango_cairo_create_layout(fe->cr));
262 static void draw_pango_layout(frontend *fe, PangoLayout *layout,
263 int x, int y)
265 cairo_move_to(fe->cr, x, y);
266 pango_cairo_show_layout(fe->cr, layout);
269 static void save_screenshot_png(frontend *fe, const char *screenshot_file)
271 cairo_surface_write_to_png(fe->image, screenshot_file);
274 static void do_clip(frontend *fe, int x, int y, int w, int h)
276 cairo_new_path(fe->cr);
277 cairo_rectangle(fe->cr, x, y, w, h);
278 cairo_clip(fe->cr);
281 static void do_unclip(frontend *fe)
283 cairo_reset_clip(fe->cr);
286 static void do_draw_rect(frontend *fe, int x, int y, int w, int h)
288 cairo_save(fe->cr);
289 cairo_new_path(fe->cr);
290 cairo_set_antialias(fe->cr, CAIRO_ANTIALIAS_NONE);
291 cairo_rectangle(fe->cr, x, y, w, h);
292 cairo_fill(fe->cr);
293 cairo_restore(fe->cr);
296 static void do_draw_line(frontend *fe, int x1, int y1, int x2, int y2)
298 cairo_new_path(fe->cr);
299 cairo_move_to(fe->cr, x1 + 0.5, y1 + 0.5);
300 cairo_line_to(fe->cr, x2 + 0.5, y2 + 0.5);
301 cairo_stroke(fe->cr);
304 static void do_draw_thick_line(frontend *fe, float thickness,
305 float x1, float y1, float x2, float y2)
307 cairo_save(fe->cr);
308 cairo_set_line_width(fe->cr, thickness);
309 cairo_new_path(fe->cr);
310 cairo_move_to(fe->cr, x1, y1);
311 cairo_line_to(fe->cr, x2, y2);
312 cairo_stroke(fe->cr);
313 cairo_restore(fe->cr);
316 static void do_draw_poly(frontend *fe, int *coords, int npoints,
317 int fillcolour, int outlinecolour)
319 int i;
321 cairo_new_path(fe->cr);
322 for (i = 0; i < npoints; i++)
323 cairo_line_to(fe->cr, coords[i*2] + 0.5, coords[i*2 + 1] + 0.5);
324 cairo_close_path(fe->cr);
325 if (fillcolour >= 0) {
326 set_colour(fe, fillcolour);
327 cairo_fill_preserve(fe->cr);
329 assert(outlinecolour >= 0);
330 set_colour(fe, outlinecolour);
331 cairo_stroke(fe->cr);
334 static void do_draw_circle(frontend *fe, int cx, int cy, int radius,
335 int fillcolour, int outlinecolour)
337 cairo_new_path(fe->cr);
338 cairo_arc(fe->cr, cx + 0.5, cy + 0.5, radius, 0, 2*PI);
339 cairo_close_path(fe->cr); /* Just in case... */
340 if (fillcolour >= 0) {
341 set_colour(fe, fillcolour);
342 cairo_fill_preserve(fe->cr);
344 assert(outlinecolour >= 0);
345 set_colour(fe, outlinecolour);
346 cairo_stroke(fe->cr);
349 static void setup_blitter(blitter *bl, int w, int h)
351 bl->image = cairo_image_surface_create(CAIRO_FORMAT_RGB24, w, h);
354 static void teardown_blitter(blitter *bl)
356 cairo_surface_destroy(bl->image);
359 static void do_blitter_save(frontend *fe, blitter *bl, int x, int y)
361 cairo_t *cr = cairo_create(bl->image);
363 cairo_set_source_surface(cr, fe->image, -x, -y);
364 cairo_paint(cr);
365 cairo_destroy(cr);
368 static void do_blitter_load(frontend *fe, blitter *bl, int x, int y)
370 cairo_set_source_surface(fe->cr, bl->image, x, y);
371 cairo_paint(fe->cr);
374 static void clear_backing_store(frontend *fe)
376 fe->image = NULL;
379 static void setup_backing_store(frontend *fe)
381 cairo_t *cr;
382 int i;
384 fe->pixmap = gdk_pixmap_new(fe->area->window, fe->pw, fe->ph, -1);
385 fe->image = cairo_image_surface_create(CAIRO_FORMAT_RGB24,
386 fe->pw, fe->ph);
388 for (i = 0; i < 3; i++) {
389 switch (i) {
390 case 0: cr = cairo_create(fe->image); break;
391 case 1: cr = gdk_cairo_create(fe->pixmap); break;
392 case 2: cr = gdk_cairo_create(fe->area->window); break;
394 cairo_set_source_rgb(cr,
395 fe->colours[0], fe->colours[1], fe->colours[2]);
396 cairo_paint(cr);
397 cairo_destroy(cr);
401 static int backing_store_ok(frontend *fe)
403 return (!!fe->image);
406 static void teardown_backing_store(frontend *fe)
408 cairo_surface_destroy(fe->image);
409 gdk_pixmap_unref(fe->pixmap);
410 fe->image = NULL;
413 #endif
415 /* ----------------------------------------------------------------------
416 * GDK drawing functions.
419 #ifndef USE_CAIRO
421 static void setup_drawing(frontend *fe)
423 fe->gc = gdk_gc_new(fe->area->window);
426 static void teardown_drawing(frontend *fe)
428 gdk_gc_unref(fe->gc);
429 fe->gc = NULL;
432 static void snaffle_colours(frontend *fe)
434 int i, ncolours;
435 float *colours;
436 gboolean *success;
438 fe->colmap = gdk_colormap_get_system();
439 colours = midend_colours(fe->me, &ncolours);
440 fe->ncolours = ncolours;
441 fe->colours = snewn(ncolours, GdkColor);
442 for (i = 0; i < ncolours; i++) {
443 fe->colours[i].red = colours[i*3] * 0xFFFF;
444 fe->colours[i].green = colours[i*3+1] * 0xFFFF;
445 fe->colours[i].blue = colours[i*3+2] * 0xFFFF;
447 success = snewn(ncolours, gboolean);
448 gdk_colormap_alloc_colors(fe->colmap, fe->colours, ncolours,
449 FALSE, FALSE, success);
450 for (i = 0; i < ncolours; i++) {
451 if (!success[i]) {
452 g_error("couldn't allocate colour %d (#%02x%02x%02x)\n",
453 i, fe->colours[i].red >> 8,
454 fe->colours[i].green >> 8,
455 fe->colours[i].blue >> 8);
460 static void set_window_background(frontend *fe, int colour)
462 fe->backgroundindex = colour;
463 gdk_window_set_background(fe->area->window, &fe->colours[colour]);
464 gdk_window_set_background(fe->window->window, &fe->colours[colour]);
467 static void set_colour(frontend *fe, int colour)
469 gdk_gc_set_foreground(fe->gc, &fe->colours[colour]);
472 #ifdef USE_PANGO
473 static PangoLayout *make_pango_layout(frontend *fe)
475 return (pango_layout_new(gtk_widget_get_pango_context(fe->area)));
478 static void draw_pango_layout(frontend *fe, PangoLayout *layout,
479 int x, int y)
481 gdk_draw_layout(fe->pixmap, fe->gc, x, y, layout);
483 #endif
485 static void save_screenshot_png(frontend *fe, const char *screenshot_file)
487 GdkPixbuf *pb;
488 GError *gerror = NULL;
490 midend_redraw(fe->me);
492 pb = gdk_pixbuf_get_from_drawable(NULL, fe->pixmap,
493 NULL, 0, 0, 0, 0, -1, -1);
494 gdk_pixbuf_save(pb, screenshot_file, "png", &gerror, NULL);
497 static void do_clip(frontend *fe, int x, int y, int w, int h)
499 GdkRectangle rect;
501 rect.x = x;
502 rect.y = y;
503 rect.width = w;
504 rect.height = h;
505 gdk_gc_set_clip_rectangle(fe->gc, &rect);
508 static void do_unclip(frontend *fe)
510 GdkRectangle rect;
512 rect.x = 0;
513 rect.y = 0;
514 rect.width = fe->w;
515 rect.height = fe->h;
516 gdk_gc_set_clip_rectangle(fe->gc, &rect);
519 static void do_draw_rect(frontend *fe, int x, int y, int w, int h)
521 gdk_draw_rectangle(fe->pixmap, fe->gc, 1, x, y, w, h);
524 static void do_draw_line(frontend *fe, int x1, int y1, int x2, int y2)
526 gdk_draw_line(fe->pixmap, fe->gc, x1, y1, x2, y2);
529 static void do_draw_thick_line(frontend *fe, float thickness,
530 float x1, float y1, float x2, float y2)
532 GdkGCValues save;
534 gdk_gc_get_values(fe->gc, &save);
535 gdk_gc_set_line_attributes(fe->gc,
536 thickness,
537 GDK_LINE_SOLID,
538 GDK_CAP_BUTT,
539 GDK_JOIN_BEVEL);
540 gdk_draw_line(fe->pixmap, fe->gc, x1, y1, x2, y2);
541 gdk_gc_set_line_attributes(fe->gc,
542 save.line_width,
543 save.line_style,
544 save.cap_style,
545 save.join_style);
548 static void do_draw_poly(frontend *fe, int *coords, int npoints,
549 int fillcolour, int outlinecolour)
551 GdkPoint *points = snewn(npoints, GdkPoint);
552 int i;
554 for (i = 0; i < npoints; i++) {
555 points[i].x = coords[i*2];
556 points[i].y = coords[i*2+1];
559 if (fillcolour >= 0) {
560 set_colour(fe, fillcolour);
561 gdk_draw_polygon(fe->pixmap, fe->gc, TRUE, points, npoints);
563 assert(outlinecolour >= 0);
564 set_colour(fe, outlinecolour);
567 * In principle we ought to be able to use gdk_draw_polygon for
568 * the outline as well. In fact, it turns out to interact badly
569 * with a clipping region, for no terribly obvious reason, so I
570 * draw the outline as a sequence of lines instead.
572 for (i = 0; i < npoints; i++)
573 gdk_draw_line(fe->pixmap, fe->gc,
574 points[i].x, points[i].y,
575 points[(i+1)%npoints].x, points[(i+1)%npoints].y);
577 sfree(points);
580 static void do_draw_circle(frontend *fe, int cx, int cy, int radius,
581 int fillcolour, int outlinecolour)
583 if (fillcolour >= 0) {
584 set_colour(fe, fillcolour);
585 gdk_draw_arc(fe->pixmap, fe->gc, TRUE,
586 cx - radius, cy - radius,
587 2 * radius, 2 * radius, 0, 360 * 64);
590 assert(outlinecolour >= 0);
591 set_colour(fe, outlinecolour);
592 gdk_draw_arc(fe->pixmap, fe->gc, FALSE,
593 cx - radius, cy - radius,
594 2 * radius, 2 * radius, 0, 360 * 64);
597 static void setup_blitter(blitter *bl, int w, int h)
600 * We can't create the pixmap right now, because fe->window
601 * might not yet exist. So we just cache w and h and create it
602 * during the firs call to blitter_save.
604 bl->pixmap = NULL;
607 static void teardown_blitter(blitter *bl)
609 if (bl->pixmap)
610 gdk_pixmap_unref(bl->pixmap);
613 static void do_blitter_save(frontend *fe, blitter *bl, int x, int y)
615 if (!bl->pixmap)
616 bl->pixmap = gdk_pixmap_new(fe->area->window, bl->w, bl->h, -1);
617 gdk_draw_pixmap(bl->pixmap,
618 fe->area->style->fg_gc[GTK_WIDGET_STATE(fe->area)],
619 fe->pixmap,
620 x, y, 0, 0, bl->w, bl->h);
623 static void do_blitter_load(frontend *fe, blitter *bl, int x, int y)
625 assert(bl->pixmap);
626 gdk_draw_pixmap(fe->pixmap,
627 fe->area->style->fg_gc[GTK_WIDGET_STATE(fe->area)],
628 bl->pixmap,
629 0, 0, x, y, bl->w, bl->h);
632 static void clear_backing_store(frontend *fe)
634 fe->pixmap = NULL;
637 static void setup_backing_store(frontend *fe)
639 GdkGC *gc;
641 fe->pixmap = gdk_pixmap_new(fe->area->window, fe->pw, fe->ph, -1);
643 gc = gdk_gc_new(fe->area->window);
644 gdk_gc_set_foreground(gc, &fe->colours[0]);
645 gdk_draw_rectangle(fe->pixmap, gc, 1, 0, 0, fe->pw, fe->ph);
646 gdk_draw_rectangle(fe->area->window, gc, 1, 0, 0, fe->w, fe->h);
647 gdk_gc_unref(gc);
650 static int backing_store_ok(frontend *fe)
652 return (!!fe->pixmap);
655 static void teardown_backing_store(frontend *fe)
657 gdk_pixmap_unref(fe->pixmap);
658 fe->pixmap = NULL;
661 #endif
663 static void repaint_rectangle(frontend *fe, GtkWidget *widget,
664 int x, int y, int w, int h)
666 GdkGC *gc = gdk_gc_new(widget->window);
667 #ifdef USE_CAIRO
668 gdk_gc_set_foreground(gc, &fe->background);
669 #else
670 gdk_gc_set_foreground(gc, &fe->colours[fe->backgroundindex]);
671 #endif
672 if (x < fe->ox) {
673 gdk_draw_rectangle(widget->window, gc,
674 TRUE, x, y, fe->ox - x, h);
675 w -= (fe->ox - x);
676 x = fe->ox;
678 if (y < fe->oy) {
679 gdk_draw_rectangle(widget->window, gc,
680 TRUE, x, y, w, fe->oy - y);
681 h -= (fe->oy - y);
682 y = fe->oy;
684 if (w > fe->pw) {
685 gdk_draw_rectangle(widget->window, gc,
686 TRUE, x + fe->pw, y, w - fe->pw, h);
687 w = fe->pw;
689 if (h > fe->ph) {
690 gdk_draw_rectangle(widget->window, gc,
691 TRUE, x, y + fe->ph, w, h - fe->ph);
692 h = fe->ph;
694 gdk_draw_pixmap(widget->window, gc, fe->pixmap,
695 x - fe->ox, y - fe->oy, x, y, w, h);
696 gdk_gc_unref(gc);
699 /* ----------------------------------------------------------------------
700 * Pango font functions.
703 #ifdef USE_PANGO
705 static void add_font(frontend *fe, int index, int fonttype, int fontsize)
708 * Use Pango to find the closest match to the requested
709 * font.
711 PangoFontDescription *fd;
713 fd = pango_font_description_new();
714 /* `Monospace' and `Sans' are meta-families guaranteed to exist */
715 pango_font_description_set_family(fd, fonttype == FONT_FIXED ?
716 "Monospace" : "Sans");
717 pango_font_description_set_weight(fd, PANGO_WEIGHT_BOLD);
719 * I found some online Pango documentation which
720 * described a function called
721 * pango_font_description_set_absolute_size(), which is
722 * _exactly_ what I want here. Unfortunately, none of
723 * my local Pango installations have it (presumably
724 * they're too old), so I'm going to have to hack round
725 * it by figuring out the point size myself. This
726 * limits me to X and probably also breaks in later
727 * Pango installations, so ideally I should add another
728 * CHECK_VERSION type ifdef and use set_absolute_size
729 * where available. All very annoying.
731 #ifdef HAVE_SENSIBLE_ABSOLUTE_SIZE_FUNCTION
732 pango_font_description_set_absolute_size(fd, PANGO_SCALE*fontsize);
733 #else
735 Display *d = GDK_DISPLAY();
736 int s = DefaultScreen(d);
737 double resolution =
738 (PANGO_SCALE * 72.27 / 25.4) *
739 ((double) DisplayWidthMM(d, s) / DisplayWidth (d, s));
740 pango_font_description_set_size(fd, resolution * fontsize);
742 #endif
743 fe->fonts[index].desc = fd;
746 static void align_and_draw_text(frontend *fe,
747 int index, int align, int x, int y,
748 const char *text)
750 PangoLayout *layout;
751 PangoRectangle rect;
753 layout = make_pango_layout(fe);
756 * Create a layout.
758 pango_layout_set_font_description(layout, fe->fonts[index].desc);
759 pango_layout_set_text(layout, text, strlen(text));
760 pango_layout_get_pixel_extents(layout, NULL, &rect);
762 if (align & ALIGN_VCENTRE)
763 rect.y -= rect.height / 2;
764 else
765 rect.y -= rect.height;
767 if (align & ALIGN_HCENTRE)
768 rect.x -= rect.width / 2;
769 else if (align & ALIGN_HRIGHT)
770 rect.x -= rect.width;
772 draw_pango_layout(fe, layout, rect.x + x, rect.y + y);
774 g_object_unref(layout);
777 #endif
779 /* ----------------------------------------------------------------------
780 * Old-fashioned font functions.
783 #ifndef USE_PANGO
785 static void add_font(int index, int fonttype, int fontsize)
788 * In GTK 1.2, I don't know of any plausible way to
789 * pick a suitable font, so I'm just going to be
790 * tedious.
792 fe->fonts[i].font = gdk_font_load(fonttype == FONT_FIXED ?
793 "fixed" : "variable");
796 static void align_and_draw_text(int index, int align, int x, int y,
797 const char *text)
799 int lb, rb, wid, asc, desc;
802 * Measure vertical string extents with respect to the same
803 * string always...
805 gdk_string_extents(fe->fonts[i].font,
806 "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
807 &lb, &rb, &wid, &asc, &desc);
808 if (align & ALIGN_VCENTRE)
809 y += asc - (asc+desc)/2;
810 else
811 y += asc;
814 * ... but horizontal extents with respect to the provided
815 * string. This means that multiple pieces of text centred
816 * on the same y-coordinate don't have different baselines.
818 gdk_string_extents(fe->fonts[i].font, text,
819 &lb, &rb, &wid, &asc, &desc);
821 if (align & ALIGN_HCENTRE)
822 x -= wid / 2;
823 else if (align & ALIGN_HRIGHT)
824 x -= wid;
827 * Actually draw the text.
829 gdk_draw_string(fe->pixmap, fe->fonts[i].font, fe->gc, x, y, text);
832 #endif
834 /* ----------------------------------------------------------------------
835 * The exported drawing functions.
838 void gtk_start_draw(void *handle)
840 frontend *fe = (frontend *)handle;
841 fe->bbox_l = fe->w;
842 fe->bbox_r = 0;
843 fe->bbox_u = fe->h;
844 fe->bbox_d = 0;
845 setup_drawing(fe);
848 void gtk_clip(void *handle, int x, int y, int w, int h)
850 frontend *fe = (frontend *)handle;
851 do_clip(fe, x, y, w, h);
854 void gtk_unclip(void *handle)
856 frontend *fe = (frontend *)handle;
857 do_unclip(fe);
860 void gtk_draw_text(void *handle, int x, int y, int fonttype, int fontsize,
861 int align, int colour, char *text)
863 frontend *fe = (frontend *)handle;
864 int i;
867 * Find or create the font.
869 for (i = 0; i < fe->nfonts; i++)
870 if (fe->fonts[i].type == fonttype && fe->fonts[i].size == fontsize)
871 break;
873 if (i == fe->nfonts) {
874 if (fe->fontsize <= fe->nfonts) {
875 fe->fontsize = fe->nfonts + 10;
876 fe->fonts = sresize(fe->fonts, fe->fontsize, struct font);
879 fe->nfonts++;
881 fe->fonts[i].type = fonttype;
882 fe->fonts[i].size = fontsize;
883 add_font(fe, i, fonttype, fontsize);
887 * Do the job.
889 set_colour(fe, colour);
890 align_and_draw_text(fe, i, align, x, y, text);
893 void gtk_draw_rect(void *handle, int x, int y, int w, int h, int colour)
895 frontend *fe = (frontend *)handle;
896 set_colour(fe, colour);
897 do_draw_rect(fe, x, y, w, h);
900 void gtk_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
902 frontend *fe = (frontend *)handle;
903 set_colour(fe, colour);
904 do_draw_line(fe, x1, y1, x2, y2);
907 void gtk_draw_thick_line(void *handle, float thickness,
908 float x1, float y1, float x2, float y2, int colour)
910 frontend *fe = (frontend *)handle;
911 set_colour(fe, colour);
912 do_draw_thick_line(fe, thickness, x1, y1, x2, y2);
915 void gtk_draw_poly(void *handle, int *coords, int npoints,
916 int fillcolour, int outlinecolour)
918 frontend *fe = (frontend *)handle;
919 do_draw_poly(fe, coords, npoints, fillcolour, outlinecolour);
922 void gtk_draw_circle(void *handle, int cx, int cy, int radius,
923 int fillcolour, int outlinecolour)
925 frontend *fe = (frontend *)handle;
926 do_draw_circle(fe, cx, cy, radius, fillcolour, outlinecolour);
929 blitter *gtk_blitter_new(void *handle, int w, int h)
931 blitter *bl = snew(blitter);
932 setup_blitter(bl, w, h);
933 bl->w = w;
934 bl->h = h;
935 return bl;
938 void gtk_blitter_free(void *handle, blitter *bl)
940 teardown_blitter(bl);
941 sfree(bl);
944 void gtk_blitter_save(void *handle, blitter *bl, int x, int y)
946 frontend *fe = (frontend *)handle;
947 do_blitter_save(fe, bl, x, y);
948 bl->x = x;
949 bl->y = y;
952 void gtk_blitter_load(void *handle, blitter *bl, int x, int y)
954 frontend *fe = (frontend *)handle;
955 if (x == BLITTER_FROMSAVED && y == BLITTER_FROMSAVED) {
956 x = bl->x;
957 y = bl->y;
959 do_blitter_load(fe, bl, x, y);
962 void gtk_draw_update(void *handle, int x, int y, int w, int h)
964 frontend *fe = (frontend *)handle;
965 if (fe->bbox_l > x ) fe->bbox_l = x ;
966 if (fe->bbox_r < x+w) fe->bbox_r = x+w;
967 if (fe->bbox_u > y ) fe->bbox_u = y ;
968 if (fe->bbox_d < y+h) fe->bbox_d = y+h;
971 void gtk_end_draw(void *handle)
973 frontend *fe = (frontend *)handle;
975 teardown_drawing(fe);
977 if (fe->bbox_l < fe->bbox_r && fe->bbox_u < fe->bbox_d) {
978 repaint_rectangle(fe, fe->area,
979 fe->bbox_l - 1 + fe->ox,
980 fe->bbox_u - 1 + fe->oy,
981 fe->bbox_r - fe->bbox_l + 2,
982 fe->bbox_d - fe->bbox_u + 2);
986 #ifdef USE_PANGO
987 char *gtk_text_fallback(void *handle, const char *const *strings, int nstrings)
990 * We assume Pango can cope with any UTF-8 likely to be emitted
991 * by a puzzle.
993 return dupstr(strings[0]);
995 #endif
997 const struct drawing_api gtk_drawing = {
998 gtk_draw_text,
999 gtk_draw_rect,
1000 gtk_draw_line,
1001 gtk_draw_poly,
1002 gtk_draw_circle,
1003 gtk_draw_update,
1004 gtk_clip,
1005 gtk_unclip,
1006 gtk_start_draw,
1007 gtk_end_draw,
1008 gtk_status_bar,
1009 gtk_blitter_new,
1010 gtk_blitter_free,
1011 gtk_blitter_save,
1012 gtk_blitter_load,
1013 NULL, NULL, NULL, NULL, NULL, NULL, /* {begin,end}_{doc,page,puzzle} */
1014 NULL, NULL, /* line_width, line_dotted */
1015 #ifdef USE_PANGO
1016 gtk_text_fallback,
1017 #else
1018 NULL,
1019 #endif
1020 #ifdef NO_THICK_LINE
1021 NULL,
1022 #else
1023 gtk_draw_thick_line,
1024 #endif
1027 static void destroy(GtkWidget *widget, gpointer data)
1029 frontend *fe = (frontend *)data;
1030 deactivate_timer(fe);
1031 midend_free(fe->me);
1032 gtk_main_quit();
1035 static gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data)
1037 frontend *fe = (frontend *)data;
1038 int keyval;
1039 int shift = (event->state & GDK_SHIFT_MASK) ? MOD_SHFT : 0;
1040 int ctrl = (event->state & GDK_CONTROL_MASK) ? MOD_CTRL : 0;
1042 if (!backing_store_ok(fe))
1043 return TRUE;
1045 #if !GTK_CHECK_VERSION(2,0,0)
1046 /* Gtk 1.2 passes a key event to this function even if it's also
1047 * defined as an accelerator.
1048 * Gtk 2 doesn't do this, and this function appears not to exist there. */
1049 if (fe->accelgroup &&
1050 gtk_accel_group_get_entry(fe->accelgroup,
1051 event->keyval, event->state))
1052 return TRUE;
1053 #endif
1055 /* Handle mnemonics. */
1056 if (gtk_window_activate_key(GTK_WINDOW(fe->window), event))
1057 return TRUE;
1059 if (event->keyval == GDK_Up)
1060 keyval = shift | ctrl | CURSOR_UP;
1061 else if (event->keyval == GDK_KP_Up || event->keyval == GDK_KP_8)
1062 keyval = MOD_NUM_KEYPAD | '8';
1063 else if (event->keyval == GDK_Down)
1064 keyval = shift | ctrl | CURSOR_DOWN;
1065 else if (event->keyval == GDK_KP_Down || event->keyval == GDK_KP_2)
1066 keyval = MOD_NUM_KEYPAD | '2';
1067 else if (event->keyval == GDK_Left)
1068 keyval = shift | ctrl | CURSOR_LEFT;
1069 else if (event->keyval == GDK_KP_Left || event->keyval == GDK_KP_4)
1070 keyval = MOD_NUM_KEYPAD | '4';
1071 else if (event->keyval == GDK_Right)
1072 keyval = shift | ctrl | CURSOR_RIGHT;
1073 else if (event->keyval == GDK_KP_Right || event->keyval == GDK_KP_6)
1074 keyval = MOD_NUM_KEYPAD | '6';
1075 else if (event->keyval == GDK_KP_Home || event->keyval == GDK_KP_7)
1076 keyval = MOD_NUM_KEYPAD | '7';
1077 else if (event->keyval == GDK_KP_End || event->keyval == GDK_KP_1)
1078 keyval = MOD_NUM_KEYPAD | '1';
1079 else if (event->keyval == GDK_KP_Page_Up || event->keyval == GDK_KP_9)
1080 keyval = MOD_NUM_KEYPAD | '9';
1081 else if (event->keyval == GDK_KP_Page_Down || event->keyval == GDK_KP_3)
1082 keyval = MOD_NUM_KEYPAD | '3';
1083 else if (event->keyval == GDK_KP_Insert || event->keyval == GDK_KP_0)
1084 keyval = MOD_NUM_KEYPAD | '0';
1085 else if (event->keyval == GDK_KP_Begin || event->keyval == GDK_KP_5)
1086 keyval = MOD_NUM_KEYPAD | '5';
1087 else if (event->keyval == GDK_BackSpace ||
1088 event->keyval == GDK_Delete ||
1089 event->keyval == GDK_KP_Delete)
1090 keyval = '\177';
1091 else if (event->string[0] && !event->string[1])
1092 keyval = (unsigned char)event->string[0];
1093 else
1094 keyval = -1;
1096 if (keyval >= 0 &&
1097 !midend_process_key(fe->me, 0, 0, keyval))
1098 gtk_widget_destroy(fe->window);
1100 return TRUE;
1103 static gint button_event(GtkWidget *widget, GdkEventButton *event,
1104 gpointer data)
1106 frontend *fe = (frontend *)data;
1107 int button;
1109 if (!backing_store_ok(fe))
1110 return TRUE;
1112 if (event->type != GDK_BUTTON_PRESS && event->type != GDK_BUTTON_RELEASE)
1113 return TRUE;
1115 if (event->button == 2 || (event->state & GDK_SHIFT_MASK))
1116 button = MIDDLE_BUTTON;
1117 else if (event->button == 3 || (event->state & GDK_MOD1_MASK))
1118 button = RIGHT_BUTTON;
1119 else if (event->button == 1)
1120 button = LEFT_BUTTON;
1121 else
1122 return FALSE; /* don't even know what button! */
1124 if (event->type == GDK_BUTTON_RELEASE)
1125 button += LEFT_RELEASE - LEFT_BUTTON;
1127 if (!midend_process_key(fe->me, event->x - fe->ox,
1128 event->y - fe->oy, button))
1129 gtk_widget_destroy(fe->window);
1131 return TRUE;
1134 static gint motion_event(GtkWidget *widget, GdkEventMotion *event,
1135 gpointer data)
1137 frontend *fe = (frontend *)data;
1138 int button;
1140 if (!backing_store_ok(fe))
1141 return TRUE;
1143 if (event->state & (GDK_BUTTON2_MASK | GDK_SHIFT_MASK))
1144 button = MIDDLE_DRAG;
1145 else if (event->state & GDK_BUTTON1_MASK)
1146 button = LEFT_DRAG;
1147 else if (event->state & GDK_BUTTON3_MASK)
1148 button = RIGHT_DRAG;
1149 else
1150 return FALSE; /* don't even know what button! */
1152 if (!midend_process_key(fe->me, event->x - fe->ox,
1153 event->y - fe->oy, button))
1154 gtk_widget_destroy(fe->window);
1155 #if GTK_CHECK_VERSION(2,12,0)
1156 gdk_event_request_motions(event);
1157 #else
1158 gdk_window_get_pointer(widget->window, NULL, NULL, NULL);
1159 #endif
1161 return TRUE;
1164 static gint expose_area(GtkWidget *widget, GdkEventExpose *event,
1165 gpointer data)
1167 frontend *fe = (frontend *)data;
1169 if (backing_store_ok(fe)) {
1170 repaint_rectangle(fe, widget,
1171 event->area.x, event->area.y,
1172 event->area.width, event->area.height);
1174 return TRUE;
1177 static gint map_window(GtkWidget *widget, GdkEvent *event,
1178 gpointer data)
1180 frontend *fe = (frontend *)data;
1183 * Apparently we need to do this because otherwise the status
1184 * bar will fail to update immediately. Annoying, but there we
1185 * go.
1187 gtk_widget_queue_draw(fe->window);
1189 return TRUE;
1192 static gint configure_area(GtkWidget *widget,
1193 GdkEventConfigure *event, gpointer data)
1195 frontend *fe = (frontend *)data;
1196 int x, y;
1198 if (backing_store_ok(fe))
1199 teardown_backing_store(fe);
1201 x = fe->w = event->width;
1202 y = fe->h = event->height;
1203 midend_size(fe->me, &x, &y, TRUE);
1204 fe->pw = x;
1205 fe->ph = y;
1206 fe->ox = (fe->w - fe->pw) / 2;
1207 fe->oy = (fe->h - fe->ph) / 2;
1209 setup_backing_store(fe);
1210 midend_force_redraw(fe->me);
1212 return TRUE;
1215 static gint timer_func(gpointer data)
1217 frontend *fe = (frontend *)data;
1219 if (fe->timer_active) {
1220 struct timeval now;
1221 float elapsed;
1222 gettimeofday(&now, NULL);
1223 elapsed = ((now.tv_usec - fe->last_time.tv_usec) * 0.000001F +
1224 (now.tv_sec - fe->last_time.tv_sec));
1225 midend_timer(fe->me, elapsed); /* may clear timer_active */
1226 fe->last_time = now;
1229 return fe->timer_active;
1232 void deactivate_timer(frontend *fe)
1234 if (!fe)
1235 return; /* can happen due to --generate */
1236 if (fe->timer_active)
1237 gtk_timeout_remove(fe->timer_id);
1238 fe->timer_active = FALSE;
1241 void activate_timer(frontend *fe)
1243 if (!fe)
1244 return; /* can happen due to --generate */
1245 if (!fe->timer_active) {
1246 fe->timer_id = gtk_timeout_add(20, timer_func, fe);
1247 gettimeofday(&fe->last_time, NULL);
1249 fe->timer_active = TRUE;
1252 static void window_destroy(GtkWidget *widget, gpointer data)
1254 gtk_main_quit();
1257 static void msgbox_button_clicked(GtkButton *button, gpointer data)
1259 GtkWidget *window = GTK_WIDGET(data);
1260 int v, *ip;
1262 ip = (int *)gtk_object_get_data(GTK_OBJECT(window), "user-data");
1263 v = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(button), "user-data"));
1264 *ip = v;
1266 gtk_widget_destroy(GTK_WIDGET(data));
1269 static int win_key_press(GtkWidget *widget, GdkEventKey *event, gpointer data)
1271 GtkObject *cancelbutton = GTK_OBJECT(data);
1274 * `Escape' effectively clicks the cancel button
1276 if (event->keyval == GDK_Escape) {
1277 gtk_signal_emit_by_name(GTK_OBJECT(cancelbutton), "clicked");
1278 return TRUE;
1281 return FALSE;
1284 enum { MB_OK, MB_YESNO };
1286 int message_box(GtkWidget *parent, char *title, char *msg, int centre,
1287 int type)
1289 GtkWidget *window, *hbox, *text, *button;
1290 char *titles;
1291 int i, def, cancel;
1293 window = gtk_dialog_new();
1294 text = gtk_label_new(msg);
1295 gtk_misc_set_alignment(GTK_MISC(text), 0.0, 0.0);
1296 hbox = gtk_hbox_new(FALSE, 0);
1297 gtk_box_pack_start(GTK_BOX(hbox), text, FALSE, FALSE, 20);
1298 gtk_box_pack_start(GTK_BOX(GTK_DIALOG(window)->vbox),
1299 hbox, FALSE, FALSE, 20);
1300 gtk_widget_show(text);
1301 gtk_widget_show(hbox);
1302 gtk_window_set_title(GTK_WINDOW(window), title);
1303 gtk_label_set_line_wrap(GTK_LABEL(text), TRUE);
1305 if (type == MB_OK) {
1306 titles = GTK_STOCK_OK "\0";
1307 def = cancel = 0;
1308 } else {
1309 assert(type == MB_YESNO);
1310 titles = GTK_STOCK_NO "\0" GTK_STOCK_YES "\0";
1311 def = 1;
1312 cancel = 0;
1314 i = 0;
1316 while (*titles) {
1317 button = gtk_button_new_from_stock(titles);
1318 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(window)->action_area),
1319 button, FALSE, FALSE, 0);
1320 gtk_widget_show(button);
1321 if (i == def) {
1322 GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
1323 gtk_window_set_default(GTK_WINDOW(window), button);
1325 if (i == cancel) {
1326 gtk_signal_connect(GTK_OBJECT(window), "key_press_event",
1327 GTK_SIGNAL_FUNC(win_key_press), button);
1329 gtk_signal_connect(GTK_OBJECT(button), "clicked",
1330 GTK_SIGNAL_FUNC(msgbox_button_clicked), window);
1331 gtk_object_set_data(GTK_OBJECT(button), "user-data",
1332 GINT_TO_POINTER(i));
1333 titles += strlen(titles)+1;
1334 i++;
1336 gtk_object_set_data(GTK_OBJECT(window), "user-data",
1337 GINT_TO_POINTER(&i));
1338 gtk_signal_connect(GTK_OBJECT(window), "destroy",
1339 GTK_SIGNAL_FUNC(window_destroy), NULL);
1340 gtk_window_set_modal(GTK_WINDOW(window), TRUE);
1341 gtk_window_set_transient_for(GTK_WINDOW(window), GTK_WINDOW(parent));
1342 /* set_transient_window_pos(parent, window); */
1343 gtk_widget_show(window);
1344 i = -1;
1345 gtk_main();
1346 return (type == MB_YESNO ? i == 1 : TRUE);
1349 void error_box(GtkWidget *parent, char *msg)
1351 message_box(parent, "Error", msg, FALSE, MB_OK);
1354 static void config_ok_button_clicked(GtkButton *button, gpointer data)
1356 frontend *fe = (frontend *)data;
1357 char *err;
1359 err = midend_set_config(fe->me, fe->cfg_which, fe->cfg);
1361 if (err)
1362 error_box(fe->cfgbox, err);
1363 else {
1364 fe->cfgret = TRUE;
1365 gtk_widget_destroy(fe->cfgbox);
1366 changed_preset(fe);
1370 static void config_cancel_button_clicked(GtkButton *button, gpointer data)
1372 frontend *fe = (frontend *)data;
1374 gtk_widget_destroy(fe->cfgbox);
1377 static int editbox_key(GtkWidget *widget, GdkEventKey *event, gpointer data)
1380 * GtkEntry has a nasty habit of eating the Return key, which
1381 * is unhelpful since it doesn't actually _do_ anything with it
1382 * (it calls gtk_widget_activate, but our edit boxes never need
1383 * activating). So I catch Return before GtkEntry sees it, and
1384 * pass it straight on to the parent widget. Effect: hitting
1385 * Return in an edit box will now activate the default button
1386 * in the dialog just like it will everywhere else.
1388 if (event->keyval == GDK_Return && widget->parent != NULL) {
1389 gint return_val;
1390 gtk_signal_emit_stop_by_name(GTK_OBJECT(widget), "key_press_event");
1391 gtk_signal_emit_by_name(GTK_OBJECT(widget->parent), "key_press_event",
1392 event, &return_val);
1393 return return_val;
1395 return FALSE;
1398 static void editbox_changed(GtkEditable *ed, gpointer data)
1400 config_item *i = (config_item *)data;
1402 sfree(i->sval);
1403 i->sval = dupstr(gtk_entry_get_text(GTK_ENTRY(ed)));
1406 static void button_toggled(GtkToggleButton *tb, gpointer data)
1408 config_item *i = (config_item *)data;
1410 i->ival = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(tb));
1413 static void droplist_sel(GtkMenuItem *item, gpointer data)
1415 config_item *i = (config_item *)data;
1417 i->ival = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(item),
1418 "user-data"));
1421 static int get_config(frontend *fe, int which)
1423 GtkWidget *w, *table, *cancel;
1424 char *title;
1425 config_item *i;
1426 int y;
1428 fe->cfg = midend_get_config(fe->me, which, &title);
1429 fe->cfg_which = which;
1430 fe->cfgret = FALSE;
1432 fe->cfgbox = gtk_dialog_new();
1433 gtk_window_set_title(GTK_WINDOW(fe->cfgbox), title);
1434 sfree(title);
1436 w = gtk_button_new_from_stock(GTK_STOCK_CANCEL);
1437 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(fe->cfgbox)->action_area),
1438 w, FALSE, FALSE, 0);
1439 gtk_widget_show(w);
1440 gtk_signal_connect(GTK_OBJECT(w), "clicked",
1441 GTK_SIGNAL_FUNC(config_cancel_button_clicked), fe);
1442 cancel = w;
1444 w = gtk_button_new_from_stock(GTK_STOCK_OK);
1445 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(fe->cfgbox)->action_area),
1446 w, FALSE, FALSE, 0);
1447 gtk_widget_show(w);
1448 GTK_WIDGET_SET_FLAGS(w, GTK_CAN_DEFAULT);
1449 gtk_window_set_default(GTK_WINDOW(fe->cfgbox), w);
1450 gtk_signal_connect(GTK_OBJECT(w), "clicked",
1451 GTK_SIGNAL_FUNC(config_ok_button_clicked), fe);
1453 table = gtk_table_new(1, 2, FALSE);
1454 y = 0;
1455 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(fe->cfgbox)->vbox),
1456 table, FALSE, FALSE, 0);
1457 gtk_widget_show(table);
1459 for (i = fe->cfg; i->type != C_END; i++) {
1460 gtk_table_resize(GTK_TABLE(table), y+1, 2);
1462 switch (i->type) {
1463 case C_STRING:
1465 * Edit box with a label beside it.
1468 w = gtk_label_new(i->name);
1469 gtk_misc_set_alignment(GTK_MISC(w), 0.0, 0.5);
1470 gtk_table_attach(GTK_TABLE(table), w, 0, 1, y, y+1,
1471 GTK_SHRINK | GTK_FILL,
1472 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1473 3, 3);
1474 gtk_widget_show(w);
1476 w = gtk_entry_new();
1477 gtk_table_attach(GTK_TABLE(table), w, 1, 2, y, y+1,
1478 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1479 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1480 3, 3);
1481 gtk_entry_set_text(GTK_ENTRY(w), i->sval);
1482 gtk_signal_connect(GTK_OBJECT(w), "changed",
1483 GTK_SIGNAL_FUNC(editbox_changed), i);
1484 gtk_signal_connect(GTK_OBJECT(w), "key_press_event",
1485 GTK_SIGNAL_FUNC(editbox_key), NULL);
1486 gtk_widget_show(w);
1488 break;
1490 case C_BOOLEAN:
1492 * Simple checkbox.
1494 w = gtk_check_button_new_with_label(i->name);
1495 gtk_signal_connect(GTK_OBJECT(w), "toggled",
1496 GTK_SIGNAL_FUNC(button_toggled), i);
1497 gtk_table_attach(GTK_TABLE(table), w, 0, 2, y, y+1,
1498 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1499 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1500 3, 3);
1501 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(w), i->ival);
1502 gtk_widget_show(w);
1503 break;
1505 case C_CHOICES:
1507 * Drop-down list (GtkOptionMenu).
1510 w = gtk_label_new(i->name);
1511 gtk_misc_set_alignment(GTK_MISC(w), 0.0, 0.5);
1512 gtk_table_attach(GTK_TABLE(table), w, 0, 1, y, y+1,
1513 GTK_SHRINK | GTK_FILL,
1514 GTK_EXPAND | GTK_SHRINK | GTK_FILL ,
1515 3, 3);
1516 gtk_widget_show(w);
1518 w = gtk_option_menu_new();
1519 gtk_table_attach(GTK_TABLE(table), w, 1, 2, y, y+1,
1520 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1521 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1522 3, 3);
1523 gtk_widget_show(w);
1526 int c, val;
1527 char *p, *q, *name;
1528 GtkWidget *menuitem;
1529 GtkWidget *menu = gtk_menu_new();
1531 gtk_option_menu_set_menu(GTK_OPTION_MENU(w), menu);
1533 c = *i->sval;
1534 p = i->sval+1;
1535 val = 0;
1537 while (*p) {
1538 q = p;
1539 while (*q && *q != c)
1540 q++;
1542 name = snewn(q-p+1, char);
1543 strncpy(name, p, q-p);
1544 name[q-p] = '\0';
1546 if (*q) q++; /* eat delimiter */
1548 menuitem = gtk_menu_item_new_with_label(name);
1549 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1550 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1551 GINT_TO_POINTER(val));
1552 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1553 GTK_SIGNAL_FUNC(droplist_sel), i);
1554 gtk_widget_show(menuitem);
1556 val++;
1558 p = q;
1561 gtk_option_menu_set_history(GTK_OPTION_MENU(w), i->ival);
1564 break;
1567 y++;
1570 gtk_signal_connect(GTK_OBJECT(fe->cfgbox), "destroy",
1571 GTK_SIGNAL_FUNC(window_destroy), NULL);
1572 gtk_signal_connect(GTK_OBJECT(fe->cfgbox), "key_press_event",
1573 GTK_SIGNAL_FUNC(win_key_press), cancel);
1574 gtk_window_set_modal(GTK_WINDOW(fe->cfgbox), TRUE);
1575 gtk_window_set_transient_for(GTK_WINDOW(fe->cfgbox),
1576 GTK_WINDOW(fe->window));
1577 /* set_transient_window_pos(fe->window, fe->cfgbox); */
1578 gtk_widget_show(fe->cfgbox);
1579 gtk_main();
1581 free_cfg(fe->cfg);
1583 return fe->cfgret;
1586 static void menu_key_event(GtkMenuItem *menuitem, gpointer data)
1588 frontend *fe = (frontend *)data;
1589 int key = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(menuitem),
1590 "user-data"));
1591 if (!midend_process_key(fe->me, 0, 0, key))
1592 gtk_widget_destroy(fe->window);
1595 static void get_size(frontend *fe, int *px, int *py)
1597 int x, y;
1600 * Currently I don't want to make the GTK port scale large
1601 * puzzles to fit on the screen. This is because X does permit
1602 * extremely large windows and many window managers provide a
1603 * means of navigating round them, and the users I consulted
1604 * before deciding said that they'd rather have enormous puzzle
1605 * windows spanning multiple screen pages than have them
1606 * shrunk. I could change my mind later or introduce
1607 * configurability; this would be the place to do so, by
1608 * replacing the initial values of x and y with the screen
1609 * dimensions.
1611 x = INT_MAX;
1612 y = INT_MAX;
1613 midend_size(fe->me, &x, &y, FALSE);
1614 *px = x;
1615 *py = y;
1618 #if !GTK_CHECK_VERSION(2,0,0)
1619 #define gtk_window_resize(win, x, y) \
1620 gdk_window_resize(GTK_WIDGET(win)->window, x, y)
1621 #endif
1624 * Called when any other code in this file has changed the
1625 * selected game parameters.
1627 static void changed_preset(frontend *fe)
1629 int n = midend_which_preset(fe->me);
1631 fe->preset_threaded = TRUE;
1632 if (n < 0 && fe->preset_custom) {
1633 gtk_check_menu_item_set_active(
1634 GTK_CHECK_MENU_ITEM(fe->preset_custom),
1635 TRUE);
1636 } else {
1637 GSList *gs = fe->preset_radio;
1638 int i = fe->n_preset_menu_items - 1 - n;
1639 if (fe->preset_custom)
1640 gs = gs->next;
1641 while (i && gs) {
1642 i--;
1643 gs = gs->next;
1645 if (gs) {
1646 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(gs->data),
1647 TRUE);
1648 } else for (gs = fe->preset_radio; gs; gs = gs->next) {
1649 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(gs->data),
1650 FALSE);
1653 fe->preset_threaded = FALSE;
1656 * Update the greying on the Copy menu option.
1658 if (fe->copy_menu_item) {
1659 int enabled = midend_can_format_as_text_now(fe->me);
1660 gtk_widget_set_sensitive(fe->copy_menu_item, enabled);
1664 static void resize_fe(frontend *fe)
1666 int x, y;
1668 get_size(fe, &x, &y);
1669 fe->w = x;
1670 fe->h = y;
1671 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
1673 GtkRequisition req;
1674 gtk_widget_size_request(GTK_WIDGET(fe->window), &req);
1675 gtk_window_resize(GTK_WINDOW(fe->window), req.width, req.height);
1678 * Now that we've established the preferred size of the window,
1679 * reduce the drawing area's size request so the user can shrink
1680 * the window.
1682 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), 1, 1);
1685 static void menu_preset_event(GtkMenuItem *menuitem, gpointer data)
1687 frontend *fe = (frontend *)data;
1688 game_params *params =
1689 (game_params *)gtk_object_get_data(GTK_OBJECT(menuitem), "user-data");
1691 if (fe->preset_threaded ||
1692 (GTK_IS_CHECK_MENU_ITEM(menuitem) &&
1693 !gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(menuitem))))
1694 return;
1695 midend_set_params(fe->me, params);
1696 midend_new_game(fe->me);
1697 changed_preset(fe);
1698 resize_fe(fe);
1701 GdkAtom compound_text_atom, utf8_string_atom;
1702 int paste_initialised = FALSE;
1704 static void set_selection(frontend *fe, GdkAtom selection)
1706 if (!paste_initialised) {
1707 compound_text_atom = gdk_atom_intern("COMPOUND_TEXT", FALSE);
1708 utf8_string_atom = gdk_atom_intern("UTF8_STRING", FALSE);
1709 paste_initialised = TRUE;
1713 * For this simple application we can safely assume that the
1714 * data passed to this function is pure ASCII, which means we
1715 * can return precisely the same stuff for types STRING,
1716 * COMPOUND_TEXT or UTF8_STRING.
1719 if (gtk_selection_owner_set(fe->area, selection, CurrentTime)) {
1720 gtk_selection_clear_targets(fe->area, selection);
1721 gtk_selection_add_target(fe->area, selection,
1722 GDK_SELECTION_TYPE_STRING, 1);
1723 gtk_selection_add_target(fe->area, selection, compound_text_atom, 1);
1724 gtk_selection_add_target(fe->area, selection, utf8_string_atom, 1);
1728 void write_clip(frontend *fe, char *data)
1730 if (fe->paste_data)
1731 sfree(fe->paste_data);
1733 fe->paste_data = data;
1734 fe->paste_data_len = strlen(data);
1736 set_selection(fe, GDK_SELECTION_PRIMARY);
1737 set_selection(fe, GDK_SELECTION_CLIPBOARD);
1740 void selection_get(GtkWidget *widget, GtkSelectionData *seldata,
1741 guint info, guint time_stamp, gpointer data)
1743 frontend *fe = (frontend *)data;
1744 gtk_selection_data_set(seldata, seldata->target, 8,
1745 fe->paste_data, fe->paste_data_len);
1748 gint selection_clear(GtkWidget *widget, GdkEventSelection *seldata,
1749 gpointer data)
1751 frontend *fe = (frontend *)data;
1753 if (fe->paste_data)
1754 sfree(fe->paste_data);
1755 fe->paste_data = NULL;
1756 fe->paste_data_len = 0;
1757 return TRUE;
1760 static void menu_copy_event(GtkMenuItem *menuitem, gpointer data)
1762 frontend *fe = (frontend *)data;
1763 char *text;
1765 text = midend_text_format(fe->me);
1767 if (text) {
1768 write_clip(fe, text);
1769 } else {
1770 gdk_beep();
1774 #ifdef OLD_FILESEL
1776 static void filesel_ok(GtkButton *button, gpointer data)
1778 frontend *fe = (frontend *)data;
1780 gpointer filesel = gtk_object_get_data(GTK_OBJECT(button), "user-data");
1782 const char *name =
1783 gtk_file_selection_get_filename(GTK_FILE_SELECTION(filesel));
1785 fe->filesel_name = dupstr(name);
1788 static char *file_selector(frontend *fe, char *title, int save)
1790 GtkWidget *filesel =
1791 gtk_file_selection_new(title);
1793 fe->filesel_name = NULL;
1795 gtk_window_set_modal(GTK_WINDOW(filesel), TRUE);
1796 gtk_object_set_data
1797 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "user-data",
1798 (gpointer)filesel);
1799 gtk_signal_connect
1800 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "clicked",
1801 GTK_SIGNAL_FUNC(filesel_ok), fe);
1802 gtk_signal_connect_object
1803 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "clicked",
1804 GTK_SIGNAL_FUNC(gtk_widget_destroy), (gpointer)filesel);
1805 gtk_signal_connect_object
1806 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->cancel_button), "clicked",
1807 GTK_SIGNAL_FUNC(gtk_widget_destroy), (gpointer)filesel);
1808 gtk_signal_connect(GTK_OBJECT(filesel), "destroy",
1809 GTK_SIGNAL_FUNC(window_destroy), NULL);
1810 gtk_widget_show(filesel);
1811 gtk_window_set_transient_for(GTK_WINDOW(filesel), GTK_WINDOW(fe->window));
1812 gtk_main();
1814 return fe->filesel_name;
1817 #else
1819 static char *file_selector(frontend *fe, char *title, int save)
1821 char *filesel_name = NULL;
1823 GtkWidget *filesel =
1824 gtk_file_chooser_dialog_new(title,
1825 GTK_WINDOW(fe->window),
1826 save ? GTK_FILE_CHOOSER_ACTION_SAVE :
1827 GTK_FILE_CHOOSER_ACTION_OPEN,
1828 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
1829 save ? GTK_STOCK_SAVE : GTK_STOCK_OPEN,
1830 GTK_RESPONSE_ACCEPT,
1831 NULL);
1833 if (gtk_dialog_run(GTK_DIALOG(filesel)) == GTK_RESPONSE_ACCEPT) {
1834 const char *name = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(filesel));
1835 filesel_name = dupstr(name);
1838 gtk_widget_destroy(filesel);
1840 return filesel_name;
1843 #endif
1845 struct savefile_write_ctx {
1846 FILE *fp;
1847 int error;
1850 static void savefile_write(void *wctx, void *buf, int len)
1852 struct savefile_write_ctx *ctx = (struct savefile_write_ctx *)wctx;
1853 if (fwrite(buf, 1, len, ctx->fp) < len)
1854 ctx->error = errno;
1857 static int savefile_read(void *wctx, void *buf, int len)
1859 FILE *fp = (FILE *)wctx;
1860 int ret;
1862 ret = fread(buf, 1, len, fp);
1863 return (ret == len);
1866 static void menu_save_event(GtkMenuItem *menuitem, gpointer data)
1868 frontend *fe = (frontend *)data;
1869 char *name;
1871 name = file_selector(fe, "Enter name of game file to save", TRUE);
1873 if (name) {
1874 FILE *fp;
1876 if ((fp = fopen(name, "r")) != NULL) {
1877 char buf[256 + FILENAME_MAX];
1878 fclose(fp);
1879 /* file exists */
1881 sprintf(buf, "Are you sure you want to overwrite the"
1882 " file \"%.*s\"?",
1883 FILENAME_MAX, name);
1884 if (!message_box(fe->window, "Question", buf, TRUE, MB_YESNO))
1885 return;
1888 fp = fopen(name, "w");
1889 sfree(name);
1891 if (!fp) {
1892 error_box(fe->window, "Unable to open save file");
1893 return;
1897 struct savefile_write_ctx ctx;
1898 ctx.fp = fp;
1899 ctx.error = 0;
1900 midend_serialise(fe->me, savefile_write, &ctx);
1901 fclose(fp);
1902 if (ctx.error) {
1903 char boxmsg[512];
1904 sprintf(boxmsg, "Error writing save file: %.400s",
1905 strerror(errno));
1906 error_box(fe->window, boxmsg);
1907 return;
1914 static void menu_load_event(GtkMenuItem *menuitem, gpointer data)
1916 frontend *fe = (frontend *)data;
1917 char *name, *err;
1919 name = file_selector(fe, "Enter name of saved game file to load", FALSE);
1921 if (name) {
1922 FILE *fp = fopen(name, "r");
1923 sfree(name);
1925 if (!fp) {
1926 error_box(fe->window, "Unable to open saved game file");
1927 return;
1930 err = midend_deserialise(fe->me, savefile_read, fp);
1932 fclose(fp);
1934 if (err) {
1935 error_box(fe->window, err);
1936 return;
1939 changed_preset(fe);
1940 resize_fe(fe);
1944 static void menu_solve_event(GtkMenuItem *menuitem, gpointer data)
1946 frontend *fe = (frontend *)data;
1947 char *msg;
1949 msg = midend_solve(fe->me);
1951 if (msg)
1952 error_box(fe->window, msg);
1955 static void menu_restart_event(GtkMenuItem *menuitem, gpointer data)
1957 frontend *fe = (frontend *)data;
1959 midend_restart_game(fe->me);
1962 static void menu_config_event(GtkMenuItem *menuitem, gpointer data)
1964 frontend *fe = (frontend *)data;
1965 int which = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(menuitem),
1966 "user-data"));
1968 if (fe->preset_threaded ||
1969 (GTK_IS_CHECK_MENU_ITEM(menuitem) &&
1970 !gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(menuitem))))
1971 return;
1972 changed_preset(fe); /* Put the old preset back! */
1973 if (!get_config(fe, which))
1974 return;
1976 midend_new_game(fe->me);
1977 resize_fe(fe);
1980 static void menu_about_event(GtkMenuItem *menuitem, gpointer data)
1982 frontend *fe = (frontend *)data;
1983 char titlebuf[256];
1984 char textbuf[1024];
1986 sprintf(titlebuf, "About %.200s", thegame.name);
1987 sprintf(textbuf,
1988 "%.200s\n\n"
1989 "from Simon Tatham's Portable Puzzle Collection\n\n"
1990 "%.500s", thegame.name, ver);
1992 message_box(fe->window, titlebuf, textbuf, TRUE, MB_OK);
1995 static GtkWidget *add_menu_item_with_key(frontend *fe, GtkContainer *cont,
1996 char *text, int key)
1998 GtkWidget *menuitem = gtk_menu_item_new_with_label(text);
1999 int keyqual;
2000 gtk_container_add(cont, menuitem);
2001 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
2002 GINT_TO_POINTER(key));
2003 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2004 GTK_SIGNAL_FUNC(menu_key_event), fe);
2005 switch (key & ~0x1F) {
2006 case 0x00:
2007 key += 0x60;
2008 keyqual = GDK_CONTROL_MASK;
2009 break;
2010 case 0x40:
2011 key += 0x20;
2012 keyqual = GDK_SHIFT_MASK;
2013 break;
2014 default:
2015 keyqual = 0;
2016 break;
2018 gtk_widget_add_accelerator(menuitem,
2019 "activate", fe->accelgroup,
2020 key, keyqual,
2021 GTK_ACCEL_VISIBLE);
2022 gtk_widget_show(menuitem);
2023 return menuitem;
2026 static void add_menu_separator(GtkContainer *cont)
2028 GtkWidget *menuitem = gtk_menu_item_new();
2029 gtk_container_add(cont, menuitem);
2030 gtk_widget_show(menuitem);
2033 enum { ARG_EITHER, ARG_SAVE, ARG_ID }; /* for argtype */
2035 static frontend *new_window(char *arg, int argtype, char **error)
2037 frontend *fe;
2038 GtkBox *vbox, *hbox;
2039 GtkWidget *menubar, *menu, *menuitem;
2040 GdkPixmap *iconpm;
2041 GList *iconlist;
2042 int x, y, n;
2043 char errbuf[1024];
2044 extern char *const *const xpm_icons[];
2045 extern const int n_xpm_icons;
2047 fe = snew(frontend);
2049 fe->timer_active = FALSE;
2050 fe->timer_id = -1;
2052 fe->me = midend_new(fe, &thegame, &gtk_drawing, fe);
2054 if (arg) {
2055 char *err;
2056 FILE *fp;
2058 errbuf[0] = '\0';
2060 switch (argtype) {
2061 case ARG_ID:
2062 err = midend_game_id(fe->me, arg);
2063 if (!err)
2064 midend_new_game(fe->me);
2065 else
2066 sprintf(errbuf, "Invalid game ID: %.800s", err);
2067 break;
2068 case ARG_SAVE:
2069 fp = fopen(arg, "r");
2070 if (!fp) {
2071 sprintf(errbuf, "Error opening file: %.800s", strerror(errno));
2072 } else {
2073 err = midend_deserialise(fe->me, savefile_read, fp);
2074 if (err)
2075 sprintf(errbuf, "Invalid save file: %.800s", err);
2076 fclose(fp);
2078 break;
2079 default /*case ARG_EITHER*/:
2081 * First try treating the argument as a game ID.
2083 err = midend_game_id(fe->me, arg);
2084 if (!err) {
2086 * It's a valid game ID.
2088 midend_new_game(fe->me);
2089 } else {
2090 FILE *fp = fopen(arg, "r");
2091 if (!fp) {
2092 sprintf(errbuf, "Supplied argument is neither a game ID (%.400s)"
2093 " nor a save file (%.400s)", err, strerror(errno));
2094 } else {
2095 err = midend_deserialise(fe->me, savefile_read, fp);
2096 if (err)
2097 sprintf(errbuf, "%.800s", err);
2098 fclose(fp);
2101 break;
2103 if (*errbuf) {
2104 *error = dupstr(errbuf);
2105 midend_free(fe->me);
2106 sfree(fe);
2107 return NULL;
2110 } else {
2111 midend_new_game(fe->me);
2114 fe->window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
2115 gtk_window_set_title(GTK_WINDOW(fe->window), thegame.name);
2117 vbox = GTK_BOX(gtk_vbox_new(FALSE, 0));
2118 gtk_container_add(GTK_CONTAINER(fe->window), GTK_WIDGET(vbox));
2119 gtk_widget_show(GTK_WIDGET(vbox));
2121 fe->accelgroup = gtk_accel_group_new();
2122 gtk_window_add_accel_group(GTK_WINDOW(fe->window), fe->accelgroup);
2124 hbox = GTK_BOX(gtk_hbox_new(FALSE, 0));
2125 gtk_box_pack_start(vbox, GTK_WIDGET(hbox), FALSE, FALSE, 0);
2126 gtk_widget_show(GTK_WIDGET(hbox));
2128 menubar = gtk_menu_bar_new();
2129 gtk_box_pack_start(hbox, menubar, TRUE, TRUE, 0);
2130 gtk_widget_show(menubar);
2132 menuitem = gtk_menu_item_new_with_mnemonic("_Game");
2133 gtk_container_add(GTK_CONTAINER(menubar), menuitem);
2134 gtk_widget_show(menuitem);
2136 menu = gtk_menu_new();
2137 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
2139 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "New", 'n');
2141 menuitem = gtk_menu_item_new_with_label("Restart");
2142 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2143 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2144 GTK_SIGNAL_FUNC(menu_restart_event), fe);
2145 gtk_widget_show(menuitem);
2147 menuitem = gtk_menu_item_new_with_label("Specific...");
2148 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
2149 GINT_TO_POINTER(CFG_DESC));
2150 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2151 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2152 GTK_SIGNAL_FUNC(menu_config_event), fe);
2153 gtk_widget_show(menuitem);
2155 menuitem = gtk_menu_item_new_with_label("Random Seed...");
2156 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
2157 GINT_TO_POINTER(CFG_SEED));
2158 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2159 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2160 GTK_SIGNAL_FUNC(menu_config_event), fe);
2161 gtk_widget_show(menuitem);
2163 fe->preset_radio = NULL;
2164 fe->preset_custom = NULL;
2165 fe->n_preset_menu_items = 0;
2166 fe->preset_threaded = FALSE;
2167 if ((n = midend_num_presets(fe->me)) > 0 || thegame.can_configure) {
2168 GtkWidget *submenu;
2169 int i;
2171 menuitem = gtk_menu_item_new_with_mnemonic("_Type");
2172 gtk_container_add(GTK_CONTAINER(menubar), menuitem);
2173 gtk_widget_show(menuitem);
2175 submenu = gtk_menu_new();
2176 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), submenu);
2178 for (i = 0; i < n; i++) {
2179 char *name;
2180 game_params *params;
2182 midend_fetch_preset(fe->me, i, &name, &params);
2184 menuitem =
2185 gtk_radio_menu_item_new_with_label(fe->preset_radio, name);
2186 fe->preset_radio =
2187 gtk_radio_menu_item_group(GTK_RADIO_MENU_ITEM(menuitem));
2188 fe->n_preset_menu_items++;
2189 gtk_container_add(GTK_CONTAINER(submenu), menuitem);
2190 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data", params);
2191 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2192 GTK_SIGNAL_FUNC(menu_preset_event), fe);
2193 gtk_widget_show(menuitem);
2196 if (thegame.can_configure) {
2197 menuitem = fe->preset_custom =
2198 gtk_radio_menu_item_new_with_label(fe->preset_radio,
2199 "Custom...");
2200 fe->preset_radio =
2201 gtk_radio_menu_item_group(GTK_RADIO_MENU_ITEM(menuitem));
2202 gtk_container_add(GTK_CONTAINER(submenu), menuitem);
2203 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
2204 GPOINTER_TO_INT(CFG_SETTINGS));
2205 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2206 GTK_SIGNAL_FUNC(menu_config_event), fe);
2207 gtk_widget_show(menuitem);
2212 add_menu_separator(GTK_CONTAINER(menu));
2213 menuitem = gtk_menu_item_new_with_label("Load...");
2214 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2215 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2216 GTK_SIGNAL_FUNC(menu_load_event), fe);
2217 gtk_widget_show(menuitem);
2218 menuitem = gtk_menu_item_new_with_label("Save...");
2219 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2220 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2221 GTK_SIGNAL_FUNC(menu_save_event), fe);
2222 gtk_widget_show(menuitem);
2223 #ifndef STYLUS_BASED
2224 add_menu_separator(GTK_CONTAINER(menu));
2225 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Undo", 'u');
2226 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Redo", 'r');
2227 #endif
2228 if (thegame.can_format_as_text_ever) {
2229 add_menu_separator(GTK_CONTAINER(menu));
2230 menuitem = gtk_menu_item_new_with_label("Copy");
2231 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2232 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2233 GTK_SIGNAL_FUNC(menu_copy_event), fe);
2234 gtk_widget_show(menuitem);
2235 fe->copy_menu_item = menuitem;
2236 } else {
2237 fe->copy_menu_item = NULL;
2239 if (thegame.can_solve) {
2240 add_menu_separator(GTK_CONTAINER(menu));
2241 menuitem = gtk_menu_item_new_with_label("Solve");
2242 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2243 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2244 GTK_SIGNAL_FUNC(menu_solve_event), fe);
2245 gtk_widget_show(menuitem);
2247 add_menu_separator(GTK_CONTAINER(menu));
2248 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Exit", 'q');
2250 menuitem = gtk_menu_item_new_with_mnemonic("_Help");
2251 gtk_container_add(GTK_CONTAINER(menubar), menuitem);
2252 gtk_widget_show(menuitem);
2254 menu = gtk_menu_new();
2255 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
2257 menuitem = gtk_menu_item_new_with_label("About");
2258 gtk_container_add(GTK_CONTAINER(menu), menuitem);
2259 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2260 GTK_SIGNAL_FUNC(menu_about_event), fe);
2261 gtk_widget_show(menuitem);
2263 #ifdef STYLUS_BASED
2264 menuitem=gtk_button_new_with_mnemonic("_Redo");
2265 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
2266 GINT_TO_POINTER((int)('r')));
2267 gtk_signal_connect(GTK_OBJECT(menuitem), "clicked",
2268 GTK_SIGNAL_FUNC(menu_key_event), fe);
2269 gtk_box_pack_end(hbox, menuitem, FALSE, FALSE, 0);
2270 gtk_widget_show(menuitem);
2272 menuitem=gtk_button_new_with_mnemonic("_Undo");
2273 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
2274 GINT_TO_POINTER((int)('u')));
2275 gtk_signal_connect(GTK_OBJECT(menuitem), "clicked",
2276 GTK_SIGNAL_FUNC(menu_key_event), fe);
2277 gtk_box_pack_end(hbox, menuitem, FALSE, FALSE, 0);
2278 gtk_widget_show(menuitem);
2280 if (thegame.flags & REQUIRE_NUMPAD) {
2281 hbox = GTK_BOX(gtk_hbox_new(FALSE, 0));
2282 gtk_box_pack_start(vbox, GTK_WIDGET(hbox), FALSE, FALSE, 0);
2283 gtk_widget_show(GTK_WIDGET(hbox));
2285 *((int*)errbuf)=0;
2286 errbuf[1]='\0';
2287 for(errbuf[0]='0';errbuf[0]<='9';errbuf[0]++) {
2288 menuitem=gtk_button_new_with_label(errbuf);
2289 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
2290 GINT_TO_POINTER((int)(errbuf[0])));
2291 gtk_signal_connect(GTK_OBJECT(menuitem), "clicked",
2292 GTK_SIGNAL_FUNC(menu_key_event), fe);
2293 gtk_box_pack_start(hbox, menuitem, TRUE, TRUE, 0);
2294 gtk_widget_show(menuitem);
2297 #endif /* STYLUS_BASED */
2299 changed_preset(fe);
2301 snaffle_colours(fe);
2303 if (midend_wants_statusbar(fe->me)) {
2304 GtkWidget *viewport;
2305 GtkRequisition req;
2307 viewport = gtk_viewport_new(NULL, NULL);
2308 gtk_viewport_set_shadow_type(GTK_VIEWPORT(viewport), GTK_SHADOW_NONE);
2309 fe->statusbar = gtk_statusbar_new();
2310 gtk_container_add(GTK_CONTAINER(viewport), fe->statusbar);
2311 gtk_widget_show(viewport);
2312 gtk_box_pack_end(vbox, viewport, FALSE, FALSE, 0);
2313 gtk_widget_show(fe->statusbar);
2314 fe->statusctx = gtk_statusbar_get_context_id
2315 (GTK_STATUSBAR(fe->statusbar), "game");
2316 gtk_statusbar_push(GTK_STATUSBAR(fe->statusbar), fe->statusctx,
2317 "test");
2318 gtk_widget_size_request(fe->statusbar, &req);
2319 #if 0
2320 /* For GTK 2.0, should we be using gtk_widget_set_size_request? */
2321 #endif
2322 gtk_widget_set_usize(viewport, -1, req.height);
2323 } else
2324 fe->statusbar = NULL;
2326 fe->area = gtk_drawing_area_new();
2327 #if GTK_CHECK_VERSION(2,0,0)
2328 GTK_WIDGET_UNSET_FLAGS(fe->area, GTK_DOUBLE_BUFFERED);
2329 #endif
2330 get_size(fe, &x, &y);
2331 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
2332 fe->w = x;
2333 fe->h = y;
2335 gtk_box_pack_end(vbox, fe->area, TRUE, TRUE, 0);
2337 clear_backing_store(fe);
2338 fe->fonts = NULL;
2339 fe->nfonts = fe->fontsize = 0;
2341 fe->paste_data = NULL;
2342 fe->paste_data_len = 0;
2344 gtk_signal_connect(GTK_OBJECT(fe->window), "destroy",
2345 GTK_SIGNAL_FUNC(destroy), fe);
2346 gtk_signal_connect(GTK_OBJECT(fe->window), "key_press_event",
2347 GTK_SIGNAL_FUNC(key_event), fe);
2348 gtk_signal_connect(GTK_OBJECT(fe->area), "button_press_event",
2349 GTK_SIGNAL_FUNC(button_event), fe);
2350 gtk_signal_connect(GTK_OBJECT(fe->area), "button_release_event",
2351 GTK_SIGNAL_FUNC(button_event), fe);
2352 gtk_signal_connect(GTK_OBJECT(fe->area), "motion_notify_event",
2353 GTK_SIGNAL_FUNC(motion_event), fe);
2354 gtk_signal_connect(GTK_OBJECT(fe->area), "selection_get",
2355 GTK_SIGNAL_FUNC(selection_get), fe);
2356 gtk_signal_connect(GTK_OBJECT(fe->area), "selection_clear_event",
2357 GTK_SIGNAL_FUNC(selection_clear), fe);
2358 gtk_signal_connect(GTK_OBJECT(fe->area), "expose_event",
2359 GTK_SIGNAL_FUNC(expose_area), fe);
2360 gtk_signal_connect(GTK_OBJECT(fe->window), "map_event",
2361 GTK_SIGNAL_FUNC(map_window), fe);
2362 gtk_signal_connect(GTK_OBJECT(fe->area), "configure_event",
2363 GTK_SIGNAL_FUNC(configure_area), fe);
2365 gtk_widget_add_events(GTK_WIDGET(fe->area),
2366 GDK_BUTTON_PRESS_MASK |
2367 GDK_BUTTON_RELEASE_MASK |
2368 GDK_BUTTON_MOTION_MASK |
2369 GDK_POINTER_MOTION_HINT_MASK);
2371 if (n_xpm_icons) {
2372 gtk_widget_realize(fe->window);
2373 iconpm = gdk_pixmap_create_from_xpm_d(fe->window->window, NULL,
2374 NULL, (gchar **)xpm_icons[0]);
2375 gdk_window_set_icon(fe->window->window, NULL, iconpm, NULL);
2376 iconlist = NULL;
2377 for (n = 0; n < n_xpm_icons; n++) {
2378 iconlist =
2379 g_list_append(iconlist,
2380 gdk_pixbuf_new_from_xpm_data((const gchar **)
2381 xpm_icons[n]));
2383 gdk_window_set_icon_list(fe->window->window, iconlist);
2386 gtk_widget_show(fe->area);
2387 gtk_widget_show(fe->window);
2390 * Now that we've established the preferred size of the window,
2391 * reduce the drawing area's size request so the user can shrink
2392 * the window.
2394 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), 1, 1);
2395 set_window_background(fe, 0);
2397 return fe;
2400 char *fgetline(FILE *fp)
2402 char *ret = snewn(512, char);
2403 int size = 512, len = 0;
2404 while (fgets(ret + len, size - len, fp)) {
2405 len += strlen(ret + len);
2406 if (ret[len-1] == '\n')
2407 break; /* got a newline, we're done */
2408 size = len + 512;
2409 ret = sresize(ret, size, char);
2411 if (len == 0) { /* first fgets returned NULL */
2412 sfree(ret);
2413 return NULL;
2415 ret[len] = '\0';
2416 return ret;
2419 int main(int argc, char **argv)
2421 char *pname = argv[0];
2422 char *error;
2423 int ngenerate = 0, print = FALSE, px = 1, py = 1;
2424 int soln = FALSE, colour = FALSE;
2425 float scale = 1.0F;
2426 float redo_proportion = 0.0F;
2427 char *savefile = NULL, *savesuffix = NULL;
2428 char *arg = NULL;
2429 int argtype = ARG_EITHER;
2430 char *screenshot_file = NULL;
2431 int doing_opts = TRUE;
2432 int ac = argc;
2433 char **av = argv;
2434 char errbuf[500];
2437 * Command line parsing in this function is rather fiddly,
2438 * because GTK wants to have a go at argc/argv _first_ - and
2439 * yet we can't let it, because gtk_init() will bomb out if it
2440 * can't open an X display, whereas in fact we want to permit
2441 * our --generate and --print modes to run without an X
2442 * display.
2444 * So what we do is:
2445 * - we parse the command line ourselves, without modifying
2446 * argc/argv
2447 * - if we encounter an error which might plausibly be the
2448 * result of a GTK command line (i.e. not detailed errors in
2449 * particular options of ours) we store the error message
2450 * and terminate parsing.
2451 * - if we got enough out of the command line to know it
2452 * specifies a non-X mode of operation, we either display
2453 * the stored error and return failure, or if there is no
2454 * stored error we do the non-X operation and return
2455 * success.
2456 * - otherwise, we go straight to gtk_init().
2459 errbuf[0] = '\0';
2460 while (--ac > 0) {
2461 char *p = *++av;
2462 if (doing_opts && !strcmp(p, "--version")) {
2463 printf("%s, from Simon Tatham's Portable Puzzle Collection\n%s\n",
2464 thegame.name, ver);
2465 return 0;
2466 } else if (doing_opts && !strcmp(p, "--generate")) {
2467 if (--ac > 0) {
2468 ngenerate = atoi(*++av);
2469 if (!ngenerate) {
2470 fprintf(stderr, "%s: '--generate' expected a number\n",
2471 pname);
2472 return 1;
2474 } else
2475 ngenerate = 1;
2476 } else if (doing_opts && !strcmp(p, "--save")) {
2477 if (--ac > 0) {
2478 savefile = *++av;
2479 } else {
2480 fprintf(stderr, "%s: '--save' expected a filename\n",
2481 pname);
2482 return 1;
2484 } else if (doing_opts && (!strcmp(p, "--save-suffix") ||
2485 !strcmp(p, "--savesuffix"))) {
2486 if (--ac > 0) {
2487 savesuffix = *++av;
2488 } else {
2489 fprintf(stderr, "%s: '--save-suffix' expected a filename\n",
2490 pname);
2491 return 1;
2493 } else if (doing_opts && !strcmp(p, "--print")) {
2494 if (!thegame.can_print) {
2495 fprintf(stderr, "%s: this game does not support printing\n",
2496 pname);
2497 return 1;
2499 print = TRUE;
2500 if (--ac > 0) {
2501 char *dim = *++av;
2502 if (sscanf(dim, "%dx%d", &px, &py) != 2) {
2503 fprintf(stderr, "%s: unable to parse argument '%s' to "
2504 "'--print'\n", pname, dim);
2505 return 1;
2507 } else {
2508 px = py = 1;
2510 } else if (doing_opts && !strcmp(p, "--scale")) {
2511 if (--ac > 0) {
2512 scale = atof(*++av);
2513 } else {
2514 fprintf(stderr, "%s: no argument supplied to '--scale'\n",
2515 pname);
2516 return 1;
2518 } else if (doing_opts && !strcmp(p, "--redo")) {
2520 * This is an internal option which I don't expect
2521 * users to have any particular use for. The effect of
2522 * --redo is that once the game has been loaded and
2523 * initialised, the next move in the redo chain is
2524 * replayed, and the game screen is redrawn part way
2525 * through the making of the move. This is only
2526 * meaningful if there _is_ a next move in the redo
2527 * chain, which means in turn that this option is only
2528 * useful if you're also passing a save file on the
2529 * command line.
2531 * This option is used by the script which generates
2532 * the puzzle icons and website screenshots, and I
2533 * don't imagine it's useful for anything else.
2534 * (Unless, I suppose, users don't like my screenshots
2535 * and want to generate their own in the same way for
2536 * some repackaged version of the puzzles.)
2538 if (--ac > 0) {
2539 redo_proportion = atof(*++av);
2540 } else {
2541 fprintf(stderr, "%s: no argument supplied to '--redo'\n",
2542 pname);
2543 return 1;
2545 } else if (doing_opts && !strcmp(p, "--screenshot")) {
2547 * Another internal option for the icon building
2548 * script. This causes a screenshot of the central
2549 * drawing area (i.e. not including the menu bar or
2550 * status bar) to be saved to a PNG file once the
2551 * window has been drawn, and then the application
2552 * quits immediately.
2554 if (--ac > 0) {
2555 screenshot_file = *++av;
2556 } else {
2557 fprintf(stderr, "%s: no argument supplied to '--screenshot'\n",
2558 pname);
2559 return 1;
2561 } else if (doing_opts && (!strcmp(p, "--with-solutions") ||
2562 !strcmp(p, "--with-solution") ||
2563 !strcmp(p, "--with-solns") ||
2564 !strcmp(p, "--with-soln") ||
2565 !strcmp(p, "--solutions") ||
2566 !strcmp(p, "--solution") ||
2567 !strcmp(p, "--solns") ||
2568 !strcmp(p, "--soln"))) {
2569 soln = TRUE;
2570 } else if (doing_opts && !strcmp(p, "--colour")) {
2571 if (!thegame.can_print_in_colour) {
2572 fprintf(stderr, "%s: this game does not support colour"
2573 " printing\n", pname);
2574 return 1;
2576 colour = TRUE;
2577 } else if (doing_opts && !strcmp(p, "--load")) {
2578 argtype = ARG_SAVE;
2579 } else if (doing_opts && !strcmp(p, "--game")) {
2580 argtype = ARG_ID;
2581 } else if (doing_opts && !strcmp(p, "--")) {
2582 doing_opts = FALSE;
2583 } else if (!doing_opts || p[0] != '-') {
2584 if (arg) {
2585 fprintf(stderr, "%s: more than one argument supplied\n",
2586 pname);
2587 return 1;
2589 arg = p;
2590 } else {
2591 sprintf(errbuf, "%.100s: unrecognised option '%.100s'\n",
2592 pname, p);
2593 break;
2597 if (*errbuf) {
2598 fputs(errbuf, stderr);
2599 return 1;
2603 * Special standalone mode for generating puzzle IDs on the
2604 * command line. Useful for generating puzzles to be printed
2605 * out and solved offline (for puzzles where that even makes
2606 * sense - Solo, for example, is a lot more pencil-and-paper
2607 * friendly than Twiddle!)
2609 * Usage:
2611 * <puzzle-name> --generate [<n> [<params>]]
2613 * <n>, if present, is the number of puzzle IDs to generate.
2614 * <params>, if present, is the same type of parameter string
2615 * you would pass to the puzzle when running it in GUI mode,
2616 * including optional extras such as the expansion factor in
2617 * Rectangles and the difficulty level in Solo.
2619 * If you specify <params>, you must also specify <n> (although
2620 * you may specify it to be 1). Sorry; that was the
2621 * simplest-to-parse command-line syntax I came up with.
2623 if (ngenerate > 0 || print || savefile || savesuffix) {
2624 int i, n = 1;
2625 midend *me;
2626 char *id;
2627 document *doc = NULL;
2629 n = ngenerate;
2631 me = midend_new(NULL, &thegame, NULL, NULL);
2632 i = 0;
2634 if (savefile && !savesuffix)
2635 savesuffix = "";
2636 if (!savefile && savesuffix)
2637 savefile = "";
2639 if (print)
2640 doc = document_new(px, py, scale);
2643 * In this loop, we either generate a game ID or read one
2644 * from stdin depending on whether we're in generate mode;
2645 * then we either write it to stdout or print it, depending
2646 * on whether we're in print mode. Thus, this loop handles
2647 * generate-to-stdout, print-from-stdin and generate-and-
2648 * immediately-print modes.
2650 * (It could also handle a copy-stdin-to-stdout mode,
2651 * although there's currently no combination of options
2652 * which will cause this loop to be activated in that mode.
2653 * It wouldn't be _entirely_ pointless, though, because
2654 * stdin could contain bare params strings or random-seed
2655 * IDs, and stdout would contain nothing but fully
2656 * generated descriptive game IDs.)
2658 while (ngenerate == 0 || i < n) {
2659 char *pstr, *err;
2661 if (ngenerate == 0) {
2662 pstr = fgetline(stdin);
2663 if (!pstr)
2664 break;
2665 pstr[strcspn(pstr, "\r\n")] = '\0';
2666 } else {
2667 if (arg) {
2668 pstr = snewn(strlen(arg) + 40, char);
2670 strcpy(pstr, arg);
2671 if (i > 0 && strchr(arg, '#'))
2672 sprintf(pstr + strlen(pstr), "-%d", i);
2673 } else
2674 pstr = NULL;
2677 if (pstr) {
2678 err = midend_game_id(me, pstr);
2679 if (err) {
2680 fprintf(stderr, "%s: error parsing '%s': %s\n",
2681 pname, pstr, err);
2682 return 1;
2685 sfree(pstr);
2687 midend_new_game(me);
2689 if (doc) {
2690 err = midend_print_puzzle(me, doc, soln);
2691 if (err) {
2692 fprintf(stderr, "%s: error in printing: %s\n", pname, err);
2693 return 1;
2696 if (savefile) {
2697 struct savefile_write_ctx ctx;
2698 char *realname = snewn(40 + strlen(savefile) +
2699 strlen(savesuffix), char);
2700 sprintf(realname, "%s%d%s", savefile, i, savesuffix);
2701 ctx.fp = fopen(realname, "w");
2702 if (!ctx.fp) {
2703 fprintf(stderr, "%s: open: %s\n", realname,
2704 strerror(errno));
2705 return 1;
2707 sfree(realname);
2708 midend_serialise(me, savefile_write, &ctx);
2709 if (ctx.error) {
2710 fprintf(stderr, "%s: write: %s\n", realname,
2711 strerror(ctx.error));
2712 return 1;
2714 if (fclose(ctx.fp)) {
2715 fprintf(stderr, "%s: close: %s\n", realname,
2716 strerror(errno));
2717 return 1;
2720 if (!doc && !savefile) {
2721 id = midend_get_game_id(me);
2722 puts(id);
2723 sfree(id);
2726 i++;
2729 if (doc) {
2730 psdata *ps = ps_init(stdout, colour);
2731 document_print(doc, ps_drawing_api(ps));
2732 document_free(doc);
2733 ps_free(ps);
2736 midend_free(me);
2738 return 0;
2739 } else {
2740 frontend *fe;
2742 gtk_init(&argc, &argv);
2744 fe = new_window(arg, argtype, &error);
2746 if (!fe) {
2747 fprintf(stderr, "%s: %s\n", pname, error);
2748 return 1;
2751 if (screenshot_file) {
2753 * Some puzzles will not redraw their entire area if
2754 * given a partially completed animation, which means
2755 * we must redraw now and _then_ redraw again after
2756 * freezing the move timer.
2758 midend_force_redraw(fe->me);
2761 if (redo_proportion) {
2762 /* Start a redo. */
2763 midend_process_key(fe->me, 0, 0, 'r');
2764 /* And freeze the timer at the specified position. */
2765 midend_freeze_timer(fe->me, redo_proportion);
2768 if (screenshot_file) {
2769 save_screenshot_png(fe, screenshot_file);
2770 exit(0);
2773 gtk_main();
2776 return 0;