2 * gtk.c: GTK front end for my puzzle collection.
16 #include <gdk/gdkkeysyms.h>
18 #include <gdk-pixbuf/gdk-pixbuf.h>
22 #include <X11/Xutil.h>
23 #include <X11/Xatom.h>
27 #if GTK_CHECK_VERSION(2,0,0)
29 # ifdef PANGO_VERSION_CHECK
30 # if PANGO_VERSION_CHECK(1,8,0)
31 # define HAVE_SENSIBLE_ABSOLUTE_SIZE_FUNCTION
35 #if !GTK_CHECK_VERSION(2,4,0)
40 static FILE *debug_fp = NULL;
45 debug_fp = fopen("debug.log", "w");
56 void debug_printf(char *fmt, ...)
62 vsprintf(buf, fmt, ap);
68 /* ----------------------------------------------------------------------
69 * Error reporting functions used elsewhere.
72 void fatal(char *fmt, ...)
76 fprintf(stderr, "fatal error: ");
79 vfprintf(stderr, fmt, ap);
82 fprintf(stderr, "\n");
86 /* ----------------------------------------------------------------------
87 * GTK front end to puzzles.
90 static void changed_preset(frontend *fe);
94 PangoFontDescription *desc;
103 * This structure holds all the data relevant to a single window.
104 * In principle this would allow us to open multiple independent
105 * puzzle windows, although I can't currently see any real point in
106 * doing so. I'm just coding cleanly because there's no
107 * particularly good reason not to.
111 GtkAccelGroup *accelgroup;
113 GtkWidget *statusbar;
122 int bbox_l, bbox_r, bbox_u, bbox_d;
123 int timer_active, timer_id;
124 struct timeval last_time;
126 int nfonts, fontsize;
128 int cfg_which, cfgret;
132 int pw, ph; /* pixmap size (w, h are area size) */
133 int ox, oy; /* offset of pixmap in drawing area */
138 GtkWidget **preset_bullets;
139 GtkWidget *preset_custom_bullet;
140 GtkWidget *copy_menu_item;
143 void get_random_seed(void **randseed, int *randseedsize)
145 struct timeval *tvp = snew(struct timeval);
146 gettimeofday(tvp, NULL);
147 *randseed = (void *)tvp;
148 *randseedsize = sizeof(struct timeval);
151 void frontend_default_colour(frontend *fe, float *output)
153 GdkColor col = fe->window->style->bg[GTK_STATE_NORMAL];
154 output[0] = col.red / 65535.0;
155 output[1] = col.green / 65535.0;
156 output[2] = col.blue / 65535.0;
159 void gtk_status_bar(void *handle, char *text)
161 frontend *fe = (frontend *)handle;
163 assert(fe->statusbar);
165 gtk_statusbar_pop(GTK_STATUSBAR(fe->statusbar), fe->statusctx);
166 gtk_statusbar_push(GTK_STATUSBAR(fe->statusbar), fe->statusctx, text);
169 void gtk_start_draw(void *handle)
171 frontend *fe = (frontend *)handle;
172 fe->gc = gdk_gc_new(fe->area->window);
179 void gtk_clip(void *handle, int x, int y, int w, int h)
181 frontend *fe = (frontend *)handle;
189 gdk_gc_set_clip_rectangle(fe->gc, &rect);
192 void gtk_unclip(void *handle)
194 frontend *fe = (frontend *)handle;
202 gdk_gc_set_clip_rectangle(fe->gc, &rect);
205 void gtk_draw_text(void *handle, int x, int y, int fonttype, int fontsize,
206 int align, int colour, char *text)
208 frontend *fe = (frontend *)handle;
212 * Find or create the font.
214 for (i = 0; i < fe->nfonts; i++)
215 if (fe->fonts[i].type == fonttype && fe->fonts[i].size == fontsize)
218 if (i == fe->nfonts) {
219 if (fe->fontsize <= fe->nfonts) {
220 fe->fontsize = fe->nfonts + 10;
221 fe->fonts = sresize(fe->fonts, fe->fontsize, struct font);
226 fe->fonts[i].type = fonttype;
227 fe->fonts[i].size = fontsize;
231 * Use Pango to find the closest match to the requested
235 PangoFontDescription *fd;
237 fd = pango_font_description_new();
238 /* `Monospace' and `Sans' are meta-families guaranteed to exist */
239 pango_font_description_set_family(fd, fonttype == FONT_FIXED ?
240 "Monospace" : "Sans");
241 pango_font_description_set_weight(fd, PANGO_WEIGHT_BOLD);
243 * I found some online Pango documentation which
244 * described a function called
245 * pango_font_description_set_absolute_size(), which is
246 * _exactly_ what I want here. Unfortunately, none of
247 * my local Pango installations have it (presumably
248 * they're too old), so I'm going to have to hack round
249 * it by figuring out the point size myself. This
250 * limits me to X and probably also breaks in later
251 * Pango installations, so ideally I should add another
252 * CHECK_VERSION type ifdef and use set_absolute_size
253 * where available. All very annoying.
255 #ifdef HAVE_SENSIBLE_ABSOLUTE_SIZE_FUNCTION
256 pango_font_description_set_absolute_size(fd, PANGO_SCALE*fontsize);
259 Display *d = GDK_DISPLAY();
260 int s = DefaultScreen(d);
262 (PANGO_SCALE * 72.27 / 25.4) *
263 ((double) DisplayWidthMM(d, s) / DisplayWidth (d, s));
264 pango_font_description_set_size(fd, resolution * fontsize);
267 fe->fonts[i].desc = fd;
272 * In GTK 1.2, I don't know of any plausible way to
273 * pick a suitable font, so I'm just going to be
276 fe->fonts[i].font = gdk_font_load(fonttype == FONT_FIXED ?
277 "fixed" : "variable");
285 gdk_gc_set_foreground(fe->gc, &fe->colours[colour]);
296 layout = pango_layout_new(gtk_widget_get_pango_context(fe->area));
297 pango_layout_set_font_description(layout, fe->fonts[i].desc);
298 pango_layout_set_text(layout, text, strlen(text));
299 pango_layout_get_pixel_extents(layout, NULL, &rect);
301 if (align & ALIGN_VCENTRE)
302 rect.y -= rect.height / 2;
304 rect.y -= rect.height;
306 if (align & ALIGN_HCENTRE)
307 rect.x -= rect.width / 2;
308 else if (align & ALIGN_HRIGHT)
309 rect.x -= rect.width;
311 gdk_draw_layout(fe->pixmap, fe->gc, rect.x + x, rect.y + y, layout);
313 g_object_unref(layout);
318 * Find string dimensions and process alignment.
321 int lb, rb, wid, asc, desc;
324 * Measure vertical string extents with respect to the same
327 gdk_string_extents(fe->fonts[i].font,
328 "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
329 &lb, &rb, &wid, &asc, &desc);
330 if (align & ALIGN_VCENTRE)
331 y += asc - (asc+desc)/2;
336 * ... but horizontal extents with respect to the provided
337 * string. This means that multiple pieces of text centred
338 * on the same y-coordinate don't have different baselines.
340 gdk_string_extents(fe->fonts[i].font, text,
341 &lb, &rb, &wid, &asc, &desc);
343 if (align & ALIGN_HCENTRE)
345 else if (align & ALIGN_HRIGHT)
351 * Actually draw the text.
353 gdk_draw_string(fe->pixmap, fe->fonts[i].font, fe->gc, x, y, text);
358 void gtk_draw_rect(void *handle, int x, int y, int w, int h, int colour)
360 frontend *fe = (frontend *)handle;
361 gdk_gc_set_foreground(fe->gc, &fe->colours[colour]);
362 gdk_draw_rectangle(fe->pixmap, fe->gc, 1, x, y, w, h);
365 void gtk_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
367 frontend *fe = (frontend *)handle;
368 gdk_gc_set_foreground(fe->gc, &fe->colours[colour]);
369 gdk_draw_line(fe->pixmap, fe->gc, x1, y1, x2, y2);
372 void gtk_draw_poly(void *handle, int *coords, int npoints,
373 int fillcolour, int outlinecolour)
375 frontend *fe = (frontend *)handle;
376 GdkPoint *points = snewn(npoints, GdkPoint);
379 for (i = 0; i < npoints; i++) {
380 points[i].x = coords[i*2];
381 points[i].y = coords[i*2+1];
384 if (fillcolour >= 0) {
385 gdk_gc_set_foreground(fe->gc, &fe->colours[fillcolour]);
386 gdk_draw_polygon(fe->pixmap, fe->gc, TRUE, points, npoints);
388 assert(outlinecolour >= 0);
389 gdk_gc_set_foreground(fe->gc, &fe->colours[outlinecolour]);
392 * In principle we ought to be able to use gdk_draw_polygon for
393 * the outline as well. In fact, it turns out to interact badly
394 * with a clipping region, for no terribly obvious reason, so I
395 * draw the outline as a sequence of lines instead.
397 for (i = 0; i < npoints; i++)
398 gdk_draw_line(fe->pixmap, fe->gc,
399 points[i].x, points[i].y,
400 points[(i+1)%npoints].x, points[(i+1)%npoints].y);
405 void gtk_draw_circle(void *handle, int cx, int cy, int radius,
406 int fillcolour, int outlinecolour)
408 frontend *fe = (frontend *)handle;
409 if (fillcolour >= 0) {
410 gdk_gc_set_foreground(fe->gc, &fe->colours[fillcolour]);
411 gdk_draw_arc(fe->pixmap, fe->gc, TRUE,
412 cx - radius, cy - radius,
413 2 * radius, 2 * radius, 0, 360 * 64);
416 assert(outlinecolour >= 0);
417 gdk_gc_set_foreground(fe->gc, &fe->colours[outlinecolour]);
418 gdk_draw_arc(fe->pixmap, fe->gc, FALSE,
419 cx - radius, cy - radius,
420 2 * radius, 2 * radius, 0, 360 * 64);
428 blitter *gtk_blitter_new(void *handle, int w, int h)
431 * We can't create the pixmap right now, because fe->window
432 * might not yet exist. So we just cache w and h and create it
433 * during the firs call to blitter_save.
435 blitter *bl = snew(blitter);
442 void gtk_blitter_free(void *handle, blitter *bl)
445 gdk_pixmap_unref(bl->pixmap);
449 void gtk_blitter_save(void *handle, blitter *bl, int x, int y)
451 frontend *fe = (frontend *)handle;
453 bl->pixmap = gdk_pixmap_new(fe->area->window, bl->w, bl->h, -1);
456 gdk_draw_pixmap(bl->pixmap,
457 fe->area->style->fg_gc[GTK_WIDGET_STATE(fe->area)],
459 x, y, 0, 0, bl->w, bl->h);
462 void gtk_blitter_load(void *handle, blitter *bl, int x, int y)
464 frontend *fe = (frontend *)handle;
466 if (x == BLITTER_FROMSAVED && y == BLITTER_FROMSAVED) {
470 gdk_draw_pixmap(fe->pixmap,
471 fe->area->style->fg_gc[GTK_WIDGET_STATE(fe->area)],
473 0, 0, x, y, bl->w, bl->h);
476 void gtk_draw_update(void *handle, int x, int y, int w, int h)
478 frontend *fe = (frontend *)handle;
479 if (fe->bbox_l > x ) fe->bbox_l = x ;
480 if (fe->bbox_r < x+w) fe->bbox_r = x+w;
481 if (fe->bbox_u > y ) fe->bbox_u = y ;
482 if (fe->bbox_d < y+h) fe->bbox_d = y+h;
485 void gtk_end_draw(void *handle)
487 frontend *fe = (frontend *)handle;
488 gdk_gc_unref(fe->gc);
491 if (fe->bbox_l < fe->bbox_r && fe->bbox_u < fe->bbox_d) {
492 gdk_draw_pixmap(fe->area->window,
493 fe->area->style->fg_gc[GTK_WIDGET_STATE(fe->area)],
495 fe->bbox_l, fe->bbox_u,
496 fe->ox + fe->bbox_l, fe->oy + fe->bbox_u,
497 fe->bbox_r - fe->bbox_l, fe->bbox_d - fe->bbox_u);
501 const struct drawing_api gtk_drawing = {
517 NULL, NULL, NULL, NULL, NULL, NULL, /* {begin,end}_{doc,page,puzzle} */
518 NULL, /* line_width */
521 static void destroy(GtkWidget *widget, gpointer data)
523 frontend *fe = (frontend *)data;
524 deactivate_timer(fe);
529 static gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data)
531 frontend *fe = (frontend *)data;
533 int shift = (event->state & GDK_SHIFT_MASK) ? MOD_SHFT : 0;
534 int ctrl = (event->state & GDK_CONTROL_MASK) ? MOD_CTRL : 0;
539 #if !GTK_CHECK_VERSION(2,0,0)
540 /* Gtk 1.2 passes a key event to this function even if it's also
541 * defined as an accelerator.
542 * Gtk 2 doesn't do this, and this function appears not to exist there. */
543 if (fe->accelgroup &&
544 gtk_accel_group_get_entry(fe->accelgroup,
545 event->keyval, event->state))
549 if (event->keyval == GDK_Up)
550 keyval = shift | ctrl | CURSOR_UP;
551 else if (event->keyval == GDK_KP_Up || event->keyval == GDK_KP_8)
552 keyval = MOD_NUM_KEYPAD | '8';
553 else if (event->keyval == GDK_Down)
554 keyval = shift | ctrl | CURSOR_DOWN;
555 else if (event->keyval == GDK_KP_Down || event->keyval == GDK_KP_2)
556 keyval = MOD_NUM_KEYPAD | '2';
557 else if (event->keyval == GDK_Left)
558 keyval = shift | ctrl | CURSOR_LEFT;
559 else if (event->keyval == GDK_KP_Left || event->keyval == GDK_KP_4)
560 keyval = MOD_NUM_KEYPAD | '4';
561 else if (event->keyval == GDK_Right)
562 keyval = shift | ctrl | CURSOR_RIGHT;
563 else if (event->keyval == GDK_KP_Right || event->keyval == GDK_KP_6)
564 keyval = MOD_NUM_KEYPAD | '6';
565 else if (event->keyval == GDK_KP_Home || event->keyval == GDK_KP_7)
566 keyval = MOD_NUM_KEYPAD | '7';
567 else if (event->keyval == GDK_KP_End || event->keyval == GDK_KP_1)
568 keyval = MOD_NUM_KEYPAD | '1';
569 else if (event->keyval == GDK_KP_Page_Up || event->keyval == GDK_KP_9)
570 keyval = MOD_NUM_KEYPAD | '9';
571 else if (event->keyval == GDK_KP_Page_Down || event->keyval == GDK_KP_3)
572 keyval = MOD_NUM_KEYPAD | '3';
573 else if (event->keyval == GDK_KP_Insert || event->keyval == GDK_KP_0)
574 keyval = MOD_NUM_KEYPAD | '0';
575 else if (event->keyval == GDK_KP_Begin || event->keyval == GDK_KP_5)
576 keyval = MOD_NUM_KEYPAD | '5';
577 else if (event->keyval == GDK_BackSpace ||
578 event->keyval == GDK_Delete ||
579 event->keyval == GDK_KP_Delete)
581 else if (event->string[0] && !event->string[1])
582 keyval = (unsigned char)event->string[0];
587 !midend_process_key(fe->me, 0, 0, keyval))
588 gtk_widget_destroy(fe->window);
593 static gint button_event(GtkWidget *widget, GdkEventButton *event,
596 frontend *fe = (frontend *)data;
602 if (event->type != GDK_BUTTON_PRESS && event->type != GDK_BUTTON_RELEASE)
605 if (event->button == 2 || (event->state & GDK_SHIFT_MASK))
606 button = MIDDLE_BUTTON;
607 else if (event->button == 3 || (event->state & GDK_MOD1_MASK))
608 button = RIGHT_BUTTON;
609 else if (event->button == 1)
610 button = LEFT_BUTTON;
612 return FALSE; /* don't even know what button! */
614 if (event->type == GDK_BUTTON_RELEASE)
615 button += LEFT_RELEASE - LEFT_BUTTON;
617 if (!midend_process_key(fe->me, event->x - fe->ox,
618 event->y - fe->oy, button))
619 gtk_widget_destroy(fe->window);
624 static gint motion_event(GtkWidget *widget, GdkEventMotion *event,
627 frontend *fe = (frontend *)data;
633 if (event->state & (GDK_BUTTON2_MASK | GDK_SHIFT_MASK))
634 button = MIDDLE_DRAG;
635 else if (event->state & GDK_BUTTON1_MASK)
637 else if (event->state & GDK_BUTTON3_MASK)
640 return FALSE; /* don't even know what button! */
642 if (!midend_process_key(fe->me, event->x - fe->ox,
643 event->y - fe->oy, button))
644 gtk_widget_destroy(fe->window);
649 static gint expose_area(GtkWidget *widget, GdkEventExpose *event,
652 frontend *fe = (frontend *)data;
655 gdk_draw_pixmap(widget->window,
656 widget->style->fg_gc[GTK_WIDGET_STATE(widget)],
658 event->area.x - fe->ox, event->area.y - fe->oy,
659 event->area.x, event->area.y,
660 event->area.width, event->area.height);
665 static gint map_window(GtkWidget *widget, GdkEvent *event,
668 frontend *fe = (frontend *)data;
671 * Apparently we need to do this because otherwise the status
672 * bar will fail to update immediately. Annoying, but there we
675 gtk_widget_queue_draw(fe->window);
680 static gint configure_area(GtkWidget *widget,
681 GdkEventConfigure *event, gpointer data)
683 frontend *fe = (frontend *)data;
688 gdk_pixmap_unref(fe->pixmap);
690 x = fe->w = event->width;
691 y = fe->h = event->height;
692 midend_size(fe->me, &x, &y, TRUE);
695 fe->ox = (fe->w - fe->pw) / 2;
696 fe->oy = (fe->h - fe->ph) / 2;
698 fe->pixmap = gdk_pixmap_new(widget->window, fe->pw, fe->ph, -1);
700 gc = gdk_gc_new(fe->area->window);
701 gdk_gc_set_foreground(gc, &fe->colours[0]);
702 gdk_draw_rectangle(fe->pixmap, gc, 1, 0, 0, fe->pw, fe->ph);
703 gdk_draw_rectangle(widget->window, gc, 1, 0, 0,
704 event->width, event->height);
707 midend_force_redraw(fe->me);
712 static gint timer_func(gpointer data)
714 frontend *fe = (frontend *)data;
716 if (fe->timer_active) {
719 gettimeofday(&now, NULL);
720 elapsed = ((now.tv_usec - fe->last_time.tv_usec) * 0.000001F +
721 (now.tv_sec - fe->last_time.tv_sec));
722 midend_timer(fe->me, elapsed); /* may clear timer_active */
726 return fe->timer_active;
729 void deactivate_timer(frontend *fe)
732 return; /* can happen due to --generate */
733 if (fe->timer_active)
734 gtk_timeout_remove(fe->timer_id);
735 fe->timer_active = FALSE;
738 void activate_timer(frontend *fe)
741 return; /* can happen due to --generate */
742 if (!fe->timer_active) {
743 fe->timer_id = gtk_timeout_add(20, timer_func, fe);
744 gettimeofday(&fe->last_time, NULL);
746 fe->timer_active = TRUE;
749 static void window_destroy(GtkWidget *widget, gpointer data)
754 static void msgbox_button_clicked(GtkButton *button, gpointer data)
756 GtkWidget *window = GTK_WIDGET(data);
759 ip = (int *)gtk_object_get_data(GTK_OBJECT(window), "user-data");
760 v = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(button), "user-data"));
763 gtk_widget_destroy(GTK_WIDGET(data));
766 static int win_key_press(GtkWidget *widget, GdkEventKey *event, gpointer data)
768 GtkObject *cancelbutton = GTK_OBJECT(data);
771 * `Escape' effectively clicks the cancel button
773 if (event->keyval == GDK_Escape) {
774 gtk_signal_emit_by_name(GTK_OBJECT(cancelbutton), "clicked");
781 enum { MB_OK, MB_YESNO };
783 int message_box(GtkWidget *parent, char *title, char *msg, int centre,
786 GtkWidget *window, *hbox, *text, *button;
790 window = gtk_dialog_new();
791 text = gtk_label_new(msg);
792 gtk_misc_set_alignment(GTK_MISC(text), 0.0, 0.0);
793 hbox = gtk_hbox_new(FALSE, 0);
794 gtk_box_pack_start(GTK_BOX(hbox), text, FALSE, FALSE, 20);
795 gtk_box_pack_start(GTK_BOX(GTK_DIALOG(window)->vbox),
796 hbox, FALSE, FALSE, 20);
797 gtk_widget_show(text);
798 gtk_widget_show(hbox);
799 gtk_window_set_title(GTK_WINDOW(window), title);
800 gtk_label_set_line_wrap(GTK_LABEL(text), TRUE);
806 assert(type == MB_YESNO);
807 titles = "Yes\0No\0";
814 button = gtk_button_new_with_label(titles);
815 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(window)->action_area),
816 button, FALSE, FALSE, 0);
817 gtk_widget_show(button);
819 GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
820 gtk_window_set_default(GTK_WINDOW(window), button);
823 gtk_signal_connect(GTK_OBJECT(window), "key_press_event",
824 GTK_SIGNAL_FUNC(win_key_press), button);
826 gtk_signal_connect(GTK_OBJECT(button), "clicked",
827 GTK_SIGNAL_FUNC(msgbox_button_clicked), window);
828 gtk_object_set_data(GTK_OBJECT(button), "user-data",
830 titles += strlen(titles)+1;
833 gtk_object_set_data(GTK_OBJECT(window), "user-data",
834 GINT_TO_POINTER(&i));
835 gtk_signal_connect(GTK_OBJECT(window), "destroy",
836 GTK_SIGNAL_FUNC(window_destroy), NULL);
837 gtk_window_set_modal(GTK_WINDOW(window), TRUE);
838 gtk_window_set_transient_for(GTK_WINDOW(window), GTK_WINDOW(parent));
839 /* set_transient_window_pos(parent, window); */
840 gtk_widget_show(window);
843 return (type == MB_YESNO ? i == 0 : TRUE);
846 void error_box(GtkWidget *parent, char *msg)
848 message_box(parent, "Error", msg, FALSE, MB_OK);
851 static void config_ok_button_clicked(GtkButton *button, gpointer data)
853 frontend *fe = (frontend *)data;
856 err = midend_set_config(fe->me, fe->cfg_which, fe->cfg);
859 error_box(fe->cfgbox, err);
862 gtk_widget_destroy(fe->cfgbox);
867 static void config_cancel_button_clicked(GtkButton *button, gpointer data)
869 frontend *fe = (frontend *)data;
871 gtk_widget_destroy(fe->cfgbox);
874 static int editbox_key(GtkWidget *widget, GdkEventKey *event, gpointer data)
877 * GtkEntry has a nasty habit of eating the Return key, which
878 * is unhelpful since it doesn't actually _do_ anything with it
879 * (it calls gtk_widget_activate, but our edit boxes never need
880 * activating). So I catch Return before GtkEntry sees it, and
881 * pass it straight on to the parent widget. Effect: hitting
882 * Return in an edit box will now activate the default button
883 * in the dialog just like it will everywhere else.
885 if (event->keyval == GDK_Return && widget->parent != NULL) {
887 gtk_signal_emit_stop_by_name(GTK_OBJECT(widget), "key_press_event");
888 gtk_signal_emit_by_name(GTK_OBJECT(widget->parent), "key_press_event",
895 static void editbox_changed(GtkEditable *ed, gpointer data)
897 config_item *i = (config_item *)data;
900 i->sval = dupstr(gtk_entry_get_text(GTK_ENTRY(ed)));
903 static void button_toggled(GtkToggleButton *tb, gpointer data)
905 config_item *i = (config_item *)data;
907 i->ival = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(tb));
910 static void droplist_sel(GtkMenuItem *item, gpointer data)
912 config_item *i = (config_item *)data;
914 i->ival = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(item),
918 static int get_config(frontend *fe, int which)
920 GtkWidget *w, *table, *cancel;
925 fe->cfg = midend_get_config(fe->me, which, &title);
926 fe->cfg_which = which;
929 fe->cfgbox = gtk_dialog_new();
930 gtk_window_set_title(GTK_WINDOW(fe->cfgbox), title);
933 w = gtk_button_new_with_label("OK");
934 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(fe->cfgbox)->action_area),
937 GTK_WIDGET_SET_FLAGS(w, GTK_CAN_DEFAULT);
938 gtk_window_set_default(GTK_WINDOW(fe->cfgbox), w);
939 gtk_signal_connect(GTK_OBJECT(w), "clicked",
940 GTK_SIGNAL_FUNC(config_ok_button_clicked), fe);
942 w = gtk_button_new_with_label("Cancel");
943 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(fe->cfgbox)->action_area),
946 gtk_signal_connect(GTK_OBJECT(w), "clicked",
947 GTK_SIGNAL_FUNC(config_cancel_button_clicked), fe);
950 table = gtk_table_new(1, 2, FALSE);
952 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(fe->cfgbox)->vbox),
953 table, FALSE, FALSE, 0);
954 gtk_widget_show(table);
956 for (i = fe->cfg; i->type != C_END; i++) {
957 gtk_table_resize(GTK_TABLE(table), y+1, 2);
962 * Edit box with a label beside it.
965 w = gtk_label_new(i->name);
966 gtk_misc_set_alignment(GTK_MISC(w), 0.0, 0.5);
967 gtk_table_attach(GTK_TABLE(table), w, 0, 1, y, y+1,
968 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
969 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
974 gtk_table_attach(GTK_TABLE(table), w, 1, 2, y, y+1,
975 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
976 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
978 gtk_entry_set_text(GTK_ENTRY(w), i->sval);
979 gtk_signal_connect(GTK_OBJECT(w), "changed",
980 GTK_SIGNAL_FUNC(editbox_changed), i);
981 gtk_signal_connect(GTK_OBJECT(w), "key_press_event",
982 GTK_SIGNAL_FUNC(editbox_key), NULL);
991 w = gtk_check_button_new_with_label(i->name);
992 gtk_signal_connect(GTK_OBJECT(w), "toggled",
993 GTK_SIGNAL_FUNC(button_toggled), i);
994 gtk_table_attach(GTK_TABLE(table), w, 0, 2, y, y+1,
995 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
996 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
998 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(w), i->ival);
1004 * Drop-down list (GtkOptionMenu).
1007 w = gtk_label_new(i->name);
1008 gtk_misc_set_alignment(GTK_MISC(w), 0.0, 0.5);
1009 gtk_table_attach(GTK_TABLE(table), w, 0, 1, y, y+1,
1010 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1011 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1015 w = gtk_option_menu_new();
1016 gtk_table_attach(GTK_TABLE(table), w, 1, 2, y, y+1,
1017 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1018 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1025 GtkWidget *menuitem;
1026 GtkWidget *menu = gtk_menu_new();
1028 gtk_option_menu_set_menu(GTK_OPTION_MENU(w), menu);
1036 while (*q && *q != c)
1039 name = snewn(q-p+1, char);
1040 strncpy(name, p, q-p);
1043 if (*q) q++; /* eat delimiter */
1045 menuitem = gtk_menu_item_new_with_label(name);
1046 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1047 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1048 GINT_TO_POINTER(val));
1049 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1050 GTK_SIGNAL_FUNC(droplist_sel), i);
1051 gtk_widget_show(menuitem);
1058 gtk_option_menu_set_history(GTK_OPTION_MENU(w), i->ival);
1067 gtk_signal_connect(GTK_OBJECT(fe->cfgbox), "destroy",
1068 GTK_SIGNAL_FUNC(window_destroy), NULL);
1069 gtk_signal_connect(GTK_OBJECT(fe->cfgbox), "key_press_event",
1070 GTK_SIGNAL_FUNC(win_key_press), cancel);
1071 gtk_window_set_modal(GTK_WINDOW(fe->cfgbox), TRUE);
1072 gtk_window_set_transient_for(GTK_WINDOW(fe->cfgbox),
1073 GTK_WINDOW(fe->window));
1074 /* set_transient_window_pos(fe->window, fe->cfgbox); */
1075 gtk_widget_show(fe->cfgbox);
1083 static void menu_key_event(GtkMenuItem *menuitem, gpointer data)
1085 frontend *fe = (frontend *)data;
1086 int key = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(menuitem),
1088 if (!midend_process_key(fe->me, 0, 0, key))
1089 gtk_widget_destroy(fe->window);
1092 static void get_size(frontend *fe, int *px, int *py)
1097 * Currently I don't want to make the GTK port scale large
1098 * puzzles to fit on the screen. This is because X does permit
1099 * extremely large windows and many window managers provide a
1100 * means of navigating round them, and the users I consulted
1101 * before deciding said that they'd rather have enormous puzzle
1102 * windows spanning multiple screen pages than have them
1103 * shrunk. I could change my mind later or introduce
1104 * configurability; this would be the place to do so, by
1105 * replacing the initial values of x and y with the screen
1110 midend_size(fe->me, &x, &y, FALSE);
1115 #if !GTK_CHECK_VERSION(2,0,0)
1116 #define gtk_window_resize(win, x, y) \
1117 gdk_window_resize(GTK_WIDGET(win)->window, x, y)
1120 static void update_menuitem_bullet(GtkWidget *label, int visible)
1123 gtk_label_set_text(GTK_LABEL(label), "\xE2\x80\xA2");
1125 gtk_label_set_text(GTK_LABEL(label), "");
1130 * Called when any other code in this file has changed the
1131 * selected game parameters.
1133 static void changed_preset(frontend *fe)
1135 int n = midend_which_preset(fe->me);
1139 * Update the tick mark in the Type menu.
1141 if (fe->preset_bullets) {
1142 for (i = 0; i < fe->npresets; i++)
1143 update_menuitem_bullet(fe->preset_bullets[i], n == i);
1145 if (fe->preset_custom_bullet) {
1146 update_menuitem_bullet(fe->preset_custom_bullet, n < 0);
1150 * Update the greying on the Copy menu option.
1152 if (fe->copy_menu_item) {
1153 int enabled = midend_can_format_as_text_now(fe->me);
1154 gtk_widget_set_sensitive(fe->copy_menu_item, enabled);
1158 static void resize_fe(frontend *fe)
1162 get_size(fe, &x, &y);
1165 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
1168 gtk_widget_size_request(GTK_WIDGET(fe->window), &req);
1169 gtk_window_resize(GTK_WINDOW(fe->window), req.width, req.height);
1172 * Now that we've established the preferred size of the window,
1173 * reduce the drawing area's size request so the user can shrink
1176 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), 1, 1);
1179 static void menu_preset_event(GtkMenuItem *menuitem, gpointer data)
1181 frontend *fe = (frontend *)data;
1182 game_params *params =
1183 (game_params *)gtk_object_get_data(GTK_OBJECT(menuitem), "user-data");
1185 midend_set_params(fe->me, params);
1186 midend_new_game(fe->me);
1191 GdkAtom compound_text_atom, utf8_string_atom;
1192 int paste_initialised = FALSE;
1196 unsigned char empty[] = { 0 };
1198 if (paste_initialised)
1201 if (!compound_text_atom)
1202 compound_text_atom = gdk_atom_intern("COMPOUND_TEXT", FALSE);
1203 if (!utf8_string_atom)
1204 utf8_string_atom = gdk_atom_intern("UTF8_STRING", FALSE);
1207 * Ensure that all the cut buffers exist - according to the
1208 * ICCCM, we must do this before we start using cut buffers.
1210 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1211 XA_CUT_BUFFER0, XA_STRING, 8, PropModeAppend, empty, 0);
1212 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1213 XA_CUT_BUFFER1, XA_STRING, 8, PropModeAppend, empty, 0);
1214 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1215 XA_CUT_BUFFER2, XA_STRING, 8, PropModeAppend, empty, 0);
1216 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1217 XA_CUT_BUFFER3, XA_STRING, 8, PropModeAppend, empty, 0);
1218 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1219 XA_CUT_BUFFER4, XA_STRING, 8, PropModeAppend, empty, 0);
1220 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1221 XA_CUT_BUFFER5, XA_STRING, 8, PropModeAppend, empty, 0);
1222 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1223 XA_CUT_BUFFER6, XA_STRING, 8, PropModeAppend, empty, 0);
1224 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1225 XA_CUT_BUFFER7, XA_STRING, 8, PropModeAppend, empty, 0);
1228 /* Store data in a cut-buffer. */
1229 void store_cutbuffer(char *ptr, int len)
1231 /* ICCCM says we must rotate the buffers before storing to buffer 0. */
1232 XRotateBuffers(GDK_DISPLAY(), 1);
1233 XStoreBytes(GDK_DISPLAY(), ptr, len);
1236 void write_clip(frontend *fe, char *data)
1241 sfree(fe->paste_data);
1244 * For this simple application we can safely assume that the
1245 * data passed to this function is pure ASCII, which means we
1246 * can return precisely the same stuff for types STRING,
1247 * COMPOUND_TEXT or UTF8_STRING.
1250 fe->paste_data = data;
1251 fe->paste_data_len = strlen(data);
1253 store_cutbuffer(fe->paste_data, fe->paste_data_len);
1255 if (gtk_selection_owner_set(fe->area, GDK_SELECTION_PRIMARY,
1257 gtk_selection_clear_targets(fe->area, GDK_SELECTION_PRIMARY);
1258 gtk_selection_add_target(fe->area, GDK_SELECTION_PRIMARY,
1259 GDK_SELECTION_TYPE_STRING, 1);
1260 gtk_selection_add_target(fe->area, GDK_SELECTION_PRIMARY,
1261 compound_text_atom, 1);
1262 gtk_selection_add_target(fe->area, GDK_SELECTION_PRIMARY,
1263 utf8_string_atom, 1);
1267 void selection_get(GtkWidget *widget, GtkSelectionData *seldata,
1268 guint info, guint time_stamp, gpointer data)
1270 frontend *fe = (frontend *)data;
1271 gtk_selection_data_set(seldata, seldata->target, 8,
1272 fe->paste_data, fe->paste_data_len);
1275 gint selection_clear(GtkWidget *widget, GdkEventSelection *seldata,
1278 frontend *fe = (frontend *)data;
1281 sfree(fe->paste_data);
1282 fe->paste_data = NULL;
1283 fe->paste_data_len = 0;
1287 static void menu_copy_event(GtkMenuItem *menuitem, gpointer data)
1289 frontend *fe = (frontend *)data;
1292 text = midend_text_format(fe->me);
1295 write_clip(fe, text);
1303 static void filesel_ok(GtkButton *button, gpointer data)
1305 frontend *fe = (frontend *)data;
1307 gpointer filesel = gtk_object_get_data(GTK_OBJECT(button), "user-data");
1310 gtk_file_selection_get_filename(GTK_FILE_SELECTION(filesel));
1312 fe->filesel_name = dupstr(name);
1315 static char *file_selector(frontend *fe, char *title, int save)
1317 GtkWidget *filesel =
1318 gtk_file_selection_new(title);
1320 fe->filesel_name = NULL;
1322 gtk_window_set_modal(GTK_WINDOW(filesel), TRUE);
1324 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "user-data",
1327 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "clicked",
1328 GTK_SIGNAL_FUNC(filesel_ok), fe);
1329 gtk_signal_connect_object
1330 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "clicked",
1331 GTK_SIGNAL_FUNC(gtk_widget_destroy), (gpointer)filesel);
1332 gtk_signal_connect_object
1333 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->cancel_button), "clicked",
1334 GTK_SIGNAL_FUNC(gtk_widget_destroy), (gpointer)filesel);
1335 gtk_signal_connect(GTK_OBJECT(filesel), "destroy",
1336 GTK_SIGNAL_FUNC(window_destroy), NULL);
1337 gtk_widget_show(filesel);
1338 gtk_window_set_transient_for(GTK_WINDOW(filesel), GTK_WINDOW(fe->window));
1341 return fe->filesel_name;
1346 static char *file_selector(frontend *fe, char *title, int save)
1348 char *filesel_name = NULL;
1350 GtkWidget *filesel =
1351 gtk_file_chooser_dialog_new(title,
1352 GTK_WINDOW(fe->window),
1353 save ? GTK_FILE_CHOOSER_ACTION_SAVE :
1354 GTK_FILE_CHOOSER_ACTION_OPEN,
1355 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
1356 save ? GTK_STOCK_SAVE : GTK_STOCK_OPEN,
1357 GTK_RESPONSE_ACCEPT,
1360 if (gtk_dialog_run(GTK_DIALOG(filesel)) == GTK_RESPONSE_ACCEPT) {
1361 const char *name = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(filesel));
1362 filesel_name = dupstr(name);
1365 gtk_widget_destroy(filesel);
1367 return filesel_name;
1372 struct savefile_write_ctx {
1377 static void savefile_write(void *wctx, void *buf, int len)
1379 struct savefile_write_ctx *ctx = (struct savefile_write_ctx *)wctx;
1380 if (fwrite(buf, 1, len, ctx->fp) < len)
1384 static int savefile_read(void *wctx, void *buf, int len)
1386 FILE *fp = (FILE *)wctx;
1389 ret = fread(buf, 1, len, fp);
1390 return (ret == len);
1393 static void menu_save_event(GtkMenuItem *menuitem, gpointer data)
1395 frontend *fe = (frontend *)data;
1398 name = file_selector(fe, "Enter name of game file to save", TRUE);
1403 if ((fp = fopen(name, "r")) != NULL) {
1404 char buf[256 + FILENAME_MAX];
1408 sprintf(buf, "Are you sure you want to overwrite the"
1410 FILENAME_MAX, name);
1411 if (!message_box(fe->window, "Question", buf, TRUE, MB_YESNO))
1415 fp = fopen(name, "w");
1419 error_box(fe->window, "Unable to open save file");
1424 struct savefile_write_ctx ctx;
1427 midend_serialise(fe->me, savefile_write, &ctx);
1431 sprintf(boxmsg, "Error writing save file: %.400s",
1433 error_box(fe->window, boxmsg);
1441 static void menu_load_event(GtkMenuItem *menuitem, gpointer data)
1443 frontend *fe = (frontend *)data;
1446 name = file_selector(fe, "Enter name of saved game file to load", FALSE);
1449 FILE *fp = fopen(name, "r");
1453 error_box(fe->window, "Unable to open saved game file");
1457 err = midend_deserialise(fe->me, savefile_read, fp);
1462 error_box(fe->window, err);
1471 static void menu_solve_event(GtkMenuItem *menuitem, gpointer data)
1473 frontend *fe = (frontend *)data;
1476 msg = midend_solve(fe->me);
1479 error_box(fe->window, msg);
1482 static void menu_restart_event(GtkMenuItem *menuitem, gpointer data)
1484 frontend *fe = (frontend *)data;
1486 midend_restart_game(fe->me);
1489 static void menu_config_event(GtkMenuItem *menuitem, gpointer data)
1491 frontend *fe = (frontend *)data;
1492 int which = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(menuitem),
1495 if (!get_config(fe, which))
1498 midend_new_game(fe->me);
1502 static void menu_about_event(GtkMenuItem *menuitem, gpointer data)
1504 frontend *fe = (frontend *)data;
1508 sprintf(titlebuf, "About %.200s", thegame.name);
1511 "from Simon Tatham's Portable Puzzle Collection\n\n"
1512 "%.500s", thegame.name, ver);
1514 message_box(fe->window, titlebuf, textbuf, TRUE, MB_OK);
1517 static GtkWidget *add_menu_item_with_key(frontend *fe, GtkContainer *cont,
1518 char *text, int key)
1520 GtkWidget *menuitem = gtk_menu_item_new_with_label(text);
1522 gtk_container_add(cont, menuitem);
1523 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1524 GINT_TO_POINTER(key));
1525 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1526 GTK_SIGNAL_FUNC(menu_key_event), fe);
1527 switch (key & ~0x1F) {
1530 keyqual = GDK_CONTROL_MASK;
1534 keyqual = GDK_SHIFT_MASK;
1540 gtk_widget_add_accelerator(menuitem,
1541 "activate", fe->accelgroup,
1544 gtk_widget_show(menuitem);
1548 static void add_menu_separator(GtkContainer *cont)
1550 GtkWidget *menuitem = gtk_menu_item_new();
1551 gtk_container_add(cont, menuitem);
1552 gtk_widget_show(menuitem);
1555 enum { ARG_EITHER, ARG_SAVE, ARG_ID }; /* for argtype */
1557 static GtkWidget *make_preset_menuitem(GtkWidget **bulletlabel,
1560 GtkWidget *hbox, *lab1, *lab2, *menuitem;
1563 hbox = gtk_hbox_new(FALSE, 0);
1564 gtk_widget_show(hbox);
1565 lab1 = gtk_label_new("\xE2\x80\xA2 ");
1566 gtk_widget_show(lab1);
1567 gtk_box_pack_start(GTK_BOX(hbox), lab1, FALSE, FALSE, 0);
1568 gtk_misc_set_alignment(GTK_MISC(lab1), 0.0, 0.0);
1569 lab2 = gtk_label_new(name);
1570 gtk_widget_show(lab2);
1571 gtk_box_pack_start(GTK_BOX(hbox), lab2, TRUE, TRUE, 0);
1572 gtk_misc_set_alignment(GTK_MISC(lab2), 0.0, 0.0);
1574 gtk_widget_size_request(lab1, &req);
1575 gtk_widget_set_usize(lab1, req.width, -1);
1576 gtk_label_set_text(GTK_LABEL(lab1), "");
1578 menuitem = gtk_menu_item_new();
1579 gtk_container_add(GTK_CONTAINER(menuitem), hbox);
1581 *bulletlabel = lab1;
1585 static frontend *new_window(char *arg, int argtype, char **error)
1589 GtkWidget *menubar, *menu, *menuitem;
1594 extern char *const *const xpm_icons[];
1595 extern const int n_xpm_icons;
1597 fe = snew(frontend);
1599 fe->timer_active = FALSE;
1602 fe->me = midend_new(fe, &thegame, >k_drawing, fe);
1612 err = midend_game_id(fe->me, arg);
1614 midend_new_game(fe->me);
1616 sprintf(errbuf, "Invalid game ID: %.800s", err);
1619 fp = fopen(arg, "r");
1621 sprintf(errbuf, "Error opening file: %.800s", strerror(errno));
1623 err = midend_deserialise(fe->me, savefile_read, fp);
1625 sprintf(errbuf, "Invalid save file: %.800s", err);
1629 default /*case ARG_EITHER*/:
1631 * First try treating the argument as a game ID.
1633 err = midend_game_id(fe->me, arg);
1636 * It's a valid game ID.
1638 midend_new_game(fe->me);
1640 FILE *fp = fopen(arg, "r");
1642 sprintf(errbuf, "Supplied argument is neither a game ID (%.400s)"
1643 " nor a save file (%.400s)", err, strerror(errno));
1645 err = midend_deserialise(fe->me, savefile_read, fp);
1647 sprintf(errbuf, "%.800s", err);
1654 *error = dupstr(errbuf);
1655 midend_free(fe->me);
1661 midend_new_game(fe->me);
1664 fe->window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1665 gtk_window_set_title(GTK_WINDOW(fe->window), thegame.name);
1667 vbox = GTK_BOX(gtk_vbox_new(FALSE, 0));
1668 gtk_container_add(GTK_CONTAINER(fe->window), GTK_WIDGET(vbox));
1669 gtk_widget_show(GTK_WIDGET(vbox));
1671 fe->accelgroup = gtk_accel_group_new();
1672 gtk_window_add_accel_group(GTK_WINDOW(fe->window), fe->accelgroup);
1674 menubar = gtk_menu_bar_new();
1675 gtk_box_pack_start(vbox, menubar, FALSE, FALSE, 0);
1676 gtk_widget_show(menubar);
1678 menuitem = gtk_menu_item_new_with_label("Game");
1679 gtk_container_add(GTK_CONTAINER(menubar), menuitem);
1680 gtk_widget_show(menuitem);
1682 menu = gtk_menu_new();
1683 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
1685 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "New", 'n');
1687 menuitem = gtk_menu_item_new_with_label("Restart");
1688 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1689 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1690 GTK_SIGNAL_FUNC(menu_restart_event), fe);
1691 gtk_widget_show(menuitem);
1693 menuitem = gtk_menu_item_new_with_label("Specific...");
1694 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1695 GINT_TO_POINTER(CFG_DESC));
1696 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1697 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1698 GTK_SIGNAL_FUNC(menu_config_event), fe);
1699 gtk_widget_show(menuitem);
1701 menuitem = gtk_menu_item_new_with_label("Random Seed...");
1702 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1703 GINT_TO_POINTER(CFG_SEED));
1704 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1705 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1706 GTK_SIGNAL_FUNC(menu_config_event), fe);
1707 gtk_widget_show(menuitem);
1709 if ((n = midend_num_presets(fe->me)) > 0 || thegame.can_configure) {
1713 menuitem = gtk_menu_item_new_with_label("Type");
1714 gtk_container_add(GTK_CONTAINER(menubar), menuitem);
1715 gtk_widget_show(menuitem);
1717 submenu = gtk_menu_new();
1718 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), submenu);
1721 fe->preset_bullets = snewn(n, GtkWidget *);
1723 for (i = 0; i < n; i++) {
1725 game_params *params;
1727 midend_fetch_preset(fe->me, i, &name, ¶ms);
1729 menuitem = make_preset_menuitem(&fe->preset_bullets[i], name);
1731 gtk_container_add(GTK_CONTAINER(submenu), menuitem);
1732 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data", params);
1733 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1734 GTK_SIGNAL_FUNC(menu_preset_event), fe);
1735 gtk_widget_show(menuitem);
1738 if (thegame.can_configure) {
1739 menuitem = make_preset_menuitem(&fe->preset_custom_bullet,
1742 gtk_container_add(GTK_CONTAINER(submenu), menuitem);
1743 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1744 GPOINTER_TO_INT(CFG_SETTINGS));
1745 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1746 GTK_SIGNAL_FUNC(menu_config_event), fe);
1747 gtk_widget_show(menuitem);
1749 fe->preset_custom_bullet = NULL;
1753 fe->preset_bullets = NULL;
1754 fe->preset_custom_bullet = NULL;
1757 add_menu_separator(GTK_CONTAINER(menu));
1758 menuitem = gtk_menu_item_new_with_label("Load...");
1759 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1760 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1761 GTK_SIGNAL_FUNC(menu_load_event), fe);
1762 gtk_widget_show(menuitem);
1763 menuitem = gtk_menu_item_new_with_label("Save...");
1764 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1765 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1766 GTK_SIGNAL_FUNC(menu_save_event), fe);
1767 gtk_widget_show(menuitem);
1768 add_menu_separator(GTK_CONTAINER(menu));
1769 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Undo", 'u');
1770 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Redo", 'r');
1771 if (thegame.can_format_as_text_ever) {
1772 add_menu_separator(GTK_CONTAINER(menu));
1773 menuitem = gtk_menu_item_new_with_label("Copy");
1774 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1775 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1776 GTK_SIGNAL_FUNC(menu_copy_event), fe);
1777 gtk_widget_show(menuitem);
1778 fe->copy_menu_item = menuitem;
1780 fe->copy_menu_item = NULL;
1782 if (thegame.can_solve) {
1783 add_menu_separator(GTK_CONTAINER(menu));
1784 menuitem = gtk_menu_item_new_with_label("Solve");
1785 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1786 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1787 GTK_SIGNAL_FUNC(menu_solve_event), fe);
1788 gtk_widget_show(menuitem);
1790 add_menu_separator(GTK_CONTAINER(menu));
1791 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Exit", 'q');
1793 menuitem = gtk_menu_item_new_with_label("Help");
1794 gtk_container_add(GTK_CONTAINER(menubar), menuitem);
1795 gtk_widget_show(menuitem);
1797 menu = gtk_menu_new();
1798 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
1800 menuitem = gtk_menu_item_new_with_label("About");
1801 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1802 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1803 GTK_SIGNAL_FUNC(menu_about_event), fe);
1804 gtk_widget_show(menuitem);
1813 fe->colmap = gdk_colormap_get_system();
1814 colours = midend_colours(fe->me, &ncolours);
1815 fe->ncolours = ncolours;
1816 fe->colours = snewn(ncolours, GdkColor);
1817 for (i = 0; i < ncolours; i++) {
1818 fe->colours[i].red = colours[i*3] * 0xFFFF;
1819 fe->colours[i].green = colours[i*3+1] * 0xFFFF;
1820 fe->colours[i].blue = colours[i*3+2] * 0xFFFF;
1822 success = snewn(ncolours, gboolean);
1823 gdk_colormap_alloc_colors(fe->colmap, fe->colours, ncolours,
1824 FALSE, FALSE, success);
1825 for (i = 0; i < ncolours; i++) {
1827 g_error("couldn't allocate colour %d (#%02x%02x%02x)\n",
1828 i, fe->colours[i].red >> 8,
1829 fe->colours[i].green >> 8,
1830 fe->colours[i].blue >> 8);
1835 if (midend_wants_statusbar(fe->me)) {
1836 GtkWidget *viewport;
1839 viewport = gtk_viewport_new(NULL, NULL);
1840 gtk_viewport_set_shadow_type(GTK_VIEWPORT(viewport), GTK_SHADOW_NONE);
1841 fe->statusbar = gtk_statusbar_new();
1842 gtk_container_add(GTK_CONTAINER(viewport), fe->statusbar);
1843 gtk_widget_show(viewport);
1844 gtk_box_pack_end(vbox, viewport, FALSE, FALSE, 0);
1845 gtk_widget_show(fe->statusbar);
1846 fe->statusctx = gtk_statusbar_get_context_id
1847 (GTK_STATUSBAR(fe->statusbar), "game");
1848 gtk_statusbar_push(GTK_STATUSBAR(fe->statusbar), fe->statusctx,
1850 gtk_widget_size_request(fe->statusbar, &req);
1852 /* For GTK 2.0, should we be using gtk_widget_set_size_request? */
1854 gtk_widget_set_usize(viewport, -1, req.height);
1856 fe->statusbar = NULL;
1858 fe->area = gtk_drawing_area_new();
1859 get_size(fe, &x, &y);
1860 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
1864 gtk_box_pack_end(vbox, fe->area, TRUE, TRUE, 0);
1868 fe->nfonts = fe->fontsize = 0;
1870 fe->paste_data = NULL;
1871 fe->paste_data_len = 0;
1873 gtk_signal_connect(GTK_OBJECT(fe->window), "destroy",
1874 GTK_SIGNAL_FUNC(destroy), fe);
1875 gtk_signal_connect(GTK_OBJECT(fe->window), "key_press_event",
1876 GTK_SIGNAL_FUNC(key_event), fe);
1877 gtk_signal_connect(GTK_OBJECT(fe->area), "button_press_event",
1878 GTK_SIGNAL_FUNC(button_event), fe);
1879 gtk_signal_connect(GTK_OBJECT(fe->area), "button_release_event",
1880 GTK_SIGNAL_FUNC(button_event), fe);
1881 gtk_signal_connect(GTK_OBJECT(fe->area), "motion_notify_event",
1882 GTK_SIGNAL_FUNC(motion_event), fe);
1883 gtk_signal_connect(GTK_OBJECT(fe->area), "selection_get",
1884 GTK_SIGNAL_FUNC(selection_get), fe);
1885 gtk_signal_connect(GTK_OBJECT(fe->area), "selection_clear_event",
1886 GTK_SIGNAL_FUNC(selection_clear), fe);
1887 gtk_signal_connect(GTK_OBJECT(fe->area), "expose_event",
1888 GTK_SIGNAL_FUNC(expose_area), fe);
1889 gtk_signal_connect(GTK_OBJECT(fe->window), "map_event",
1890 GTK_SIGNAL_FUNC(map_window), fe);
1891 gtk_signal_connect(GTK_OBJECT(fe->area), "configure_event",
1892 GTK_SIGNAL_FUNC(configure_area), fe);
1894 gtk_widget_add_events(GTK_WIDGET(fe->area),
1895 GDK_BUTTON_PRESS_MASK |
1896 GDK_BUTTON_RELEASE_MASK |
1897 GDK_BUTTON_MOTION_MASK);
1900 gtk_widget_realize(fe->window);
1901 iconpm = gdk_pixmap_create_from_xpm_d(fe->window->window, NULL,
1902 NULL, (gchar **)xpm_icons[0]);
1903 gdk_window_set_icon(fe->window->window, NULL, iconpm, NULL);
1905 for (n = 0; n < n_xpm_icons; n++) {
1907 g_list_append(iconlist,
1908 gdk_pixbuf_new_from_xpm_data((const gchar **)
1911 gdk_window_set_icon_list(fe->window->window, iconlist);
1914 gtk_widget_show(fe->area);
1915 gtk_widget_show(fe->window);
1918 * Now that we've established the preferred size of the window,
1919 * reduce the drawing area's size request so the user can shrink
1922 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), 1, 1);
1924 gdk_window_set_background(fe->area->window, &fe->colours[0]);
1925 gdk_window_set_background(fe->window->window, &fe->colours[0]);
1930 char *fgetline(FILE *fp)
1932 char *ret = snewn(512, char);
1933 int size = 512, len = 0;
1934 while (fgets(ret + len, size - len, fp)) {
1935 len += strlen(ret + len);
1936 if (ret[len-1] == '\n')
1937 break; /* got a newline, we're done */
1939 ret = sresize(ret, size, char);
1941 if (len == 0) { /* first fgets returned NULL */
1949 int main(int argc, char **argv)
1951 char *pname = argv[0];
1953 int ngenerate = 0, print = FALSE, px = 1, py = 1;
1954 int soln = FALSE, colour = FALSE;
1956 float redo_proportion = 0.0F;
1957 char *savefile = NULL, *savesuffix = NULL;
1959 int argtype = ARG_EITHER;
1960 char *screenshot_file = NULL;
1961 int doing_opts = TRUE;
1967 * Command line parsing in this function is rather fiddly,
1968 * because GTK wants to have a go at argc/argv _first_ - and
1969 * yet we can't let it, because gtk_init() will bomb out if it
1970 * can't open an X display, whereas in fact we want to permit
1971 * our --generate and --print modes to run without an X
1975 * - we parse the command line ourselves, without modifying
1977 * - if we encounter an error which might plausibly be the
1978 * result of a GTK command line (i.e. not detailed errors in
1979 * particular options of ours) we store the error message
1980 * and terminate parsing.
1981 * - if we got enough out of the command line to know it
1982 * specifies a non-X mode of operation, we either display
1983 * the stored error and return failure, or if there is no
1984 * stored error we do the non-X operation and return
1986 * - otherwise, we go straight to gtk_init().
1992 if (doing_opts && !strcmp(p, "--version")) {
1993 printf("%s, from Simon Tatham's Portable Puzzle Collection\n%s\n",
1996 } else if (doing_opts && !strcmp(p, "--generate")) {
1998 ngenerate = atoi(*++av);
2000 fprintf(stderr, "%s: '--generate' expected a number\n",
2006 } else if (doing_opts && !strcmp(p, "--save")) {
2010 fprintf(stderr, "%s: '--save' expected a filename\n",
2014 } else if (doing_opts && (!strcmp(p, "--save-suffix") ||
2015 !strcmp(p, "--savesuffix"))) {
2019 fprintf(stderr, "%s: '--save-suffix' expected a filename\n",
2023 } else if (doing_opts && !strcmp(p, "--print")) {
2024 if (!thegame.can_print) {
2025 fprintf(stderr, "%s: this game does not support printing\n",
2032 if (sscanf(dim, "%dx%d", &px, &py) != 2) {
2033 fprintf(stderr, "%s: unable to parse argument '%s' to "
2034 "'--print'\n", pname, dim);
2040 } else if (doing_opts && !strcmp(p, "--scale")) {
2042 scale = atof(*++av);
2044 fprintf(stderr, "%s: no argument supplied to '--scale'\n",
2048 } else if (doing_opts && !strcmp(p, "--redo")) {
2050 * This is an internal option which I don't expect
2051 * users to have any particular use for. The effect of
2052 * --redo is that once the game has been loaded and
2053 * initialised, the next move in the redo chain is
2054 * replayed, and the game screen is redrawn part way
2055 * through the making of the move. This is only
2056 * meaningful if there _is_ a next move in the redo
2057 * chain, which means in turn that this option is only
2058 * useful if you're also passing a save file on the
2061 * This option is used by the script which generates
2062 * the puzzle icons and website screenshots, and I
2063 * don't imagine it's useful for anything else.
2064 * (Unless, I suppose, users don't like my screenshots
2065 * and want to generate their own in the same way for
2066 * some repackaged version of the puzzles.)
2069 redo_proportion = atof(*++av);
2071 fprintf(stderr, "%s: no argument supplied to '--redo'\n",
2075 } else if (doing_opts && !strcmp(p, "--screenshot")) {
2077 * Another internal option for the icon building
2078 * script. This causes a screenshot of the central
2079 * drawing area (i.e. not including the menu bar or
2080 * status bar) to be saved to a PNG file once the
2081 * window has been drawn, and then the application
2082 * quits immediately.
2085 screenshot_file = *++av;
2087 fprintf(stderr, "%s: no argument supplied to '--screenshot'\n",
2091 } else if (doing_opts && (!strcmp(p, "--with-solutions") ||
2092 !strcmp(p, "--with-solution") ||
2093 !strcmp(p, "--with-solns") ||
2094 !strcmp(p, "--with-soln") ||
2095 !strcmp(p, "--solutions") ||
2096 !strcmp(p, "--solution") ||
2097 !strcmp(p, "--solns") ||
2098 !strcmp(p, "--soln"))) {
2100 } else if (doing_opts && !strcmp(p, "--colour")) {
2101 if (!thegame.can_print_in_colour) {
2102 fprintf(stderr, "%s: this game does not support colour"
2103 " printing\n", pname);
2107 } else if (doing_opts && !strcmp(p, "--load")) {
2109 } else if (doing_opts && !strcmp(p, "--game")) {
2111 } else if (doing_opts && !strcmp(p, "--")) {
2113 } else if (!doing_opts || p[0] != '-') {
2115 fprintf(stderr, "%s: more than one argument supplied\n",
2121 sprintf(errbuf, "%.100s: unrecognised option '%.100s'\n",
2128 fputs(errbuf, stderr);
2133 * Special standalone mode for generating puzzle IDs on the
2134 * command line. Useful for generating puzzles to be printed
2135 * out and solved offline (for puzzles where that even makes
2136 * sense - Solo, for example, is a lot more pencil-and-paper
2137 * friendly than Twiddle!)
2141 * <puzzle-name> --generate [<n> [<params>]]
2143 * <n>, if present, is the number of puzzle IDs to generate.
2144 * <params>, if present, is the same type of parameter string
2145 * you would pass to the puzzle when running it in GUI mode,
2146 * including optional extras such as the expansion factor in
2147 * Rectangles and the difficulty level in Solo.
2149 * If you specify <params>, you must also specify <n> (although
2150 * you may specify it to be 1). Sorry; that was the
2151 * simplest-to-parse command-line syntax I came up with.
2153 if (ngenerate > 0 || print || savefile || savesuffix) {
2157 document *doc = NULL;
2161 me = midend_new(NULL, &thegame, NULL, NULL);
2164 if (savefile && !savesuffix)
2166 if (!savefile && savesuffix)
2170 doc = document_new(px, py, scale);
2173 * In this loop, we either generate a game ID or read one
2174 * from stdin depending on whether we're in generate mode;
2175 * then we either write it to stdout or print it, depending
2176 * on whether we're in print mode. Thus, this loop handles
2177 * generate-to-stdout, print-from-stdin and generate-and-
2178 * immediately-print modes.
2180 * (It could also handle a copy-stdin-to-stdout mode,
2181 * although there's currently no combination of options
2182 * which will cause this loop to be activated in that mode.
2183 * It wouldn't be _entirely_ pointless, though, because
2184 * stdin could contain bare params strings or random-seed
2185 * IDs, and stdout would contain nothing but fully
2186 * generated descriptive game IDs.)
2188 while (ngenerate == 0 || i < n) {
2191 if (ngenerate == 0) {
2192 pstr = fgetline(stdin);
2195 pstr[strcspn(pstr, "\r\n")] = '\0';
2198 pstr = snewn(strlen(arg) + 40, char);
2201 if (i > 0 && strchr(arg, '#'))
2202 sprintf(pstr + strlen(pstr), "-%d", i);
2208 err = midend_game_id(me, pstr);
2210 fprintf(stderr, "%s: error parsing '%s': %s\n",
2217 midend_new_game(me);
2220 err = midend_print_puzzle(me, doc, soln);
2222 fprintf(stderr, "%s: error in printing: %s\n", pname, err);
2227 struct savefile_write_ctx ctx;
2228 char *realname = snewn(40 + strlen(savefile) +
2229 strlen(savesuffix), char);
2230 sprintf(realname, "%s%d%s", savefile, i, savesuffix);
2231 ctx.fp = fopen(realname, "w");
2233 fprintf(stderr, "%s: open: %s\n", realname,
2238 midend_serialise(me, savefile_write, &ctx);
2240 fprintf(stderr, "%s: write: %s\n", realname,
2241 strerror(ctx.error));
2244 if (fclose(ctx.fp)) {
2245 fprintf(stderr, "%s: close: %s\n", realname,
2250 if (!doc && !savefile) {
2251 id = midend_get_game_id(me);
2260 psdata *ps = ps_init(stdout, colour);
2261 document_print(doc, ps_drawing_api(ps));
2272 gtk_init(&argc, &argv);
2274 fe = new_window(arg, argtype, &error);
2277 fprintf(stderr, "%s: %s\n", pname, error);
2281 if (screenshot_file) {
2283 * Some puzzles will not redraw their entire area if
2284 * given a partially completed animation, which means
2285 * we must redraw now and _then_ redraw again after
2286 * freezing the move timer.
2288 midend_force_redraw(fe->me);
2291 if (redo_proportion) {
2293 midend_process_key(fe->me, 0, 0, 'r');
2294 /* And freeze the timer at the specified position. */
2295 midend_freeze_timer(fe->me, redo_proportion);
2298 if (screenshot_file) {
2300 GError *gerror = NULL;
2302 midend_redraw(fe->me);
2304 pb = gdk_pixbuf_get_from_drawable(NULL, fe->pixmap,
2305 NULL, 0, 0, 0, 0, -1, -1);
2306 gdk_pixbuf_save(pb, screenshot_file, "png", &gerror, NULL);