Patch from James H to provide resizability on Windows.
[sgt/puzzles] / gtk.c
CommitLineData
720a8fb7 1/*
2 * gtk.c: GTK front end for my puzzle collection.
3 */
4
5#include <stdio.h>
fd1a1a2b 6#include <assert.h>
720a8fb7 7#include <stdlib.h>
2ef96bd6 8#include <time.h>
720a8fb7 9#include <stdarg.h>
c8230524 10#include <string.h>
dafd6cf6 11#include <errno.h>
720a8fb7 12
8c1fd974 13#include <sys/time.h>
14
83680571 15#include <gtk/gtk.h>
1482ee76 16#include <gdk/gdkkeysyms.h>
83680571 17
f12cdd72 18#include <gdk-pixbuf/gdk-pixbuf.h>
19
a9668451 20#include <gdk/gdkx.h>
21#include <X11/Xlib.h>
9b4b03d3 22#include <X11/Xutil.h>
23#include <X11/Xatom.h>
a9668451 24
720a8fb7 25#include "puzzles.h"
26
1fad7a3b 27#if GTK_CHECK_VERSION(2,0,0)
28#define USE_PANGO
29#endif
30
81ff8295 31#ifdef DEBUGGING
32static FILE *debug_fp = NULL;
33
34void dputs(char *buf)
35{
36 if (!debug_fp) {
37 debug_fp = fopen("debug.log", "w");
38 }
39
40 fputs(buf, stderr);
41
42 if (debug_fp) {
43 fputs(buf, debug_fp);
44 fflush(debug_fp);
45 }
46}
47
48void debug_printf(char *fmt, ...)
49{
50 char buf[4096];
51 va_list ap;
52
53 va_start(ap, fmt);
54 vsprintf(buf, fmt, ap);
55 dputs(buf);
56 va_end(ap);
57}
58#endif
59
83680571 60/* ----------------------------------------------------------------------
61 * Error reporting functions used elsewhere.
62 */
63
720a8fb7 64void fatal(char *fmt, ...)
65{
66 va_list ap;
67
68 fprintf(stderr, "fatal error: ");
69
70 va_start(ap, fmt);
71 vfprintf(stderr, fmt, ap);
72 va_end(ap);
73
74 fprintf(stderr, "\n");
75 exit(1);
76}
83680571 77
78/* ----------------------------------------------------------------------
79 * GTK front end to puzzles.
80 */
81
4efb3868 82struct font {
1fad7a3b 83#ifdef USE_PANGO
84 PangoFontDescription *desc;
85#else
4efb3868 86 GdkFont *font;
1fad7a3b 87#endif
4efb3868 88 int type;
89 int size;
90};
91
83680571 92/*
93 * This structure holds all the data relevant to a single window.
94 * In principle this would allow us to open multiple independent
95 * puzzle windows, although I can't currently see any real point in
96 * doing so. I'm just coding cleanly because there's no
97 * particularly good reason not to.
98 */
2ef96bd6 99struct frontend {
83680571 100 GtkWidget *window;
a383a9be 101 GtkAccelGroup *accelgroup;
7f77ea24 102 GtkWidget *area;
fd1a1a2b 103 GtkWidget *statusbar;
104 guint statusctx;
2ef96bd6 105 GdkPixmap *pixmap;
106 GdkColor *colours;
107 int ncolours;
108 GdkColormap *colmap;
109 int w, h;
dafd6cf6 110 midend *me;
2ef96bd6 111 GdkGC *gc;
112 int bbox_l, bbox_r, bbox_u, bbox_d;
20ee89e3 113 int timer_active, timer_id;
8c1fd974 114 struct timeval last_time;
4efb3868 115 struct font *fonts;
116 int nfonts, fontsize;
c8230524 117 config_item *cfg;
5928817c 118 int cfg_which, cfgret;
c8230524 119 GtkWidget *cfgbox;
23e8c9fd 120 void *paste_data;
9b4b03d3 121 int paste_data_len;
1e3e152d 122 int pw, ph; /* pixmap size (w, h are area size) */
123 int ox, oy; /* offset of pixmap in drawing area */
a4393230 124 char *filesel_name;
83680571 125};
126
cbb5549e 127void get_random_seed(void **randseed, int *randseedsize)
128{
102d0d14 129 struct timeval *tvp = snew(struct timeval);
130 gettimeofday(tvp, NULL);
131 *randseed = (void *)tvp;
132 *randseedsize = sizeof(struct timeval);
cbb5549e 133}
134
2ef96bd6 135void frontend_default_colour(frontend *fe, float *output)
136{
137 GdkColor col = fe->window->style->bg[GTK_STATE_NORMAL];
138 output[0] = col.red / 65535.0;
139 output[1] = col.green / 65535.0;
140 output[2] = col.blue / 65535.0;
141}
142
dafd6cf6 143void gtk_status_bar(void *handle, char *text)
fd1a1a2b 144{
dafd6cf6 145 frontend *fe = (frontend *)handle;
48dcdd62 146
fd1a1a2b 147 assert(fe->statusbar);
148
83c0438f 149 gtk_statusbar_pop(GTK_STATUSBAR(fe->statusbar), fe->statusctx);
150 gtk_statusbar_push(GTK_STATUSBAR(fe->statusbar), fe->statusctx, text);
fd1a1a2b 151}
152
dafd6cf6 153void gtk_start_draw(void *handle)
2ef96bd6 154{
dafd6cf6 155 frontend *fe = (frontend *)handle;
2ef96bd6 156 fe->gc = gdk_gc_new(fe->area->window);
157 fe->bbox_l = fe->w;
158 fe->bbox_r = 0;
159 fe->bbox_u = fe->h;
160 fe->bbox_d = 0;
161}
162
dafd6cf6 163void gtk_clip(void *handle, int x, int y, int w, int h)
4efb3868 164{
dafd6cf6 165 frontend *fe = (frontend *)handle;
4efb3868 166 GdkRectangle rect;
167
168 rect.x = x;
169 rect.y = y;
170 rect.width = w;
171 rect.height = h;
172
173 gdk_gc_set_clip_rectangle(fe->gc, &rect);
174}
175
dafd6cf6 176void gtk_unclip(void *handle)
4efb3868 177{
dafd6cf6 178 frontend *fe = (frontend *)handle;
4efb3868 179 GdkRectangle rect;
180
181 rect.x = 0;
182 rect.y = 0;
183 rect.width = fe->w;
184 rect.height = fe->h;
185
186 gdk_gc_set_clip_rectangle(fe->gc, &rect);
187}
188
dafd6cf6 189void gtk_draw_text(void *handle, int x, int y, int fonttype, int fontsize,
190 int align, int colour, char *text)
4efb3868 191{
dafd6cf6 192 frontend *fe = (frontend *)handle;
4efb3868 193 int i;
194
195 /*
196 * Find or create the font.
197 */
198 for (i = 0; i < fe->nfonts; i++)
199 if (fe->fonts[i].type == fonttype && fe->fonts[i].size == fontsize)
200 break;
201
202 if (i == fe->nfonts) {
203 if (fe->fontsize <= fe->nfonts) {
204 fe->fontsize = fe->nfonts + 10;
205 fe->fonts = sresize(fe->fonts, fe->fontsize, struct font);
206 }
207
208 fe->nfonts++;
209
210 fe->fonts[i].type = fonttype;
211 fe->fonts[i].size = fontsize;
212
1fad7a3b 213#ifdef USE_PANGO
4efb3868 214 /*
a9668451 215 * Use Pango to find the closest match to the requested
216 * font.
4efb3868 217 */
a9668451 218 {
219 PangoFontDescription *fd;
220
221 fd = pango_font_description_new();
222 /* `Monospace' and `Sans' are meta-families guaranteed to exist */
223 pango_font_description_set_family(fd, fonttype == FONT_FIXED ?
224 "Monospace" : "Sans");
2e837d78 225 pango_font_description_set_weight(fd, PANGO_WEIGHT_BOLD);
a9668451 226 /*
227 * I found some online Pango documentation which
228 * described a function called
229 * pango_font_description_set_absolute_size(), which is
230 * _exactly_ what I want here. Unfortunately, none of
231 * my local Pango installations have it (presumably
232 * they're too old), so I'm going to have to hack round
233 * it by figuring out the point size myself. This
234 * limits me to X and probably also breaks in later
235 * Pango installations, so ideally I should add another
236 * CHECK_VERSION type ifdef and use set_absolute_size
237 * where available. All very annoying.
238 */
239#ifdef HAVE_SENSIBLE_ABSOLUTE_SIZE_FUNCTION
240 pango_font_description_set_absolute_size(fd, PANGO_SCALE*fontsize);
241#else
242 {
243 Display *d = GDK_DISPLAY();
244 int s = DefaultScreen(d);
245 double resolution =
246 (PANGO_SCALE * 72.27 / 25.4) *
247 ((double) DisplayWidthMM(d, s) / DisplayWidth (d, s));
248 pango_font_description_set_size(fd, resolution * fontsize);
249 }
250#endif
1fad7a3b 251 fe->fonts[i].desc = fd;
a9668451 252 }
253
1fad7a3b 254#else
255 /*
256 * In GTK 1.2, I don't know of any plausible way to
257 * pick a suitable font, so I'm just going to be
258 * tedious.
259 */
260 fe->fonts[i].font = gdk_font_load(fonttype == FONT_FIXED ?
261 "fixed" : "variable");
a9668451 262#endif
1fad7a3b 263
264 }
265
266 /*
267 * Set the colour.
268 */
269 gdk_gc_set_foreground(fe->gc, &fe->colours[colour]);
270
271#ifdef USE_PANGO
272
273 {
274 PangoLayout *layout;
275 PangoRectangle rect;
276
277 /*
278 * Create a layout.
279 */
280 layout = pango_layout_new(gtk_widget_get_pango_context(fe->area));
281 pango_layout_set_font_description(layout, fe->fonts[i].desc);
282 pango_layout_set_text(layout, text, strlen(text));
283 pango_layout_get_pixel_extents(layout, NULL, &rect);
284
285 if (align & ALIGN_VCENTRE)
286 rect.y -= rect.height / 2;
86e60e3d 287 else
288 rect.y -= rect.height;
1fad7a3b 289
290 if (align & ALIGN_HCENTRE)
291 rect.x -= rect.width / 2;
292 else if (align & ALIGN_HRIGHT)
293 rect.x -= rect.width;
294
295 gdk_draw_layout(fe->pixmap, fe->gc, rect.x + x, rect.y + y, layout);
296
297 g_object_unref(layout);
4efb3868 298 }
299
1fad7a3b 300#else
4efb3868 301 /*
302 * Find string dimensions and process alignment.
303 */
304 {
305 int lb, rb, wid, asc, desc;
306
3bcf831a 307 /*
308 * Measure vertical string extents with respect to the same
309 * string always...
310 */
311 gdk_string_extents(fe->fonts[i].font,
312 "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
4efb3868 313 &lb, &rb, &wid, &asc, &desc);
314 if (align & ALIGN_VCENTRE)
315 y += asc - (asc+desc)/2;
86e60e3d 316 else
317 y += asc;
4efb3868 318
3bcf831a 319 /*
320 * ... but horizontal extents with respect to the provided
321 * string. This means that multiple pieces of text centred
322 * on the same y-coordinate don't have different baselines.
323 */
324 gdk_string_extents(fe->fonts[i].font, text,
325 &lb, &rb, &wid, &asc, &desc);
326
4efb3868 327 if (align & ALIGN_HCENTRE)
328 x -= wid / 2;
329 else if (align & ALIGN_HRIGHT)
330 x -= wid;
331
332 }
333
334 /*
1fad7a3b 335 * Actually draw the text.
4efb3868 336 */
4efb3868 337 gdk_draw_string(fe->pixmap, fe->fonts[i].font, fe->gc, x, y, text);
1fad7a3b 338#endif
339
4efb3868 340}
341
dafd6cf6 342void gtk_draw_rect(void *handle, int x, int y, int w, int h, int colour)
2ef96bd6 343{
dafd6cf6 344 frontend *fe = (frontend *)handle;
2ef96bd6 345 gdk_gc_set_foreground(fe->gc, &fe->colours[colour]);
346 gdk_draw_rectangle(fe->pixmap, fe->gc, 1, x, y, w, h);
347}
348
dafd6cf6 349void gtk_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
2ef96bd6 350{
dafd6cf6 351 frontend *fe = (frontend *)handle;
2ef96bd6 352 gdk_gc_set_foreground(fe->gc, &fe->colours[colour]);
353 gdk_draw_line(fe->pixmap, fe->gc, x1, y1, x2, y2);
354}
355
dafd6cf6 356void gtk_draw_poly(void *handle, int *coords, int npoints,
357 int fillcolour, int outlinecolour)
2ef96bd6 358{
dafd6cf6 359 frontend *fe = (frontend *)handle;
2ef96bd6 360 GdkPoint *points = snewn(npoints, GdkPoint);
361 int i;
362
363 for (i = 0; i < npoints; i++) {
364 points[i].x = coords[i*2];
365 points[i].y = coords[i*2+1];
366 }
367
28b5987d 368 if (fillcolour >= 0) {
369 gdk_gc_set_foreground(fe->gc, &fe->colours[fillcolour]);
370 gdk_draw_polygon(fe->pixmap, fe->gc, TRUE, points, npoints);
371 }
372 assert(outlinecolour >= 0);
373 gdk_gc_set_foreground(fe->gc, &fe->colours[outlinecolour]);
dddad8fb 374
375 /*
376 * In principle we ought to be able to use gdk_draw_polygon for
377 * the outline as well. In fact, it turns out to interact badly
378 * with a clipping region, for no terribly obvious reason, so I
379 * draw the outline as a sequence of lines instead.
380 */
381 for (i = 0; i < npoints; i++)
382 gdk_draw_line(fe->pixmap, fe->gc,
383 points[i].x, points[i].y,
384 points[(i+1)%npoints].x, points[(i+1)%npoints].y);
2ef96bd6 385
386 sfree(points);
387}
388
dafd6cf6 389void gtk_draw_circle(void *handle, int cx, int cy, int radius,
390 int fillcolour, int outlinecolour)
550efd7f 391{
dafd6cf6 392 frontend *fe = (frontend *)handle;
28b5987d 393 if (fillcolour >= 0) {
394 gdk_gc_set_foreground(fe->gc, &fe->colours[fillcolour]);
395 gdk_draw_arc(fe->pixmap, fe->gc, TRUE,
396 cx - radius, cy - radius,
397 2 * radius, 2 * radius, 0, 360 * 64);
398 }
399
400 assert(outlinecolour >= 0);
401 gdk_gc_set_foreground(fe->gc, &fe->colours[outlinecolour]);
402 gdk_draw_arc(fe->pixmap, fe->gc, FALSE,
403 cx - radius, cy - radius,
404 2 * radius, 2 * radius, 0, 360 * 64);
550efd7f 405}
406
3161048d 407struct blitter {
408 GdkPixmap *pixmap;
409 int w, h, x, y;
410};
411
dafd6cf6 412blitter *gtk_blitter_new(void *handle, int w, int h)
3161048d 413{
414 /*
415 * We can't create the pixmap right now, because fe->window
416 * might not yet exist. So we just cache w and h and create it
417 * during the firs call to blitter_save.
418 */
419 blitter *bl = snew(blitter);
420 bl->pixmap = NULL;
421 bl->w = w;
422 bl->h = h;
423 return bl;
424}
425
dafd6cf6 426void gtk_blitter_free(void *handle, blitter *bl)
3161048d 427{
428 if (bl->pixmap)
429 gdk_pixmap_unref(bl->pixmap);
430 sfree(bl);
431}
432
dafd6cf6 433void gtk_blitter_save(void *handle, blitter *bl, int x, int y)
3161048d 434{
dafd6cf6 435 frontend *fe = (frontend *)handle;
3161048d 436 if (!bl->pixmap)
437 bl->pixmap = gdk_pixmap_new(fe->area->window, bl->w, bl->h, -1);
438 bl->x = x;
439 bl->y = y;
440 gdk_draw_pixmap(bl->pixmap,
441 fe->area->style->fg_gc[GTK_WIDGET_STATE(fe->area)],
442 fe->pixmap,
443 x, y, 0, 0, bl->w, bl->h);
444}
445
dafd6cf6 446void gtk_blitter_load(void *handle, blitter *bl, int x, int y)
3161048d 447{
dafd6cf6 448 frontend *fe = (frontend *)handle;
3161048d 449 assert(bl->pixmap);
450 if (x == BLITTER_FROMSAVED && y == BLITTER_FROMSAVED) {
451 x = bl->x;
452 y = bl->y;
453 }
454 gdk_draw_pixmap(fe->pixmap,
455 fe->area->style->fg_gc[GTK_WIDGET_STATE(fe->area)],
456 bl->pixmap,
457 0, 0, x, y, bl->w, bl->h);
458}
459
dafd6cf6 460void gtk_draw_update(void *handle, int x, int y, int w, int h)
2ef96bd6 461{
dafd6cf6 462 frontend *fe = (frontend *)handle;
2ef96bd6 463 if (fe->bbox_l > x ) fe->bbox_l = x ;
464 if (fe->bbox_r < x+w) fe->bbox_r = x+w;
465 if (fe->bbox_u > y ) fe->bbox_u = y ;
466 if (fe->bbox_d < y+h) fe->bbox_d = y+h;
467}
468
dafd6cf6 469void gtk_end_draw(void *handle)
2ef96bd6 470{
dafd6cf6 471 frontend *fe = (frontend *)handle;
2ef96bd6 472 gdk_gc_unref(fe->gc);
473 fe->gc = NULL;
474
475 if (fe->bbox_l < fe->bbox_r && fe->bbox_u < fe->bbox_d) {
476 gdk_draw_pixmap(fe->area->window,
477 fe->area->style->fg_gc[GTK_WIDGET_STATE(fe->area)],
478 fe->pixmap,
479 fe->bbox_l, fe->bbox_u,
1e3e152d 480 fe->ox + fe->bbox_l, fe->oy + fe->bbox_u,
2ef96bd6 481 fe->bbox_r - fe->bbox_l, fe->bbox_d - fe->bbox_u);
482 }
483}
484
dafd6cf6 485const struct drawing_api gtk_drawing = {
486 gtk_draw_text,
487 gtk_draw_rect,
488 gtk_draw_line,
489 gtk_draw_poly,
490 gtk_draw_circle,
491 gtk_draw_update,
492 gtk_clip,
493 gtk_unclip,
494 gtk_start_draw,
495 gtk_end_draw,
496 gtk_status_bar,
497 gtk_blitter_new,
498 gtk_blitter_free,
499 gtk_blitter_save,
500 gtk_blitter_load,
501 NULL, NULL, NULL, NULL, NULL, NULL, /* {begin,end}_{doc,page,puzzle} */
502 NULL, /* line_width */
503};
504
83680571 505static void destroy(GtkWidget *widget, gpointer data)
506{
f49650a7 507 frontend *fe = (frontend *)data;
508 deactivate_timer(fe);
a4393230 509 midend_free(fe->me);
83680571 510 gtk_main_quit();
511}
512
2ef96bd6 513static gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data)
7f77ea24 514{
2ef96bd6 515 frontend *fe = (frontend *)data;
1482ee76 516 int keyval;
f0ee053c 517 int shift = (event->state & GDK_SHIFT_MASK) ? MOD_SHFT : 0;
518 int ctrl = (event->state & GDK_CONTROL_MASK) ? MOD_CTRL : 0;
7f77ea24 519
2ef96bd6 520 if (!fe->pixmap)
521 return TRUE;
7f77ea24 522
08d7c4ba 523#if !GTK_CHECK_VERSION(2,0,0)
524 /* Gtk 1.2 passes a key event to this function even if it's also
525 * defined as an accelerator.
526 * Gtk 2 doesn't do this, and this function appears not to exist there. */
527 if (fe->accelgroup &&
528 gtk_accel_group_get_entry(fe->accelgroup,
529 event->keyval, event->state))
530 return TRUE;
531#endif
532
3c833d45 533 if (event->keyval == GDK_Up)
f0ee053c 534 keyval = shift | ctrl | CURSOR_UP;
3c833d45 535 else if (event->keyval == GDK_KP_Up || event->keyval == GDK_KP_8)
536 keyval = MOD_NUM_KEYPAD | '8';
537 else if (event->keyval == GDK_Down)
f0ee053c 538 keyval = shift | ctrl | CURSOR_DOWN;
3c833d45 539 else if (event->keyval == GDK_KP_Down || event->keyval == GDK_KP_2)
540 keyval = MOD_NUM_KEYPAD | '2';
541 else if (event->keyval == GDK_Left)
f0ee053c 542 keyval = shift | ctrl | CURSOR_LEFT;
3c833d45 543 else if (event->keyval == GDK_KP_Left || event->keyval == GDK_KP_4)
544 keyval = MOD_NUM_KEYPAD | '4';
545 else if (event->keyval == GDK_Right)
f0ee053c 546 keyval = shift | ctrl | CURSOR_RIGHT;
3c833d45 547 else if (event->keyval == GDK_KP_Right || event->keyval == GDK_KP_6)
548 keyval = MOD_NUM_KEYPAD | '6';
c71454c0 549 else if (event->keyval == GDK_KP_Home || event->keyval == GDK_KP_7)
3c833d45 550 keyval = MOD_NUM_KEYPAD | '7';
c71454c0 551 else if (event->keyval == GDK_KP_End || event->keyval == GDK_KP_1)
3c833d45 552 keyval = MOD_NUM_KEYPAD | '1';
c71454c0 553 else if (event->keyval == GDK_KP_Page_Up || event->keyval == GDK_KP_9)
3c833d45 554 keyval = MOD_NUM_KEYPAD | '9';
c71454c0 555 else if (event->keyval == GDK_KP_Page_Down || event->keyval == GDK_KP_3)
3c833d45 556 keyval = MOD_NUM_KEYPAD | '3';
557 else if (event->keyval == GDK_KP_Insert || event->keyval == GDK_KP_0)
558 keyval = MOD_NUM_KEYPAD | '0';
559 else if (event->keyval == GDK_KP_Begin || event->keyval == GDK_KP_5)
560 keyval = MOD_NUM_KEYPAD | '5';
0eb4d76e 561 else if (event->keyval == GDK_BackSpace ||
562 event->keyval == GDK_Delete ||
563 event->keyval == GDK_KP_Delete)
564 keyval = '\177';
3c833d45 565 else if (event->string[0] && !event->string[1])
566 keyval = (unsigned char)event->string[0];
1482ee76 567 else
568 keyval = -1;
569
570 if (keyval >= 0 &&
571 !midend_process_key(fe->me, 0, 0, keyval))
2ef96bd6 572 gtk_widget_destroy(fe->window);
7f77ea24 573
574 return TRUE;
575}
576
2ef96bd6 577static gint button_event(GtkWidget *widget, GdkEventButton *event,
578 gpointer data)
7f77ea24 579{
2ef96bd6 580 frontend *fe = (frontend *)data;
581 int button;
582
583 if (!fe->pixmap)
584 return TRUE;
585
74a4e547 586 if (event->type != GDK_BUTTON_PRESS && event->type != GDK_BUTTON_RELEASE)
2ef96bd6 587 return TRUE;
7f77ea24 588
b0f06719 589 if (event->button == 2 || (event->state & GDK_SHIFT_MASK))
2ef96bd6 590 button = MIDDLE_BUTTON;
97c2790f 591 else if (event->button == 3 || (event->state & GDK_MOD1_MASK))
592 button = RIGHT_BUTTON;
b0f06719 593 else if (event->button == 1)
594 button = LEFT_BUTTON;
2ef96bd6 595 else
596 return FALSE; /* don't even know what button! */
597
74a4e547 598 if (event->type == GDK_BUTTON_RELEASE)
599 button += LEFT_RELEASE - LEFT_BUTTON;
600
1e3e152d 601 if (!midend_process_key(fe->me, event->x - fe->ox,
602 event->y - fe->oy, button))
74a4e547 603 gtk_widget_destroy(fe->window);
604
605 return TRUE;
606}
607
608static gint motion_event(GtkWidget *widget, GdkEventMotion *event,
609 gpointer data)
610{
611 frontend *fe = (frontend *)data;
612 int button;
613
614 if (!fe->pixmap)
615 return TRUE;
616
74a4e547 617 if (event->state & (GDK_BUTTON2_MASK | GDK_SHIFT_MASK))
618 button = MIDDLE_DRAG;
619 else if (event->state & GDK_BUTTON1_MASK)
620 button = LEFT_DRAG;
621 else if (event->state & GDK_BUTTON3_MASK)
622 button = RIGHT_DRAG;
623 else
624 return FALSE; /* don't even know what button! */
625
1e3e152d 626 if (!midend_process_key(fe->me, event->x - fe->ox,
627 event->y - fe->oy, button))
2ef96bd6 628 gtk_widget_destroy(fe->window);
7f77ea24 629
630 return TRUE;
631}
632
2ef96bd6 633static gint expose_area(GtkWidget *widget, GdkEventExpose *event,
634 gpointer data)
83680571 635{
2ef96bd6 636 frontend *fe = (frontend *)data;
637
638 if (fe->pixmap) {
639 gdk_draw_pixmap(widget->window,
640 widget->style->fg_gc[GTK_WIDGET_STATE(widget)],
641 fe->pixmap,
1e3e152d 642 event->area.x - fe->ox, event->area.y - fe->oy,
2ef96bd6 643 event->area.x, event->area.y,
644 event->area.width, event->area.height);
645 }
646 return TRUE;
647}
648
fd1a1a2b 649static gint map_window(GtkWidget *widget, GdkEvent *event,
650 gpointer data)
651{
652 frontend *fe = (frontend *)data;
653
654 /*
655 * Apparently we need to do this because otherwise the status
656 * bar will fail to update immediately. Annoying, but there we
657 * go.
658 */
659 gtk_widget_queue_draw(fe->window);
660
661 return TRUE;
662}
663
2ef96bd6 664static gint configure_area(GtkWidget *widget,
665 GdkEventConfigure *event, gpointer data)
666{
667 frontend *fe = (frontend *)data;
668 GdkGC *gc;
1e3e152d 669 int x, y;
2ef96bd6 670
eb2ad6f1 671 if (fe->pixmap)
672 gdk_pixmap_unref(fe->pixmap);
673
1e3e152d 674 x = fe->w = event->width;
675 y = fe->h = event->height;
676 midend_size(fe->me, &x, &y, TRUE);
677 fe->pw = x;
678 fe->ph = y;
679 fe->ox = (fe->w - fe->pw) / 2;
680 fe->oy = (fe->h - fe->ph) / 2;
681
682 fe->pixmap = gdk_pixmap_new(widget->window, fe->pw, fe->ph, -1);
2ef96bd6 683
684 gc = gdk_gc_new(fe->area->window);
685 gdk_gc_set_foreground(gc, &fe->colours[0]);
1e3e152d 686 gdk_draw_rectangle(fe->pixmap, gc, 1, 0, 0, fe->pw, fe->ph);
47432032 687 gdk_draw_rectangle(widget->window, gc, 1, 0, 0,
688 event->width, event->height);
2ef96bd6 689 gdk_gc_unref(gc);
690
008b4378 691 midend_force_redraw(fe->me);
2ef96bd6 692
693 return TRUE;
694}
695
696static gint timer_func(gpointer data)
697{
698 frontend *fe = (frontend *)data;
699
8c1fd974 700 if (fe->timer_active) {
701 struct timeval now;
702 float elapsed;
703 gettimeofday(&now, NULL);
704 elapsed = ((now.tv_usec - fe->last_time.tv_usec) * 0.000001F +
705 (now.tv_sec - fe->last_time.tv_sec));
706 midend_timer(fe->me, elapsed); /* may clear timer_active */
707 fe->last_time = now;
708 }
2ef96bd6 709
710 return fe->timer_active;
711}
712
713void deactivate_timer(frontend *fe)
714{
dafd6cf6 715 if (!fe)
716 return; /* can happen due to --generate */
20ee89e3 717 if (fe->timer_active)
718 gtk_timeout_remove(fe->timer_id);
2ef96bd6 719 fe->timer_active = FALSE;
720}
721
722void activate_timer(frontend *fe)
723{
dafd6cf6 724 if (!fe)
725 return; /* can happen due to --generate */
8c1fd974 726 if (!fe->timer_active) {
20ee89e3 727 fe->timer_id = gtk_timeout_add(20, timer_func, fe);
8c1fd974 728 gettimeofday(&fe->last_time, NULL);
729 }
2ef96bd6 730 fe->timer_active = TRUE;
731}
732
c8230524 733static void window_destroy(GtkWidget *widget, gpointer data)
734{
735 gtk_main_quit();
736}
737
668be019 738static void msgbox_button_clicked(GtkButton *button, gpointer data)
c8230524 739{
668be019 740 GtkWidget *window = GTK_WIDGET(data);
741 int v, *ip;
742
743 ip = (int *)gtk_object_get_data(GTK_OBJECT(window), "user-data");
744 v = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(button), "user-data"));
745 *ip = v;
746
c8230524 747 gtk_widget_destroy(GTK_WIDGET(data));
748}
749
a163b7c2 750static int win_key_press(GtkWidget *widget, GdkEventKey *event, gpointer data)
751{
752 GtkObject *cancelbutton = GTK_OBJECT(data);
753
754 /*
755 * `Escape' effectively clicks the cancel button
756 */
757 if (event->keyval == GDK_Escape) {
758 gtk_signal_emit_by_name(GTK_OBJECT(cancelbutton), "clicked");
759 return TRUE;
760 }
761
762 return FALSE;
763}
764
668be019 765enum { MB_OK, MB_YESNO };
766
767int message_box(GtkWidget *parent, char *title, char *msg, int centre,
768 int type)
c8230524 769{
668be019 770 GtkWidget *window, *hbox, *text, *button;
771 char *titles;
772 int i, def, cancel;
c8230524 773
774 window = gtk_dialog_new();
775 text = gtk_label_new(msg);
776 gtk_misc_set_alignment(GTK_MISC(text), 0.0, 0.0);
777 hbox = gtk_hbox_new(FALSE, 0);
778 gtk_box_pack_start(GTK_BOX(hbox), text, FALSE, FALSE, 20);
779 gtk_box_pack_start(GTK_BOX(GTK_DIALOG(window)->vbox),
780 hbox, FALSE, FALSE, 20);
781 gtk_widget_show(text);
782 gtk_widget_show(hbox);
97098757 783 gtk_window_set_title(GTK_WINDOW(window), title);
c8230524 784 gtk_label_set_line_wrap(GTK_LABEL(text), TRUE);
668be019 785
786 if (type == MB_OK) {
787 titles = "OK\0";
788 def = cancel = 0;
789 } else {
790 assert(type == MB_YESNO);
791 titles = "Yes\0No\0";
792 def = 0;
793 cancel = 1;
794 }
795 i = 0;
796
797 while (*titles) {
798 button = gtk_button_new_with_label(titles);
799 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(window)->action_area),
800 button, FALSE, FALSE, 0);
801 gtk_widget_show(button);
802 if (i == def) {
803 GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
804 gtk_window_set_default(GTK_WINDOW(window), button);
805 }
806 if (i == cancel) {
807 gtk_signal_connect(GTK_OBJECT(window), "key_press_event",
808 GTK_SIGNAL_FUNC(win_key_press), button);
809 }
810 gtk_signal_connect(GTK_OBJECT(button), "clicked",
811 GTK_SIGNAL_FUNC(msgbox_button_clicked), window);
812 gtk_object_set_data(GTK_OBJECT(button), "user-data",
813 GINT_TO_POINTER(i));
814 titles += strlen(titles)+1;
815 i++;
816 }
817 gtk_object_set_data(GTK_OBJECT(window), "user-data",
818 GINT_TO_POINTER(&i));
a1ed9f0e 819 gtk_signal_connect(GTK_OBJECT(window), "destroy",
820 GTK_SIGNAL_FUNC(window_destroy), NULL);
c8230524 821 gtk_window_set_modal(GTK_WINDOW(window), TRUE);
822 gtk_window_set_transient_for(GTK_WINDOW(window), GTK_WINDOW(parent));
23e8c9fd 823 /* set_transient_window_pos(parent, window); */
c8230524 824 gtk_widget_show(window);
668be019 825 i = -1;
c8230524 826 gtk_main();
668be019 827 return (type == MB_YESNO ? i == 0 : TRUE);
c8230524 828}
829
97098757 830void error_box(GtkWidget *parent, char *msg)
831{
668be019 832 message_box(parent, "Error", msg, FALSE, MB_OK);
97098757 833}
834
c8230524 835static void config_ok_button_clicked(GtkButton *button, gpointer data)
836{
837 frontend *fe = (frontend *)data;
838 char *err;
839
5928817c 840 err = midend_set_config(fe->me, fe->cfg_which, fe->cfg);
c8230524 841
842 if (err)
843 error_box(fe->cfgbox, err);
844 else {
845 fe->cfgret = TRUE;
846 gtk_widget_destroy(fe->cfgbox);
847 }
848}
849
850static void config_cancel_button_clicked(GtkButton *button, gpointer data)
851{
852 frontend *fe = (frontend *)data;
853
854 gtk_widget_destroy(fe->cfgbox);
855}
856
a163b7c2 857static int editbox_key(GtkWidget *widget, GdkEventKey *event, gpointer data)
858{
859 /*
860 * GtkEntry has a nasty habit of eating the Return key, which
861 * is unhelpful since it doesn't actually _do_ anything with it
862 * (it calls gtk_widget_activate, but our edit boxes never need
863 * activating). So I catch Return before GtkEntry sees it, and
864 * pass it straight on to the parent widget. Effect: hitting
865 * Return in an edit box will now activate the default button
866 * in the dialog just like it will everywhere else.
867 */
868 if (event->keyval == GDK_Return && widget->parent != NULL) {
869 gint return_val;
870 gtk_signal_emit_stop_by_name(GTK_OBJECT(widget), "key_press_event");
871 gtk_signal_emit_by_name(GTK_OBJECT(widget->parent), "key_press_event",
872 event, &return_val);
873 return return_val;
874 }
875 return FALSE;
876}
877
c8230524 878static void editbox_changed(GtkEditable *ed, gpointer data)
879{
880 config_item *i = (config_item *)data;
881
882 sfree(i->sval);
883 i->sval = dupstr(gtk_entry_get_text(GTK_ENTRY(ed)));
884}
885
886static void button_toggled(GtkToggleButton *tb, gpointer data)
887{
888 config_item *i = (config_item *)data;
889
890 i->ival = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(tb));
891}
892
893static void droplist_sel(GtkMenuItem *item, gpointer data)
894{
895 config_item *i = (config_item *)data;
896
897 i->ival = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(item),
898 "user-data"));
899}
900
5928817c 901static int get_config(frontend *fe, int which)
c8230524 902{
a163b7c2 903 GtkWidget *w, *table, *cancel;
5928817c 904 char *title;
c8230524 905 config_item *i;
906 int y;
907
5928817c 908 fe->cfg = midend_get_config(fe->me, which, &title);
909 fe->cfg_which = which;
c8230524 910 fe->cfgret = FALSE;
911
912 fe->cfgbox = gtk_dialog_new();
5928817c 913 gtk_window_set_title(GTK_WINDOW(fe->cfgbox), title);
914 sfree(title);
c8230524 915
916 w = gtk_button_new_with_label("OK");
917 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(fe->cfgbox)->action_area),
918 w, FALSE, FALSE, 0);
919 gtk_widget_show(w);
920 GTK_WIDGET_SET_FLAGS(w, GTK_CAN_DEFAULT);
921 gtk_window_set_default(GTK_WINDOW(fe->cfgbox), w);
922 gtk_signal_connect(GTK_OBJECT(w), "clicked",
923 GTK_SIGNAL_FUNC(config_ok_button_clicked), fe);
924
925 w = gtk_button_new_with_label("Cancel");
926 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(fe->cfgbox)->action_area),
927 w, FALSE, FALSE, 0);
928 gtk_widget_show(w);
929 gtk_signal_connect(GTK_OBJECT(w), "clicked",
930 GTK_SIGNAL_FUNC(config_cancel_button_clicked), fe);
a163b7c2 931 cancel = w;
c8230524 932
933 table = gtk_table_new(1, 2, FALSE);
934 y = 0;
935 gtk_box_pack_end(GTK_BOX(GTK_DIALOG(fe->cfgbox)->vbox),
936 table, FALSE, FALSE, 0);
937 gtk_widget_show(table);
938
95709966 939 for (i = fe->cfg; i->type != C_END; i++) {
c8230524 940 gtk_table_resize(GTK_TABLE(table), y+1, 2);
941
942 switch (i->type) {
95709966 943 case C_STRING:
c8230524 944 /*
945 * Edit box with a label beside it.
946 */
947
948 w = gtk_label_new(i->name);
949 gtk_misc_set_alignment(GTK_MISC(w), 0.0, 0.5);
950 gtk_table_attach(GTK_TABLE(table), w, 0, 1, y, y+1,
951 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
952 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
953 3, 3);
954 gtk_widget_show(w);
955
956 w = gtk_entry_new();
957 gtk_table_attach(GTK_TABLE(table), w, 1, 2, y, y+1,
958 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
959 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
960 3, 3);
961 gtk_entry_set_text(GTK_ENTRY(w), i->sval);
962 gtk_signal_connect(GTK_OBJECT(w), "changed",
963 GTK_SIGNAL_FUNC(editbox_changed), i);
a163b7c2 964 gtk_signal_connect(GTK_OBJECT(w), "key_press_event",
965 GTK_SIGNAL_FUNC(editbox_key), NULL);
c8230524 966 gtk_widget_show(w);
967
968 break;
969
95709966 970 case C_BOOLEAN:
c8230524 971 /*
972 * Simple checkbox.
973 */
974 w = gtk_check_button_new_with_label(i->name);
975 gtk_signal_connect(GTK_OBJECT(w), "toggled",
976 GTK_SIGNAL_FUNC(button_toggled), i);
977 gtk_table_attach(GTK_TABLE(table), w, 0, 2, y, y+1,
978 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
979 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
980 3, 3);
981 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(w), i->ival);
982 gtk_widget_show(w);
983 break;
984
95709966 985 case C_CHOICES:
c8230524 986 /*
987 * Drop-down list (GtkOptionMenu).
988 */
989
990 w = gtk_label_new(i->name);
991 gtk_misc_set_alignment(GTK_MISC(w), 0.0, 0.5);
992 gtk_table_attach(GTK_TABLE(table), w, 0, 1, y, y+1,
993 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
994 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
995 3, 3);
996 gtk_widget_show(w);
997
998 w = gtk_option_menu_new();
999 gtk_table_attach(GTK_TABLE(table), w, 1, 2, y, y+1,
1000 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1001 GTK_EXPAND | GTK_SHRINK | GTK_FILL,
1002 3, 3);
1003 gtk_widget_show(w);
1004
1005 {
1006 int c, val;
1007 char *p, *q, *name;
1008 GtkWidget *menuitem;
1009 GtkWidget *menu = gtk_menu_new();
1010
1011 gtk_option_menu_set_menu(GTK_OPTION_MENU(w), menu);
1012
1013 c = *i->sval;
1014 p = i->sval+1;
1015 val = 0;
1016
1017 while (*p) {
1018 q = p;
1019 while (*q && *q != c)
1020 q++;
1021
1022 name = snewn(q-p+1, char);
1023 strncpy(name, p, q-p);
1024 name[q-p] = '\0';
1025
1026 if (*q) q++; /* eat delimiter */
1027
1028 menuitem = gtk_menu_item_new_with_label(name);
1029 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1030 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1031 GINT_TO_POINTER(val));
1032 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1033 GTK_SIGNAL_FUNC(droplist_sel), i);
1034 gtk_widget_show(menuitem);
1035
1036 val++;
1037
1038 p = q;
1039 }
1040
1041 gtk_option_menu_set_history(GTK_OPTION_MENU(w), i->ival);
1042 }
1043
1044 break;
1045 }
1046
1047 y++;
1048 }
1049
1050 gtk_signal_connect(GTK_OBJECT(fe->cfgbox), "destroy",
1051 GTK_SIGNAL_FUNC(window_destroy), NULL);
a163b7c2 1052 gtk_signal_connect(GTK_OBJECT(fe->cfgbox), "key_press_event",
1053 GTK_SIGNAL_FUNC(win_key_press), cancel);
c8230524 1054 gtk_window_set_modal(GTK_WINDOW(fe->cfgbox), TRUE);
1055 gtk_window_set_transient_for(GTK_WINDOW(fe->cfgbox),
1056 GTK_WINDOW(fe->window));
23e8c9fd 1057 /* set_transient_window_pos(fe->window, fe->cfgbox); */
c8230524 1058 gtk_widget_show(fe->cfgbox);
1059 gtk_main();
1060
077f3cbe 1061 free_cfg(fe->cfg);
c8230524 1062
1063 return fe->cfgret;
1064}
1065
eb2ad6f1 1066static void menu_key_event(GtkMenuItem *menuitem, gpointer data)
1067{
1068 frontend *fe = (frontend *)data;
1069 int key = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(menuitem),
1070 "user-data"));
1071 if (!midend_process_key(fe->me, 0, 0, key))
1072 gtk_widget_destroy(fe->window);
1073}
1074
1e3e152d 1075static void get_size(frontend *fe, int *px, int *py)
1076{
1077 int x, y;
1078
1079 /*
1080 * Currently I don't want to make the GTK port scale large
1081 * puzzles to fit on the screen. This is because X does permit
1082 * extremely large windows and many window managers provide a
1083 * means of navigating round them, and the users I consulted
1084 * before deciding said that they'd rather have enormous puzzle
1085 * windows spanning multiple screen pages than have them
1086 * shrunk. I could change my mind later or introduce
1087 * configurability; this would be the place to do so, by
1088 * replacing the initial values of x and y with the screen
1089 * dimensions.
1090 */
1091 x = INT_MAX;
1092 y = INT_MAX;
1093 midend_size(fe->me, &x, &y, FALSE);
1094 *px = x;
1095 *py = y;
1096}
1097
ef429a6c 1098#if !GTK_CHECK_VERSION(2,0,0)
1099#define gtk_window_resize(win, x, y) \
1100 gdk_window_resize(GTK_WIDGET(win)->window, x, y)
1101#endif
1102
eb2ad6f1 1103static void menu_preset_event(GtkMenuItem *menuitem, gpointer data)
1104{
1105 frontend *fe = (frontend *)data;
1106 game_params *params =
1107 (game_params *)gtk_object_get_data(GTK_OBJECT(menuitem), "user-data");
1108 int x, y;
1109
1110 midend_set_params(fe->me, params);
5928817c 1111 midend_new_game(fe->me);
1e3e152d 1112 get_size(fe, &x, &y);
eb2ad6f1 1113 fe->w = x;
1114 fe->h = y;
1e3e152d 1115 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
4e1f57ba 1116 {
1117 GtkRequisition req;
1118 gtk_widget_size_request(GTK_WIDGET(fe->window), &req);
cbdf34a0 1119 gtk_window_resize(GTK_WINDOW(fe->window), req.width, req.height);
4e1f57ba 1120 }
eb2ad6f1 1121}
1122
9b4b03d3 1123GdkAtom compound_text_atom, utf8_string_atom;
1124int paste_initialised = FALSE;
1125
1126void init_paste()
1127{
23e8c9fd 1128 unsigned char empty[] = { 0 };
1129
9b4b03d3 1130 if (paste_initialised)
1131 return;
1132
1133 if (!compound_text_atom)
1134 compound_text_atom = gdk_atom_intern("COMPOUND_TEXT", FALSE);
1135 if (!utf8_string_atom)
1136 utf8_string_atom = gdk_atom_intern("UTF8_STRING", FALSE);
1137
1138 /*
1139 * Ensure that all the cut buffers exist - according to the
1140 * ICCCM, we must do this before we start using cut buffers.
1141 */
1142 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
23e8c9fd 1143 XA_CUT_BUFFER0, XA_STRING, 8, PropModeAppend, empty, 0);
9b4b03d3 1144 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
23e8c9fd 1145 XA_CUT_BUFFER1, XA_STRING, 8, PropModeAppend, empty, 0);
9b4b03d3 1146 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
23e8c9fd 1147 XA_CUT_BUFFER2, XA_STRING, 8, PropModeAppend, empty, 0);
9b4b03d3 1148 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
23e8c9fd 1149 XA_CUT_BUFFER3, XA_STRING, 8, PropModeAppend, empty, 0);
9b4b03d3 1150 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
23e8c9fd 1151 XA_CUT_BUFFER4, XA_STRING, 8, PropModeAppend, empty, 0);
9b4b03d3 1152 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
23e8c9fd 1153 XA_CUT_BUFFER5, XA_STRING, 8, PropModeAppend, empty, 0);
9b4b03d3 1154 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
23e8c9fd 1155 XA_CUT_BUFFER6, XA_STRING, 8, PropModeAppend, empty, 0);
9b4b03d3 1156 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
23e8c9fd 1157 XA_CUT_BUFFER7, XA_STRING, 8, PropModeAppend, empty, 0);
9b4b03d3 1158}
1159
1160/* Store data in a cut-buffer. */
1161void store_cutbuffer(char *ptr, int len)
1162{
1163 /* ICCCM says we must rotate the buffers before storing to buffer 0. */
1164 XRotateBuffers(GDK_DISPLAY(), 1);
1165 XStoreBytes(GDK_DISPLAY(), ptr, len);
1166}
1167
1168void write_clip(frontend *fe, char *data)
1169{
1170 init_paste();
1171
1172 if (fe->paste_data)
1173 sfree(fe->paste_data);
1174
1175 /*
1176 * For this simple application we can safely assume that the
1177 * data passed to this function is pure ASCII, which means we
1178 * can return precisely the same stuff for types STRING,
1179 * COMPOUND_TEXT or UTF8_STRING.
1180 */
1181
1182 fe->paste_data = data;
1183 fe->paste_data_len = strlen(data);
1184
1185 store_cutbuffer(fe->paste_data, fe->paste_data_len);
1186
1187 if (gtk_selection_owner_set(fe->area, GDK_SELECTION_PRIMARY,
1188 CurrentTime)) {
1189 gtk_selection_add_target(fe->area, GDK_SELECTION_PRIMARY,
1190 GDK_SELECTION_TYPE_STRING, 1);
1191 gtk_selection_add_target(fe->area, GDK_SELECTION_PRIMARY,
1192 compound_text_atom, 1);
1193 gtk_selection_add_target(fe->area, GDK_SELECTION_PRIMARY,
1194 utf8_string_atom, 1);
1195 }
1196}
1197
1198void selection_get(GtkWidget *widget, GtkSelectionData *seldata,
1199 guint info, guint time_stamp, gpointer data)
1200{
1201 frontend *fe = (frontend *)data;
1202 gtk_selection_data_set(seldata, seldata->target, 8,
1203 fe->paste_data, fe->paste_data_len);
1204}
1205
1206gint selection_clear(GtkWidget *widget, GdkEventSelection *seldata,
1207 gpointer data)
1208{
1209 frontend *fe = (frontend *)data;
1210
1211 if (fe->paste_data)
1212 sfree(fe->paste_data);
1213 fe->paste_data = NULL;
1214 fe->paste_data_len = 0;
1215 return TRUE;
1216}
1217
1218static void menu_copy_event(GtkMenuItem *menuitem, gpointer data)
1219{
1220 frontend *fe = (frontend *)data;
1221 char *text;
1222
1223 text = midend_text_format(fe->me);
1224
1225 if (text) {
1226 write_clip(fe, text);
1227 } else {
1228 gdk_beep();
1229 }
1230}
1231
a4393230 1232static void filesel_ok(GtkButton *button, gpointer data)
1233{
1234 frontend *fe = (frontend *)data;
1235
1236 gpointer filesel = gtk_object_get_data(GTK_OBJECT(button), "user-data");
1237
1238 const char *name =
1239 gtk_file_selection_get_filename(GTK_FILE_SELECTION(filesel));
1240
1241 fe->filesel_name = dupstr(name);
1242}
1243
1244static char *file_selector(frontend *fe, char *title, int save)
1245{
1246 GtkWidget *filesel =
1247 gtk_file_selection_new(title);
1248
1249 fe->filesel_name = NULL;
1250
1251 gtk_window_set_modal(GTK_WINDOW(filesel), TRUE);
1252 gtk_object_set_data
1253 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "user-data",
1254 (gpointer)filesel);
1255 gtk_signal_connect
1256 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "clicked",
1257 GTK_SIGNAL_FUNC(filesel_ok), fe);
1258 gtk_signal_connect_object
1259 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "clicked",
1260 GTK_SIGNAL_FUNC(gtk_widget_destroy), (gpointer)filesel);
1261 gtk_signal_connect_object
1262 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->cancel_button), "clicked",
1263 GTK_SIGNAL_FUNC(gtk_widget_destroy), (gpointer)filesel);
1264 gtk_signal_connect(GTK_OBJECT(filesel), "destroy",
1265 GTK_SIGNAL_FUNC(window_destroy), NULL);
1266 gtk_widget_show(filesel);
1267 gtk_window_set_transient_for(GTK_WINDOW(filesel), GTK_WINDOW(fe->window));
1268 gtk_main();
1269
1270 return fe->filesel_name;
1271}
1272
1273static void savefile_write(void *wctx, void *buf, int len)
1274{
1275 FILE *fp = (FILE *)wctx;
1276 fwrite(buf, 1, len, fp);
1277}
1278
1279static int savefile_read(void *wctx, void *buf, int len)
1280{
1281 FILE *fp = (FILE *)wctx;
1282 int ret;
1283
1284 ret = fread(buf, 1, len, fp);
1285 return (ret == len);
1286}
1287
1288static void menu_save_event(GtkMenuItem *menuitem, gpointer data)
1289{
1290 frontend *fe = (frontend *)data;
1291 char *name;
1292
1293 name = file_selector(fe, "Enter name of game file to save", TRUE);
1294
1295 if (name) {
668be019 1296 FILE *fp;
1297
1298 if ((fp = fopen(name, "r")) != NULL) {
1299 char buf[256 + FILENAME_MAX];
1300 fclose(fp);
1301 /* file exists */
1302
1303 sprintf(buf, "Are you sure you want to overwrite the"
1304 " file \"%.*s\"?",
1305 FILENAME_MAX, name);
1306 if (!message_box(fe->window, "Question", buf, TRUE, MB_YESNO))
1307 return;
1308 }
1309
1310 fp = fopen(name, "w");
a4393230 1311 sfree(name);
1312
1313 if (!fp) {
1314 error_box(fe->window, "Unable to open save file");
1315 return;
1316 }
1317
1318 midend_serialise(fe->me, savefile_write, fp);
1319
1320 fclose(fp);
1321 }
1322}
1323
1324static void menu_load_event(GtkMenuItem *menuitem, gpointer data)
1325{
1326 frontend *fe = (frontend *)data;
1327 char *name, *err;
1328 int x, y;
1329
1330 name = file_selector(fe, "Enter name of saved game file to load", FALSE);
1331
1332 if (name) {
1333 FILE *fp = fopen(name, "r");
1334 sfree(name);
1335
1336 if (!fp) {
1337 error_box(fe->window, "Unable to open saved game file");
1338 return;
1339 }
1340
1341 err = midend_deserialise(fe->me, savefile_read, fp);
1342
1343 fclose(fp);
1344
1345 if (err) {
1346 error_box(fe->window, err);
1347 return;
1348 }
1349
1350 get_size(fe, &x, &y);
1351 fe->w = x;
1352 fe->h = y;
1353 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
1354 {
1355 GtkRequisition req;
1356 gtk_widget_size_request(GTK_WIDGET(fe->window), &req);
1357 gtk_window_resize(GTK_WINDOW(fe->window), req.width, req.height);
1358 }
1359
1360 }
1361}
1362
2ac6d24e 1363static void menu_solve_event(GtkMenuItem *menuitem, gpointer data)
1364{
1365 frontend *fe = (frontend *)data;
1366 char *msg;
1367
1368 msg = midend_solve(fe->me);
1369
1370 if (msg)
1371 error_box(fe->window, msg);
1372}
1373
7f89707c 1374static void menu_restart_event(GtkMenuItem *menuitem, gpointer data)
1375{
1376 frontend *fe = (frontend *)data;
1377
1378 midend_restart_game(fe->me);
1379}
1380
c8230524 1381static void menu_config_event(GtkMenuItem *menuitem, gpointer data)
1382{
1383 frontend *fe = (frontend *)data;
5928817c 1384 int which = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(menuitem),
1385 "user-data"));
c8230524 1386 int x, y;
1387
5928817c 1388 if (!get_config(fe, which))
c8230524 1389 return;
1390
5928817c 1391 midend_new_game(fe->me);
1e3e152d 1392 get_size(fe, &x, &y);
c8230524 1393 fe->w = x;
1394 fe->h = y;
1e3e152d 1395 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
4e1f57ba 1396 {
1397 GtkRequisition req;
1398 gtk_widget_size_request(GTK_WIDGET(fe->window), &req);
cbdf34a0 1399 gtk_window_resize(GTK_WINDOW(fe->window), req.width, req.height);
4e1f57ba 1400 }
c8230524 1401}
1402
97098757 1403static void menu_about_event(GtkMenuItem *menuitem, gpointer data)
1404{
1405 frontend *fe = (frontend *)data;
1406 char titlebuf[256];
1407 char textbuf[1024];
1408
1409 sprintf(titlebuf, "About %.200s", thegame.name);
1410 sprintf(textbuf,
1411 "%.200s\n\n"
1412 "from Simon Tatham's Portable Puzzle Collection\n\n"
1413 "%.500s", thegame.name, ver);
1414
668be019 1415 message_box(fe->window, titlebuf, textbuf, TRUE, MB_OK);
97098757 1416}
1417
eb2ad6f1 1418static GtkWidget *add_menu_item_with_key(frontend *fe, GtkContainer *cont,
1419 char *text, int key)
1420{
1421 GtkWidget *menuitem = gtk_menu_item_new_with_label(text);
a383a9be 1422 int keyqual;
eb2ad6f1 1423 gtk_container_add(cont, menuitem);
1424 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1425 GINT_TO_POINTER(key));
1426 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1427 GTK_SIGNAL_FUNC(menu_key_event), fe);
a383a9be 1428 switch (key & ~0x1F) {
1429 case 0x00:
1430 key += 0x60;
1431 keyqual = GDK_CONTROL_MASK;
1432 break;
1433 case 0x40:
1434 key += 0x20;
1435 keyqual = GDK_SHIFT_MASK;
1436 break;
1437 default:
1438 keyqual = 0;
1439 break;
1440 }
1441 gtk_widget_add_accelerator(menuitem,
1442 "activate", fe->accelgroup,
1443 key, keyqual,
1444 GTK_ACCEL_VISIBLE);
eb2ad6f1 1445 gtk_widget_show(menuitem);
1446 return menuitem;
1447}
1448
1449static void add_menu_separator(GtkContainer *cont)
1450{
1451 GtkWidget *menuitem = gtk_menu_item_new();
1452 gtk_container_add(cont, menuitem);
1453 gtk_widget_show(menuitem);
1454}
1455
afc306fc 1456enum { ARG_EITHER, ARG_SAVE, ARG_ID }; /* for argtype */
1457
1458static frontend *new_window(char *arg, int argtype, char **error)
2ef96bd6 1459{
1460 frontend *fe;
eb2ad6f1 1461 GtkBox *vbox;
1462 GtkWidget *menubar, *menu, *menuitem;
f12cdd72 1463 GdkPixmap *iconpm;
1464 GList *iconlist;
eb2ad6f1 1465 int x, y, n;
dafd6cf6 1466 char errbuf[1024];
f12cdd72 1467 extern char *const *const xpm_icons[];
1468 extern const int n_xpm_icons;
83680571 1469
2ef96bd6 1470 fe = snew(frontend);
83680571 1471
171fbdaa 1472 fe->timer_active = FALSE;
1473 fe->timer_id = -1;
1474
dafd6cf6 1475 fe->me = midend_new(fe, &thegame, &gtk_drawing, fe);
171fbdaa 1476
7d1cfbb7 1477 if (arg) {
1478 char *err;
afc306fc 1479 FILE *fp;
dafd6cf6 1480
1481 errbuf[0] = '\0';
1482
afc306fc 1483 switch (argtype) {
1484 case ARG_ID:
1485 err = midend_game_id(fe->me, arg);
1486 if (!err)
1487 midend_new_game(fe->me);
1488 else
1489 sprintf(errbuf, "Invalid game ID: %.800s", err);
1490 break;
1491 case ARG_SAVE:
1492 fp = fopen(arg, "r");
7d1cfbb7 1493 if (!fp) {
afc306fc 1494 sprintf(errbuf, "Error opening file: %.800s", strerror(errno));
7d1cfbb7 1495 } else {
1496 err = midend_deserialise(fe->me, savefile_read, fp);
93548721 1497 if (err)
afc306fc 1498 sprintf(errbuf, "Invalid save file: %.800s", err);
93548721 1499 fclose(fp);
7d1cfbb7 1500 }
afc306fc 1501 break;
1502 default /*case ARG_EITHER*/:
1503 /*
1504 * First try treating the argument as a game ID.
1505 */
1506 err = midend_game_id(fe->me, arg);
1507 if (!err) {
1508 /*
1509 * It's a valid game ID.
1510 */
1511 midend_new_game(fe->me);
1512 } else {
1513 FILE *fp = fopen(arg, "r");
1514 if (!fp) {
1515 sprintf(errbuf, "Supplied argument is neither a game ID (%.400s)"
1516 " nor a save file (%.400s)", err, strerror(errno));
1517 } else {
1518 err = midend_deserialise(fe->me, savefile_read, fp);
1519 if (err)
1520 sprintf(errbuf, "%.800s", err);
1521 fclose(fp);
1522 }
1523 }
1524 break;
1525 }
dafd6cf6 1526 if (*errbuf) {
1527 *error = dupstr(errbuf);
7d1cfbb7 1528 midend_free(fe->me);
1529 sfree(fe);
1530 return NULL;
1531 }
1532
1533 } else {
1534 midend_new_game(fe->me);
8b7938e7 1535 }
7f77ea24 1536
2ef96bd6 1537 fe->window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
be8d5aa1 1538 gtk_window_set_title(GTK_WINDOW(fe->window), thegame.name);
47432032 1539
eb2ad6f1 1540 vbox = GTK_BOX(gtk_vbox_new(FALSE, 0));
1541 gtk_container_add(GTK_CONTAINER(fe->window), GTK_WIDGET(vbox));
1542 gtk_widget_show(GTK_WIDGET(vbox));
1543
a383a9be 1544 fe->accelgroup = gtk_accel_group_new();
1545 gtk_window_add_accel_group(GTK_WINDOW(fe->window), fe->accelgroup);
1546
eb2ad6f1 1547 menubar = gtk_menu_bar_new();
1548 gtk_box_pack_start(vbox, menubar, FALSE, FALSE, 0);
1549 gtk_widget_show(menubar);
1550
1551 menuitem = gtk_menu_item_new_with_label("Game");
1552 gtk_container_add(GTK_CONTAINER(menubar), menuitem);
1553 gtk_widget_show(menuitem);
1554
1555 menu = gtk_menu_new();
1556 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
1557
1558 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "New", 'n');
7f89707c 1559
1560 menuitem = gtk_menu_item_new_with_label("Restart");
1561 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1562 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1563 GTK_SIGNAL_FUNC(menu_restart_event), fe);
1564 gtk_widget_show(menuitem);
eb2ad6f1 1565
5928817c 1566 menuitem = gtk_menu_item_new_with_label("Specific...");
1567 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1185e3c5 1568 GINT_TO_POINTER(CFG_DESC));
1569 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1570 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1571 GTK_SIGNAL_FUNC(menu_config_event), fe);
1572 gtk_widget_show(menuitem);
1573
1574 menuitem = gtk_menu_item_new_with_label("Random Seed...");
1575 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
5928817c 1576 GINT_TO_POINTER(CFG_SEED));
1577 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1578 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1579 GTK_SIGNAL_FUNC(menu_config_event), fe);
1580 gtk_widget_show(menuitem);
1581
be8d5aa1 1582 if ((n = midend_num_presets(fe->me)) > 0 || thegame.can_configure) {
eb2ad6f1 1583 GtkWidget *submenu;
1584 int i;
1585
1586 menuitem = gtk_menu_item_new_with_label("Type");
c8230524 1587 gtk_container_add(GTK_CONTAINER(menubar), menuitem);
eb2ad6f1 1588 gtk_widget_show(menuitem);
1589
1590 submenu = gtk_menu_new();
1591 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), submenu);
1592
1593 for (i = 0; i < n; i++) {
1594 char *name;
1595 game_params *params;
1596
1597 midend_fetch_preset(fe->me, i, &name, &params);
1598
1599 menuitem = gtk_menu_item_new_with_label(name);
1600 gtk_container_add(GTK_CONTAINER(submenu), menuitem);
1601 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data", params);
1602 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1603 GTK_SIGNAL_FUNC(menu_preset_event), fe);
1604 gtk_widget_show(menuitem);
1605 }
c8230524 1606
be8d5aa1 1607 if (thegame.can_configure) {
c8230524 1608 menuitem = gtk_menu_item_new_with_label("Custom...");
5928817c 1609 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1610 GPOINTER_TO_INT(CFG_SETTINGS));
c8230524 1611 gtk_container_add(GTK_CONTAINER(submenu), menuitem);
1612 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1613 GTK_SIGNAL_FUNC(menu_config_event), fe);
1614 gtk_widget_show(menuitem);
1615 }
eb2ad6f1 1616 }
1617
668be019 1618 add_menu_separator(GTK_CONTAINER(menu));
cccb7f09 1619 menuitem = gtk_menu_item_new_with_label("Load...");
668be019 1620 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1621 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1622 GTK_SIGNAL_FUNC(menu_load_event), fe);
1623 gtk_widget_show(menuitem);
cccb7f09 1624 menuitem = gtk_menu_item_new_with_label("Save...");
668be019 1625 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1626 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1627 GTK_SIGNAL_FUNC(menu_save_event), fe);
1628 gtk_widget_show(menuitem);
eb2ad6f1 1629 add_menu_separator(GTK_CONTAINER(menu));
1630 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Undo", 'u');
a383a9be 1631 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Redo", 'r');
9b4b03d3 1632 if (thegame.can_format_as_text) {
1633 add_menu_separator(GTK_CONTAINER(menu));
1634 menuitem = gtk_menu_item_new_with_label("Copy");
1635 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1636 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1637 GTK_SIGNAL_FUNC(menu_copy_event), fe);
1638 gtk_widget_show(menuitem);
1639 }
2ac6d24e 1640 if (thegame.can_solve) {
1641 add_menu_separator(GTK_CONTAINER(menu));
1642 menuitem = gtk_menu_item_new_with_label("Solve");
1643 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1644 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1645 GTK_SIGNAL_FUNC(menu_solve_event), fe);
1646 gtk_widget_show(menuitem);
1647 }
eb2ad6f1 1648 add_menu_separator(GTK_CONTAINER(menu));
1649 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Exit", 'q');
7f77ea24 1650
97098757 1651 menuitem = gtk_menu_item_new_with_label("Help");
1652 gtk_container_add(GTK_CONTAINER(menubar), menuitem);
1653 gtk_widget_show(menuitem);
1654
1655 menu = gtk_menu_new();
1656 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
1657
1658 menuitem = gtk_menu_item_new_with_label("About");
1659 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1660 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1661 GTK_SIGNAL_FUNC(menu_about_event), fe);
1662 gtk_widget_show(menuitem);
1663
2ef96bd6 1664 {
1665 int i, ncolours;
1666 float *colours;
1667 gboolean *success;
7f77ea24 1668
2ef96bd6 1669 fe->colmap = gdk_colormap_get_system();
1670 colours = midend_colours(fe->me, &ncolours);
1671 fe->ncolours = ncolours;
1672 fe->colours = snewn(ncolours, GdkColor);
1673 for (i = 0; i < ncolours; i++) {
813593cc 1674 fe->colours[i].red = colours[i*3] * 0xFFFF;
1675 fe->colours[i].green = colours[i*3+1] * 0xFFFF;
1676 fe->colours[i].blue = colours[i*3+2] * 0xFFFF;
2ef96bd6 1677 }
1678 success = snewn(ncolours, gboolean);
1679 gdk_colormap_alloc_colors(fe->colmap, fe->colours, ncolours,
1680 FALSE, FALSE, success);
1681 for (i = 0; i < ncolours; i++) {
1682 if (!success[i])
1683 g_error("couldn't allocate colour %d (#%02x%02x%02x)\n",
1684 i, fe->colours[i].red >> 8,
1685 fe->colours[i].green >> 8,
1686 fe->colours[i].blue >> 8);
1687 }
1688 }
7f77ea24 1689
fd1a1a2b 1690 if (midend_wants_statusbar(fe->me)) {
5725d728 1691 GtkWidget *viewport;
1692 GtkRequisition req;
1693
1694 viewport = gtk_viewport_new(NULL, NULL);
1695 gtk_viewport_set_shadow_type(GTK_VIEWPORT(viewport), GTK_SHADOW_NONE);
fd1a1a2b 1696 fe->statusbar = gtk_statusbar_new();
5725d728 1697 gtk_container_add(GTK_CONTAINER(viewport), fe->statusbar);
1698 gtk_widget_show(viewport);
1699 gtk_box_pack_end(vbox, viewport, FALSE, FALSE, 0);
fd1a1a2b 1700 gtk_widget_show(fe->statusbar);
1701 fe->statusctx = gtk_statusbar_get_context_id
1702 (GTK_STATUSBAR(fe->statusbar), "game");
1703 gtk_statusbar_push(GTK_STATUSBAR(fe->statusbar), fe->statusctx,
5725d728 1704 "test");
1705 gtk_widget_size_request(fe->statusbar, &req);
1706#if 0
1707 /* For GTK 2.0, should we be using gtk_widget_set_size_request? */
1708#endif
60d42abc 1709 gtk_widget_set_usize(viewport, -1, req.height);
fd1a1a2b 1710 } else
1711 fe->statusbar = NULL;
1712
2ef96bd6 1713 fe->area = gtk_drawing_area_new();
1e3e152d 1714 get_size(fe, &x, &y);
2ef96bd6 1715 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
1716 fe->w = x;
1717 fe->h = y;
1718
1e3e152d 1719 gtk_box_pack_end(vbox, fe->area, TRUE, TRUE, 0);
2ef96bd6 1720
1721 fe->pixmap = NULL;
4efb3868 1722 fe->fonts = NULL;
1723 fe->nfonts = fe->fontsize = 0;
2ef96bd6 1724
9b4b03d3 1725 fe->paste_data = NULL;
1726 fe->paste_data_len = 0;
1727
2ef96bd6 1728 gtk_signal_connect(GTK_OBJECT(fe->window), "destroy",
1729 GTK_SIGNAL_FUNC(destroy), fe);
1730 gtk_signal_connect(GTK_OBJECT(fe->window), "key_press_event",
1731 GTK_SIGNAL_FUNC(key_event), fe);
1732 gtk_signal_connect(GTK_OBJECT(fe->area), "button_press_event",
1733 GTK_SIGNAL_FUNC(button_event), fe);
74a4e547 1734 gtk_signal_connect(GTK_OBJECT(fe->area), "button_release_event",
1735 GTK_SIGNAL_FUNC(button_event), fe);
1736 gtk_signal_connect(GTK_OBJECT(fe->area), "motion_notify_event",
1737 GTK_SIGNAL_FUNC(motion_event), fe);
9b4b03d3 1738 gtk_signal_connect(GTK_OBJECT(fe->area), "selection_get",
1739 GTK_SIGNAL_FUNC(selection_get), fe);
1740 gtk_signal_connect(GTK_OBJECT(fe->area), "selection_clear_event",
1741 GTK_SIGNAL_FUNC(selection_clear), fe);
2ef96bd6 1742 gtk_signal_connect(GTK_OBJECT(fe->area), "expose_event",
1743 GTK_SIGNAL_FUNC(expose_area), fe);
fd1a1a2b 1744 gtk_signal_connect(GTK_OBJECT(fe->window), "map_event",
1745 GTK_SIGNAL_FUNC(map_window), fe);
2ef96bd6 1746 gtk_signal_connect(GTK_OBJECT(fe->area), "configure_event",
1747 GTK_SIGNAL_FUNC(configure_area), fe);
1748
74a4e547 1749 gtk_widget_add_events(GTK_WIDGET(fe->area),
1750 GDK_BUTTON_PRESS_MASK |
1751 GDK_BUTTON_RELEASE_MASK |
1752 GDK_BUTTON_MOTION_MASK);
2ef96bd6 1753
f12cdd72 1754 if (n_xpm_icons) {
1755 gtk_widget_realize(fe->window);
1756 iconpm = gdk_pixmap_create_from_xpm_d(fe->window->window, NULL,
1757 NULL, (gchar **)xpm_icons[0]);
1758 gdk_window_set_icon(fe->window->window, NULL, iconpm, NULL);
1759 iconlist = NULL;
1760 for (n = 0; n < n_xpm_icons; n++) {
1761 iconlist =
1762 g_list_append(iconlist,
1763 gdk_pixbuf_new_from_xpm_data((const gchar **)
1764 xpm_icons[n]));
1765 }
1766 gdk_window_set_icon_list(fe->window->window, iconlist);
1767 }
1768
2ef96bd6 1769 gtk_widget_show(fe->area);
1770 gtk_widget_show(fe->window);
1771
1e3e152d 1772 gdk_window_set_background(fe->area->window, &fe->colours[0]);
1773 gdk_window_set_background(fe->window->window, &fe->colours[0]);
1774
2ef96bd6 1775 return fe;
83680571 1776}
1777
dafd6cf6 1778char *fgetline(FILE *fp)
1779{
1780 char *ret = snewn(512, char);
1781 int size = 512, len = 0;
1782 while (fgets(ret + len, size - len, fp)) {
1783 len += strlen(ret + len);
1784 if (ret[len-1] == '\n')
1785 break; /* got a newline, we're done */
1786 size = len + 512;
1787 ret = sresize(ret, size, char);
1788 }
1789 if (len == 0) { /* first fgets returned NULL */
1790 sfree(ret);
1791 return NULL;
1792 }
1793 ret[len] = '\0';
1794 return ret;
1795}
1796
83680571 1797int main(int argc, char **argv)
1798{
8b7938e7 1799 char *pname = argv[0];
1800 char *error;
dafd6cf6 1801 int ngenerate = 0, print = FALSE, px = 1, py = 1;
1802 int soln = FALSE, colour = FALSE;
1803 float scale = 1.0F;
afc306fc 1804 float redo_proportion = 0.0F;
dafd6cf6 1805 char *arg = NULL;
afc306fc 1806 int argtype = ARG_EITHER;
9edb9f35 1807 char *screenshot_file = NULL;
dafd6cf6 1808 int doing_opts = TRUE;
1809 int ac = argc;
1810 char **av = argv;
1811 char errbuf[500];
8b7938e7 1812
dafd6cf6 1813 /*
1814 * Command line parsing in this function is rather fiddly,
1815 * because GTK wants to have a go at argc/argv _first_ - and
1816 * yet we can't let it, because gtk_init() will bomb out if it
1817 * can't open an X display, whereas in fact we want to permit
1818 * our --generate and --print modes to run without an X
1819 * display.
1820 *
1821 * So what we do is:
1822 * - we parse the command line ourselves, without modifying
1823 * argc/argv
1824 * - if we encounter an error which might plausibly be the
1825 * result of a GTK command line (i.e. not detailed errors in
1826 * particular options of ours) we store the error message
1827 * and terminate parsing.
1828 * - if we got enough out of the command line to know it
1829 * specifies a non-X mode of operation, we either display
1830 * the stored error and return failure, or if there is no
1831 * stored error we do the non-X operation and return
1832 * success.
1833 * - otherwise, we go straight to gtk_init().
1834 */
1835
1836 errbuf[0] = '\0';
1837 while (--ac > 0) {
1838 char *p = *++av;
1839 if (doing_opts && !strcmp(p, "--version")) {
1840 printf("%s, from Simon Tatham's Portable Puzzle Collection\n%s\n",
1841 thegame.name, ver);
1842 return 0;
1843 } else if (doing_opts && !strcmp(p, "--generate")) {
1844 if (--ac > 0) {
1845 ngenerate = atoi(*++av);
1846 if (!ngenerate) {
1847 fprintf(stderr, "%s: '--generate' expected a number\n",
1848 pname);
1849 return 1;
1850 }
1851 } else
1852 ngenerate = 1;
1853 } else if (doing_opts && !strcmp(p, "--print")) {
1854 if (!thegame.can_print) {
1855 fprintf(stderr, "%s: this game does not support printing\n",
1856 pname);
1857 return 1;
1858 }
1859 print = TRUE;
1860 if (--ac > 0) {
1861 char *dim = *++av;
1862 if (sscanf(dim, "%dx%d", &px, &py) != 2) {
1863 fprintf(stderr, "%s: unable to parse argument '%s' to "
1864 "'--print'\n", pname, dim);
1865 return 1;
1866 }
1867 } else {
1868 px = py = 1;
1869 }
1870 } else if (doing_opts && !strcmp(p, "--scale")) {
1871 if (--ac > 0) {
1872 scale = atof(*++av);
1873 } else {
1874 fprintf(stderr, "%s: no argument supplied to '--scale'\n",
1875 pname);
1876 return 1;
1877 }
afc306fc 1878 } else if (doing_opts && !strcmp(p, "--redo")) {
1879 /*
1880 * This is an internal option which I don't expect
1881 * users to have any particular use for. The effect of
1882 * --redo is that once the game has been loaded and
1883 * initialised, the next move in the redo chain is
1884 * replayed, and the game screen is redrawn part way
1885 * through the making of the move. This is only
1886 * meaningful if there _is_ a next move in the redo
1887 * chain, which means in turn that this option is only
1888 * useful if you're also passing a save file on the
1889 * command line.
1890 *
1891 * This option is used by the script which generates
1892 * the puzzle icons and website screenshots, and I
1893 * don't imagine it's useful for anything else.
1894 * (Unless, I suppose, users don't like my screenshots
1895 * and want to generate their own in the same way for
1896 * some repackaged version of the puzzles.)
1897 */
1898 if (--ac > 0) {
1899 redo_proportion = atof(*++av);
1900 } else {
1901 fprintf(stderr, "%s: no argument supplied to '--redo'\n",
1902 pname);
1903 return 1;
1904 }
9edb9f35 1905 } else if (doing_opts && !strcmp(p, "--screenshot")) {
afc306fc 1906 /*
1907 * Another internal option for the icon building
9edb9f35 1908 * script. This causes a screenshot of the central
afc306fc 1909 * drawing area (i.e. not including the menu bar or
9edb9f35 1910 * status bar) to be saved to a PNG file once the
1911 * window has been drawn, and then the application
1912 * quits immediately.
afc306fc 1913 */
9edb9f35 1914 if (--ac > 0) {
1915 screenshot_file = *++av;
1916 } else {
1917 fprintf(stderr, "%s: no argument supplied to '--screenshot'\n",
1918 pname);
1919 return 1;
1920 }
dafd6cf6 1921 } else if (doing_opts && (!strcmp(p, "--with-solutions") ||
1922 !strcmp(p, "--with-solution") ||
1923 !strcmp(p, "--with-solns") ||
1924 !strcmp(p, "--with-soln") ||
1925 !strcmp(p, "--solutions") ||
1926 !strcmp(p, "--solution") ||
1927 !strcmp(p, "--solns") ||
1928 !strcmp(p, "--soln"))) {
1929 soln = TRUE;
1930 } else if (doing_opts && !strcmp(p, "--colour")) {
1931 if (!thegame.can_print_in_colour) {
1932 fprintf(stderr, "%s: this game does not support colour"
1933 " printing\n", pname);
1934 return 1;
1935 }
1936 colour = TRUE;
afc306fc 1937 } else if (doing_opts && !strcmp(p, "--load")) {
1938 argtype = ARG_SAVE;
1939 } else if (doing_opts && !strcmp(p, "--game")) {
1940 argtype = ARG_ID;
dafd6cf6 1941 } else if (doing_opts && !strcmp(p, "--")) {
1942 doing_opts = FALSE;
1943 } else if (!doing_opts || p[0] != '-') {
1944 if (arg) {
1945 fprintf(stderr, "%s: more than one argument supplied\n",
1946 pname);
1947 return 1;
1948 }
1949 arg = p;
1950 } else {
1951 sprintf(errbuf, "%.100s: unrecognised option '%.100s'\n",
1952 pname, p);
1953 break;
1954 }
45f953cc 1955 }
1956
95c76d7c 1957 if (*errbuf) {
1958 fputs(errbuf, stderr);
1959 return 1;
1960 }
1961
d91e1fc9 1962 /*
1963 * Special standalone mode for generating puzzle IDs on the
1964 * command line. Useful for generating puzzles to be printed
1965 * out and solved offline (for puzzles where that even makes
1966 * sense - Solo, for example, is a lot more pencil-and-paper
dafd6cf6 1967 * friendly than Twiddle!)
d91e1fc9 1968 *
1969 * Usage:
1970 *
1971 * <puzzle-name> --generate [<n> [<params>]]
1972 *
1973 * <n>, if present, is the number of puzzle IDs to generate.
1974 * <params>, if present, is the same type of parameter string
1975 * you would pass to the puzzle when running it in GUI mode,
1976 * including optional extras such as the expansion factor in
1977 * Rectangles and the difficulty level in Solo.
1978 *
1979 * If you specify <params>, you must also specify <n> (although
1980 * you may specify it to be 1). Sorry; that was the
1981 * simplest-to-parse command-line syntax I came up with.
1982 */
dafd6cf6 1983 if (ngenerate > 0 || print) {
1984 int i, n = 1;
1985 midend *me;
1986 char *id;
1987 document *doc = NULL;
1988
dafd6cf6 1989 n = ngenerate;
1990
1991 me = midend_new(NULL, &thegame, NULL, NULL);
1992 i = 0;
1993
1994 if (print)
1995 doc = document_new(px, py, scale);
1996
1997 /*
1998 * In this loop, we either generate a game ID or read one
1999 * from stdin depending on whether we're in generate mode;
2000 * then we either write it to stdout or print it, depending
2001 * on whether we're in print mode. Thus, this loop handles
2002 * generate-to-stdout, print-from-stdin and generate-and-
2003 * immediately-print modes.
2004 *
2005 * (It could also handle a copy-stdin-to-stdout mode,
2006 * although there's currently no combination of options
2007 * which will cause this loop to be activated in that mode.
2008 * It wouldn't be _entirely_ pointless, though, because
2009 * stdin could contain bare params strings or random-seed
2010 * IDs, and stdout would contain nothing but fully
2011 * generated descriptive game IDs.)
2012 */
2013 while (ngenerate == 0 || i < n) {
2014 char *pstr, *err;
2015
2016 if (ngenerate == 0) {
2017 pstr = fgetline(stdin);
2018 if (!pstr)
2019 break;
2020 pstr[strcspn(pstr, "\r\n")] = '\0';
2021 } else {
2022 if (arg) {
2023 pstr = snewn(strlen(arg) + 40, char);
2024
2025 strcpy(pstr, arg);
2026 if (i > 0 && strchr(arg, '#'))
2027 sprintf(pstr + strlen(pstr), "-%d", i);
2028 } else
2029 pstr = NULL;
2030 }
2031
2032 if (pstr) {
2033 err = midend_game_id(me, pstr);
2034 if (err) {
2035 fprintf(stderr, "%s: error parsing '%s': %s\n",
2036 pname, pstr, err);
2037 return 1;
2038 }
2039 }
2040 sfree(pstr);
2041
2042 midend_new_game(me);
2043
2044 if (doc) {
2045 err = midend_print_puzzle(me, doc, soln);
2046 if (err) {
2047 fprintf(stderr, "%s: error in printing: %s\n", pname, err);
2048 return 1;
2049 }
2050 } else {
2051 id = midend_get_game_id(me);
2052 puts(id);
2053 sfree(id);
2054 }
2055
2056 i++;
d91e1fc9 2057 }
8b7938e7 2058
dafd6cf6 2059 if (doc) {
2060 psdata *ps = ps_init(stdout, colour);
2061 document_print(doc, ps_drawing_api(ps));
2062 document_free(doc);
2063 ps_free(ps);
2064 }
2065
2066 midend_free(me);
2067
d91e1fc9 2068 return 0;
2069 } else {
afc306fc 2070 frontend *fe;
d91e1fc9 2071
2072 gtk_init(&argc, &argv);
2073
afc306fc 2074 fe = new_window(arg, argtype, &error);
2075
2076 if (!fe) {
d91e1fc9 2077 fprintf(stderr, "%s: %s\n", pname, error);
2078 return 1;
2079 }
2080
9edb9f35 2081 if (screenshot_file) {
afc306fc 2082 /*
2083 * Some puzzles will not redraw their entire area if
2084 * given a partially completed animation, which means
2085 * we must redraw now and _then_ redraw again after
2086 * freezing the move timer.
2087 */
2088 midend_force_redraw(fe->me);
2089 }
2090
2091 if (redo_proportion) {
2092 /* Start a redo. */
2093 midend_process_key(fe->me, 0, 0, 'r');
2094 /* And freeze the timer at the specified position. */
2095 midend_freeze_timer(fe->me, redo_proportion);
2096 }
2097
9edb9f35 2098 if (screenshot_file) {
2099 GdkPixbuf *pb;
851e6f7c 2100 GError *gerror = NULL;
9edb9f35 2101
afc306fc 2102 midend_redraw(fe->me);
9edb9f35 2103
2104 pb = gdk_pixbuf_get_from_drawable(NULL, fe->pixmap,
2105 NULL, 0, 0, 0, 0, -1, -1);
5136fa6a 2106 gdk_pixbuf_save(pb, screenshot_file, "png", &gerror, NULL);
9edb9f35 2107
2108 exit(0);
afc306fc 2109 }
2110
d91e1fc9 2111 gtk_main();
2112 }
83680571 2113
2114 return 0;
2115}