chiark / gitweb /
I've just realised that the JS puzzles' permalinks were not updating
[sgt-puzzles.git] / emcc.c
1 /*
2  * emcc.c: the C component of an Emscripten-based web/Javascript front
3  * end for Puzzles.
4  *
5  * The Javascript parts of this system live in emcclib.js and
6  * emccpre.js. It also depends on being run in the context of a web
7  * page containing an appropriate collection of bits and pieces (a
8  * canvas, some buttons and links etc), which is generated for each
9  * puzzle by the script html/jspage.pl.
10  */
11
12 /*
13  * Further thoughts on possible enhancements:
14  *
15  *  - I think it might be feasible to have these JS puzzles permit
16  *    loading and saving games in disk files. Saving would be done by
17  *    constructing a data: URI encapsulating the save file, and then
18  *    telling the browser to visit that URI with the effect that it
19  *    would naturally pop up a 'where would you like to save this'
20  *    dialog box. Loading, more or less similarly, might be feasible
21  *    by using the DOM File API to ask the user to select a file and
22  *    permit us to see its contents.
23  *
24  *  - it ought to be possible to make the puzzle canvases resizable,
25  *    by superimposing some kind of draggable resize handle. Also I
26  *    quite like the idea of having a few buttons for standard sizes:
27  *    reset to default size, maximise to the browser window dimensions
28  *    (if we can find those out), and perhaps even go full-screen.
29  *
30  *  - I should think about whether these webified puzzles can support
31  *    touchscreen-based tablet browsers (assuming there are any that
32  *    can cope with the reasonably modern JS and run it fast enough to
33  *    be worthwhile).
34  *
35  *  - think about making use of localStorage. It might be useful to
36  *    let the user save games into there as an alternative to disk
37  *    files - disk files are all very well for getting the save right
38  *    out of your browser to (e.g.) email to me as a bug report, but
39  *    for just resuming a game you were in the middle of, you'd
40  *    probably rather have a nice simple 'quick save' and 'quick load'
41  *    button pair. Also, that might be a useful place to store
42  *    preferences, if I ever get round to writing a preferences UI.
43  *
44  *  - some CSS to make the button bar and configuration dialogs a
45  *    little less ugly would probably not go amiss.
46  *
47  *  - this is a downright silly idea, but it does occur to me that if
48  *    I were to write a PDF output driver for the Puzzles printing
49  *    API, then I might be able to implement a sort of 'printing'
50  *    feature in this front end, using data: URIs again. (Ask the user
51  *    exactly what they want printed, then construct an appropriate
52  *    PDF and embed it in a gigantic data: URI. Then they can print
53  *    that using whatever they normally use to print PDFs!)
54  */
55
56 #include <string.h>
57
58 #include "puzzles.h"
59
60 /*
61  * Extern references to Javascript functions provided in emcclib.js.
62  */
63 extern void js_debug(const char *);
64 extern void js_error_box(const char *message);
65 extern void js_remove_type_dropdown(void);
66 extern void js_remove_solve_button(void);
67 extern void js_add_preset(const char *name);
68 extern int js_get_selected_preset(void);
69 extern void js_select_preset(int n);
70 extern void js_get_date_64(unsigned *p);
71 extern void js_update_permalinks(const char *desc, const char *seed);
72 extern void js_enable_undo_redo(int undo, int redo);
73 extern void js_activate_timer();
74 extern void js_deactivate_timer();
75 extern void js_canvas_start_draw(void);
76 extern void js_canvas_draw_update(int x, int y, int w, int h);
77 extern void js_canvas_end_draw(void);
78 extern void js_canvas_draw_rect(int x, int y, int w, int h,
79                                 const char *colour);
80 extern void js_canvas_clip_rect(int x, int y, int w, int h);
81 extern void js_canvas_unclip(void);
82 extern void js_canvas_draw_line(float x1, float y1, float x2, float y2,
83                                 int width, const char *colour);
84 extern void js_canvas_draw_poly(int *points, int npoints,
85                                 const char *fillcolour,
86                                 const char *outlinecolour);
87 extern void js_canvas_draw_circle(int x, int y, int r,
88                                   const char *fillcolour,
89                                   const char *outlinecolour);
90 extern int js_canvas_find_font_midpoint(int height, const char *fontptr);
91 extern void js_canvas_draw_text(int x, int y, int halign,
92                                 const char *colptr, const char *fontptr,
93                                 const char *text);
94 extern int js_canvas_new_blitter(int w, int h);
95 extern void js_canvas_free_blitter(int id);
96 extern void js_canvas_copy_to_blitter(int id, int x, int y, int w, int h);
97 extern void js_canvas_copy_from_blitter(int id, int x, int y, int w, int h);
98 extern void js_canvas_make_statusbar(void);
99 extern void js_canvas_set_statusbar(const char *text);
100 extern void js_canvas_set_size(int w, int h);
101
102 extern void js_dialog_init(const char *title);
103 extern void js_dialog_string(int i, const char *title, const char *initvalue);
104 extern void js_dialog_choices(int i, const char *title, const char *choicelist,
105                               int initvalue);
106 extern void js_dialog_boolean(int i, const char *title, int initvalue);
107 extern void js_dialog_launch(void);
108 extern void js_dialog_cleanup(void);
109 extern void js_focus_canvas(void);
110
111 /*
112  * Call JS to get the date, and use that to initialise our random
113  * number generator to invent the first game seed.
114  */
115 void get_random_seed(void **randseed, int *randseedsize)
116 {
117     unsigned *ret = snewn(2, unsigned);
118     js_get_date_64(ret);
119     *randseed = ret;
120     *randseedsize = 2*sizeof(unsigned);
121 }
122
123 /*
124  * Fatal error, called in cases of complete despair such as when
125  * malloc() has returned NULL.
126  */
127 void fatal(char *fmt, ...)
128 {
129     char buf[512];
130     va_list ap;
131
132     strcpy(buf, "puzzle fatal error: ");
133
134     va_start(ap, fmt);
135     vsnprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), fmt, ap);
136     va_end(ap);
137
138     js_error_box(buf);
139 }
140
141 /*
142  * HTMLish names for the colours allocated by the puzzle.
143  */
144 char **colour_strings;
145 int ncolours;
146
147 /*
148  * The global midend object.
149  */
150 midend *me;
151
152 /* ----------------------------------------------------------------------
153  * Timing functions.
154  */
155 int timer_active = FALSE;
156 void deactivate_timer(frontend *fe)
157 {
158     js_deactivate_timer();
159     timer_active = FALSE;
160 }
161 void activate_timer(frontend *fe)
162 {
163     if (!timer_active) {
164         js_activate_timer();
165         timer_active = TRUE;
166     }
167 }
168 void timer_callback(double tplus)
169 {
170     if (timer_active)
171         midend_timer(me, tplus);
172 }
173
174 /* ----------------------------------------------------------------------
175  * Helper function to resize the canvas, and variables to remember its
176  * size for other functions (e.g. trimming blitter rectangles).
177  */
178 static int canvas_w, canvas_h;
179 static void resize(void)
180 {
181     int w, h;
182     w = h = INT_MAX;
183     midend_size(me, &w, &h, FALSE);
184     js_canvas_set_size(w, h);
185     canvas_w = w;
186     canvas_h = h;
187 }
188
189 /*
190  * HTML doesn't give us a default frontend colour of its own, so we
191  * just make up a lightish grey ourselves.
192  */
193 void frontend_default_colour(frontend *fe, float *output)
194 {
195     output[0] = output[1] = output[2] = 0.9F;
196 }
197
198 /*
199  * Helper function called from all over the place to ensure the undo
200  * and redo buttons get properly enabled and disabled after every move
201  * or undo or new-game event.
202  */
203 static void update_undo_redo(void)
204 {
205     js_enable_undo_redo(midend_can_undo(me), midend_can_redo(me));
206 }
207
208 /*
209  * Mouse event handlers called from JS.
210  */
211 void mousedown(int x, int y, int button)
212 {
213     button = (button == 0 ? LEFT_BUTTON :
214               button == 1 ? MIDDLE_BUTTON : RIGHT_BUTTON);
215     midend_process_key(me, x, y, button);
216     update_undo_redo();
217 }
218
219 void mouseup(int x, int y, int button)
220 {
221     button = (button == 0 ? LEFT_RELEASE :
222               button == 1 ? MIDDLE_RELEASE : RIGHT_RELEASE);
223     midend_process_key(me, x, y, button);
224     update_undo_redo();
225 }
226
227 void mousemove(int x, int y, int buttons)
228 {
229     int button = (buttons & 2 ? MIDDLE_DRAG :
230                   buttons & 4 ? RIGHT_DRAG : LEFT_DRAG);
231     midend_process_key(me, x, y, button);
232     update_undo_redo();
233 }
234
235 /*
236  * Keyboard handler called from JS.
237  */
238 void key(int keycode, int charcode, int shift, int ctrl)
239 {
240     int keyevent = -1;
241     if (charcode != 0) {
242         keyevent = charcode & (ctrl ? 0x1F : 0xFF);
243     } else {
244         switch (keycode) {
245           case 8:
246             keyevent = '\177';         /* backspace */
247             break;
248           case 13:
249             keyevent = 13;             /* return */
250             break;
251           case 37:
252             keyevent = CURSOR_LEFT;
253             break;
254           case 38:
255             keyevent = CURSOR_UP;
256             break;
257           case 39:
258             keyevent = CURSOR_RIGHT;
259             break;
260           case 40:
261             keyevent = CURSOR_DOWN;
262             break;
263             /*
264              * We interpret Home, End, PgUp and PgDn as numeric keypad
265              * controls regardless of whether they're the ones on the
266              * numeric keypad (since we can't tell). The effect of
267              * this should only be that the non-numeric-pad versions
268              * of those keys generate directions in 8-way movement
269              * puzzles like Cube and Inertia.
270              */
271           case 35:                     /* End */
272             keyevent = MOD_NUM_KEYPAD | '1';
273             break;
274           case 34:                     /* PgDn */
275             keyevent = MOD_NUM_KEYPAD | '3';
276             break;
277           case 36:                     /* Home */
278             keyevent = MOD_NUM_KEYPAD | '7';
279             break;
280           case 33:                     /* PgUp */
281             keyevent = MOD_NUM_KEYPAD | '9';
282             break;
283           case 96: case 97: case 98: case 99: case 100:
284           case 101: case 102: case 103: case 104: case 105:
285             keyevent = MOD_NUM_KEYPAD | ('0' + keycode - 96);
286             break;
287           default:
288             /* not a key we care about */
289             return;
290         }
291     }
292     if (shift && keyevent >= 0x100)
293         keyevent |= MOD_SHFT;
294     if (ctrl && keyevent >= 0x100)
295         keyevent |= MOD_CTRL;
296
297     midend_process_key(me, 0, 0, keyevent);
298     update_undo_redo();
299 }
300
301 /*
302  * Helper function called from several places to update the permalinks
303  * whenever a new game is created.
304  */
305 static void update_permalinks(void)
306 {
307     char *desc, *seed;
308     desc = midend_get_game_id(me);
309     seed = midend_get_random_seed(me);
310     js_update_permalinks(desc, seed);
311     sfree(desc);
312     sfree(seed);
313 }
314
315 /*
316  * Callback from the midend when the game ids change, so we can update
317  * the permalinks.
318  */
319 static void ids_changed(void *ignored)
320 {
321     update_permalinks();
322 }
323
324 /* ----------------------------------------------------------------------
325  * Implementation of the drawing API by calling Javascript canvas
326  * drawing functions. (Well, half of it; the other half is on the JS
327  * side.)
328  */
329 static void js_start_draw(void *handle)
330 {
331     js_canvas_start_draw();
332 }
333
334 static void js_clip(void *handle, int x, int y, int w, int h)
335 {
336     js_canvas_clip_rect(x, y, w, h);
337 }
338
339 static void js_unclip(void *handle)
340 {
341     js_canvas_unclip();
342 }
343
344 static void js_draw_text(void *handle, int x, int y, int fonttype,
345                          int fontsize, int align, int colour, char *text)
346 {
347     char fontstyle[80];
348     int halign;
349
350     sprintf(fontstyle, "%dpx %s", fontsize,
351             fonttype == FONT_FIXED ? "monospace" : "sans-serif");
352
353     if (align & ALIGN_VCENTRE)
354         y += js_canvas_find_font_midpoint(fontsize, fontstyle);
355
356     if (align & ALIGN_HCENTRE)
357         halign = 1;
358     else if (align & ALIGN_HRIGHT)
359         halign = 2;
360     else
361         halign = 0;
362
363     js_canvas_draw_text(x, y, halign, colour_strings[colour], fontstyle, text);
364 }
365
366 static void js_draw_rect(void *handle, int x, int y, int w, int h, int colour)
367 {
368     js_canvas_draw_rect(x, y, w, h, colour_strings[colour]);
369 }
370
371 static void js_draw_line(void *handle, int x1, int y1, int x2, int y2,
372                          int colour)
373 {
374     js_canvas_draw_line(x1, y1, x2, y2, 1, colour_strings[colour]);
375 }
376
377 static void js_draw_thick_line(void *handle, float thickness,
378                                float x1, float y1, float x2, float y2,
379                                int colour)
380 {
381     js_canvas_draw_line(x1, y1, x2, y2, thickness, colour_strings[colour]);
382 }
383
384 static void js_draw_poly(void *handle, int *coords, int npoints,
385                          int fillcolour, int outlinecolour)
386 {
387     js_canvas_draw_poly(coords, npoints,
388                         fillcolour >= 0 ? colour_strings[fillcolour] : NULL,
389                         colour_strings[outlinecolour]);
390 }
391
392 static void js_draw_circle(void *handle, int cx, int cy, int radius,
393                            int fillcolour, int outlinecolour)
394 {
395     js_canvas_draw_circle(cx, cy, radius,
396                           fillcolour >= 0 ? colour_strings[fillcolour] : NULL,
397                           colour_strings[outlinecolour]);
398 }
399
400 struct blitter {
401     int id;                            /* allocated on the js side */
402     int w, h;                          /* easier to retain here */
403 };
404
405 static blitter *js_blitter_new(void *handle, int w, int h)
406 {
407     blitter *bl = snew(blitter);
408     bl->w = w;
409     bl->h = h;
410     bl->id = js_canvas_new_blitter(w, h);
411     return bl;
412 }
413
414 static void js_blitter_free(void *handle, blitter *bl)
415 {
416     js_canvas_free_blitter(bl->id);
417     sfree(bl);
418 }
419
420 static void trim_rect(int *x, int *y, int *w, int *h)
421 {
422     int x0, x1, y0, y1;
423
424     /*
425      * Reduce the size of the copied rectangle to stop it going
426      * outside the bounds of the canvas.
427      */
428
429     /* Transform from x,y,w,h form into coordinates of all edges */
430     x0 = *x;
431     y0 = *y;
432     x1 = *x + *w;
433     y1 = *y + *h;
434
435     /* Clip each coordinate at both extremes of the canvas */
436     x0 = (x0 < 0 ? 0 : x0 > canvas_w ? canvas_w : x0);
437     x1 = (x1 < 0 ? 0 : x1 > canvas_w ? canvas_w : x1);
438     y0 = (y0 < 0 ? 0 : y0 > canvas_h ? canvas_h : y0);
439     y1 = (y1 < 0 ? 0 : y1 > canvas_h ? canvas_h : y1); 
440
441     /* Transform back into x,y,w,h to return */
442     *x = x0;
443     *y = y0;
444     *w = x1 - x0;
445     *h = y1 - y0;
446 }
447
448 static void js_blitter_save(void *handle, blitter *bl, int x, int y)
449 {
450     int w = bl->w, h = bl->h;
451     trim_rect(&x, &y, &w, &h);
452     if (w > 0 && h > 0)
453         js_canvas_copy_to_blitter(bl->id, x, y, w, h);
454 }
455
456 static void js_blitter_load(void *handle, blitter *bl, int x, int y)
457 {
458     int w = bl->w, h = bl->h;
459     trim_rect(&x, &y, &w, &h);
460     if (w > 0 && h > 0)
461         js_canvas_copy_from_blitter(bl->id, x, y, w, h);
462 }
463
464 static void js_draw_update(void *handle, int x, int y, int w, int h)
465 {
466     trim_rect(&x, &y, &w, &h);
467     if (w > 0 && h > 0)
468         js_canvas_draw_update(x, y, w, h);
469 }
470
471 static void js_end_draw(void *handle)
472 {
473     js_canvas_end_draw();
474 }
475
476 static void js_status_bar(void *handle, char *text)
477 {
478     js_canvas_set_statusbar(text);
479 }
480
481 static char *js_text_fallback(void *handle, const char *const *strings,
482                               int nstrings)
483 {
484     return dupstr(strings[0]); /* Emscripten has no trouble with UTF-8 */
485 }
486
487 const struct drawing_api js_drawing = {
488     js_draw_text,
489     js_draw_rect,
490     js_draw_line,
491     js_draw_poly,
492     js_draw_circle,
493     js_draw_update,
494     js_clip,
495     js_unclip,
496     js_start_draw,
497     js_end_draw,
498     js_status_bar,
499     js_blitter_new,
500     js_blitter_free,
501     js_blitter_save,
502     js_blitter_load,
503     NULL, NULL, NULL, NULL, NULL, NULL, /* {begin,end}_{doc,page,puzzle} */
504     NULL, NULL,                        /* line_width, line_dotted */
505     js_text_fallback,
506     js_draw_thick_line,
507 };
508
509 /* ----------------------------------------------------------------------
510  * Presets and game-configuration dialog support.
511  */
512 static game_params **presets;
513 static int custom_preset;
514 int have_presets_dropdown;
515
516 void select_appropriate_preset(void)
517 {
518     if (have_presets_dropdown) {
519         int preset = midend_which_preset(me);
520         js_select_preset(preset < 0 ? custom_preset : preset);
521     }
522 }
523
524 static config_item *cfg = NULL;
525 static int cfg_which;
526
527 /*
528  * Set up a dialog box. This is pretty easy on the C side; most of the
529  * work is done in JS.
530  */
531 static void cfg_start(int which)
532 {
533     char *title;
534     int i;
535
536     cfg = midend_get_config(me, which, &title);
537     cfg_which = which;
538
539     js_dialog_init(title);
540     sfree(title);
541
542     for (i = 0; cfg[i].type != C_END; i++) {
543         switch (cfg[i].type) {
544           case C_STRING:
545             js_dialog_string(i, cfg[i].name, cfg[i].sval);
546             break;
547           case C_BOOLEAN:
548             js_dialog_boolean(i, cfg[i].name, cfg[i].ival);
549             break;
550           case C_CHOICES:
551             js_dialog_choices(i, cfg[i].name, cfg[i].sval, cfg[i].ival);
552             break;
553         }
554     }
555
556     js_dialog_launch();
557 }
558
559 /*
560  * Callbacks from JS when the OK button is clicked, to return the
561  * final state of each control.
562  */
563 void dlg_return_sval(int index, const char *val)
564 {
565     sfree(cfg[index].sval);
566     cfg[index].sval = dupstr(val);
567 }
568 void dlg_return_ival(int index, int val)
569 {
570     cfg[index].ival = val;
571 }
572
573 /*
574  * Called when the user clicks OK or Cancel. use_results will be TRUE
575  * or FALSE respectively, in those cases. We terminate the dialog box,
576  * unless the user selected an invalid combination of parameters.
577  */
578 static void cfg_end(int use_results)
579 {
580     if (use_results) {
581         /*
582          * User hit OK.
583          */
584         char *err = midend_set_config(me, cfg_which, cfg);
585
586         if (err) {
587             /*
588              * The settings were unacceptable, so leave the config box
589              * open for the user to adjust them and try again.
590              */
591             js_error_box(err);
592         } else {
593             /*
594              * New settings are fine; start a new game and close the
595              * dialog.
596              */
597             select_appropriate_preset();
598             midend_new_game(me);
599             resize();
600             midend_redraw(me);
601             free_cfg(cfg);
602             js_dialog_cleanup();
603         }
604     } else {
605         /*
606          * User hit Cancel. Close the dialog, but also we must still
607          * reselect the right element of the dropdown list.
608          *
609          * (Because: imagine you have a preset selected, and then you
610          * select Custom from the list, but change your mind and hit
611          * Esc. The Custom option will now still be selected in the
612          * list, whereas obviously it should show the preset you still
613          * _actually_ have selected. Worse still, it'll be the visible
614          * rather than invisible Custom option - see the comment in
615          * js_add_preset in emcclib.js - so you won't even be able to
616          * select Custom without a faffy workaround.)
617          */
618         select_appropriate_preset();
619
620         free_cfg(cfg);
621         js_dialog_cleanup();
622     }
623 }
624
625 /* ----------------------------------------------------------------------
626  * Called from JS when a command is given to the puzzle by clicking a
627  * button or control of some sort.
628  */
629 void command(int n)
630 {
631     switch (n) {
632       case 0:                          /* specific game ID */
633         cfg_start(CFG_DESC);
634         break;
635       case 1:                          /* random game seed */
636         cfg_start(CFG_SEED);
637         break;
638       case 2:                          /* game parameter dropdown changed */
639         {
640             int i = js_get_selected_preset();
641             if (i == custom_preset) {
642                 /*
643                  * The user selected 'Custom', so launch the config
644                  * box.
645                  */
646                 if (thegame.can_configure) /* (double-check just in case) */
647                     cfg_start(CFG_SETTINGS);
648             } else {
649                 /*
650                  * The user selected a preset, so just switch straight
651                  * to that.
652                  */
653                 midend_set_params(me, presets[i]);
654                 midend_new_game(me);
655                 resize();
656                 midend_redraw(me);
657                 update_undo_redo();
658                 js_focus_canvas();
659             }
660         }
661         break;
662       case 3:                          /* OK clicked in a config box */
663         cfg_end(TRUE);
664         update_undo_redo();
665         break;
666       case 4:                          /* Cancel clicked in a config box */
667         cfg_end(FALSE);
668         update_undo_redo();
669         break;
670       case 5:                          /* New Game */
671         midend_process_key(me, 0, 0, 'n');
672         update_undo_redo();
673         js_focus_canvas();
674         break;
675       case 6:                          /* Restart */
676         midend_restart_game(me);
677         update_undo_redo();
678         js_focus_canvas();
679         break;
680       case 7:                          /* Undo */
681         midend_process_key(me, 0, 0, 'u');
682         update_undo_redo();
683         js_focus_canvas();
684         break;
685       case 8:                          /* Redo */
686         midend_process_key(me, 0, 0, 'r');
687         update_undo_redo();
688         js_focus_canvas();
689         break;
690       case 9:                          /* Solve */
691         if (thegame.can_solve) {
692             char *msg = midend_solve(me);
693             if (msg)
694                 js_error_box(msg);
695         }
696         update_undo_redo();
697         js_focus_canvas();
698         break;
699     }
700 }
701
702 /* ----------------------------------------------------------------------
703  * Setup function called at page load time. It's called main() because
704  * that's the most convenient thing in Emscripten, but it's not main()
705  * in the usual sense of bounding the program's entire execution.
706  * Instead, this function returns once the initial puzzle is set up
707  * and working, and everything thereafter happens by means of JS event
708  * handlers sending us callbacks.
709  */
710 int main(int argc, char **argv)
711 {
712     char *param_err;
713     float *colours;
714     int i;
715
716     /*
717      * Instantiate a midend.
718      */
719     me = midend_new(NULL, &thegame, &js_drawing, NULL);
720
721     /*
722      * Chuck in the HTML fragment ID if we have one (trimming the
723      * leading # off the front first). If that's invalid, we retain
724      * the error message and will display it at the end, after setting
725      * up a random puzzle as usual.
726      */
727     if (argc > 1 && argv[1][0] == '#' && argv[1][1] != '\0')
728         param_err = midend_game_id(me, argv[1] + 1);
729     else
730         param_err = NULL;
731
732     /*
733      * Create either a random game or the specified one, and set the
734      * canvas size appropriately.
735      */
736     midend_new_game(me);
737     resize();
738
739     /*
740      * Create a status bar, if needed.
741      */
742     if (midend_wants_statusbar(me))
743         js_canvas_make_statusbar();
744
745     /*
746      * Set up the game-type dropdown with presets and/or the Custom
747      * option. We remember the index of the Custom option (as
748      * custom_preset) so that we can easily treat it specially when
749      * it's selected.
750      */
751     custom_preset = midend_num_presets(me);
752     if (custom_preset == 0) {
753         /*
754          * This puzzle doesn't have selectable game types at all.
755          * Completely remove the drop-down list from the page.
756          */
757         js_remove_type_dropdown();
758         have_presets_dropdown = FALSE;
759     } else {
760         int preset;
761
762         presets = snewn(custom_preset, game_params *);
763         for (i = 0; i < custom_preset; i++) {
764             char *name;
765             midend_fetch_preset(me, i, &name, &presets[i]);
766             js_add_preset(name);
767         }
768         if (thegame.can_configure)
769             js_add_preset(NULL);   /* the 'Custom' entry in the dropdown */
770
771         have_presets_dropdown = TRUE;
772
773         /*
774          * Now ensure the appropriate element of the presets menu
775          * starts off selected, in case it isn't the first one in the
776          * list (e.g. Slant).
777          */
778         select_appropriate_preset();
779     }
780
781     /*
782      * Remove the Solve button if the game doesn't support it.
783      */
784     if (!thegame.can_solve)
785         js_remove_solve_button();
786
787     /*
788      * Retrieve the game's colours, and convert them into #abcdef type
789      * hex ID strings.
790      */
791     colours = midend_colours(me, &ncolours);
792     colour_strings = snewn(ncolours, char *);
793     for (i = 0; i < ncolours; i++) {
794         char col[40];
795         sprintf(col, "#%02x%02x%02x",
796                 (unsigned)(0.5 + 255 * colours[i*3+0]),
797                 (unsigned)(0.5 + 255 * colours[i*3+1]),
798                 (unsigned)(0.5 + 255 * colours[i*3+2]));
799         colour_strings[i] = dupstr(col);
800     }
801
802     /*
803      * Request notification when the game ids change (e.g. if the user
804      * presses 'n', and also when Mines supersedes its game
805      * description), so that we can proactively update the permalink.
806      */
807     midend_request_id_changes(me, ids_changed, NULL);
808
809     /*
810      * Draw the puzzle's initial state, and set up the permalinks and
811      * undo/redo greying out.
812      */
813     midend_redraw(me);
814     update_permalinks();
815     update_undo_redo();
816
817     /*
818      * If we were given an erroneous game ID in argv[1], now's the
819      * time to put up the error box about it, after we've fully set up
820      * a random puzzle. Then when the user clicks 'ok', we have a
821      * puzzle for them.
822      */
823     if (param_err)
824         js_error_box(param_err);
825
826     /*
827      * Done. Return to JS, and await callbacks!
828      */
829     return 0;
830 }