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 /* Handle mnemonics. */
550 if (gtk_window_activate_key(GTK_WINDOW(fe->window), event))
553 if (event->keyval == GDK_Up)
554 keyval = shift | ctrl | CURSOR_UP;
555 else if (event->keyval == GDK_KP_Up || event->keyval == GDK_KP_8)
556 keyval = MOD_NUM_KEYPAD | '8';
557 else if (event->keyval == GDK_Down)
558 keyval = shift | ctrl | CURSOR_DOWN;
559 else if (event->keyval == GDK_KP_Down || event->keyval == GDK_KP_2)
560 keyval = MOD_NUM_KEYPAD | '2';
561 else if (event->keyval == GDK_Left)
562 keyval = shift | ctrl | CURSOR_LEFT;
563 else if (event->keyval == GDK_KP_Left || event->keyval == GDK_KP_4)
564 keyval = MOD_NUM_KEYPAD | '4';
565 else if (event->keyval == GDK_Right)
566 keyval = shift | ctrl | CURSOR_RIGHT;
567 else if (event->keyval == GDK_KP_Right || event->keyval == GDK_KP_6)
568 keyval = MOD_NUM_KEYPAD | '6';
569 else if (event->keyval == GDK_KP_Home || event->keyval == GDK_KP_7)
570 keyval = MOD_NUM_KEYPAD | '7';
571 else if (event->keyval == GDK_KP_End || event->keyval == GDK_KP_1)
572 keyval = MOD_NUM_KEYPAD | '1';
573 else if (event->keyval == GDK_KP_Page_Up || event->keyval == GDK_KP_9)
574 keyval = MOD_NUM_KEYPAD | '9';
575 else if (event->keyval == GDK_KP_Page_Down || event->keyval == GDK_KP_3)
576 keyval = MOD_NUM_KEYPAD | '3';
577 else if (event->keyval == GDK_KP_Insert || event->keyval == GDK_KP_0)
578 keyval = MOD_NUM_KEYPAD | '0';
579 else if (event->keyval == GDK_KP_Begin || event->keyval == GDK_KP_5)
580 keyval = MOD_NUM_KEYPAD | '5';
581 else if (event->keyval == GDK_BackSpace ||
582 event->keyval == GDK_Delete ||
583 event->keyval == GDK_KP_Delete)
585 else if (event->string[0] && !event->string[1])
586 keyval = (unsigned char)event->string[0];
591 !midend_process_key(fe->me, 0, 0, keyval))
592 gtk_widget_destroy(fe->window);
597 static gint button_event(GtkWidget *widget, GdkEventButton *event,
600 frontend *fe = (frontend *)data;
606 if (event->type != GDK_BUTTON_PRESS && event->type != GDK_BUTTON_RELEASE)
609 if (event->button == 2 || (event->state & GDK_SHIFT_MASK))
610 button = MIDDLE_BUTTON;
611 else if (event->button == 3 || (event->state & GDK_MOD1_MASK))
612 button = RIGHT_BUTTON;
613 else if (event->button == 1)
614 button = LEFT_BUTTON;
616 return FALSE; /* don't even know what button! */
618 if (event->type == GDK_BUTTON_RELEASE)
619 button += LEFT_RELEASE - LEFT_BUTTON;
621 if (!midend_process_key(fe->me, event->x - fe->ox,
622 event->y - fe->oy, button))
623 gtk_widget_destroy(fe->window);
628 static gint motion_event(GtkWidget *widget, GdkEventMotion *event,
631 frontend *fe = (frontend *)data;
637 if (event->state & (GDK_BUTTON2_MASK | GDK_SHIFT_MASK))
638 button = MIDDLE_DRAG;
639 else if (event->state & GDK_BUTTON1_MASK)
641 else if (event->state & GDK_BUTTON3_MASK)
644 return FALSE; /* don't even know what button! */
646 if (!midend_process_key(fe->me, event->x - fe->ox,
647 event->y - fe->oy, button))
648 gtk_widget_destroy(fe->window);
649 #if GTK_CHECK_VERSION(2,12,0)
650 gdk_event_request_motions(event);
652 gdk_window_get_pointer(widget->window, NULL, NULL, NULL);
658 static gint expose_area(GtkWidget *widget, GdkEventExpose *event,
661 frontend *fe = (frontend *)data;
664 gdk_draw_pixmap(widget->window,
665 widget->style->fg_gc[GTK_WIDGET_STATE(widget)],
667 event->area.x - fe->ox, event->area.y - fe->oy,
668 event->area.x, event->area.y,
669 event->area.width, event->area.height);
674 static gint map_window(GtkWidget *widget, GdkEvent *event,
677 frontend *fe = (frontend *)data;
680 * Apparently we need to do this because otherwise the status
681 * bar will fail to update immediately. Annoying, but there we
684 gtk_widget_queue_draw(fe->window);
689 static gint configure_area(GtkWidget *widget,
690 GdkEventConfigure *event, gpointer data)
692 frontend *fe = (frontend *)data;
697 gdk_pixmap_unref(fe->pixmap);
699 x = fe->w = event->width;
700 y = fe->h = event->height;
701 midend_size(fe->me, &x, &y, TRUE);
704 fe->ox = (fe->w - fe->pw) / 2;
705 fe->oy = (fe->h - fe->ph) / 2;
707 fe->pixmap = gdk_pixmap_new(widget->window, fe->pw, fe->ph, -1);
709 gc = gdk_gc_new(fe->area->window);
710 gdk_gc_set_foreground(gc, &fe->colours[0]);
711 gdk_draw_rectangle(fe->pixmap, gc, 1, 0, 0, fe->pw, fe->ph);
712 gdk_draw_rectangle(widget->window, gc, 1, 0, 0,
713 event->width, event->height);
716 midend_force_redraw(fe->me);
721 static gint timer_func(gpointer data)
723 frontend *fe = (frontend *)data;
725 if (fe->timer_active) {
728 gettimeofday(&now, NULL);
729 elapsed = ((now.tv_usec - fe->last_time.tv_usec) * 0.000001F +
730 (now.tv_sec - fe->last_time.tv_sec));
731 midend_timer(fe->me, elapsed); /* may clear timer_active */
735 return fe->timer_active;
738 void deactivate_timer(frontend *fe)
741 return; /* can happen due to --generate */
742 if (fe->timer_active)
743 gtk_timeout_remove(fe->timer_id);
744 fe->timer_active = FALSE;
747 void activate_timer(frontend *fe)
750 return; /* can happen due to --generate */
751 if (!fe->timer_active) {
752 fe->timer_id = gtk_timeout_add(20, timer_func, fe);
753 gettimeofday(&fe->last_time, NULL);
755 fe->timer_active = TRUE;
758 static void window_destroy(GtkWidget *widget, gpointer data)
763 static void msgbox_button_clicked(GtkButton *button, gpointer data)
765 GtkWidget *window = GTK_WIDGET(data);
768 ip = (int *)gtk_object_get_data(GTK_OBJECT(window), "user-data");
769 v = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(button), "user-data"));
772 gtk_widget_destroy(GTK_WIDGET(data));
775 static int win_key_press(GtkWidget *widget, GdkEventKey *event, gpointer data)
777 GtkObject *cancelbutton = GTK_OBJECT(data);
780 * `Escape' effectively clicks the cancel button
782 if (event->keyval == GDK_Escape) {
783 gtk_signal_emit_by_name(GTK_OBJECT(cancelbutton), "clicked");
790 enum { MB_OK, MB_YESNO };
792 int message_box(GtkWidget *parent, char *title, char *msg, int centre,
795 GtkWidget *window, *hbox, *text, *button;
799 window = gtk_dialog_new();
800 text = gtk_label_new(msg);
801 gtk_misc_set_alignment(GTK_MISC(text), 0.0, 0.0);
802 hbox = gtk_hbox_new(FALSE, 0);
803 gtk_box_pack_start(GTK_BOX(hbox), text, FALSE, FALSE, 20);
804 gtk_box_pack_start(GTK_BOX(GTK_DIALOG(window)->vbox),
805 hbox, FALSE, FALSE, 20);
806 gtk_widget_show(text);
807 gtk_widget_show(hbox);
808 gtk_window_set_title(GTK_WINDOW(window), title);
809 gtk_label_set_line_wrap(GTK_LABEL(text), TRUE);
815 assert(type == MB_YESNO);
816 titles = "Yes\0No\0";
823 button = gtk_button_new_with_label(titles);
824 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(window)->action_area),
825 button, FALSE, FALSE, 0);
826 gtk_widget_show(button);
828 GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
829 gtk_window_set_default(GTK_WINDOW(window), button);
832 gtk_signal_connect(GTK_OBJECT(window), "key_press_event",
833 GTK_SIGNAL_FUNC(win_key_press), button);
835 gtk_signal_connect(GTK_OBJECT(button), "clicked",
836 GTK_SIGNAL_FUNC(msgbox_button_clicked), window);
837 gtk_object_set_data(GTK_OBJECT(button), "user-data",
839 titles += strlen(titles)+1;
842 gtk_object_set_data(GTK_OBJECT(window), "user-data",
843 GINT_TO_POINTER(&i));
844 gtk_signal_connect(GTK_OBJECT(window), "destroy",
845 GTK_SIGNAL_FUNC(window_destroy), NULL);
846 gtk_window_set_modal(GTK_WINDOW(window), TRUE);
847 gtk_window_set_transient_for(GTK_WINDOW(window), GTK_WINDOW(parent));
848 /* set_transient_window_pos(parent, window); */
849 gtk_widget_show(window);
852 return (type == MB_YESNO ? i == 0 : TRUE);
855 void error_box(GtkWidget *parent, char *msg)
857 message_box(parent, "Error", msg, FALSE, MB_OK);
860 static void config_ok_button_clicked(GtkButton *button, gpointer data)
862 frontend *fe = (frontend *)data;
865 err = midend_set_config(fe->me, fe->cfg_which, fe->cfg);
868 error_box(fe->cfgbox, err);
871 gtk_widget_destroy(fe->cfgbox);
876 static void config_cancel_button_clicked(GtkButton *button, gpointer data)
878 frontend *fe = (frontend *)data;
880 gtk_widget_destroy(fe->cfgbox);
883 static int editbox_key(GtkWidget *widget, GdkEventKey *event, gpointer data)
886 * GtkEntry has a nasty habit of eating the Return key, which
887 * is unhelpful since it doesn't actually _do_ anything with it
888 * (it calls gtk_widget_activate, but our edit boxes never need
889 * activating). So I catch Return before GtkEntry sees it, and
890 * pass it straight on to the parent widget. Effect: hitting
891 * Return in an edit box will now activate the default button
892 * in the dialog just like it will everywhere else.
894 if (event->keyval == GDK_Return && widget->parent != NULL) {
896 gtk_signal_emit_stop_by_name(GTK_OBJECT(widget), "key_press_event");
897 gtk_signal_emit_by_name(GTK_OBJECT(widget->parent), "key_press_event",
904 static void editbox_changed(GtkEditable *ed, gpointer data)
906 config_item *i = (config_item *)data;
909 i->sval = dupstr(gtk_entry_get_text(GTK_ENTRY(ed)));
912 static void button_toggled(GtkToggleButton *tb, gpointer data)
914 config_item *i = (config_item *)data;
916 i->ival = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(tb));
919 static void droplist_sel(GtkMenuItem *item, gpointer data)
921 config_item *i = (config_item *)data;
923 i->ival = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(item),
927 static int get_config(frontend *fe, int which)
929 GtkWidget *w, *table, *cancel;
934 fe->cfg = midend_get_config(fe->me, which, &title);
935 fe->cfg_which = which;
938 fe->cfgbox = gtk_dialog_new();
939 gtk_window_set_title(GTK_WINDOW(fe->cfgbox), title);
942 w = gtk_button_new_with_label("OK");
943 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(fe->cfgbox)->action_area),
946 GTK_WIDGET_SET_FLAGS(w, GTK_CAN_DEFAULT);
947 gtk_window_set_default(GTK_WINDOW(fe->cfgbox), w);
948 gtk_signal_connect(GTK_OBJECT(w), "clicked",
949 GTK_SIGNAL_FUNC(config_ok_button_clicked), fe);
951 w = gtk_button_new_with_label("Cancel");
952 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(fe->cfgbox)->action_area),
955 gtk_signal_connect(GTK_OBJECT(w), "clicked",
956 GTK_SIGNAL_FUNC(config_cancel_button_clicked), fe);
959 table = gtk_table_new(1, 2, FALSE);
961 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(fe->cfgbox)->vbox),
962 table, FALSE, FALSE, 0);
963 gtk_widget_show(table);
965 for (i = fe->cfg; i->type != C_END; i++) {
966 gtk_table_resize(GTK_TABLE(table), y+1, 2);
971 * Edit box with a label beside it.
974 w = gtk_label_new(i->name);
975 gtk_misc_set_alignment(GTK_MISC(w), 0.0, 0.5);
976 gtk_table_attach(GTK_TABLE(table), w, 0, 1, y, y+1,
977 GTK_SHRINK | GTK_FILL,
978 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
983 gtk_table_attach(GTK_TABLE(table), w, 1, 2, y, y+1,
984 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
985 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
987 gtk_entry_set_text(GTK_ENTRY(w), i->sval);
988 gtk_signal_connect(GTK_OBJECT(w), "changed",
989 GTK_SIGNAL_FUNC(editbox_changed), i);
990 gtk_signal_connect(GTK_OBJECT(w), "key_press_event",
991 GTK_SIGNAL_FUNC(editbox_key), NULL);
1000 w = gtk_check_button_new_with_label(i->name);
1001 gtk_signal_connect(GTK_OBJECT(w), "toggled",
1002 GTK_SIGNAL_FUNC(button_toggled), i);
1003 gtk_table_attach(GTK_TABLE(table), w, 0, 2, y, y+1,
1004 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1005 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1007 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(w), i->ival);
1013 * Drop-down list (GtkOptionMenu).
1016 w = gtk_label_new(i->name);
1017 gtk_misc_set_alignment(GTK_MISC(w), 0.0, 0.5);
1018 gtk_table_attach(GTK_TABLE(table), w, 0, 1, y, y+1,
1019 GTK_SHRINK | GTK_FILL,
1020 GTK_EXPAND | GTK_SHRINK | GTK_FILL ,
1024 w = gtk_option_menu_new();
1025 gtk_table_attach(GTK_TABLE(table), w, 1, 2, y, y+1,
1026 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1027 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1034 GtkWidget *menuitem;
1035 GtkWidget *menu = gtk_menu_new();
1037 gtk_option_menu_set_menu(GTK_OPTION_MENU(w), menu);
1045 while (*q && *q != c)
1048 name = snewn(q-p+1, char);
1049 strncpy(name, p, q-p);
1052 if (*q) q++; /* eat delimiter */
1054 menuitem = gtk_menu_item_new_with_label(name);
1055 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1056 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1057 GINT_TO_POINTER(val));
1058 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1059 GTK_SIGNAL_FUNC(droplist_sel), i);
1060 gtk_widget_show(menuitem);
1067 gtk_option_menu_set_history(GTK_OPTION_MENU(w), i->ival);
1076 gtk_signal_connect(GTK_OBJECT(fe->cfgbox), "destroy",
1077 GTK_SIGNAL_FUNC(window_destroy), NULL);
1078 gtk_signal_connect(GTK_OBJECT(fe->cfgbox), "key_press_event",
1079 GTK_SIGNAL_FUNC(win_key_press), cancel);
1080 gtk_window_set_modal(GTK_WINDOW(fe->cfgbox), TRUE);
1081 gtk_window_set_transient_for(GTK_WINDOW(fe->cfgbox),
1082 GTK_WINDOW(fe->window));
1083 /* set_transient_window_pos(fe->window, fe->cfgbox); */
1084 gtk_widget_show(fe->cfgbox);
1092 static void menu_key_event(GtkMenuItem *menuitem, gpointer data)
1094 frontend *fe = (frontend *)data;
1095 int key = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(menuitem),
1097 if (!midend_process_key(fe->me, 0, 0, key))
1098 gtk_widget_destroy(fe->window);
1101 static void get_size(frontend *fe, int *px, int *py)
1106 * Currently I don't want to make the GTK port scale large
1107 * puzzles to fit on the screen. This is because X does permit
1108 * extremely large windows and many window managers provide a
1109 * means of navigating round them, and the users I consulted
1110 * before deciding said that they'd rather have enormous puzzle
1111 * windows spanning multiple screen pages than have them
1112 * shrunk. I could change my mind later or introduce
1113 * configurability; this would be the place to do so, by
1114 * replacing the initial values of x and y with the screen
1119 midend_size(fe->me, &x, &y, FALSE);
1124 #if !GTK_CHECK_VERSION(2,0,0)
1125 #define gtk_window_resize(win, x, y) \
1126 gdk_window_resize(GTK_WIDGET(win)->window, x, y)
1129 static void update_menuitem_bullet(GtkWidget *label, int visible)
1132 gtk_label_set_text(GTK_LABEL(label), "\xE2\x80\xA2");
1134 gtk_label_set_text(GTK_LABEL(label), "");
1139 * Called when any other code in this file has changed the
1140 * selected game parameters.
1142 static void changed_preset(frontend *fe)
1144 int n = midend_which_preset(fe->me);
1148 * Update the tick mark in the Type menu.
1150 if (fe->preset_bullets) {
1151 for (i = 0; i < fe->npresets; i++)
1152 update_menuitem_bullet(fe->preset_bullets[i], n == i);
1154 if (fe->preset_custom_bullet) {
1155 update_menuitem_bullet(fe->preset_custom_bullet, n < 0);
1159 * Update the greying on the Copy menu option.
1161 if (fe->copy_menu_item) {
1162 int enabled = midend_can_format_as_text_now(fe->me);
1163 gtk_widget_set_sensitive(fe->copy_menu_item, enabled);
1167 static void resize_fe(frontend *fe)
1171 get_size(fe, &x, &y);
1174 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
1177 gtk_widget_size_request(GTK_WIDGET(fe->window), &req);
1178 gtk_window_resize(GTK_WINDOW(fe->window), req.width, req.height);
1181 * Now that we've established the preferred size of the window,
1182 * reduce the drawing area's size request so the user can shrink
1185 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), 1, 1);
1188 static void menu_preset_event(GtkMenuItem *menuitem, gpointer data)
1190 frontend *fe = (frontend *)data;
1191 game_params *params =
1192 (game_params *)gtk_object_get_data(GTK_OBJECT(menuitem), "user-data");
1194 midend_set_params(fe->me, params);
1195 midend_new_game(fe->me);
1200 GdkAtom compound_text_atom, utf8_string_atom;
1201 int paste_initialised = FALSE;
1205 unsigned char empty[] = { 0 };
1207 if (paste_initialised)
1210 if (!compound_text_atom)
1211 compound_text_atom = gdk_atom_intern("COMPOUND_TEXT", FALSE);
1212 if (!utf8_string_atom)
1213 utf8_string_atom = gdk_atom_intern("UTF8_STRING", FALSE);
1216 * Ensure that all the cut buffers exist - according to the
1217 * ICCCM, we must do this before we start using cut buffers.
1219 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1220 XA_CUT_BUFFER0, XA_STRING, 8, PropModeAppend, empty, 0);
1221 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1222 XA_CUT_BUFFER1, XA_STRING, 8, PropModeAppend, empty, 0);
1223 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1224 XA_CUT_BUFFER2, XA_STRING, 8, PropModeAppend, empty, 0);
1225 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1226 XA_CUT_BUFFER3, XA_STRING, 8, PropModeAppend, empty, 0);
1227 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1228 XA_CUT_BUFFER4, XA_STRING, 8, PropModeAppend, empty, 0);
1229 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1230 XA_CUT_BUFFER5, XA_STRING, 8, PropModeAppend, empty, 0);
1231 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1232 XA_CUT_BUFFER6, XA_STRING, 8, PropModeAppend, empty, 0);
1233 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1234 XA_CUT_BUFFER7, XA_STRING, 8, PropModeAppend, empty, 0);
1237 /* Store data in a cut-buffer. */
1238 void store_cutbuffer(char *ptr, int len)
1240 /* ICCCM says we must rotate the buffers before storing to buffer 0. */
1241 XRotateBuffers(GDK_DISPLAY(), 1);
1242 XStoreBytes(GDK_DISPLAY(), ptr, len);
1245 void write_clip(frontend *fe, char *data)
1250 sfree(fe->paste_data);
1253 * For this simple application we can safely assume that the
1254 * data passed to this function is pure ASCII, which means we
1255 * can return precisely the same stuff for types STRING,
1256 * COMPOUND_TEXT or UTF8_STRING.
1259 fe->paste_data = data;
1260 fe->paste_data_len = strlen(data);
1262 store_cutbuffer(fe->paste_data, fe->paste_data_len);
1264 if (gtk_selection_owner_set(fe->area, GDK_SELECTION_PRIMARY,
1266 gtk_selection_clear_targets(fe->area, GDK_SELECTION_PRIMARY);
1267 gtk_selection_add_target(fe->area, GDK_SELECTION_PRIMARY,
1268 GDK_SELECTION_TYPE_STRING, 1);
1269 gtk_selection_add_target(fe->area, GDK_SELECTION_PRIMARY,
1270 compound_text_atom, 1);
1271 gtk_selection_add_target(fe->area, GDK_SELECTION_PRIMARY,
1272 utf8_string_atom, 1);
1276 void selection_get(GtkWidget *widget, GtkSelectionData *seldata,
1277 guint info, guint time_stamp, gpointer data)
1279 frontend *fe = (frontend *)data;
1280 gtk_selection_data_set(seldata, seldata->target, 8,
1281 fe->paste_data, fe->paste_data_len);
1284 gint selection_clear(GtkWidget *widget, GdkEventSelection *seldata,
1287 frontend *fe = (frontend *)data;
1290 sfree(fe->paste_data);
1291 fe->paste_data = NULL;
1292 fe->paste_data_len = 0;
1296 static void menu_copy_event(GtkMenuItem *menuitem, gpointer data)
1298 frontend *fe = (frontend *)data;
1301 text = midend_text_format(fe->me);
1304 write_clip(fe, text);
1312 static void filesel_ok(GtkButton *button, gpointer data)
1314 frontend *fe = (frontend *)data;
1316 gpointer filesel = gtk_object_get_data(GTK_OBJECT(button), "user-data");
1319 gtk_file_selection_get_filename(GTK_FILE_SELECTION(filesel));
1321 fe->filesel_name = dupstr(name);
1324 static char *file_selector(frontend *fe, char *title, int save)
1326 GtkWidget *filesel =
1327 gtk_file_selection_new(title);
1329 fe->filesel_name = NULL;
1331 gtk_window_set_modal(GTK_WINDOW(filesel), TRUE);
1333 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "user-data",
1336 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "clicked",
1337 GTK_SIGNAL_FUNC(filesel_ok), fe);
1338 gtk_signal_connect_object
1339 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "clicked",
1340 GTK_SIGNAL_FUNC(gtk_widget_destroy), (gpointer)filesel);
1341 gtk_signal_connect_object
1342 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->cancel_button), "clicked",
1343 GTK_SIGNAL_FUNC(gtk_widget_destroy), (gpointer)filesel);
1344 gtk_signal_connect(GTK_OBJECT(filesel), "destroy",
1345 GTK_SIGNAL_FUNC(window_destroy), NULL);
1346 gtk_widget_show(filesel);
1347 gtk_window_set_transient_for(GTK_WINDOW(filesel), GTK_WINDOW(fe->window));
1350 return fe->filesel_name;
1355 static char *file_selector(frontend *fe, char *title, int save)
1357 char *filesel_name = NULL;
1359 GtkWidget *filesel =
1360 gtk_file_chooser_dialog_new(title,
1361 GTK_WINDOW(fe->window),
1362 save ? GTK_FILE_CHOOSER_ACTION_SAVE :
1363 GTK_FILE_CHOOSER_ACTION_OPEN,
1364 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
1365 save ? GTK_STOCK_SAVE : GTK_STOCK_OPEN,
1366 GTK_RESPONSE_ACCEPT,
1369 if (gtk_dialog_run(GTK_DIALOG(filesel)) == GTK_RESPONSE_ACCEPT) {
1370 const char *name = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(filesel));
1371 filesel_name = dupstr(name);
1374 gtk_widget_destroy(filesel);
1376 return filesel_name;
1381 struct savefile_write_ctx {
1386 static void savefile_write(void *wctx, void *buf, int len)
1388 struct savefile_write_ctx *ctx = (struct savefile_write_ctx *)wctx;
1389 if (fwrite(buf, 1, len, ctx->fp) < len)
1393 static int savefile_read(void *wctx, void *buf, int len)
1395 FILE *fp = (FILE *)wctx;
1398 ret = fread(buf, 1, len, fp);
1399 return (ret == len);
1402 static void menu_save_event(GtkMenuItem *menuitem, gpointer data)
1404 frontend *fe = (frontend *)data;
1407 name = file_selector(fe, "Enter name of game file to save", TRUE);
1412 if ((fp = fopen(name, "r")) != NULL) {
1413 char buf[256 + FILENAME_MAX];
1417 sprintf(buf, "Are you sure you want to overwrite the"
1419 FILENAME_MAX, name);
1420 if (!message_box(fe->window, "Question", buf, TRUE, MB_YESNO))
1424 fp = fopen(name, "w");
1428 error_box(fe->window, "Unable to open save file");
1433 struct savefile_write_ctx ctx;
1436 midend_serialise(fe->me, savefile_write, &ctx);
1440 sprintf(boxmsg, "Error writing save file: %.400s",
1442 error_box(fe->window, boxmsg);
1450 static void menu_load_event(GtkMenuItem *menuitem, gpointer data)
1452 frontend *fe = (frontend *)data;
1455 name = file_selector(fe, "Enter name of saved game file to load", FALSE);
1458 FILE *fp = fopen(name, "r");
1462 error_box(fe->window, "Unable to open saved game file");
1466 err = midend_deserialise(fe->me, savefile_read, fp);
1471 error_box(fe->window, err);
1480 static void menu_solve_event(GtkMenuItem *menuitem, gpointer data)
1482 frontend *fe = (frontend *)data;
1485 msg = midend_solve(fe->me);
1488 error_box(fe->window, msg);
1491 static void menu_restart_event(GtkMenuItem *menuitem, gpointer data)
1493 frontend *fe = (frontend *)data;
1495 midend_restart_game(fe->me);
1498 static void menu_config_event(GtkMenuItem *menuitem, gpointer data)
1500 frontend *fe = (frontend *)data;
1501 int which = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(menuitem),
1504 if (!get_config(fe, which))
1507 midend_new_game(fe->me);
1511 static void menu_about_event(GtkMenuItem *menuitem, gpointer data)
1513 frontend *fe = (frontend *)data;
1517 sprintf(titlebuf, "About %.200s", thegame.name);
1520 "from Simon Tatham's Portable Puzzle Collection\n\n"
1521 "%.500s", thegame.name, ver);
1523 message_box(fe->window, titlebuf, textbuf, TRUE, MB_OK);
1526 static GtkWidget *add_menu_item_with_key(frontend *fe, GtkContainer *cont,
1527 char *text, int key)
1529 GtkWidget *menuitem = gtk_menu_item_new_with_label(text);
1531 gtk_container_add(cont, menuitem);
1532 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1533 GINT_TO_POINTER(key));
1534 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1535 GTK_SIGNAL_FUNC(menu_key_event), fe);
1536 switch (key & ~0x1F) {
1539 keyqual = GDK_CONTROL_MASK;
1543 keyqual = GDK_SHIFT_MASK;
1549 gtk_widget_add_accelerator(menuitem,
1550 "activate", fe->accelgroup,
1553 gtk_widget_show(menuitem);
1557 static void add_menu_separator(GtkContainer *cont)
1559 GtkWidget *menuitem = gtk_menu_item_new();
1560 gtk_container_add(cont, menuitem);
1561 gtk_widget_show(menuitem);
1564 enum { ARG_EITHER, ARG_SAVE, ARG_ID }; /* for argtype */
1566 static GtkWidget *make_preset_menuitem(GtkWidget **bulletlabel,
1569 GtkWidget *hbox, *lab1, *lab2, *menuitem;
1572 hbox = gtk_hbox_new(FALSE, 0);
1573 gtk_widget_show(hbox);
1574 lab1 = gtk_label_new("\xE2\x80\xA2 ");
1575 gtk_widget_show(lab1);
1576 gtk_box_pack_start(GTK_BOX(hbox), lab1, FALSE, FALSE, 0);
1577 gtk_misc_set_alignment(GTK_MISC(lab1), 0.0, 0.0);
1578 lab2 = gtk_label_new(name);
1579 gtk_widget_show(lab2);
1580 gtk_box_pack_start(GTK_BOX(hbox), lab2, TRUE, TRUE, 0);
1581 gtk_misc_set_alignment(GTK_MISC(lab2), 0.0, 0.0);
1583 gtk_widget_size_request(lab1, &req);
1584 gtk_widget_set_usize(lab1, req.width, -1);
1585 gtk_label_set_text(GTK_LABEL(lab1), "");
1587 menuitem = gtk_menu_item_new();
1588 gtk_container_add(GTK_CONTAINER(menuitem), hbox);
1590 *bulletlabel = lab1;
1594 static frontend *new_window(char *arg, int argtype, char **error)
1598 GtkWidget *menubar, *menu, *menuitem;
1603 extern char *const *const xpm_icons[];
1604 extern const int n_xpm_icons;
1606 fe = snew(frontend);
1608 fe->timer_active = FALSE;
1611 fe->me = midend_new(fe, &thegame, >k_drawing, fe);
1621 err = midend_game_id(fe->me, arg);
1623 midend_new_game(fe->me);
1625 sprintf(errbuf, "Invalid game ID: %.800s", err);
1628 fp = fopen(arg, "r");
1630 sprintf(errbuf, "Error opening file: %.800s", strerror(errno));
1632 err = midend_deserialise(fe->me, savefile_read, fp);
1634 sprintf(errbuf, "Invalid save file: %.800s", err);
1638 default /*case ARG_EITHER*/:
1640 * First try treating the argument as a game ID.
1642 err = midend_game_id(fe->me, arg);
1645 * It's a valid game ID.
1647 midend_new_game(fe->me);
1649 FILE *fp = fopen(arg, "r");
1651 sprintf(errbuf, "Supplied argument is neither a game ID (%.400s)"
1652 " nor a save file (%.400s)", err, strerror(errno));
1654 err = midend_deserialise(fe->me, savefile_read, fp);
1656 sprintf(errbuf, "%.800s", err);
1663 *error = dupstr(errbuf);
1664 midend_free(fe->me);
1670 midend_new_game(fe->me);
1673 fe->window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1674 gtk_window_set_title(GTK_WINDOW(fe->window), thegame.name);
1676 vbox = GTK_BOX(gtk_vbox_new(FALSE, 0));
1677 gtk_container_add(GTK_CONTAINER(fe->window), GTK_WIDGET(vbox));
1678 gtk_widget_show(GTK_WIDGET(vbox));
1680 fe->accelgroup = gtk_accel_group_new();
1681 gtk_window_add_accel_group(GTK_WINDOW(fe->window), fe->accelgroup);
1683 menubar = gtk_menu_bar_new();
1684 gtk_box_pack_start(vbox, menubar, FALSE, FALSE, 0);
1685 gtk_widget_show(menubar);
1687 menuitem = gtk_menu_item_new_with_mnemonic("_Game");
1688 gtk_container_add(GTK_CONTAINER(menubar), menuitem);
1689 gtk_widget_show(menuitem);
1691 menu = gtk_menu_new();
1692 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
1694 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "New", 'n');
1696 menuitem = gtk_menu_item_new_with_label("Restart");
1697 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1698 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1699 GTK_SIGNAL_FUNC(menu_restart_event), fe);
1700 gtk_widget_show(menuitem);
1702 menuitem = gtk_menu_item_new_with_label("Specific...");
1703 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1704 GINT_TO_POINTER(CFG_DESC));
1705 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1706 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1707 GTK_SIGNAL_FUNC(menu_config_event), fe);
1708 gtk_widget_show(menuitem);
1710 menuitem = gtk_menu_item_new_with_label("Random Seed...");
1711 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1712 GINT_TO_POINTER(CFG_SEED));
1713 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1714 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1715 GTK_SIGNAL_FUNC(menu_config_event), fe);
1716 gtk_widget_show(menuitem);
1718 if ((n = midend_num_presets(fe->me)) > 0 || thegame.can_configure) {
1722 menuitem = gtk_menu_item_new_with_mnemonic("_Type");
1723 gtk_container_add(GTK_CONTAINER(menubar), menuitem);
1724 gtk_widget_show(menuitem);
1726 submenu = gtk_menu_new();
1727 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), submenu);
1730 fe->preset_bullets = snewn(n, GtkWidget *);
1732 for (i = 0; i < n; i++) {
1734 game_params *params;
1736 midend_fetch_preset(fe->me, i, &name, ¶ms);
1738 menuitem = make_preset_menuitem(&fe->preset_bullets[i], name);
1740 gtk_container_add(GTK_CONTAINER(submenu), menuitem);
1741 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data", params);
1742 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1743 GTK_SIGNAL_FUNC(menu_preset_event), fe);
1744 gtk_widget_show(menuitem);
1747 if (thegame.can_configure) {
1748 menuitem = make_preset_menuitem(&fe->preset_custom_bullet,
1751 gtk_container_add(GTK_CONTAINER(submenu), menuitem);
1752 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1753 GPOINTER_TO_INT(CFG_SETTINGS));
1754 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1755 GTK_SIGNAL_FUNC(menu_config_event), fe);
1756 gtk_widget_show(menuitem);
1758 fe->preset_custom_bullet = NULL;
1762 fe->preset_bullets = NULL;
1763 fe->preset_custom_bullet = NULL;
1766 add_menu_separator(GTK_CONTAINER(menu));
1767 menuitem = gtk_menu_item_new_with_label("Load...");
1768 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1769 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1770 GTK_SIGNAL_FUNC(menu_load_event), fe);
1771 gtk_widget_show(menuitem);
1772 menuitem = gtk_menu_item_new_with_label("Save...");
1773 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1774 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1775 GTK_SIGNAL_FUNC(menu_save_event), fe);
1776 gtk_widget_show(menuitem);
1777 add_menu_separator(GTK_CONTAINER(menu));
1778 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Undo", 'u');
1779 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Redo", 'r');
1780 if (thegame.can_format_as_text_ever) {
1781 add_menu_separator(GTK_CONTAINER(menu));
1782 menuitem = gtk_menu_item_new_with_label("Copy");
1783 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1784 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1785 GTK_SIGNAL_FUNC(menu_copy_event), fe);
1786 gtk_widget_show(menuitem);
1787 fe->copy_menu_item = menuitem;
1789 fe->copy_menu_item = NULL;
1791 if (thegame.can_solve) {
1792 add_menu_separator(GTK_CONTAINER(menu));
1793 menuitem = gtk_menu_item_new_with_label("Solve");
1794 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1795 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1796 GTK_SIGNAL_FUNC(menu_solve_event), fe);
1797 gtk_widget_show(menuitem);
1799 add_menu_separator(GTK_CONTAINER(menu));
1800 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Exit", 'q');
1802 menuitem = gtk_menu_item_new_with_mnemonic("_Help");
1803 gtk_container_add(GTK_CONTAINER(menubar), menuitem);
1804 gtk_widget_show(menuitem);
1806 menu = gtk_menu_new();
1807 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
1809 menuitem = gtk_menu_item_new_with_label("About");
1810 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1811 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1812 GTK_SIGNAL_FUNC(menu_about_event), fe);
1813 gtk_widget_show(menuitem);
1822 fe->colmap = gdk_colormap_get_system();
1823 colours = midend_colours(fe->me, &ncolours);
1824 fe->ncolours = ncolours;
1825 fe->colours = snewn(ncolours, GdkColor);
1826 for (i = 0; i < ncolours; i++) {
1827 fe->colours[i].red = colours[i*3] * 0xFFFF;
1828 fe->colours[i].green = colours[i*3+1] * 0xFFFF;
1829 fe->colours[i].blue = colours[i*3+2] * 0xFFFF;
1831 success = snewn(ncolours, gboolean);
1832 gdk_colormap_alloc_colors(fe->colmap, fe->colours, ncolours,
1833 FALSE, FALSE, success);
1834 for (i = 0; i < ncolours; i++) {
1836 g_error("couldn't allocate colour %d (#%02x%02x%02x)\n",
1837 i, fe->colours[i].red >> 8,
1838 fe->colours[i].green >> 8,
1839 fe->colours[i].blue >> 8);
1844 if (midend_wants_statusbar(fe->me)) {
1845 GtkWidget *viewport;
1848 viewport = gtk_viewport_new(NULL, NULL);
1849 gtk_viewport_set_shadow_type(GTK_VIEWPORT(viewport), GTK_SHADOW_NONE);
1850 fe->statusbar = gtk_statusbar_new();
1851 gtk_container_add(GTK_CONTAINER(viewport), fe->statusbar);
1852 gtk_widget_show(viewport);
1853 gtk_box_pack_end(vbox, viewport, FALSE, FALSE, 0);
1854 gtk_widget_show(fe->statusbar);
1855 fe->statusctx = gtk_statusbar_get_context_id
1856 (GTK_STATUSBAR(fe->statusbar), "game");
1857 gtk_statusbar_push(GTK_STATUSBAR(fe->statusbar), fe->statusctx,
1859 gtk_widget_size_request(fe->statusbar, &req);
1861 /* For GTK 2.0, should we be using gtk_widget_set_size_request? */
1863 gtk_widget_set_usize(viewport, -1, req.height);
1865 fe->statusbar = NULL;
1867 fe->area = gtk_drawing_area_new();
1868 get_size(fe, &x, &y);
1869 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
1873 gtk_box_pack_end(vbox, fe->area, TRUE, TRUE, 0);
1877 fe->nfonts = fe->fontsize = 0;
1879 fe->paste_data = NULL;
1880 fe->paste_data_len = 0;
1882 gtk_signal_connect(GTK_OBJECT(fe->window), "destroy",
1883 GTK_SIGNAL_FUNC(destroy), fe);
1884 gtk_signal_connect(GTK_OBJECT(fe->window), "key_press_event",
1885 GTK_SIGNAL_FUNC(key_event), fe);
1886 gtk_signal_connect(GTK_OBJECT(fe->area), "button_press_event",
1887 GTK_SIGNAL_FUNC(button_event), fe);
1888 gtk_signal_connect(GTK_OBJECT(fe->area), "button_release_event",
1889 GTK_SIGNAL_FUNC(button_event), fe);
1890 gtk_signal_connect(GTK_OBJECT(fe->area), "motion_notify_event",
1891 GTK_SIGNAL_FUNC(motion_event), fe);
1892 gtk_signal_connect(GTK_OBJECT(fe->area), "selection_get",
1893 GTK_SIGNAL_FUNC(selection_get), fe);
1894 gtk_signal_connect(GTK_OBJECT(fe->area), "selection_clear_event",
1895 GTK_SIGNAL_FUNC(selection_clear), fe);
1896 gtk_signal_connect(GTK_OBJECT(fe->area), "expose_event",
1897 GTK_SIGNAL_FUNC(expose_area), fe);
1898 gtk_signal_connect(GTK_OBJECT(fe->window), "map_event",
1899 GTK_SIGNAL_FUNC(map_window), fe);
1900 gtk_signal_connect(GTK_OBJECT(fe->area), "configure_event",
1901 GTK_SIGNAL_FUNC(configure_area), fe);
1903 gtk_widget_add_events(GTK_WIDGET(fe->area),
1904 GDK_BUTTON_PRESS_MASK |
1905 GDK_BUTTON_RELEASE_MASK |
1906 GDK_BUTTON_MOTION_MASK |
1907 GDK_POINTER_MOTION_HINT_MASK);
1910 gtk_widget_realize(fe->window);
1911 iconpm = gdk_pixmap_create_from_xpm_d(fe->window->window, NULL,
1912 NULL, (gchar **)xpm_icons[0]);
1913 gdk_window_set_icon(fe->window->window, NULL, iconpm, NULL);
1915 for (n = 0; n < n_xpm_icons; n++) {
1917 g_list_append(iconlist,
1918 gdk_pixbuf_new_from_xpm_data((const gchar **)
1921 gdk_window_set_icon_list(fe->window->window, iconlist);
1924 gtk_widget_show(fe->area);
1925 gtk_widget_show(fe->window);
1928 * Now that we've established the preferred size of the window,
1929 * reduce the drawing area's size request so the user can shrink
1932 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), 1, 1);
1934 gdk_window_set_background(fe->area->window, &fe->colours[0]);
1935 gdk_window_set_background(fe->window->window, &fe->colours[0]);
1940 char *fgetline(FILE *fp)
1942 char *ret = snewn(512, char);
1943 int size = 512, len = 0;
1944 while (fgets(ret + len, size - len, fp)) {
1945 len += strlen(ret + len);
1946 if (ret[len-1] == '\n')
1947 break; /* got a newline, we're done */
1949 ret = sresize(ret, size, char);
1951 if (len == 0) { /* first fgets returned NULL */
1959 int main(int argc, char **argv)
1961 char *pname = argv[0];
1963 int ngenerate = 0, print = FALSE, px = 1, py = 1;
1964 int soln = FALSE, colour = FALSE;
1966 float redo_proportion = 0.0F;
1967 char *savefile = NULL, *savesuffix = NULL;
1969 int argtype = ARG_EITHER;
1970 char *screenshot_file = NULL;
1971 int doing_opts = TRUE;
1977 * Command line parsing in this function is rather fiddly,
1978 * because GTK wants to have a go at argc/argv _first_ - and
1979 * yet we can't let it, because gtk_init() will bomb out if it
1980 * can't open an X display, whereas in fact we want to permit
1981 * our --generate and --print modes to run without an X
1985 * - we parse the command line ourselves, without modifying
1987 * - if we encounter an error which might plausibly be the
1988 * result of a GTK command line (i.e. not detailed errors in
1989 * particular options of ours) we store the error message
1990 * and terminate parsing.
1991 * - if we got enough out of the command line to know it
1992 * specifies a non-X mode of operation, we either display
1993 * the stored error and return failure, or if there is no
1994 * stored error we do the non-X operation and return
1996 * - otherwise, we go straight to gtk_init().
2002 if (doing_opts && !strcmp(p, "--version")) {
2003 printf("%s, from Simon Tatham's Portable Puzzle Collection\n%s\n",
2006 } else if (doing_opts && !strcmp(p, "--generate")) {
2008 ngenerate = atoi(*++av);
2010 fprintf(stderr, "%s: '--generate' expected a number\n",
2016 } else if (doing_opts && !strcmp(p, "--save")) {
2020 fprintf(stderr, "%s: '--save' expected a filename\n",
2024 } else if (doing_opts && (!strcmp(p, "--save-suffix") ||
2025 !strcmp(p, "--savesuffix"))) {
2029 fprintf(stderr, "%s: '--save-suffix' expected a filename\n",
2033 } else if (doing_opts && !strcmp(p, "--print")) {
2034 if (!thegame.can_print) {
2035 fprintf(stderr, "%s: this game does not support printing\n",
2042 if (sscanf(dim, "%dx%d", &px, &py) != 2) {
2043 fprintf(stderr, "%s: unable to parse argument '%s' to "
2044 "'--print'\n", pname, dim);
2050 } else if (doing_opts && !strcmp(p, "--scale")) {
2052 scale = atof(*++av);
2054 fprintf(stderr, "%s: no argument supplied to '--scale'\n",
2058 } else if (doing_opts && !strcmp(p, "--redo")) {
2060 * This is an internal option which I don't expect
2061 * users to have any particular use for. The effect of
2062 * --redo is that once the game has been loaded and
2063 * initialised, the next move in the redo chain is
2064 * replayed, and the game screen is redrawn part way
2065 * through the making of the move. This is only
2066 * meaningful if there _is_ a next move in the redo
2067 * chain, which means in turn that this option is only
2068 * useful if you're also passing a save file on the
2071 * This option is used by the script which generates
2072 * the puzzle icons and website screenshots, and I
2073 * don't imagine it's useful for anything else.
2074 * (Unless, I suppose, users don't like my screenshots
2075 * and want to generate their own in the same way for
2076 * some repackaged version of the puzzles.)
2079 redo_proportion = atof(*++av);
2081 fprintf(stderr, "%s: no argument supplied to '--redo'\n",
2085 } else if (doing_opts && !strcmp(p, "--screenshot")) {
2087 * Another internal option for the icon building
2088 * script. This causes a screenshot of the central
2089 * drawing area (i.e. not including the menu bar or
2090 * status bar) to be saved to a PNG file once the
2091 * window has been drawn, and then the application
2092 * quits immediately.
2095 screenshot_file = *++av;
2097 fprintf(stderr, "%s: no argument supplied to '--screenshot'\n",
2101 } else if (doing_opts && (!strcmp(p, "--with-solutions") ||
2102 !strcmp(p, "--with-solution") ||
2103 !strcmp(p, "--with-solns") ||
2104 !strcmp(p, "--with-soln") ||
2105 !strcmp(p, "--solutions") ||
2106 !strcmp(p, "--solution") ||
2107 !strcmp(p, "--solns") ||
2108 !strcmp(p, "--soln"))) {
2110 } else if (doing_opts && !strcmp(p, "--colour")) {
2111 if (!thegame.can_print_in_colour) {
2112 fprintf(stderr, "%s: this game does not support colour"
2113 " printing\n", pname);
2117 } else if (doing_opts && !strcmp(p, "--load")) {
2119 } else if (doing_opts && !strcmp(p, "--game")) {
2121 } else if (doing_opts && !strcmp(p, "--")) {
2123 } else if (!doing_opts || p[0] != '-') {
2125 fprintf(stderr, "%s: more than one argument supplied\n",
2131 sprintf(errbuf, "%.100s: unrecognised option '%.100s'\n",
2138 fputs(errbuf, stderr);
2143 * Special standalone mode for generating puzzle IDs on the
2144 * command line. Useful for generating puzzles to be printed
2145 * out and solved offline (for puzzles where that even makes
2146 * sense - Solo, for example, is a lot more pencil-and-paper
2147 * friendly than Twiddle!)
2151 * <puzzle-name> --generate [<n> [<params>]]
2153 * <n>, if present, is the number of puzzle IDs to generate.
2154 * <params>, if present, is the same type of parameter string
2155 * you would pass to the puzzle when running it in GUI mode,
2156 * including optional extras such as the expansion factor in
2157 * Rectangles and the difficulty level in Solo.
2159 * If you specify <params>, you must also specify <n> (although
2160 * you may specify it to be 1). Sorry; that was the
2161 * simplest-to-parse command-line syntax I came up with.
2163 if (ngenerate > 0 || print || savefile || savesuffix) {
2167 document *doc = NULL;
2171 me = midend_new(NULL, &thegame, NULL, NULL);
2174 if (savefile && !savesuffix)
2176 if (!savefile && savesuffix)
2180 doc = document_new(px, py, scale);
2183 * In this loop, we either generate a game ID or read one
2184 * from stdin depending on whether we're in generate mode;
2185 * then we either write it to stdout or print it, depending
2186 * on whether we're in print mode. Thus, this loop handles
2187 * generate-to-stdout, print-from-stdin and generate-and-
2188 * immediately-print modes.
2190 * (It could also handle a copy-stdin-to-stdout mode,
2191 * although there's currently no combination of options
2192 * which will cause this loop to be activated in that mode.
2193 * It wouldn't be _entirely_ pointless, though, because
2194 * stdin could contain bare params strings or random-seed
2195 * IDs, and stdout would contain nothing but fully
2196 * generated descriptive game IDs.)
2198 while (ngenerate == 0 || i < n) {
2201 if (ngenerate == 0) {
2202 pstr = fgetline(stdin);
2205 pstr[strcspn(pstr, "\r\n")] = '\0';
2208 pstr = snewn(strlen(arg) + 40, char);
2211 if (i > 0 && strchr(arg, '#'))
2212 sprintf(pstr + strlen(pstr), "-%d", i);
2218 err = midend_game_id(me, pstr);
2220 fprintf(stderr, "%s: error parsing '%s': %s\n",
2227 midend_new_game(me);
2230 err = midend_print_puzzle(me, doc, soln);
2232 fprintf(stderr, "%s: error in printing: %s\n", pname, err);
2237 struct savefile_write_ctx ctx;
2238 char *realname = snewn(40 + strlen(savefile) +
2239 strlen(savesuffix), char);
2240 sprintf(realname, "%s%d%s", savefile, i, savesuffix);
2241 ctx.fp = fopen(realname, "w");
2243 fprintf(stderr, "%s: open: %s\n", realname,
2248 midend_serialise(me, savefile_write, &ctx);
2250 fprintf(stderr, "%s: write: %s\n", realname,
2251 strerror(ctx.error));
2254 if (fclose(ctx.fp)) {
2255 fprintf(stderr, "%s: close: %s\n", realname,
2260 if (!doc && !savefile) {
2261 id = midend_get_game_id(me);
2270 psdata *ps = ps_init(stdout, colour);
2271 document_print(doc, ps_drawing_api(ps));
2282 gtk_init(&argc, &argv);
2284 fe = new_window(arg, argtype, &error);
2287 fprintf(stderr, "%s: %s\n", pname, error);
2291 if (screenshot_file) {
2293 * Some puzzles will not redraw their entire area if
2294 * given a partially completed animation, which means
2295 * we must redraw now and _then_ redraw again after
2296 * freezing the move timer.
2298 midend_force_redraw(fe->me);
2301 if (redo_proportion) {
2303 midend_process_key(fe->me, 0, 0, 'r');
2304 /* And freeze the timer at the specified position. */
2305 midend_freeze_timer(fe->me, redo_proportion);
2308 if (screenshot_file) {
2310 GError *gerror = NULL;
2312 midend_redraw(fe->me);
2314 pb = gdk_pixbuf_get_from_drawable(NULL, fe->pixmap,
2315 NULL, 0, 0, 0, 0, -1, -1);
2316 gdk_pixbuf_save(pb, screenshot_file, "png", &gerror, NULL);