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 */
137 GSList *preset_radio;
138 int n_preset_menu_items;
140 GtkWidget *preset_custom;
141 GtkWidget *copy_menu_item;
144 void get_random_seed(void **randseed, int *randseedsize)
146 struct timeval *tvp = snew(struct timeval);
147 gettimeofday(tvp, NULL);
148 *randseed = (void *)tvp;
149 *randseedsize = sizeof(struct timeval);
152 void frontend_default_colour(frontend *fe, float *output)
154 GdkColor col = fe->window->style->bg[GTK_STATE_NORMAL];
155 output[0] = col.red / 65535.0;
156 output[1] = col.green / 65535.0;
157 output[2] = col.blue / 65535.0;
160 void gtk_status_bar(void *handle, char *text)
162 frontend *fe = (frontend *)handle;
164 assert(fe->statusbar);
166 gtk_statusbar_pop(GTK_STATUSBAR(fe->statusbar), fe->statusctx);
167 gtk_statusbar_push(GTK_STATUSBAR(fe->statusbar), fe->statusctx, text);
170 void gtk_start_draw(void *handle)
172 frontend *fe = (frontend *)handle;
173 fe->gc = gdk_gc_new(fe->area->window);
180 void gtk_clip(void *handle, int x, int y, int w, int h)
182 frontend *fe = (frontend *)handle;
190 gdk_gc_set_clip_rectangle(fe->gc, &rect);
193 void gtk_unclip(void *handle)
195 frontend *fe = (frontend *)handle;
203 gdk_gc_set_clip_rectangle(fe->gc, &rect);
206 void gtk_draw_text(void *handle, int x, int y, int fonttype, int fontsize,
207 int align, int colour, char *text)
209 frontend *fe = (frontend *)handle;
213 * Find or create the font.
215 for (i = 0; i < fe->nfonts; i++)
216 if (fe->fonts[i].type == fonttype && fe->fonts[i].size == fontsize)
219 if (i == fe->nfonts) {
220 if (fe->fontsize <= fe->nfonts) {
221 fe->fontsize = fe->nfonts + 10;
222 fe->fonts = sresize(fe->fonts, fe->fontsize, struct font);
227 fe->fonts[i].type = fonttype;
228 fe->fonts[i].size = fontsize;
232 * Use Pango to find the closest match to the requested
236 PangoFontDescription *fd;
238 fd = pango_font_description_new();
239 /* `Monospace' and `Sans' are meta-families guaranteed to exist */
240 pango_font_description_set_family(fd, fonttype == FONT_FIXED ?
241 "Monospace" : "Sans");
242 pango_font_description_set_weight(fd, PANGO_WEIGHT_BOLD);
244 * I found some online Pango documentation which
245 * described a function called
246 * pango_font_description_set_absolute_size(), which is
247 * _exactly_ what I want here. Unfortunately, none of
248 * my local Pango installations have it (presumably
249 * they're too old), so I'm going to have to hack round
250 * it by figuring out the point size myself. This
251 * limits me to X and probably also breaks in later
252 * Pango installations, so ideally I should add another
253 * CHECK_VERSION type ifdef and use set_absolute_size
254 * where available. All very annoying.
256 #ifdef HAVE_SENSIBLE_ABSOLUTE_SIZE_FUNCTION
257 pango_font_description_set_absolute_size(fd, PANGO_SCALE*fontsize);
260 Display *d = GDK_DISPLAY();
261 int s = DefaultScreen(d);
263 (PANGO_SCALE * 72.27 / 25.4) *
264 ((double) DisplayWidthMM(d, s) / DisplayWidth (d, s));
265 pango_font_description_set_size(fd, resolution * fontsize);
268 fe->fonts[i].desc = fd;
273 * In GTK 1.2, I don't know of any plausible way to
274 * pick a suitable font, so I'm just going to be
277 fe->fonts[i].font = gdk_font_load(fonttype == FONT_FIXED ?
278 "fixed" : "variable");
286 gdk_gc_set_foreground(fe->gc, &fe->colours[colour]);
297 layout = pango_layout_new(gtk_widget_get_pango_context(fe->area));
298 pango_layout_set_font_description(layout, fe->fonts[i].desc);
299 pango_layout_set_text(layout, text, strlen(text));
300 pango_layout_get_pixel_extents(layout, NULL, &rect);
302 if (align & ALIGN_VCENTRE)
303 rect.y -= rect.height / 2;
305 rect.y -= rect.height;
307 if (align & ALIGN_HCENTRE)
308 rect.x -= rect.width / 2;
309 else if (align & ALIGN_HRIGHT)
310 rect.x -= rect.width;
312 gdk_draw_layout(fe->pixmap, fe->gc, rect.x + x, rect.y + y, layout);
314 g_object_unref(layout);
319 * Find string dimensions and process alignment.
322 int lb, rb, wid, asc, desc;
325 * Measure vertical string extents with respect to the same
328 gdk_string_extents(fe->fonts[i].font,
329 "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
330 &lb, &rb, &wid, &asc, &desc);
331 if (align & ALIGN_VCENTRE)
332 y += asc - (asc+desc)/2;
337 * ... but horizontal extents with respect to the provided
338 * string. This means that multiple pieces of text centred
339 * on the same y-coordinate don't have different baselines.
341 gdk_string_extents(fe->fonts[i].font, text,
342 &lb, &rb, &wid, &asc, &desc);
344 if (align & ALIGN_HCENTRE)
346 else if (align & ALIGN_HRIGHT)
352 * Actually draw the text.
354 gdk_draw_string(fe->pixmap, fe->fonts[i].font, fe->gc, x, y, text);
359 void gtk_draw_rect(void *handle, int x, int y, int w, int h, int colour)
361 frontend *fe = (frontend *)handle;
362 gdk_gc_set_foreground(fe->gc, &fe->colours[colour]);
363 gdk_draw_rectangle(fe->pixmap, fe->gc, 1, x, y, w, h);
366 void gtk_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
368 frontend *fe = (frontend *)handle;
369 gdk_gc_set_foreground(fe->gc, &fe->colours[colour]);
370 gdk_draw_line(fe->pixmap, fe->gc, x1, y1, x2, y2);
373 void gtk_draw_poly(void *handle, int *coords, int npoints,
374 int fillcolour, int outlinecolour)
376 frontend *fe = (frontend *)handle;
377 GdkPoint *points = snewn(npoints, GdkPoint);
380 for (i = 0; i < npoints; i++) {
381 points[i].x = coords[i*2];
382 points[i].y = coords[i*2+1];
385 if (fillcolour >= 0) {
386 gdk_gc_set_foreground(fe->gc, &fe->colours[fillcolour]);
387 gdk_draw_polygon(fe->pixmap, fe->gc, TRUE, points, npoints);
389 assert(outlinecolour >= 0);
390 gdk_gc_set_foreground(fe->gc, &fe->colours[outlinecolour]);
393 * In principle we ought to be able to use gdk_draw_polygon for
394 * the outline as well. In fact, it turns out to interact badly
395 * with a clipping region, for no terribly obvious reason, so I
396 * draw the outline as a sequence of lines instead.
398 for (i = 0; i < npoints; i++)
399 gdk_draw_line(fe->pixmap, fe->gc,
400 points[i].x, points[i].y,
401 points[(i+1)%npoints].x, points[(i+1)%npoints].y);
406 void gtk_draw_circle(void *handle, int cx, int cy, int radius,
407 int fillcolour, int outlinecolour)
409 frontend *fe = (frontend *)handle;
410 if (fillcolour >= 0) {
411 gdk_gc_set_foreground(fe->gc, &fe->colours[fillcolour]);
412 gdk_draw_arc(fe->pixmap, fe->gc, TRUE,
413 cx - radius, cy - radius,
414 2 * radius, 2 * radius, 0, 360 * 64);
417 assert(outlinecolour >= 0);
418 gdk_gc_set_foreground(fe->gc, &fe->colours[outlinecolour]);
419 gdk_draw_arc(fe->pixmap, fe->gc, FALSE,
420 cx - radius, cy - radius,
421 2 * radius, 2 * radius, 0, 360 * 64);
429 blitter *gtk_blitter_new(void *handle, int w, int h)
432 * We can't create the pixmap right now, because fe->window
433 * might not yet exist. So we just cache w and h and create it
434 * during the firs call to blitter_save.
436 blitter *bl = snew(blitter);
443 void gtk_blitter_free(void *handle, blitter *bl)
446 gdk_pixmap_unref(bl->pixmap);
450 void gtk_blitter_save(void *handle, blitter *bl, int x, int y)
452 frontend *fe = (frontend *)handle;
454 bl->pixmap = gdk_pixmap_new(fe->area->window, bl->w, bl->h, -1);
457 gdk_draw_pixmap(bl->pixmap,
458 fe->area->style->fg_gc[GTK_WIDGET_STATE(fe->area)],
460 x, y, 0, 0, bl->w, bl->h);
463 void gtk_blitter_load(void *handle, blitter *bl, int x, int y)
465 frontend *fe = (frontend *)handle;
467 if (x == BLITTER_FROMSAVED && y == BLITTER_FROMSAVED) {
471 gdk_draw_pixmap(fe->pixmap,
472 fe->area->style->fg_gc[GTK_WIDGET_STATE(fe->area)],
474 0, 0, x, y, bl->w, bl->h);
477 void gtk_draw_update(void *handle, int x, int y, int w, int h)
479 frontend *fe = (frontend *)handle;
480 if (fe->bbox_l > x ) fe->bbox_l = x ;
481 if (fe->bbox_r < x+w) fe->bbox_r = x+w;
482 if (fe->bbox_u > y ) fe->bbox_u = y ;
483 if (fe->bbox_d < y+h) fe->bbox_d = y+h;
486 void gtk_end_draw(void *handle)
488 frontend *fe = (frontend *)handle;
489 gdk_gc_unref(fe->gc);
492 if (fe->bbox_l < fe->bbox_r && fe->bbox_u < fe->bbox_d) {
493 gdk_draw_pixmap(fe->area->window,
494 fe->area->style->fg_gc[GTK_WIDGET_STATE(fe->area)],
496 fe->bbox_l, fe->bbox_u,
497 fe->ox + fe->bbox_l, fe->oy + fe->bbox_u,
498 fe->bbox_r - fe->bbox_l, fe->bbox_d - fe->bbox_u);
502 const struct drawing_api gtk_drawing = {
518 NULL, NULL, NULL, NULL, NULL, NULL, /* {begin,end}_{doc,page,puzzle} */
519 NULL, /* line_width */
522 static void destroy(GtkWidget *widget, gpointer data)
524 frontend *fe = (frontend *)data;
525 deactivate_timer(fe);
530 static gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data)
532 frontend *fe = (frontend *)data;
534 int shift = (event->state & GDK_SHIFT_MASK) ? MOD_SHFT : 0;
535 int ctrl = (event->state & GDK_CONTROL_MASK) ? MOD_CTRL : 0;
540 #if !GTK_CHECK_VERSION(2,0,0)
541 /* Gtk 1.2 passes a key event to this function even if it's also
542 * defined as an accelerator.
543 * Gtk 2 doesn't do this, and this function appears not to exist there. */
544 if (fe->accelgroup &&
545 gtk_accel_group_get_entry(fe->accelgroup,
546 event->keyval, event->state))
550 /* Handle mnemonics. */
551 if (gtk_window_activate_key(GTK_WINDOW(fe->window), event))
554 if (event->keyval == GDK_Up)
555 keyval = shift | ctrl | CURSOR_UP;
556 else if (event->keyval == GDK_KP_Up || event->keyval == GDK_KP_8)
557 keyval = MOD_NUM_KEYPAD | '8';
558 else if (event->keyval == GDK_Down)
559 keyval = shift | ctrl | CURSOR_DOWN;
560 else if (event->keyval == GDK_KP_Down || event->keyval == GDK_KP_2)
561 keyval = MOD_NUM_KEYPAD | '2';
562 else if (event->keyval == GDK_Left)
563 keyval = shift | ctrl | CURSOR_LEFT;
564 else if (event->keyval == GDK_KP_Left || event->keyval == GDK_KP_4)
565 keyval = MOD_NUM_KEYPAD | '4';
566 else if (event->keyval == GDK_Right)
567 keyval = shift | ctrl | CURSOR_RIGHT;
568 else if (event->keyval == GDK_KP_Right || event->keyval == GDK_KP_6)
569 keyval = MOD_NUM_KEYPAD | '6';
570 else if (event->keyval == GDK_KP_Home || event->keyval == GDK_KP_7)
571 keyval = MOD_NUM_KEYPAD | '7';
572 else if (event->keyval == GDK_KP_End || event->keyval == GDK_KP_1)
573 keyval = MOD_NUM_KEYPAD | '1';
574 else if (event->keyval == GDK_KP_Page_Up || event->keyval == GDK_KP_9)
575 keyval = MOD_NUM_KEYPAD | '9';
576 else if (event->keyval == GDK_KP_Page_Down || event->keyval == GDK_KP_3)
577 keyval = MOD_NUM_KEYPAD | '3';
578 else if (event->keyval == GDK_KP_Insert || event->keyval == GDK_KP_0)
579 keyval = MOD_NUM_KEYPAD | '0';
580 else if (event->keyval == GDK_KP_Begin || event->keyval == GDK_KP_5)
581 keyval = MOD_NUM_KEYPAD | '5';
582 else if (event->keyval == GDK_BackSpace ||
583 event->keyval == GDK_Delete ||
584 event->keyval == GDK_KP_Delete)
586 else if (event->string[0] && !event->string[1])
587 keyval = (unsigned char)event->string[0];
592 !midend_process_key(fe->me, 0, 0, keyval))
593 gtk_widget_destroy(fe->window);
598 static gint button_event(GtkWidget *widget, GdkEventButton *event,
601 frontend *fe = (frontend *)data;
607 if (event->type != GDK_BUTTON_PRESS && event->type != GDK_BUTTON_RELEASE)
610 if (event->button == 2 || (event->state & GDK_SHIFT_MASK))
611 button = MIDDLE_BUTTON;
612 else if (event->button == 3 || (event->state & GDK_MOD1_MASK))
613 button = RIGHT_BUTTON;
614 else if (event->button == 1)
615 button = LEFT_BUTTON;
617 return FALSE; /* don't even know what button! */
619 if (event->type == GDK_BUTTON_RELEASE)
620 button += LEFT_RELEASE - LEFT_BUTTON;
622 if (!midend_process_key(fe->me, event->x - fe->ox,
623 event->y - fe->oy, button))
624 gtk_widget_destroy(fe->window);
629 static gint motion_event(GtkWidget *widget, GdkEventMotion *event,
632 frontend *fe = (frontend *)data;
638 if (event->state & (GDK_BUTTON2_MASK | GDK_SHIFT_MASK))
639 button = MIDDLE_DRAG;
640 else if (event->state & GDK_BUTTON1_MASK)
642 else if (event->state & GDK_BUTTON3_MASK)
645 return FALSE; /* don't even know what button! */
647 if (!midend_process_key(fe->me, event->x - fe->ox,
648 event->y - fe->oy, button))
649 gtk_widget_destroy(fe->window);
650 #if GTK_CHECK_VERSION(2,12,0)
651 gdk_event_request_motions(event);
653 gdk_window_get_pointer(widget->window, NULL, NULL, NULL);
659 static gint expose_area(GtkWidget *widget, GdkEventExpose *event,
662 frontend *fe = (frontend *)data;
665 gdk_draw_pixmap(widget->window,
666 widget->style->fg_gc[GTK_WIDGET_STATE(widget)],
668 event->area.x - fe->ox, event->area.y - fe->oy,
669 event->area.x, event->area.y,
670 event->area.width, event->area.height);
675 static gint map_window(GtkWidget *widget, GdkEvent *event,
678 frontend *fe = (frontend *)data;
681 * Apparently we need to do this because otherwise the status
682 * bar will fail to update immediately. Annoying, but there we
685 gtk_widget_queue_draw(fe->window);
690 static gint configure_area(GtkWidget *widget,
691 GdkEventConfigure *event, gpointer data)
693 frontend *fe = (frontend *)data;
698 gdk_pixmap_unref(fe->pixmap);
700 x = fe->w = event->width;
701 y = fe->h = event->height;
702 midend_size(fe->me, &x, &y, TRUE);
705 fe->ox = (fe->w - fe->pw) / 2;
706 fe->oy = (fe->h - fe->ph) / 2;
708 fe->pixmap = gdk_pixmap_new(widget->window, fe->pw, fe->ph, -1);
710 gc = gdk_gc_new(fe->area->window);
711 gdk_gc_set_foreground(gc, &fe->colours[0]);
712 gdk_draw_rectangle(fe->pixmap, gc, 1, 0, 0, fe->pw, fe->ph);
713 gdk_draw_rectangle(widget->window, gc, 1, 0, 0,
714 event->width, event->height);
717 midend_force_redraw(fe->me);
722 static gint timer_func(gpointer data)
724 frontend *fe = (frontend *)data;
726 if (fe->timer_active) {
729 gettimeofday(&now, NULL);
730 elapsed = ((now.tv_usec - fe->last_time.tv_usec) * 0.000001F +
731 (now.tv_sec - fe->last_time.tv_sec));
732 midend_timer(fe->me, elapsed); /* may clear timer_active */
736 return fe->timer_active;
739 void deactivate_timer(frontend *fe)
742 return; /* can happen due to --generate */
743 if (fe->timer_active)
744 gtk_timeout_remove(fe->timer_id);
745 fe->timer_active = FALSE;
748 void activate_timer(frontend *fe)
751 return; /* can happen due to --generate */
752 if (!fe->timer_active) {
753 fe->timer_id = gtk_timeout_add(20, timer_func, fe);
754 gettimeofday(&fe->last_time, NULL);
756 fe->timer_active = TRUE;
759 static void window_destroy(GtkWidget *widget, gpointer data)
764 static void msgbox_button_clicked(GtkButton *button, gpointer data)
766 GtkWidget *window = GTK_WIDGET(data);
769 ip = (int *)gtk_object_get_data(GTK_OBJECT(window), "user-data");
770 v = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(button), "user-data"));
773 gtk_widget_destroy(GTK_WIDGET(data));
776 static int win_key_press(GtkWidget *widget, GdkEventKey *event, gpointer data)
778 GtkObject *cancelbutton = GTK_OBJECT(data);
781 * `Escape' effectively clicks the cancel button
783 if (event->keyval == GDK_Escape) {
784 gtk_signal_emit_by_name(GTK_OBJECT(cancelbutton), "clicked");
791 enum { MB_OK, MB_YESNO };
793 int message_box(GtkWidget *parent, char *title, char *msg, int centre,
796 GtkWidget *window, *hbox, *text, *button;
800 window = gtk_dialog_new();
801 text = gtk_label_new(msg);
802 gtk_misc_set_alignment(GTK_MISC(text), 0.0, 0.0);
803 hbox = gtk_hbox_new(FALSE, 0);
804 gtk_box_pack_start(GTK_BOX(hbox), text, FALSE, FALSE, 20);
805 gtk_box_pack_start(GTK_BOX(GTK_DIALOG(window)->vbox),
806 hbox, FALSE, FALSE, 20);
807 gtk_widget_show(text);
808 gtk_widget_show(hbox);
809 gtk_window_set_title(GTK_WINDOW(window), title);
810 gtk_label_set_line_wrap(GTK_LABEL(text), TRUE);
816 assert(type == MB_YESNO);
817 titles = "Yes\0No\0";
824 button = gtk_button_new_with_label(titles);
825 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(window)->action_area),
826 button, FALSE, FALSE, 0);
827 gtk_widget_show(button);
829 GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
830 gtk_window_set_default(GTK_WINDOW(window), button);
833 gtk_signal_connect(GTK_OBJECT(window), "key_press_event",
834 GTK_SIGNAL_FUNC(win_key_press), button);
836 gtk_signal_connect(GTK_OBJECT(button), "clicked",
837 GTK_SIGNAL_FUNC(msgbox_button_clicked), window);
838 gtk_object_set_data(GTK_OBJECT(button), "user-data",
840 titles += strlen(titles)+1;
843 gtk_object_set_data(GTK_OBJECT(window), "user-data",
844 GINT_TO_POINTER(&i));
845 gtk_signal_connect(GTK_OBJECT(window), "destroy",
846 GTK_SIGNAL_FUNC(window_destroy), NULL);
847 gtk_window_set_modal(GTK_WINDOW(window), TRUE);
848 gtk_window_set_transient_for(GTK_WINDOW(window), GTK_WINDOW(parent));
849 /* set_transient_window_pos(parent, window); */
850 gtk_widget_show(window);
853 return (type == MB_YESNO ? i == 0 : TRUE);
856 void error_box(GtkWidget *parent, char *msg)
858 message_box(parent, "Error", msg, FALSE, MB_OK);
861 static void config_ok_button_clicked(GtkButton *button, gpointer data)
863 frontend *fe = (frontend *)data;
866 err = midend_set_config(fe->me, fe->cfg_which, fe->cfg);
869 error_box(fe->cfgbox, err);
872 gtk_widget_destroy(fe->cfgbox);
877 static void config_cancel_button_clicked(GtkButton *button, gpointer data)
879 frontend *fe = (frontend *)data;
881 gtk_widget_destroy(fe->cfgbox);
884 static int editbox_key(GtkWidget *widget, GdkEventKey *event, gpointer data)
887 * GtkEntry has a nasty habit of eating the Return key, which
888 * is unhelpful since it doesn't actually _do_ anything with it
889 * (it calls gtk_widget_activate, but our edit boxes never need
890 * activating). So I catch Return before GtkEntry sees it, and
891 * pass it straight on to the parent widget. Effect: hitting
892 * Return in an edit box will now activate the default button
893 * in the dialog just like it will everywhere else.
895 if (event->keyval == GDK_Return && widget->parent != NULL) {
897 gtk_signal_emit_stop_by_name(GTK_OBJECT(widget), "key_press_event");
898 gtk_signal_emit_by_name(GTK_OBJECT(widget->parent), "key_press_event",
905 static void editbox_changed(GtkEditable *ed, gpointer data)
907 config_item *i = (config_item *)data;
910 i->sval = dupstr(gtk_entry_get_text(GTK_ENTRY(ed)));
913 static void button_toggled(GtkToggleButton *tb, gpointer data)
915 config_item *i = (config_item *)data;
917 i->ival = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(tb));
920 static void droplist_sel(GtkMenuItem *item, gpointer data)
922 config_item *i = (config_item *)data;
924 i->ival = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(item),
928 static int get_config(frontend *fe, int which)
930 GtkWidget *w, *table, *cancel;
935 fe->cfg = midend_get_config(fe->me, which, &title);
936 fe->cfg_which = which;
939 fe->cfgbox = gtk_dialog_new();
940 gtk_window_set_title(GTK_WINDOW(fe->cfgbox), title);
943 w = gtk_button_new_with_label("OK");
944 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(fe->cfgbox)->action_area),
947 GTK_WIDGET_SET_FLAGS(w, GTK_CAN_DEFAULT);
948 gtk_window_set_default(GTK_WINDOW(fe->cfgbox), w);
949 gtk_signal_connect(GTK_OBJECT(w), "clicked",
950 GTK_SIGNAL_FUNC(config_ok_button_clicked), fe);
952 w = gtk_button_new_with_label("Cancel");
953 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(fe->cfgbox)->action_area),
956 gtk_signal_connect(GTK_OBJECT(w), "clicked",
957 GTK_SIGNAL_FUNC(config_cancel_button_clicked), fe);
960 table = gtk_table_new(1, 2, FALSE);
962 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(fe->cfgbox)->vbox),
963 table, FALSE, FALSE, 0);
964 gtk_widget_show(table);
966 for (i = fe->cfg; i->type != C_END; i++) {
967 gtk_table_resize(GTK_TABLE(table), y+1, 2);
972 * Edit box with a label beside it.
975 w = gtk_label_new(i->name);
976 gtk_misc_set_alignment(GTK_MISC(w), 0.0, 0.5);
977 gtk_table_attach(GTK_TABLE(table), w, 0, 1, y, y+1,
978 GTK_SHRINK | GTK_FILL,
979 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
984 gtk_table_attach(GTK_TABLE(table), w, 1, 2, y, y+1,
985 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
986 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
988 gtk_entry_set_text(GTK_ENTRY(w), i->sval);
989 gtk_signal_connect(GTK_OBJECT(w), "changed",
990 GTK_SIGNAL_FUNC(editbox_changed), i);
991 gtk_signal_connect(GTK_OBJECT(w), "key_press_event",
992 GTK_SIGNAL_FUNC(editbox_key), NULL);
1001 w = gtk_check_button_new_with_label(i->name);
1002 gtk_signal_connect(GTK_OBJECT(w), "toggled",
1003 GTK_SIGNAL_FUNC(button_toggled), i);
1004 gtk_table_attach(GTK_TABLE(table), w, 0, 2, y, y+1,
1005 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1006 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1008 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(w), i->ival);
1014 * Drop-down list (GtkOptionMenu).
1017 w = gtk_label_new(i->name);
1018 gtk_misc_set_alignment(GTK_MISC(w), 0.0, 0.5);
1019 gtk_table_attach(GTK_TABLE(table), w, 0, 1, y, y+1,
1020 GTK_SHRINK | GTK_FILL,
1021 GTK_EXPAND | GTK_SHRINK | GTK_FILL ,
1025 w = gtk_option_menu_new();
1026 gtk_table_attach(GTK_TABLE(table), w, 1, 2, y, y+1,
1027 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1028 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1035 GtkWidget *menuitem;
1036 GtkWidget *menu = gtk_menu_new();
1038 gtk_option_menu_set_menu(GTK_OPTION_MENU(w), menu);
1046 while (*q && *q != c)
1049 name = snewn(q-p+1, char);
1050 strncpy(name, p, q-p);
1053 if (*q) q++; /* eat delimiter */
1055 menuitem = gtk_menu_item_new_with_label(name);
1056 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1057 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1058 GINT_TO_POINTER(val));
1059 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1060 GTK_SIGNAL_FUNC(droplist_sel), i);
1061 gtk_widget_show(menuitem);
1068 gtk_option_menu_set_history(GTK_OPTION_MENU(w), i->ival);
1077 gtk_signal_connect(GTK_OBJECT(fe->cfgbox), "destroy",
1078 GTK_SIGNAL_FUNC(window_destroy), NULL);
1079 gtk_signal_connect(GTK_OBJECT(fe->cfgbox), "key_press_event",
1080 GTK_SIGNAL_FUNC(win_key_press), cancel);
1081 gtk_window_set_modal(GTK_WINDOW(fe->cfgbox), TRUE);
1082 gtk_window_set_transient_for(GTK_WINDOW(fe->cfgbox),
1083 GTK_WINDOW(fe->window));
1084 /* set_transient_window_pos(fe->window, fe->cfgbox); */
1085 gtk_widget_show(fe->cfgbox);
1093 static void menu_key_event(GtkMenuItem *menuitem, gpointer data)
1095 frontend *fe = (frontend *)data;
1096 int key = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(menuitem),
1098 if (!midend_process_key(fe->me, 0, 0, key))
1099 gtk_widget_destroy(fe->window);
1102 static void get_size(frontend *fe, int *px, int *py)
1107 * Currently I don't want to make the GTK port scale large
1108 * puzzles to fit on the screen. This is because X does permit
1109 * extremely large windows and many window managers provide a
1110 * means of navigating round them, and the users I consulted
1111 * before deciding said that they'd rather have enormous puzzle
1112 * windows spanning multiple screen pages than have them
1113 * shrunk. I could change my mind later or introduce
1114 * configurability; this would be the place to do so, by
1115 * replacing the initial values of x and y with the screen
1120 midend_size(fe->me, &x, &y, FALSE);
1125 #if !GTK_CHECK_VERSION(2,0,0)
1126 #define gtk_window_resize(win, x, y) \
1127 gdk_window_resize(GTK_WIDGET(win)->window, x, y)
1131 * Called when any other code in this file has changed the
1132 * selected game parameters.
1134 static void changed_preset(frontend *fe)
1136 int n = midend_which_preset(fe->me);
1138 fe->preset_threaded = TRUE;
1139 if (n < 0 && fe->preset_custom) {
1140 gtk_check_menu_item_set_active(
1141 GTK_CHECK_MENU_ITEM(fe->preset_custom),
1144 GSList *gs = fe->preset_radio;
1145 int i = fe->n_preset_menu_items - 1 - n;
1146 if (fe->preset_custom)
1153 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(gs->data),
1155 } else for (gs = fe->preset_radio; gs; gs = gs->next) {
1156 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(gs->data),
1160 fe->preset_threaded = FALSE;
1163 * Update the greying on the Copy menu option.
1165 if (fe->copy_menu_item) {
1166 int enabled = midend_can_format_as_text_now(fe->me);
1167 gtk_widget_set_sensitive(fe->copy_menu_item, enabled);
1171 static void resize_fe(frontend *fe)
1175 get_size(fe, &x, &y);
1178 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
1181 gtk_widget_size_request(GTK_WIDGET(fe->window), &req);
1182 gtk_window_resize(GTK_WINDOW(fe->window), req.width, req.height);
1185 * Now that we've established the preferred size of the window,
1186 * reduce the drawing area's size request so the user can shrink
1189 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), 1, 1);
1192 static void menu_preset_event(GtkMenuItem *menuitem, gpointer data)
1194 frontend *fe = (frontend *)data;
1195 game_params *params =
1196 (game_params *)gtk_object_get_data(GTK_OBJECT(menuitem), "user-data");
1198 if (fe->preset_threaded ||
1199 (GTK_IS_CHECK_MENU_ITEM(menuitem) &&
1200 !gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(menuitem))))
1202 midend_set_params(fe->me, params);
1203 midend_new_game(fe->me);
1208 GdkAtom compound_text_atom, utf8_string_atom;
1209 int paste_initialised = FALSE;
1213 unsigned char empty[] = { 0 };
1215 if (paste_initialised)
1218 if (!compound_text_atom)
1219 compound_text_atom = gdk_atom_intern("COMPOUND_TEXT", FALSE);
1220 if (!utf8_string_atom)
1221 utf8_string_atom = gdk_atom_intern("UTF8_STRING", FALSE);
1224 * Ensure that all the cut buffers exist - according to the
1225 * ICCCM, we must do this before we start using cut buffers.
1227 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1228 XA_CUT_BUFFER0, XA_STRING, 8, PropModeAppend, empty, 0);
1229 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1230 XA_CUT_BUFFER1, XA_STRING, 8, PropModeAppend, empty, 0);
1231 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1232 XA_CUT_BUFFER2, XA_STRING, 8, PropModeAppend, empty, 0);
1233 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1234 XA_CUT_BUFFER3, XA_STRING, 8, PropModeAppend, empty, 0);
1235 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1236 XA_CUT_BUFFER4, XA_STRING, 8, PropModeAppend, empty, 0);
1237 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1238 XA_CUT_BUFFER5, XA_STRING, 8, PropModeAppend, empty, 0);
1239 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1240 XA_CUT_BUFFER6, XA_STRING, 8, PropModeAppend, empty, 0);
1241 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1242 XA_CUT_BUFFER7, XA_STRING, 8, PropModeAppend, empty, 0);
1245 /* Store data in a cut-buffer. */
1246 void store_cutbuffer(char *ptr, int len)
1248 /* ICCCM says we must rotate the buffers before storing to buffer 0. */
1249 XRotateBuffers(GDK_DISPLAY(), 1);
1250 XStoreBytes(GDK_DISPLAY(), ptr, len);
1253 void write_clip(frontend *fe, char *data)
1258 sfree(fe->paste_data);
1261 * For this simple application we can safely assume that the
1262 * data passed to this function is pure ASCII, which means we
1263 * can return precisely the same stuff for types STRING,
1264 * COMPOUND_TEXT or UTF8_STRING.
1267 fe->paste_data = data;
1268 fe->paste_data_len = strlen(data);
1270 store_cutbuffer(fe->paste_data, fe->paste_data_len);
1272 if (gtk_selection_owner_set(fe->area, GDK_SELECTION_PRIMARY,
1274 gtk_selection_clear_targets(fe->area, GDK_SELECTION_PRIMARY);
1275 gtk_selection_add_target(fe->area, GDK_SELECTION_PRIMARY,
1276 GDK_SELECTION_TYPE_STRING, 1);
1277 gtk_selection_add_target(fe->area, GDK_SELECTION_PRIMARY,
1278 compound_text_atom, 1);
1279 gtk_selection_add_target(fe->area, GDK_SELECTION_PRIMARY,
1280 utf8_string_atom, 1);
1284 void selection_get(GtkWidget *widget, GtkSelectionData *seldata,
1285 guint info, guint time_stamp, gpointer data)
1287 frontend *fe = (frontend *)data;
1288 gtk_selection_data_set(seldata, seldata->target, 8,
1289 fe->paste_data, fe->paste_data_len);
1292 gint selection_clear(GtkWidget *widget, GdkEventSelection *seldata,
1295 frontend *fe = (frontend *)data;
1298 sfree(fe->paste_data);
1299 fe->paste_data = NULL;
1300 fe->paste_data_len = 0;
1304 static void menu_copy_event(GtkMenuItem *menuitem, gpointer data)
1306 frontend *fe = (frontend *)data;
1309 text = midend_text_format(fe->me);
1312 write_clip(fe, text);
1320 static void filesel_ok(GtkButton *button, gpointer data)
1322 frontend *fe = (frontend *)data;
1324 gpointer filesel = gtk_object_get_data(GTK_OBJECT(button), "user-data");
1327 gtk_file_selection_get_filename(GTK_FILE_SELECTION(filesel));
1329 fe->filesel_name = dupstr(name);
1332 static char *file_selector(frontend *fe, char *title, int save)
1334 GtkWidget *filesel =
1335 gtk_file_selection_new(title);
1337 fe->filesel_name = NULL;
1339 gtk_window_set_modal(GTK_WINDOW(filesel), TRUE);
1341 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "user-data",
1344 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "clicked",
1345 GTK_SIGNAL_FUNC(filesel_ok), fe);
1346 gtk_signal_connect_object
1347 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "clicked",
1348 GTK_SIGNAL_FUNC(gtk_widget_destroy), (gpointer)filesel);
1349 gtk_signal_connect_object
1350 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->cancel_button), "clicked",
1351 GTK_SIGNAL_FUNC(gtk_widget_destroy), (gpointer)filesel);
1352 gtk_signal_connect(GTK_OBJECT(filesel), "destroy",
1353 GTK_SIGNAL_FUNC(window_destroy), NULL);
1354 gtk_widget_show(filesel);
1355 gtk_window_set_transient_for(GTK_WINDOW(filesel), GTK_WINDOW(fe->window));
1358 return fe->filesel_name;
1363 static char *file_selector(frontend *fe, char *title, int save)
1365 char *filesel_name = NULL;
1367 GtkWidget *filesel =
1368 gtk_file_chooser_dialog_new(title,
1369 GTK_WINDOW(fe->window),
1370 save ? GTK_FILE_CHOOSER_ACTION_SAVE :
1371 GTK_FILE_CHOOSER_ACTION_OPEN,
1372 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
1373 save ? GTK_STOCK_SAVE : GTK_STOCK_OPEN,
1374 GTK_RESPONSE_ACCEPT,
1377 if (gtk_dialog_run(GTK_DIALOG(filesel)) == GTK_RESPONSE_ACCEPT) {
1378 const char *name = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(filesel));
1379 filesel_name = dupstr(name);
1382 gtk_widget_destroy(filesel);
1384 return filesel_name;
1389 struct savefile_write_ctx {
1394 static void savefile_write(void *wctx, void *buf, int len)
1396 struct savefile_write_ctx *ctx = (struct savefile_write_ctx *)wctx;
1397 if (fwrite(buf, 1, len, ctx->fp) < len)
1401 static int savefile_read(void *wctx, void *buf, int len)
1403 FILE *fp = (FILE *)wctx;
1406 ret = fread(buf, 1, len, fp);
1407 return (ret == len);
1410 static void menu_save_event(GtkMenuItem *menuitem, gpointer data)
1412 frontend *fe = (frontend *)data;
1415 name = file_selector(fe, "Enter name of game file to save", TRUE);
1420 if ((fp = fopen(name, "r")) != NULL) {
1421 char buf[256 + FILENAME_MAX];
1425 sprintf(buf, "Are you sure you want to overwrite the"
1427 FILENAME_MAX, name);
1428 if (!message_box(fe->window, "Question", buf, TRUE, MB_YESNO))
1432 fp = fopen(name, "w");
1436 error_box(fe->window, "Unable to open save file");
1441 struct savefile_write_ctx ctx;
1444 midend_serialise(fe->me, savefile_write, &ctx);
1448 sprintf(boxmsg, "Error writing save file: %.400s",
1450 error_box(fe->window, boxmsg);
1458 static void menu_load_event(GtkMenuItem *menuitem, gpointer data)
1460 frontend *fe = (frontend *)data;
1463 name = file_selector(fe, "Enter name of saved game file to load", FALSE);
1466 FILE *fp = fopen(name, "r");
1470 error_box(fe->window, "Unable to open saved game file");
1474 err = midend_deserialise(fe->me, savefile_read, fp);
1479 error_box(fe->window, err);
1488 static void menu_solve_event(GtkMenuItem *menuitem, gpointer data)
1490 frontend *fe = (frontend *)data;
1493 msg = midend_solve(fe->me);
1496 error_box(fe->window, msg);
1499 static void menu_restart_event(GtkMenuItem *menuitem, gpointer data)
1501 frontend *fe = (frontend *)data;
1503 midend_restart_game(fe->me);
1506 static void menu_config_event(GtkMenuItem *menuitem, gpointer data)
1508 frontend *fe = (frontend *)data;
1509 int which = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(menuitem),
1512 if (fe->preset_threaded ||
1513 (GTK_IS_CHECK_MENU_ITEM(menuitem) &&
1514 !gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(menuitem))))
1516 changed_preset(fe); /* Put the old preset back! */
1517 if (!get_config(fe, which))
1520 midend_new_game(fe->me);
1524 static void menu_about_event(GtkMenuItem *menuitem, gpointer data)
1526 frontend *fe = (frontend *)data;
1530 sprintf(titlebuf, "About %.200s", thegame.name);
1533 "from Simon Tatham's Portable Puzzle Collection\n\n"
1534 "%.500s", thegame.name, ver);
1536 message_box(fe->window, titlebuf, textbuf, TRUE, MB_OK);
1539 static GtkWidget *add_menu_item_with_key(frontend *fe, GtkContainer *cont,
1540 char *text, int key)
1542 GtkWidget *menuitem = gtk_menu_item_new_with_label(text);
1544 gtk_container_add(cont, menuitem);
1545 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1546 GINT_TO_POINTER(key));
1547 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1548 GTK_SIGNAL_FUNC(menu_key_event), fe);
1549 switch (key & ~0x1F) {
1552 keyqual = GDK_CONTROL_MASK;
1556 keyqual = GDK_SHIFT_MASK;
1562 gtk_widget_add_accelerator(menuitem,
1563 "activate", fe->accelgroup,
1566 gtk_widget_show(menuitem);
1570 static void add_menu_separator(GtkContainer *cont)
1572 GtkWidget *menuitem = gtk_menu_item_new();
1573 gtk_container_add(cont, menuitem);
1574 gtk_widget_show(menuitem);
1577 enum { ARG_EITHER, ARG_SAVE, ARG_ID }; /* for argtype */
1579 static frontend *new_window(char *arg, int argtype, char **error)
1583 GtkWidget *menubar, *menu, *menuitem;
1588 extern char *const *const xpm_icons[];
1589 extern const int n_xpm_icons;
1591 fe = snew(frontend);
1593 fe->timer_active = FALSE;
1596 fe->me = midend_new(fe, &thegame, >k_drawing, fe);
1606 err = midend_game_id(fe->me, arg);
1608 midend_new_game(fe->me);
1610 sprintf(errbuf, "Invalid game ID: %.800s", err);
1613 fp = fopen(arg, "r");
1615 sprintf(errbuf, "Error opening file: %.800s", strerror(errno));
1617 err = midend_deserialise(fe->me, savefile_read, fp);
1619 sprintf(errbuf, "Invalid save file: %.800s", err);
1623 default /*case ARG_EITHER*/:
1625 * First try treating the argument as a game ID.
1627 err = midend_game_id(fe->me, arg);
1630 * It's a valid game ID.
1632 midend_new_game(fe->me);
1634 FILE *fp = fopen(arg, "r");
1636 sprintf(errbuf, "Supplied argument is neither a game ID (%.400s)"
1637 " nor a save file (%.400s)", err, strerror(errno));
1639 err = midend_deserialise(fe->me, savefile_read, fp);
1641 sprintf(errbuf, "%.800s", err);
1648 *error = dupstr(errbuf);
1649 midend_free(fe->me);
1655 midend_new_game(fe->me);
1658 fe->window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1659 gtk_window_set_title(GTK_WINDOW(fe->window), thegame.name);
1661 vbox = GTK_BOX(gtk_vbox_new(FALSE, 0));
1662 gtk_container_add(GTK_CONTAINER(fe->window), GTK_WIDGET(vbox));
1663 gtk_widget_show(GTK_WIDGET(vbox));
1665 fe->accelgroup = gtk_accel_group_new();
1666 gtk_window_add_accel_group(GTK_WINDOW(fe->window), fe->accelgroup);
1668 menubar = gtk_menu_bar_new();
1669 gtk_box_pack_start(vbox, menubar, FALSE, FALSE, 0);
1670 gtk_widget_show(menubar);
1672 menuitem = gtk_menu_item_new_with_mnemonic("_Game");
1673 gtk_container_add(GTK_CONTAINER(menubar), menuitem);
1674 gtk_widget_show(menuitem);
1676 menu = gtk_menu_new();
1677 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
1679 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "New", 'n');
1681 menuitem = gtk_menu_item_new_with_label("Restart");
1682 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1683 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1684 GTK_SIGNAL_FUNC(menu_restart_event), fe);
1685 gtk_widget_show(menuitem);
1687 menuitem = gtk_menu_item_new_with_label("Specific...");
1688 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1689 GINT_TO_POINTER(CFG_DESC));
1690 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1691 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1692 GTK_SIGNAL_FUNC(menu_config_event), fe);
1693 gtk_widget_show(menuitem);
1695 menuitem = gtk_menu_item_new_with_label("Random Seed...");
1696 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1697 GINT_TO_POINTER(CFG_SEED));
1698 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1699 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1700 GTK_SIGNAL_FUNC(menu_config_event), fe);
1701 gtk_widget_show(menuitem);
1703 fe->preset_radio = NULL;
1704 fe->preset_custom = NULL;
1705 fe->n_preset_menu_items = 0;
1706 fe->preset_threaded = FALSE;
1707 if ((n = midend_num_presets(fe->me)) > 0 || thegame.can_configure) {
1711 menuitem = gtk_menu_item_new_with_mnemonic("_Type");
1712 gtk_container_add(GTK_CONTAINER(menubar), menuitem);
1713 gtk_widget_show(menuitem);
1715 submenu = gtk_menu_new();
1716 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), submenu);
1718 for (i = 0; i < n; i++) {
1720 game_params *params;
1722 midend_fetch_preset(fe->me, i, &name, ¶ms);
1725 gtk_radio_menu_item_new_with_label(fe->preset_radio, name);
1727 gtk_radio_menu_item_group(GTK_RADIO_MENU_ITEM(menuitem));
1728 fe->n_preset_menu_items++;
1729 gtk_container_add(GTK_CONTAINER(submenu), menuitem);
1730 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data", params);
1731 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1732 GTK_SIGNAL_FUNC(menu_preset_event), fe);
1733 gtk_widget_show(menuitem);
1736 if (thegame.can_configure) {
1737 menuitem = fe->preset_custom =
1738 gtk_radio_menu_item_new_with_label(fe->preset_radio,
1741 gtk_radio_menu_item_group(GTK_RADIO_MENU_ITEM(menuitem));
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);
1752 add_menu_separator(GTK_CONTAINER(menu));
1753 menuitem = gtk_menu_item_new_with_label("Load...");
1754 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1755 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1756 GTK_SIGNAL_FUNC(menu_load_event), fe);
1757 gtk_widget_show(menuitem);
1758 menuitem = gtk_menu_item_new_with_label("Save...");
1759 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1760 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1761 GTK_SIGNAL_FUNC(menu_save_event), fe);
1762 gtk_widget_show(menuitem);
1763 add_menu_separator(GTK_CONTAINER(menu));
1764 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Undo", 'u');
1765 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Redo", 'r');
1766 if (thegame.can_format_as_text_ever) {
1767 add_menu_separator(GTK_CONTAINER(menu));
1768 menuitem = gtk_menu_item_new_with_label("Copy");
1769 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1770 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1771 GTK_SIGNAL_FUNC(menu_copy_event), fe);
1772 gtk_widget_show(menuitem);
1773 fe->copy_menu_item = menuitem;
1775 fe->copy_menu_item = NULL;
1777 if (thegame.can_solve) {
1778 add_menu_separator(GTK_CONTAINER(menu));
1779 menuitem = gtk_menu_item_new_with_label("Solve");
1780 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1781 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1782 GTK_SIGNAL_FUNC(menu_solve_event), fe);
1783 gtk_widget_show(menuitem);
1785 add_menu_separator(GTK_CONTAINER(menu));
1786 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Exit", 'q');
1788 menuitem = gtk_menu_item_new_with_mnemonic("_Help");
1789 gtk_container_add(GTK_CONTAINER(menubar), menuitem);
1790 gtk_widget_show(menuitem);
1792 menu = gtk_menu_new();
1793 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
1795 menuitem = gtk_menu_item_new_with_label("About");
1796 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1797 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1798 GTK_SIGNAL_FUNC(menu_about_event), fe);
1799 gtk_widget_show(menuitem);
1808 fe->colmap = gdk_colormap_get_system();
1809 colours = midend_colours(fe->me, &ncolours);
1810 fe->ncolours = ncolours;
1811 fe->colours = snewn(ncolours, GdkColor);
1812 for (i = 0; i < ncolours; i++) {
1813 fe->colours[i].red = colours[i*3] * 0xFFFF;
1814 fe->colours[i].green = colours[i*3+1] * 0xFFFF;
1815 fe->colours[i].blue = colours[i*3+2] * 0xFFFF;
1817 success = snewn(ncolours, gboolean);
1818 gdk_colormap_alloc_colors(fe->colmap, fe->colours, ncolours,
1819 FALSE, FALSE, success);
1820 for (i = 0; i < ncolours; i++) {
1822 g_error("couldn't allocate colour %d (#%02x%02x%02x)\n",
1823 i, fe->colours[i].red >> 8,
1824 fe->colours[i].green >> 8,
1825 fe->colours[i].blue >> 8);
1830 if (midend_wants_statusbar(fe->me)) {
1831 GtkWidget *viewport;
1834 viewport = gtk_viewport_new(NULL, NULL);
1835 gtk_viewport_set_shadow_type(GTK_VIEWPORT(viewport), GTK_SHADOW_NONE);
1836 fe->statusbar = gtk_statusbar_new();
1837 gtk_container_add(GTK_CONTAINER(viewport), fe->statusbar);
1838 gtk_widget_show(viewport);
1839 gtk_box_pack_end(vbox, viewport, FALSE, FALSE, 0);
1840 gtk_widget_show(fe->statusbar);
1841 fe->statusctx = gtk_statusbar_get_context_id
1842 (GTK_STATUSBAR(fe->statusbar), "game");
1843 gtk_statusbar_push(GTK_STATUSBAR(fe->statusbar), fe->statusctx,
1845 gtk_widget_size_request(fe->statusbar, &req);
1847 /* For GTK 2.0, should we be using gtk_widget_set_size_request? */
1849 gtk_widget_set_usize(viewport, -1, req.height);
1851 fe->statusbar = NULL;
1853 fe->area = gtk_drawing_area_new();
1854 get_size(fe, &x, &y);
1855 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
1859 gtk_box_pack_end(vbox, fe->area, TRUE, TRUE, 0);
1863 fe->nfonts = fe->fontsize = 0;
1865 fe->paste_data = NULL;
1866 fe->paste_data_len = 0;
1868 gtk_signal_connect(GTK_OBJECT(fe->window), "destroy",
1869 GTK_SIGNAL_FUNC(destroy), fe);
1870 gtk_signal_connect(GTK_OBJECT(fe->window), "key_press_event",
1871 GTK_SIGNAL_FUNC(key_event), fe);
1872 gtk_signal_connect(GTK_OBJECT(fe->area), "button_press_event",
1873 GTK_SIGNAL_FUNC(button_event), fe);
1874 gtk_signal_connect(GTK_OBJECT(fe->area), "button_release_event",
1875 GTK_SIGNAL_FUNC(button_event), fe);
1876 gtk_signal_connect(GTK_OBJECT(fe->area), "motion_notify_event",
1877 GTK_SIGNAL_FUNC(motion_event), fe);
1878 gtk_signal_connect(GTK_OBJECT(fe->area), "selection_get",
1879 GTK_SIGNAL_FUNC(selection_get), fe);
1880 gtk_signal_connect(GTK_OBJECT(fe->area), "selection_clear_event",
1881 GTK_SIGNAL_FUNC(selection_clear), fe);
1882 gtk_signal_connect(GTK_OBJECT(fe->area), "expose_event",
1883 GTK_SIGNAL_FUNC(expose_area), fe);
1884 gtk_signal_connect(GTK_OBJECT(fe->window), "map_event",
1885 GTK_SIGNAL_FUNC(map_window), fe);
1886 gtk_signal_connect(GTK_OBJECT(fe->area), "configure_event",
1887 GTK_SIGNAL_FUNC(configure_area), fe);
1889 gtk_widget_add_events(GTK_WIDGET(fe->area),
1890 GDK_BUTTON_PRESS_MASK |
1891 GDK_BUTTON_RELEASE_MASK |
1892 GDK_BUTTON_MOTION_MASK |
1893 GDK_POINTER_MOTION_HINT_MASK);
1896 gtk_widget_realize(fe->window);
1897 iconpm = gdk_pixmap_create_from_xpm_d(fe->window->window, NULL,
1898 NULL, (gchar **)xpm_icons[0]);
1899 gdk_window_set_icon(fe->window->window, NULL, iconpm, NULL);
1901 for (n = 0; n < n_xpm_icons; n++) {
1903 g_list_append(iconlist,
1904 gdk_pixbuf_new_from_xpm_data((const gchar **)
1907 gdk_window_set_icon_list(fe->window->window, iconlist);
1910 gtk_widget_show(fe->area);
1911 gtk_widget_show(fe->window);
1914 * Now that we've established the preferred size of the window,
1915 * reduce the drawing area's size request so the user can shrink
1918 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), 1, 1);
1920 gdk_window_set_background(fe->area->window, &fe->colours[0]);
1921 gdk_window_set_background(fe->window->window, &fe->colours[0]);
1926 char *fgetline(FILE *fp)
1928 char *ret = snewn(512, char);
1929 int size = 512, len = 0;
1930 while (fgets(ret + len, size - len, fp)) {
1931 len += strlen(ret + len);
1932 if (ret[len-1] == '\n')
1933 break; /* got a newline, we're done */
1935 ret = sresize(ret, size, char);
1937 if (len == 0) { /* first fgets returned NULL */
1945 int main(int argc, char **argv)
1947 char *pname = argv[0];
1949 int ngenerate = 0, print = FALSE, px = 1, py = 1;
1950 int soln = FALSE, colour = FALSE;
1952 float redo_proportion = 0.0F;
1953 char *savefile = NULL, *savesuffix = NULL;
1955 int argtype = ARG_EITHER;
1956 char *screenshot_file = NULL;
1957 int doing_opts = TRUE;
1963 * Command line parsing in this function is rather fiddly,
1964 * because GTK wants to have a go at argc/argv _first_ - and
1965 * yet we can't let it, because gtk_init() will bomb out if it
1966 * can't open an X display, whereas in fact we want to permit
1967 * our --generate and --print modes to run without an X
1971 * - we parse the command line ourselves, without modifying
1973 * - if we encounter an error which might plausibly be the
1974 * result of a GTK command line (i.e. not detailed errors in
1975 * particular options of ours) we store the error message
1976 * and terminate parsing.
1977 * - if we got enough out of the command line to know it
1978 * specifies a non-X mode of operation, we either display
1979 * the stored error and return failure, or if there is no
1980 * stored error we do the non-X operation and return
1982 * - otherwise, we go straight to gtk_init().
1988 if (doing_opts && !strcmp(p, "--version")) {
1989 printf("%s, from Simon Tatham's Portable Puzzle Collection\n%s\n",
1992 } else if (doing_opts && !strcmp(p, "--generate")) {
1994 ngenerate = atoi(*++av);
1996 fprintf(stderr, "%s: '--generate' expected a number\n",
2002 } else if (doing_opts && !strcmp(p, "--save")) {
2006 fprintf(stderr, "%s: '--save' expected a filename\n",
2010 } else if (doing_opts && (!strcmp(p, "--save-suffix") ||
2011 !strcmp(p, "--savesuffix"))) {
2015 fprintf(stderr, "%s: '--save-suffix' expected a filename\n",
2019 } else if (doing_opts && !strcmp(p, "--print")) {
2020 if (!thegame.can_print) {
2021 fprintf(stderr, "%s: this game does not support printing\n",
2028 if (sscanf(dim, "%dx%d", &px, &py) != 2) {
2029 fprintf(stderr, "%s: unable to parse argument '%s' to "
2030 "'--print'\n", pname, dim);
2036 } else if (doing_opts && !strcmp(p, "--scale")) {
2038 scale = atof(*++av);
2040 fprintf(stderr, "%s: no argument supplied to '--scale'\n",
2044 } else if (doing_opts && !strcmp(p, "--redo")) {
2046 * This is an internal option which I don't expect
2047 * users to have any particular use for. The effect of
2048 * --redo is that once the game has been loaded and
2049 * initialised, the next move in the redo chain is
2050 * replayed, and the game screen is redrawn part way
2051 * through the making of the move. This is only
2052 * meaningful if there _is_ a next move in the redo
2053 * chain, which means in turn that this option is only
2054 * useful if you're also passing a save file on the
2057 * This option is used by the script which generates
2058 * the puzzle icons and website screenshots, and I
2059 * don't imagine it's useful for anything else.
2060 * (Unless, I suppose, users don't like my screenshots
2061 * and want to generate their own in the same way for
2062 * some repackaged version of the puzzles.)
2065 redo_proportion = atof(*++av);
2067 fprintf(stderr, "%s: no argument supplied to '--redo'\n",
2071 } else if (doing_opts && !strcmp(p, "--screenshot")) {
2073 * Another internal option for the icon building
2074 * script. This causes a screenshot of the central
2075 * drawing area (i.e. not including the menu bar or
2076 * status bar) to be saved to a PNG file once the
2077 * window has been drawn, and then the application
2078 * quits immediately.
2081 screenshot_file = *++av;
2083 fprintf(stderr, "%s: no argument supplied to '--screenshot'\n",
2087 } else if (doing_opts && (!strcmp(p, "--with-solutions") ||
2088 !strcmp(p, "--with-solution") ||
2089 !strcmp(p, "--with-solns") ||
2090 !strcmp(p, "--with-soln") ||
2091 !strcmp(p, "--solutions") ||
2092 !strcmp(p, "--solution") ||
2093 !strcmp(p, "--solns") ||
2094 !strcmp(p, "--soln"))) {
2096 } else if (doing_opts && !strcmp(p, "--colour")) {
2097 if (!thegame.can_print_in_colour) {
2098 fprintf(stderr, "%s: this game does not support colour"
2099 " printing\n", pname);
2103 } else if (doing_opts && !strcmp(p, "--load")) {
2105 } else if (doing_opts && !strcmp(p, "--game")) {
2107 } else if (doing_opts && !strcmp(p, "--")) {
2109 } else if (!doing_opts || p[0] != '-') {
2111 fprintf(stderr, "%s: more than one argument supplied\n",
2117 sprintf(errbuf, "%.100s: unrecognised option '%.100s'\n",
2124 fputs(errbuf, stderr);
2129 * Special standalone mode for generating puzzle IDs on the
2130 * command line. Useful for generating puzzles to be printed
2131 * out and solved offline (for puzzles where that even makes
2132 * sense - Solo, for example, is a lot more pencil-and-paper
2133 * friendly than Twiddle!)
2137 * <puzzle-name> --generate [<n> [<params>]]
2139 * <n>, if present, is the number of puzzle IDs to generate.
2140 * <params>, if present, is the same type of parameter string
2141 * you would pass to the puzzle when running it in GUI mode,
2142 * including optional extras such as the expansion factor in
2143 * Rectangles and the difficulty level in Solo.
2145 * If you specify <params>, you must also specify <n> (although
2146 * you may specify it to be 1). Sorry; that was the
2147 * simplest-to-parse command-line syntax I came up with.
2149 if (ngenerate > 0 || print || savefile || savesuffix) {
2153 document *doc = NULL;
2157 me = midend_new(NULL, &thegame, NULL, NULL);
2160 if (savefile && !savesuffix)
2162 if (!savefile && savesuffix)
2166 doc = document_new(px, py, scale);
2169 * In this loop, we either generate a game ID or read one
2170 * from stdin depending on whether we're in generate mode;
2171 * then we either write it to stdout or print it, depending
2172 * on whether we're in print mode. Thus, this loop handles
2173 * generate-to-stdout, print-from-stdin and generate-and-
2174 * immediately-print modes.
2176 * (It could also handle a copy-stdin-to-stdout mode,
2177 * although there's currently no combination of options
2178 * which will cause this loop to be activated in that mode.
2179 * It wouldn't be _entirely_ pointless, though, because
2180 * stdin could contain bare params strings or random-seed
2181 * IDs, and stdout would contain nothing but fully
2182 * generated descriptive game IDs.)
2184 while (ngenerate == 0 || i < n) {
2187 if (ngenerate == 0) {
2188 pstr = fgetline(stdin);
2191 pstr[strcspn(pstr, "\r\n")] = '\0';
2194 pstr = snewn(strlen(arg) + 40, char);
2197 if (i > 0 && strchr(arg, '#'))
2198 sprintf(pstr + strlen(pstr), "-%d", i);
2204 err = midend_game_id(me, pstr);
2206 fprintf(stderr, "%s: error parsing '%s': %s\n",
2213 midend_new_game(me);
2216 err = midend_print_puzzle(me, doc, soln);
2218 fprintf(stderr, "%s: error in printing: %s\n", pname, err);
2223 struct savefile_write_ctx ctx;
2224 char *realname = snewn(40 + strlen(savefile) +
2225 strlen(savesuffix), char);
2226 sprintf(realname, "%s%d%s", savefile, i, savesuffix);
2227 ctx.fp = fopen(realname, "w");
2229 fprintf(stderr, "%s: open: %s\n", realname,
2234 midend_serialise(me, savefile_write, &ctx);
2236 fprintf(stderr, "%s: write: %s\n", realname,
2237 strerror(ctx.error));
2240 if (fclose(ctx.fp)) {
2241 fprintf(stderr, "%s: close: %s\n", realname,
2246 if (!doc && !savefile) {
2247 id = midend_get_game_id(me);
2256 psdata *ps = ps_init(stdout, colour);
2257 document_print(doc, ps_drawing_api(ps));
2268 gtk_init(&argc, &argv);
2270 fe = new_window(arg, argtype, &error);
2273 fprintf(stderr, "%s: %s\n", pname, error);
2277 if (screenshot_file) {
2279 * Some puzzles will not redraw their entire area if
2280 * given a partially completed animation, which means
2281 * we must redraw now and _then_ redraw again after
2282 * freezing the move timer.
2284 midend_force_redraw(fe->me);
2287 if (redo_proportion) {
2289 midend_process_key(fe->me, 0, 0, 'r');
2290 /* And freeze the timer at the specified position. */
2291 midend_freeze_timer(fe->me, redo_proportion);
2294 if (screenshot_file) {
2296 GError *gerror = NULL;
2298 midend_redraw(fe->me);
2300 pb = gdk_pixbuf_get_from_drawable(NULL, fe->pixmap,
2301 NULL, 0, 0, 0, 0, -1, -1);
2302 gdk_pixbuf_save(pb, screenshot_file, "png", &gerror, NULL);