Refactoring patch from Ben Hutchings: move all the Gtk resize code into one
[sgt/puzzles] / gtk.c
1 /*
2 * gtk.c: GTK front end for my puzzle collection.
3 */
4
5 #include <stdio.h>
6 #include <assert.h>
7 #include <stdlib.h>
8 #include <time.h>
9 #include <stdarg.h>
10 #include <string.h>
11 #include <errno.h>
12
13 #include <sys/time.h>
14
15 #include <gtk/gtk.h>
16 #include <gdk/gdkkeysyms.h>
17
18 #include <gdk-pixbuf/gdk-pixbuf.h>
19
20 #include <gdk/gdkx.h>
21 #include <X11/Xlib.h>
22 #include <X11/Xutil.h>
23 #include <X11/Xatom.h>
24
25 #include "puzzles.h"
26
27 #if GTK_CHECK_VERSION(2,0,0)
28 #define USE_PANGO
29 #endif
30
31 #ifdef DEBUGGING
32 static FILE *debug_fp = NULL;
33
34 void 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
48 void 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
60 /* ----------------------------------------------------------------------
61 * Error reporting functions used elsewhere.
62 */
63
64 void 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 }
77
78 /* ----------------------------------------------------------------------
79 * GTK front end to puzzles.
80 */
81
82 struct font {
83 #ifdef USE_PANGO
84 PangoFontDescription *desc;
85 #else
86 GdkFont *font;
87 #endif
88 int type;
89 int size;
90 };
91
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 */
99 struct frontend {
100 GtkWidget *window;
101 GtkAccelGroup *accelgroup;
102 GtkWidget *area;
103 GtkWidget *statusbar;
104 guint statusctx;
105 GdkPixmap *pixmap;
106 GdkColor *colours;
107 int ncolours;
108 GdkColormap *colmap;
109 int w, h;
110 midend *me;
111 GdkGC *gc;
112 int bbox_l, bbox_r, bbox_u, bbox_d;
113 int timer_active, timer_id;
114 struct timeval last_time;
115 struct font *fonts;
116 int nfonts, fontsize;
117 config_item *cfg;
118 int cfg_which, cfgret;
119 GtkWidget *cfgbox;
120 void *paste_data;
121 int paste_data_len;
122 int pw, ph; /* pixmap size (w, h are area size) */
123 int ox, oy; /* offset of pixmap in drawing area */
124 char *filesel_name;
125 };
126
127 void get_random_seed(void **randseed, int *randseedsize)
128 {
129 struct timeval *tvp = snew(struct timeval);
130 gettimeofday(tvp, NULL);
131 *randseed = (void *)tvp;
132 *randseedsize = sizeof(struct timeval);
133 }
134
135 void 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
143 void gtk_status_bar(void *handle, char *text)
144 {
145 frontend *fe = (frontend *)handle;
146
147 assert(fe->statusbar);
148
149 gtk_statusbar_pop(GTK_STATUSBAR(fe->statusbar), fe->statusctx);
150 gtk_statusbar_push(GTK_STATUSBAR(fe->statusbar), fe->statusctx, text);
151 }
152
153 void gtk_start_draw(void *handle)
154 {
155 frontend *fe = (frontend *)handle;
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
163 void gtk_clip(void *handle, int x, int y, int w, int h)
164 {
165 frontend *fe = (frontend *)handle;
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
176 void gtk_unclip(void *handle)
177 {
178 frontend *fe = (frontend *)handle;
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
189 void gtk_draw_text(void *handle, int x, int y, int fonttype, int fontsize,
190 int align, int colour, char *text)
191 {
192 frontend *fe = (frontend *)handle;
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
213 #ifdef USE_PANGO
214 /*
215 * Use Pango to find the closest match to the requested
216 * font.
217 */
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");
225 pango_font_description_set_weight(fd, PANGO_WEIGHT_BOLD);
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
251 fe->fonts[i].desc = fd;
252 }
253
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");
262 #endif
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;
287 else
288 rect.y -= rect.height;
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);
298 }
299
300 #else
301 /*
302 * Find string dimensions and process alignment.
303 */
304 {
305 int lb, rb, wid, asc, desc;
306
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",
313 &lb, &rb, &wid, &asc, &desc);
314 if (align & ALIGN_VCENTRE)
315 y += asc - (asc+desc)/2;
316 else
317 y += asc;
318
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
327 if (align & ALIGN_HCENTRE)
328 x -= wid / 2;
329 else if (align & ALIGN_HRIGHT)
330 x -= wid;
331
332 }
333
334 /*
335 * Actually draw the text.
336 */
337 gdk_draw_string(fe->pixmap, fe->fonts[i].font, fe->gc, x, y, text);
338 #endif
339
340 }
341
342 void gtk_draw_rect(void *handle, int x, int y, int w, int h, int colour)
343 {
344 frontend *fe = (frontend *)handle;
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
349 void gtk_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
350 {
351 frontend *fe = (frontend *)handle;
352 gdk_gc_set_foreground(fe->gc, &fe->colours[colour]);
353 gdk_draw_line(fe->pixmap, fe->gc, x1, y1, x2, y2);
354 }
355
356 void gtk_draw_poly(void *handle, int *coords, int npoints,
357 int fillcolour, int outlinecolour)
358 {
359 frontend *fe = (frontend *)handle;
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
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]);
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);
385
386 sfree(points);
387 }
388
389 void gtk_draw_circle(void *handle, int cx, int cy, int radius,
390 int fillcolour, int outlinecolour)
391 {
392 frontend *fe = (frontend *)handle;
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);
405 }
406
407 struct blitter {
408 GdkPixmap *pixmap;
409 int w, h, x, y;
410 };
411
412 blitter *gtk_blitter_new(void *handle, int w, int h)
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
426 void gtk_blitter_free(void *handle, blitter *bl)
427 {
428 if (bl->pixmap)
429 gdk_pixmap_unref(bl->pixmap);
430 sfree(bl);
431 }
432
433 void gtk_blitter_save(void *handle, blitter *bl, int x, int y)
434 {
435 frontend *fe = (frontend *)handle;
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
446 void gtk_blitter_load(void *handle, blitter *bl, int x, int y)
447 {
448 frontend *fe = (frontend *)handle;
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
460 void gtk_draw_update(void *handle, int x, int y, int w, int h)
461 {
462 frontend *fe = (frontend *)handle;
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
469 void gtk_end_draw(void *handle)
470 {
471 frontend *fe = (frontend *)handle;
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,
480 fe->ox + fe->bbox_l, fe->oy + fe->bbox_u,
481 fe->bbox_r - fe->bbox_l, fe->bbox_d - fe->bbox_u);
482 }
483 }
484
485 const 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
505 static void destroy(GtkWidget *widget, gpointer data)
506 {
507 frontend *fe = (frontend *)data;
508 deactivate_timer(fe);
509 midend_free(fe->me);
510 gtk_main_quit();
511 }
512
513 static gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data)
514 {
515 frontend *fe = (frontend *)data;
516 int keyval;
517 int shift = (event->state & GDK_SHIFT_MASK) ? MOD_SHFT : 0;
518 int ctrl = (event->state & GDK_CONTROL_MASK) ? MOD_CTRL : 0;
519
520 if (!fe->pixmap)
521 return TRUE;
522
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
533 if (event->keyval == GDK_Up)
534 keyval = shift | ctrl | CURSOR_UP;
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)
538 keyval = shift | ctrl | CURSOR_DOWN;
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)
542 keyval = shift | ctrl | CURSOR_LEFT;
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)
546 keyval = shift | ctrl | CURSOR_RIGHT;
547 else if (event->keyval == GDK_KP_Right || event->keyval == GDK_KP_6)
548 keyval = MOD_NUM_KEYPAD | '6';
549 else if (event->keyval == GDK_KP_Home || event->keyval == GDK_KP_7)
550 keyval = MOD_NUM_KEYPAD | '7';
551 else if (event->keyval == GDK_KP_End || event->keyval == GDK_KP_1)
552 keyval = MOD_NUM_KEYPAD | '1';
553 else if (event->keyval == GDK_KP_Page_Up || event->keyval == GDK_KP_9)
554 keyval = MOD_NUM_KEYPAD | '9';
555 else if (event->keyval == GDK_KP_Page_Down || event->keyval == GDK_KP_3)
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';
561 else if (event->keyval == GDK_BackSpace ||
562 event->keyval == GDK_Delete ||
563 event->keyval == GDK_KP_Delete)
564 keyval = '\177';
565 else if (event->string[0] && !event->string[1])
566 keyval = (unsigned char)event->string[0];
567 else
568 keyval = -1;
569
570 if (keyval >= 0 &&
571 !midend_process_key(fe->me, 0, 0, keyval))
572 gtk_widget_destroy(fe->window);
573
574 return TRUE;
575 }
576
577 static gint button_event(GtkWidget *widget, GdkEventButton *event,
578 gpointer data)
579 {
580 frontend *fe = (frontend *)data;
581 int button;
582
583 if (!fe->pixmap)
584 return TRUE;
585
586 if (event->type != GDK_BUTTON_PRESS && event->type != GDK_BUTTON_RELEASE)
587 return TRUE;
588
589 if (event->button == 2 || (event->state & GDK_SHIFT_MASK))
590 button = MIDDLE_BUTTON;
591 else if (event->button == 3 || (event->state & GDK_MOD1_MASK))
592 button = RIGHT_BUTTON;
593 else if (event->button == 1)
594 button = LEFT_BUTTON;
595 else
596 return FALSE; /* don't even know what button! */
597
598 if (event->type == GDK_BUTTON_RELEASE)
599 button += LEFT_RELEASE - LEFT_BUTTON;
600
601 if (!midend_process_key(fe->me, event->x - fe->ox,
602 event->y - fe->oy, button))
603 gtk_widget_destroy(fe->window);
604
605 return TRUE;
606 }
607
608 static 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
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
626 if (!midend_process_key(fe->me, event->x - fe->ox,
627 event->y - fe->oy, button))
628 gtk_widget_destroy(fe->window);
629
630 return TRUE;
631 }
632
633 static gint expose_area(GtkWidget *widget, GdkEventExpose *event,
634 gpointer data)
635 {
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,
642 event->area.x - fe->ox, event->area.y - fe->oy,
643 event->area.x, event->area.y,
644 event->area.width, event->area.height);
645 }
646 return TRUE;
647 }
648
649 static 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
664 static gint configure_area(GtkWidget *widget,
665 GdkEventConfigure *event, gpointer data)
666 {
667 frontend *fe = (frontend *)data;
668 GdkGC *gc;
669 int x, y;
670
671 if (fe->pixmap)
672 gdk_pixmap_unref(fe->pixmap);
673
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);
683
684 gc = gdk_gc_new(fe->area->window);
685 gdk_gc_set_foreground(gc, &fe->colours[0]);
686 gdk_draw_rectangle(fe->pixmap, gc, 1, 0, 0, fe->pw, fe->ph);
687 gdk_draw_rectangle(widget->window, gc, 1, 0, 0,
688 event->width, event->height);
689 gdk_gc_unref(gc);
690
691 midend_force_redraw(fe->me);
692
693 return TRUE;
694 }
695
696 static gint timer_func(gpointer data)
697 {
698 frontend *fe = (frontend *)data;
699
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 }
709
710 return fe->timer_active;
711 }
712
713 void deactivate_timer(frontend *fe)
714 {
715 if (!fe)
716 return; /* can happen due to --generate */
717 if (fe->timer_active)
718 gtk_timeout_remove(fe->timer_id);
719 fe->timer_active = FALSE;
720 }
721
722 void activate_timer(frontend *fe)
723 {
724 if (!fe)
725 return; /* can happen due to --generate */
726 if (!fe->timer_active) {
727 fe->timer_id = gtk_timeout_add(20, timer_func, fe);
728 gettimeofday(&fe->last_time, NULL);
729 }
730 fe->timer_active = TRUE;
731 }
732
733 static void window_destroy(GtkWidget *widget, gpointer data)
734 {
735 gtk_main_quit();
736 }
737
738 static void msgbox_button_clicked(GtkButton *button, gpointer data)
739 {
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
747 gtk_widget_destroy(GTK_WIDGET(data));
748 }
749
750 static 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
765 enum { MB_OK, MB_YESNO };
766
767 int message_box(GtkWidget *parent, char *title, char *msg, int centre,
768 int type)
769 {
770 GtkWidget *window, *hbox, *text, *button;
771 char *titles;
772 int i, def, cancel;
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);
783 gtk_window_set_title(GTK_WINDOW(window), title);
784 gtk_label_set_line_wrap(GTK_LABEL(text), TRUE);
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));
819 gtk_signal_connect(GTK_OBJECT(window), "destroy",
820 GTK_SIGNAL_FUNC(window_destroy), NULL);
821 gtk_window_set_modal(GTK_WINDOW(window), TRUE);
822 gtk_window_set_transient_for(GTK_WINDOW(window), GTK_WINDOW(parent));
823 /* set_transient_window_pos(parent, window); */
824 gtk_widget_show(window);
825 i = -1;
826 gtk_main();
827 return (type == MB_YESNO ? i == 0 : TRUE);
828 }
829
830 void error_box(GtkWidget *parent, char *msg)
831 {
832 message_box(parent, "Error", msg, FALSE, MB_OK);
833 }
834
835 static void config_ok_button_clicked(GtkButton *button, gpointer data)
836 {
837 frontend *fe = (frontend *)data;
838 char *err;
839
840 err = midend_set_config(fe->me, fe->cfg_which, fe->cfg);
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
850 static void config_cancel_button_clicked(GtkButton *button, gpointer data)
851 {
852 frontend *fe = (frontend *)data;
853
854 gtk_widget_destroy(fe->cfgbox);
855 }
856
857 static 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
878 static 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
886 static 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
893 static 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
901 static int get_config(frontend *fe, int which)
902 {
903 GtkWidget *w, *table, *cancel;
904 char *title;
905 config_item *i;
906 int y;
907
908 fe->cfg = midend_get_config(fe->me, which, &title);
909 fe->cfg_which = which;
910 fe->cfgret = FALSE;
911
912 fe->cfgbox = gtk_dialog_new();
913 gtk_window_set_title(GTK_WINDOW(fe->cfgbox), title);
914 sfree(title);
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);
931 cancel = w;
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
939 for (i = fe->cfg; i->type != C_END; i++) {
940 gtk_table_resize(GTK_TABLE(table), y+1, 2);
941
942 switch (i->type) {
943 case C_STRING:
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);
964 gtk_signal_connect(GTK_OBJECT(w), "key_press_event",
965 GTK_SIGNAL_FUNC(editbox_key), NULL);
966 gtk_widget_show(w);
967
968 break;
969
970 case C_BOOLEAN:
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
985 case C_CHOICES:
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);
1052 gtk_signal_connect(GTK_OBJECT(fe->cfgbox), "key_press_event",
1053 GTK_SIGNAL_FUNC(win_key_press), cancel);
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));
1057 /* set_transient_window_pos(fe->window, fe->cfgbox); */
1058 gtk_widget_show(fe->cfgbox);
1059 gtk_main();
1060
1061 free_cfg(fe->cfg);
1062
1063 return fe->cfgret;
1064 }
1065
1066 static 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
1075 static 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
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
1103 static void resize_fe(frontend *fe)
1104 {
1105 int x, y;
1106
1107 get_size(fe, &x, &y);
1108 fe->w = x;
1109 fe->h = y;
1110 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
1111 {
1112 GtkRequisition req;
1113 gtk_widget_size_request(GTK_WIDGET(fe->window), &req);
1114 gtk_window_resize(GTK_WINDOW(fe->window), req.width, req.height);
1115 }
1116 }
1117
1118 static void menu_preset_event(GtkMenuItem *menuitem, gpointer data)
1119 {
1120 frontend *fe = (frontend *)data;
1121 game_params *params =
1122 (game_params *)gtk_object_get_data(GTK_OBJECT(menuitem), "user-data");
1123
1124 midend_set_params(fe->me, params);
1125 midend_new_game(fe->me);
1126 resize_fe(fe);
1127 }
1128
1129 GdkAtom compound_text_atom, utf8_string_atom;
1130 int paste_initialised = FALSE;
1131
1132 void init_paste()
1133 {
1134 unsigned char empty[] = { 0 };
1135
1136 if (paste_initialised)
1137 return;
1138
1139 if (!compound_text_atom)
1140 compound_text_atom = gdk_atom_intern("COMPOUND_TEXT", FALSE);
1141 if (!utf8_string_atom)
1142 utf8_string_atom = gdk_atom_intern("UTF8_STRING", FALSE);
1143
1144 /*
1145 * Ensure that all the cut buffers exist - according to the
1146 * ICCCM, we must do this before we start using cut buffers.
1147 */
1148 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1149 XA_CUT_BUFFER0, XA_STRING, 8, PropModeAppend, empty, 0);
1150 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1151 XA_CUT_BUFFER1, XA_STRING, 8, PropModeAppend, empty, 0);
1152 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1153 XA_CUT_BUFFER2, XA_STRING, 8, PropModeAppend, empty, 0);
1154 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1155 XA_CUT_BUFFER3, XA_STRING, 8, PropModeAppend, empty, 0);
1156 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1157 XA_CUT_BUFFER4, XA_STRING, 8, PropModeAppend, empty, 0);
1158 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1159 XA_CUT_BUFFER5, XA_STRING, 8, PropModeAppend, empty, 0);
1160 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1161 XA_CUT_BUFFER6, XA_STRING, 8, PropModeAppend, empty, 0);
1162 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1163 XA_CUT_BUFFER7, XA_STRING, 8, PropModeAppend, empty, 0);
1164 }
1165
1166 /* Store data in a cut-buffer. */
1167 void store_cutbuffer(char *ptr, int len)
1168 {
1169 /* ICCCM says we must rotate the buffers before storing to buffer 0. */
1170 XRotateBuffers(GDK_DISPLAY(), 1);
1171 XStoreBytes(GDK_DISPLAY(), ptr, len);
1172 }
1173
1174 void write_clip(frontend *fe, char *data)
1175 {
1176 init_paste();
1177
1178 if (fe->paste_data)
1179 sfree(fe->paste_data);
1180
1181 /*
1182 * For this simple application we can safely assume that the
1183 * data passed to this function is pure ASCII, which means we
1184 * can return precisely the same stuff for types STRING,
1185 * COMPOUND_TEXT or UTF8_STRING.
1186 */
1187
1188 fe->paste_data = data;
1189 fe->paste_data_len = strlen(data);
1190
1191 store_cutbuffer(fe->paste_data, fe->paste_data_len);
1192
1193 if (gtk_selection_owner_set(fe->area, GDK_SELECTION_PRIMARY,
1194 CurrentTime)) {
1195 gtk_selection_add_target(fe->area, GDK_SELECTION_PRIMARY,
1196 GDK_SELECTION_TYPE_STRING, 1);
1197 gtk_selection_add_target(fe->area, GDK_SELECTION_PRIMARY,
1198 compound_text_atom, 1);
1199 gtk_selection_add_target(fe->area, GDK_SELECTION_PRIMARY,
1200 utf8_string_atom, 1);
1201 }
1202 }
1203
1204 void selection_get(GtkWidget *widget, GtkSelectionData *seldata,
1205 guint info, guint time_stamp, gpointer data)
1206 {
1207 frontend *fe = (frontend *)data;
1208 gtk_selection_data_set(seldata, seldata->target, 8,
1209 fe->paste_data, fe->paste_data_len);
1210 }
1211
1212 gint selection_clear(GtkWidget *widget, GdkEventSelection *seldata,
1213 gpointer data)
1214 {
1215 frontend *fe = (frontend *)data;
1216
1217 if (fe->paste_data)
1218 sfree(fe->paste_data);
1219 fe->paste_data = NULL;
1220 fe->paste_data_len = 0;
1221 return TRUE;
1222 }
1223
1224 static void menu_copy_event(GtkMenuItem *menuitem, gpointer data)
1225 {
1226 frontend *fe = (frontend *)data;
1227 char *text;
1228
1229 text = midend_text_format(fe->me);
1230
1231 if (text) {
1232 write_clip(fe, text);
1233 } else {
1234 gdk_beep();
1235 }
1236 }
1237
1238 static void filesel_ok(GtkButton *button, gpointer data)
1239 {
1240 frontend *fe = (frontend *)data;
1241
1242 gpointer filesel = gtk_object_get_data(GTK_OBJECT(button), "user-data");
1243
1244 const char *name =
1245 gtk_file_selection_get_filename(GTK_FILE_SELECTION(filesel));
1246
1247 fe->filesel_name = dupstr(name);
1248 }
1249
1250 static char *file_selector(frontend *fe, char *title, int save)
1251 {
1252 GtkWidget *filesel =
1253 gtk_file_selection_new(title);
1254
1255 fe->filesel_name = NULL;
1256
1257 gtk_window_set_modal(GTK_WINDOW(filesel), TRUE);
1258 gtk_object_set_data
1259 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "user-data",
1260 (gpointer)filesel);
1261 gtk_signal_connect
1262 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "clicked",
1263 GTK_SIGNAL_FUNC(filesel_ok), fe);
1264 gtk_signal_connect_object
1265 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "clicked",
1266 GTK_SIGNAL_FUNC(gtk_widget_destroy), (gpointer)filesel);
1267 gtk_signal_connect_object
1268 (GTK_OBJECT(GTK_FILE_SELECTION(filesel)->cancel_button), "clicked",
1269 GTK_SIGNAL_FUNC(gtk_widget_destroy), (gpointer)filesel);
1270 gtk_signal_connect(GTK_OBJECT(filesel), "destroy",
1271 GTK_SIGNAL_FUNC(window_destroy), NULL);
1272 gtk_widget_show(filesel);
1273 gtk_window_set_transient_for(GTK_WINDOW(filesel), GTK_WINDOW(fe->window));
1274 gtk_main();
1275
1276 return fe->filesel_name;
1277 }
1278
1279 static void savefile_write(void *wctx, void *buf, int len)
1280 {
1281 FILE *fp = (FILE *)wctx;
1282 fwrite(buf, 1, len, fp);
1283 }
1284
1285 static int savefile_read(void *wctx, void *buf, int len)
1286 {
1287 FILE *fp = (FILE *)wctx;
1288 int ret;
1289
1290 ret = fread(buf, 1, len, fp);
1291 return (ret == len);
1292 }
1293
1294 static void menu_save_event(GtkMenuItem *menuitem, gpointer data)
1295 {
1296 frontend *fe = (frontend *)data;
1297 char *name;
1298
1299 name = file_selector(fe, "Enter name of game file to save", TRUE);
1300
1301 if (name) {
1302 FILE *fp;
1303
1304 if ((fp = fopen(name, "r")) != NULL) {
1305 char buf[256 + FILENAME_MAX];
1306 fclose(fp);
1307 /* file exists */
1308
1309 sprintf(buf, "Are you sure you want to overwrite the"
1310 " file \"%.*s\"?",
1311 FILENAME_MAX, name);
1312 if (!message_box(fe->window, "Question", buf, TRUE, MB_YESNO))
1313 return;
1314 }
1315
1316 fp = fopen(name, "w");
1317 sfree(name);
1318
1319 if (!fp) {
1320 error_box(fe->window, "Unable to open save file");
1321 return;
1322 }
1323
1324 midend_serialise(fe->me, savefile_write, fp);
1325
1326 fclose(fp);
1327 }
1328 }
1329
1330 static void menu_load_event(GtkMenuItem *menuitem, gpointer data)
1331 {
1332 frontend *fe = (frontend *)data;
1333 char *name, *err;
1334
1335 name = file_selector(fe, "Enter name of saved game file to load", FALSE);
1336
1337 if (name) {
1338 FILE *fp = fopen(name, "r");
1339 sfree(name);
1340
1341 if (!fp) {
1342 error_box(fe->window, "Unable to open saved game file");
1343 return;
1344 }
1345
1346 err = midend_deserialise(fe->me, savefile_read, fp);
1347
1348 fclose(fp);
1349
1350 if (err) {
1351 error_box(fe->window, err);
1352 return;
1353 }
1354
1355 resize_fe(fe);
1356 }
1357 }
1358
1359 static void menu_solve_event(GtkMenuItem *menuitem, gpointer data)
1360 {
1361 frontend *fe = (frontend *)data;
1362 char *msg;
1363
1364 msg = midend_solve(fe->me);
1365
1366 if (msg)
1367 error_box(fe->window, msg);
1368 }
1369
1370 static void menu_restart_event(GtkMenuItem *menuitem, gpointer data)
1371 {
1372 frontend *fe = (frontend *)data;
1373
1374 midend_restart_game(fe->me);
1375 }
1376
1377 static void menu_config_event(GtkMenuItem *menuitem, gpointer data)
1378 {
1379 frontend *fe = (frontend *)data;
1380 int which = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(menuitem),
1381 "user-data"));
1382
1383 if (!get_config(fe, which))
1384 return;
1385
1386 midend_new_game(fe->me);
1387 resize_fe(fe);
1388 }
1389
1390 static void menu_about_event(GtkMenuItem *menuitem, gpointer data)
1391 {
1392 frontend *fe = (frontend *)data;
1393 char titlebuf[256];
1394 char textbuf[1024];
1395
1396 sprintf(titlebuf, "About %.200s", thegame.name);
1397 sprintf(textbuf,
1398 "%.200s\n\n"
1399 "from Simon Tatham's Portable Puzzle Collection\n\n"
1400 "%.500s", thegame.name, ver);
1401
1402 message_box(fe->window, titlebuf, textbuf, TRUE, MB_OK);
1403 }
1404
1405 static GtkWidget *add_menu_item_with_key(frontend *fe, GtkContainer *cont,
1406 char *text, int key)
1407 {
1408 GtkWidget *menuitem = gtk_menu_item_new_with_label(text);
1409 int keyqual;
1410 gtk_container_add(cont, menuitem);
1411 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1412 GINT_TO_POINTER(key));
1413 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1414 GTK_SIGNAL_FUNC(menu_key_event), fe);
1415 switch (key & ~0x1F) {
1416 case 0x00:
1417 key += 0x60;
1418 keyqual = GDK_CONTROL_MASK;
1419 break;
1420 case 0x40:
1421 key += 0x20;
1422 keyqual = GDK_SHIFT_MASK;
1423 break;
1424 default:
1425 keyqual = 0;
1426 break;
1427 }
1428 gtk_widget_add_accelerator(menuitem,
1429 "activate", fe->accelgroup,
1430 key, keyqual,
1431 GTK_ACCEL_VISIBLE);
1432 gtk_widget_show(menuitem);
1433 return menuitem;
1434 }
1435
1436 static void add_menu_separator(GtkContainer *cont)
1437 {
1438 GtkWidget *menuitem = gtk_menu_item_new();
1439 gtk_container_add(cont, menuitem);
1440 gtk_widget_show(menuitem);
1441 }
1442
1443 enum { ARG_EITHER, ARG_SAVE, ARG_ID }; /* for argtype */
1444
1445 static frontend *new_window(char *arg, int argtype, char **error)
1446 {
1447 frontend *fe;
1448 GtkBox *vbox;
1449 GtkWidget *menubar, *menu, *menuitem;
1450 GdkPixmap *iconpm;
1451 GList *iconlist;
1452 int x, y, n;
1453 char errbuf[1024];
1454 extern char *const *const xpm_icons[];
1455 extern const int n_xpm_icons;
1456
1457 fe = snew(frontend);
1458
1459 fe->timer_active = FALSE;
1460 fe->timer_id = -1;
1461
1462 fe->me = midend_new(fe, &thegame, &gtk_drawing, fe);
1463
1464 if (arg) {
1465 char *err;
1466 FILE *fp;
1467
1468 errbuf[0] = '\0';
1469
1470 switch (argtype) {
1471 case ARG_ID:
1472 err = midend_game_id(fe->me, arg);
1473 if (!err)
1474 midend_new_game(fe->me);
1475 else
1476 sprintf(errbuf, "Invalid game ID: %.800s", err);
1477 break;
1478 case ARG_SAVE:
1479 fp = fopen(arg, "r");
1480 if (!fp) {
1481 sprintf(errbuf, "Error opening file: %.800s", strerror(errno));
1482 } else {
1483 err = midend_deserialise(fe->me, savefile_read, fp);
1484 if (err)
1485 sprintf(errbuf, "Invalid save file: %.800s", err);
1486 fclose(fp);
1487 }
1488 break;
1489 default /*case ARG_EITHER*/:
1490 /*
1491 * First try treating the argument as a game ID.
1492 */
1493 err = midend_game_id(fe->me, arg);
1494 if (!err) {
1495 /*
1496 * It's a valid game ID.
1497 */
1498 midend_new_game(fe->me);
1499 } else {
1500 FILE *fp = fopen(arg, "r");
1501 if (!fp) {
1502 sprintf(errbuf, "Supplied argument is neither a game ID (%.400s)"
1503 " nor a save file (%.400s)", err, strerror(errno));
1504 } else {
1505 err = midend_deserialise(fe->me, savefile_read, fp);
1506 if (err)
1507 sprintf(errbuf, "%.800s", err);
1508 fclose(fp);
1509 }
1510 }
1511 break;
1512 }
1513 if (*errbuf) {
1514 *error = dupstr(errbuf);
1515 midend_free(fe->me);
1516 sfree(fe);
1517 return NULL;
1518 }
1519
1520 } else {
1521 midend_new_game(fe->me);
1522 }
1523
1524 fe->window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1525 gtk_window_set_title(GTK_WINDOW(fe->window), thegame.name);
1526
1527 vbox = GTK_BOX(gtk_vbox_new(FALSE, 0));
1528 gtk_container_add(GTK_CONTAINER(fe->window), GTK_WIDGET(vbox));
1529 gtk_widget_show(GTK_WIDGET(vbox));
1530
1531 fe->accelgroup = gtk_accel_group_new();
1532 gtk_window_add_accel_group(GTK_WINDOW(fe->window), fe->accelgroup);
1533
1534 menubar = gtk_menu_bar_new();
1535 gtk_box_pack_start(vbox, menubar, FALSE, FALSE, 0);
1536 gtk_widget_show(menubar);
1537
1538 menuitem = gtk_menu_item_new_with_label("Game");
1539 gtk_container_add(GTK_CONTAINER(menubar), menuitem);
1540 gtk_widget_show(menuitem);
1541
1542 menu = gtk_menu_new();
1543 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
1544
1545 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "New", 'n');
1546
1547 menuitem = gtk_menu_item_new_with_label("Restart");
1548 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1549 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1550 GTK_SIGNAL_FUNC(menu_restart_event), fe);
1551 gtk_widget_show(menuitem);
1552
1553 menuitem = gtk_menu_item_new_with_label("Specific...");
1554 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1555 GINT_TO_POINTER(CFG_DESC));
1556 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1557 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1558 GTK_SIGNAL_FUNC(menu_config_event), fe);
1559 gtk_widget_show(menuitem);
1560
1561 menuitem = gtk_menu_item_new_with_label("Random Seed...");
1562 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1563 GINT_TO_POINTER(CFG_SEED));
1564 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1565 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1566 GTK_SIGNAL_FUNC(menu_config_event), fe);
1567 gtk_widget_show(menuitem);
1568
1569 if ((n = midend_num_presets(fe->me)) > 0 || thegame.can_configure) {
1570 GtkWidget *submenu;
1571 int i;
1572
1573 menuitem = gtk_menu_item_new_with_label("Type");
1574 gtk_container_add(GTK_CONTAINER(menubar), menuitem);
1575 gtk_widget_show(menuitem);
1576
1577 submenu = gtk_menu_new();
1578 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), submenu);
1579
1580 for (i = 0; i < n; i++) {
1581 char *name;
1582 game_params *params;
1583
1584 midend_fetch_preset(fe->me, i, &name, &params);
1585
1586 menuitem = gtk_menu_item_new_with_label(name);
1587 gtk_container_add(GTK_CONTAINER(submenu), menuitem);
1588 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data", params);
1589 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1590 GTK_SIGNAL_FUNC(menu_preset_event), fe);
1591 gtk_widget_show(menuitem);
1592 }
1593
1594 if (thegame.can_configure) {
1595 menuitem = gtk_menu_item_new_with_label("Custom...");
1596 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
1597 GPOINTER_TO_INT(CFG_SETTINGS));
1598 gtk_container_add(GTK_CONTAINER(submenu), menuitem);
1599 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1600 GTK_SIGNAL_FUNC(menu_config_event), fe);
1601 gtk_widget_show(menuitem);
1602 }
1603 }
1604
1605 add_menu_separator(GTK_CONTAINER(menu));
1606 menuitem = gtk_menu_item_new_with_label("Load...");
1607 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1608 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1609 GTK_SIGNAL_FUNC(menu_load_event), fe);
1610 gtk_widget_show(menuitem);
1611 menuitem = gtk_menu_item_new_with_label("Save...");
1612 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1613 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1614 GTK_SIGNAL_FUNC(menu_save_event), fe);
1615 gtk_widget_show(menuitem);
1616 add_menu_separator(GTK_CONTAINER(menu));
1617 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Undo", 'u');
1618 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Redo", 'r');
1619 if (thegame.can_format_as_text) {
1620 add_menu_separator(GTK_CONTAINER(menu));
1621 menuitem = gtk_menu_item_new_with_label("Copy");
1622 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1623 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1624 GTK_SIGNAL_FUNC(menu_copy_event), fe);
1625 gtk_widget_show(menuitem);
1626 }
1627 if (thegame.can_solve) {
1628 add_menu_separator(GTK_CONTAINER(menu));
1629 menuitem = gtk_menu_item_new_with_label("Solve");
1630 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1631 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1632 GTK_SIGNAL_FUNC(menu_solve_event), fe);
1633 gtk_widget_show(menuitem);
1634 }
1635 add_menu_separator(GTK_CONTAINER(menu));
1636 add_menu_item_with_key(fe, GTK_CONTAINER(menu), "Exit", 'q');
1637
1638 menuitem = gtk_menu_item_new_with_label("Help");
1639 gtk_container_add(GTK_CONTAINER(menubar), menuitem);
1640 gtk_widget_show(menuitem);
1641
1642 menu = gtk_menu_new();
1643 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
1644
1645 menuitem = gtk_menu_item_new_with_label("About");
1646 gtk_container_add(GTK_CONTAINER(menu), menuitem);
1647 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
1648 GTK_SIGNAL_FUNC(menu_about_event), fe);
1649 gtk_widget_show(menuitem);
1650
1651 {
1652 int i, ncolours;
1653 float *colours;
1654 gboolean *success;
1655
1656 fe->colmap = gdk_colormap_get_system();
1657 colours = midend_colours(fe->me, &ncolours);
1658 fe->ncolours = ncolours;
1659 fe->colours = snewn(ncolours, GdkColor);
1660 for (i = 0; i < ncolours; i++) {
1661 fe->colours[i].red = colours[i*3] * 0xFFFF;
1662 fe->colours[i].green = colours[i*3+1] * 0xFFFF;
1663 fe->colours[i].blue = colours[i*3+2] * 0xFFFF;
1664 }
1665 success = snewn(ncolours, gboolean);
1666 gdk_colormap_alloc_colors(fe->colmap, fe->colours, ncolours,
1667 FALSE, FALSE, success);
1668 for (i = 0; i < ncolours; i++) {
1669 if (!success[i])
1670 g_error("couldn't allocate colour %d (#%02x%02x%02x)\n",
1671 i, fe->colours[i].red >> 8,
1672 fe->colours[i].green >> 8,
1673 fe->colours[i].blue >> 8);
1674 }
1675 }
1676
1677 if (midend_wants_statusbar(fe->me)) {
1678 GtkWidget *viewport;
1679 GtkRequisition req;
1680
1681 viewport = gtk_viewport_new(NULL, NULL);
1682 gtk_viewport_set_shadow_type(GTK_VIEWPORT(viewport), GTK_SHADOW_NONE);
1683 fe->statusbar = gtk_statusbar_new();
1684 gtk_container_add(GTK_CONTAINER(viewport), fe->statusbar);
1685 gtk_widget_show(viewport);
1686 gtk_box_pack_end(vbox, viewport, FALSE, FALSE, 0);
1687 gtk_widget_show(fe->statusbar);
1688 fe->statusctx = gtk_statusbar_get_context_id
1689 (GTK_STATUSBAR(fe->statusbar), "game");
1690 gtk_statusbar_push(GTK_STATUSBAR(fe->statusbar), fe->statusctx,
1691 "test");
1692 gtk_widget_size_request(fe->statusbar, &req);
1693 #if 0
1694 /* For GTK 2.0, should we be using gtk_widget_set_size_request? */
1695 #endif
1696 gtk_widget_set_usize(viewport, -1, req.height);
1697 } else
1698 fe->statusbar = NULL;
1699
1700 fe->area = gtk_drawing_area_new();
1701 get_size(fe, &x, &y);
1702 gtk_drawing_area_size(GTK_DRAWING_AREA(fe->area), x, y);
1703 fe->w = x;
1704 fe->h = y;
1705
1706 gtk_box_pack_end(vbox, fe->area, TRUE, TRUE, 0);
1707
1708 fe->pixmap = NULL;
1709 fe->fonts = NULL;
1710 fe->nfonts = fe->fontsize = 0;
1711
1712 fe->paste_data = NULL;
1713 fe->paste_data_len = 0;
1714
1715 gtk_signal_connect(GTK_OBJECT(fe->window), "destroy",
1716 GTK_SIGNAL_FUNC(destroy), fe);
1717 gtk_signal_connect(GTK_OBJECT(fe->window), "key_press_event",
1718 GTK_SIGNAL_FUNC(key_event), fe);
1719 gtk_signal_connect(GTK_OBJECT(fe->area), "button_press_event",
1720 GTK_SIGNAL_FUNC(button_event), fe);
1721 gtk_signal_connect(GTK_OBJECT(fe->area), "button_release_event",
1722 GTK_SIGNAL_FUNC(button_event), fe);
1723 gtk_signal_connect(GTK_OBJECT(fe->area), "motion_notify_event",
1724 GTK_SIGNAL_FUNC(motion_event), fe);
1725 gtk_signal_connect(GTK_OBJECT(fe->area), "selection_get",
1726 GTK_SIGNAL_FUNC(selection_get), fe);
1727 gtk_signal_connect(GTK_OBJECT(fe->area), "selection_clear_event",
1728 GTK_SIGNAL_FUNC(selection_clear), fe);
1729 gtk_signal_connect(GTK_OBJECT(fe->area), "expose_event",
1730 GTK_SIGNAL_FUNC(expose_area), fe);
1731 gtk_signal_connect(GTK_OBJECT(fe->window), "map_event",
1732 GTK_SIGNAL_FUNC(map_window), fe);
1733 gtk_signal_connect(GTK_OBJECT(fe->area), "configure_event",
1734 GTK_SIGNAL_FUNC(configure_area), fe);
1735
1736 gtk_widget_add_events(GTK_WIDGET(fe->area),
1737 GDK_BUTTON_PRESS_MASK |
1738 GDK_BUTTON_RELEASE_MASK |
1739 GDK_BUTTON_MOTION_MASK);
1740
1741 if (n_xpm_icons) {
1742 gtk_widget_realize(fe->window);
1743 iconpm = gdk_pixmap_create_from_xpm_d(fe->window->window, NULL,
1744 NULL, (gchar **)xpm_icons[0]);
1745 gdk_window_set_icon(fe->window->window, NULL, iconpm, NULL);
1746 iconlist = NULL;
1747 for (n = 0; n < n_xpm_icons; n++) {
1748 iconlist =
1749 g_list_append(iconlist,
1750 gdk_pixbuf_new_from_xpm_data((const gchar **)
1751 xpm_icons[n]));
1752 }
1753 gdk_window_set_icon_list(fe->window->window, iconlist);
1754 }
1755
1756 gtk_widget_show(fe->area);
1757 gtk_widget_show(fe->window);
1758
1759 gdk_window_set_background(fe->area->window, &fe->colours[0]);
1760 gdk_window_set_background(fe->window->window, &fe->colours[0]);
1761
1762 return fe;
1763 }
1764
1765 char *fgetline(FILE *fp)
1766 {
1767 char *ret = snewn(512, char);
1768 int size = 512, len = 0;
1769 while (fgets(ret + len, size - len, fp)) {
1770 len += strlen(ret + len);
1771 if (ret[len-1] == '\n')
1772 break; /* got a newline, we're done */
1773 size = len + 512;
1774 ret = sresize(ret, size, char);
1775 }
1776 if (len == 0) { /* first fgets returned NULL */
1777 sfree(ret);
1778 return NULL;
1779 }
1780 ret[len] = '\0';
1781 return ret;
1782 }
1783
1784 int main(int argc, char **argv)
1785 {
1786 char *pname = argv[0];
1787 char *error;
1788 int ngenerate = 0, print = FALSE, px = 1, py = 1;
1789 int soln = FALSE, colour = FALSE;
1790 float scale = 1.0F;
1791 float redo_proportion = 0.0F;
1792 char *arg = NULL;
1793 int argtype = ARG_EITHER;
1794 char *screenshot_file = NULL;
1795 int doing_opts = TRUE;
1796 int ac = argc;
1797 char **av = argv;
1798 char errbuf[500];
1799
1800 /*
1801 * Command line parsing in this function is rather fiddly,
1802 * because GTK wants to have a go at argc/argv _first_ - and
1803 * yet we can't let it, because gtk_init() will bomb out if it
1804 * can't open an X display, whereas in fact we want to permit
1805 * our --generate and --print modes to run without an X
1806 * display.
1807 *
1808 * So what we do is:
1809 * - we parse the command line ourselves, without modifying
1810 * argc/argv
1811 * - if we encounter an error which might plausibly be the
1812 * result of a GTK command line (i.e. not detailed errors in
1813 * particular options of ours) we store the error message
1814 * and terminate parsing.
1815 * - if we got enough out of the command line to know it
1816 * specifies a non-X mode of operation, we either display
1817 * the stored error and return failure, or if there is no
1818 * stored error we do the non-X operation and return
1819 * success.
1820 * - otherwise, we go straight to gtk_init().
1821 */
1822
1823 errbuf[0] = '\0';
1824 while (--ac > 0) {
1825 char *p = *++av;
1826 if (doing_opts && !strcmp(p, "--version")) {
1827 printf("%s, from Simon Tatham's Portable Puzzle Collection\n%s\n",
1828 thegame.name, ver);
1829 return 0;
1830 } else if (doing_opts && !strcmp(p, "--generate")) {
1831 if (--ac > 0) {
1832 ngenerate = atoi(*++av);
1833 if (!ngenerate) {
1834 fprintf(stderr, "%s: '--generate' expected a number\n",
1835 pname);
1836 return 1;
1837 }
1838 } else
1839 ngenerate = 1;
1840 } else if (doing_opts && !strcmp(p, "--print")) {
1841 if (!thegame.can_print) {
1842 fprintf(stderr, "%s: this game does not support printing\n",
1843 pname);
1844 return 1;
1845 }
1846 print = TRUE;
1847 if (--ac > 0) {
1848 char *dim = *++av;
1849 if (sscanf(dim, "%dx%d", &px, &py) != 2) {
1850 fprintf(stderr, "%s: unable to parse argument '%s' to "
1851 "'--print'\n", pname, dim);
1852 return 1;
1853 }
1854 } else {
1855 px = py = 1;
1856 }
1857 } else if (doing_opts && !strcmp(p, "--scale")) {
1858 if (--ac > 0) {
1859 scale = atof(*++av);
1860 } else {
1861 fprintf(stderr, "%s: no argument supplied to '--scale'\n",
1862 pname);
1863 return 1;
1864 }
1865 } else if (doing_opts && !strcmp(p, "--redo")) {
1866 /*
1867 * This is an internal option which I don't expect
1868 * users to have any particular use for. The effect of
1869 * --redo is that once the game has been loaded and
1870 * initialised, the next move in the redo chain is
1871 * replayed, and the game screen is redrawn part way
1872 * through the making of the move. This is only
1873 * meaningful if there _is_ a next move in the redo
1874 * chain, which means in turn that this option is only
1875 * useful if you're also passing a save file on the
1876 * command line.
1877 *
1878 * This option is used by the script which generates
1879 * the puzzle icons and website screenshots, and I
1880 * don't imagine it's useful for anything else.
1881 * (Unless, I suppose, users don't like my screenshots
1882 * and want to generate their own in the same way for
1883 * some repackaged version of the puzzles.)
1884 */
1885 if (--ac > 0) {
1886 redo_proportion = atof(*++av);
1887 } else {
1888 fprintf(stderr, "%s: no argument supplied to '--redo'\n",
1889 pname);
1890 return 1;
1891 }
1892 } else if (doing_opts && !strcmp(p, "--screenshot")) {
1893 /*
1894 * Another internal option for the icon building
1895 * script. This causes a screenshot of the central
1896 * drawing area (i.e. not including the menu bar or
1897 * status bar) to be saved to a PNG file once the
1898 * window has been drawn, and then the application
1899 * quits immediately.
1900 */
1901 if (--ac > 0) {
1902 screenshot_file = *++av;
1903 } else {
1904 fprintf(stderr, "%s: no argument supplied to '--screenshot'\n",
1905 pname);
1906 return 1;
1907 }
1908 } else if (doing_opts && (!strcmp(p, "--with-solutions") ||
1909 !strcmp(p, "--with-solution") ||
1910 !strcmp(p, "--with-solns") ||
1911 !strcmp(p, "--with-soln") ||
1912 !strcmp(p, "--solutions") ||
1913 !strcmp(p, "--solution") ||
1914 !strcmp(p, "--solns") ||
1915 !strcmp(p, "--soln"))) {
1916 soln = TRUE;
1917 } else if (doing_opts && !strcmp(p, "--colour")) {
1918 if (!thegame.can_print_in_colour) {
1919 fprintf(stderr, "%s: this game does not support colour"
1920 " printing\n", pname);
1921 return 1;
1922 }
1923 colour = TRUE;
1924 } else if (doing_opts && !strcmp(p, "--load")) {
1925 argtype = ARG_SAVE;
1926 } else if (doing_opts && !strcmp(p, "--game")) {
1927 argtype = ARG_ID;
1928 } else if (doing_opts && !strcmp(p, "--")) {
1929 doing_opts = FALSE;
1930 } else if (!doing_opts || p[0] != '-') {
1931 if (arg) {
1932 fprintf(stderr, "%s: more than one argument supplied\n",
1933 pname);
1934 return 1;
1935 }
1936 arg = p;
1937 } else {
1938 sprintf(errbuf, "%.100s: unrecognised option '%.100s'\n",
1939 pname, p);
1940 break;
1941 }
1942 }
1943
1944 if (*errbuf) {
1945 fputs(errbuf, stderr);
1946 return 1;
1947 }
1948
1949 /*
1950 * Special standalone mode for generating puzzle IDs on the
1951 * command line. Useful for generating puzzles to be printed
1952 * out and solved offline (for puzzles where that even makes
1953 * sense - Solo, for example, is a lot more pencil-and-paper
1954 * friendly than Twiddle!)
1955 *
1956 * Usage:
1957 *
1958 * <puzzle-name> --generate [<n> [<params>]]
1959 *
1960 * <n>, if present, is the number of puzzle IDs to generate.
1961 * <params>, if present, is the same type of parameter string
1962 * you would pass to the puzzle when running it in GUI mode,
1963 * including optional extras such as the expansion factor in
1964 * Rectangles and the difficulty level in Solo.
1965 *
1966 * If you specify <params>, you must also specify <n> (although
1967 * you may specify it to be 1). Sorry; that was the
1968 * simplest-to-parse command-line syntax I came up with.
1969 */
1970 if (ngenerate > 0 || print) {
1971 int i, n = 1;
1972 midend *me;
1973 char *id;
1974 document *doc = NULL;
1975
1976 n = ngenerate;
1977
1978 me = midend_new(NULL, &thegame, NULL, NULL);
1979 i = 0;
1980
1981 if (print)
1982 doc = document_new(px, py, scale);
1983
1984 /*
1985 * In this loop, we either generate a game ID or read one
1986 * from stdin depending on whether we're in generate mode;
1987 * then we either write it to stdout or print it, depending
1988 * on whether we're in print mode. Thus, this loop handles
1989 * generate-to-stdout, print-from-stdin and generate-and-
1990 * immediately-print modes.
1991 *
1992 * (It could also handle a copy-stdin-to-stdout mode,
1993 * although there's currently no combination of options
1994 * which will cause this loop to be activated in that mode.
1995 * It wouldn't be _entirely_ pointless, though, because
1996 * stdin could contain bare params strings or random-seed
1997 * IDs, and stdout would contain nothing but fully
1998 * generated descriptive game IDs.)
1999 */
2000 while (ngenerate == 0 || i < n) {
2001 char *pstr, *err;
2002
2003 if (ngenerate == 0) {
2004 pstr = fgetline(stdin);
2005 if (!pstr)
2006 break;
2007 pstr[strcspn(pstr, "\r\n")] = '\0';
2008 } else {
2009 if (arg) {
2010 pstr = snewn(strlen(arg) + 40, char);
2011
2012 strcpy(pstr, arg);
2013 if (i > 0 && strchr(arg, '#'))
2014 sprintf(pstr + strlen(pstr), "-%d", i);
2015 } else
2016 pstr = NULL;
2017 }
2018
2019 if (pstr) {
2020 err = midend_game_id(me, pstr);
2021 if (err) {
2022 fprintf(stderr, "%s: error parsing '%s': %s\n",
2023 pname, pstr, err);
2024 return 1;
2025 }
2026 }
2027 sfree(pstr);
2028
2029 midend_new_game(me);
2030
2031 if (doc) {
2032 err = midend_print_puzzle(me, doc, soln);
2033 if (err) {
2034 fprintf(stderr, "%s: error in printing: %s\n", pname, err);
2035 return 1;
2036 }
2037 } else {
2038 id = midend_get_game_id(me);
2039 puts(id);
2040 sfree(id);
2041 }
2042
2043 i++;
2044 }
2045
2046 if (doc) {
2047 psdata *ps = ps_init(stdout, colour);
2048 document_print(doc, ps_drawing_api(ps));
2049 document_free(doc);
2050 ps_free(ps);
2051 }
2052
2053 midend_free(me);
2054
2055 return 0;
2056 } else {
2057 frontend *fe;
2058
2059 gtk_init(&argc, &argv);
2060
2061 fe = new_window(arg, argtype, &error);
2062
2063 if (!fe) {
2064 fprintf(stderr, "%s: %s\n", pname, error);
2065 return 1;
2066 }
2067
2068 if (screenshot_file) {
2069 /*
2070 * Some puzzles will not redraw their entire area if
2071 * given a partially completed animation, which means
2072 * we must redraw now and _then_ redraw again after
2073 * freezing the move timer.
2074 */
2075 midend_force_redraw(fe->me);
2076 }
2077
2078 if (redo_proportion) {
2079 /* Start a redo. */
2080 midend_process_key(fe->me, 0, 0, 'r');
2081 /* And freeze the timer at the specified position. */
2082 midend_freeze_timer(fe->me, redo_proportion);
2083 }
2084
2085 if (screenshot_file) {
2086 GdkPixbuf *pb;
2087 GError *gerror = NULL;
2088
2089 midend_redraw(fe->me);
2090
2091 pb = gdk_pixbuf_get_from_drawable(NULL, fe->pixmap,
2092 NULL, 0, 0, 0, 0, -1, -1);
2093 gdk_pixbuf_save(pb, screenshot_file, "png", &gerror, NULL);
2094
2095 exit(0);
2096 }
2097
2098 gtk_main();
2099 }
2100
2101 return 0;
2102 }