2 * emcc.c: the C component of an Emscripten-based web/Javascript front
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.
13 * Further thoughts on possible enhancements:
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.
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.
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
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.
44 * - some CSS to make the button bar and configuration dialogs a
45 * little less ugly would probably not go amiss.
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!)
61 * Extern references to Javascript functions provided in emcclib.js.
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,
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,
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);
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,
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);
112 * Call JS to get the date, and use that to initialise our random
113 * number generator to invent the first game seed.
115 void get_random_seed(void **randseed, int *randseedsize)
117 unsigned *ret = snewn(2, unsigned);
120 *randseedsize = 2*sizeof(unsigned);
124 * Fatal error, called in cases of complete despair such as when
125 * malloc() has returned NULL.
127 void fatal(char *fmt, ...)
132 strcpy(buf, "puzzle fatal error: ");
135 vsnprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), fmt, ap);
142 * HTMLish names for the colours allocated by the puzzle.
144 char **colour_strings;
148 * The global midend object.
152 /* ----------------------------------------------------------------------
155 int timer_active = FALSE;
156 void deactivate_timer(frontend *fe)
158 js_deactivate_timer();
159 timer_active = FALSE;
161 void activate_timer(frontend *fe)
168 void timer_callback(double tplus)
171 midend_timer(me, tplus);
174 /* ----------------------------------------------------------------------
175 * Helper function to resize the canvas, and variables to remember its
176 * size for other functions (e.g. trimming blitter rectangles).
178 static int canvas_w, canvas_h;
179 static void resize(void)
183 midend_size(me, &w, &h, FALSE);
184 js_canvas_set_size(w, h);
190 * HTML doesn't give us a default frontend colour of its own, so we
191 * just make up a lightish grey ourselves.
193 void frontend_default_colour(frontend *fe, float *output)
195 output[0] = output[1] = output[2] = 0.9F;
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.
203 static void update_undo_redo(void)
205 js_enable_undo_redo(midend_can_undo(me), midend_can_redo(me));
209 * Mouse event handlers called from JS.
211 void mousedown(int x, int y, int button)
213 button = (button == 0 ? LEFT_BUTTON :
214 button == 1 ? MIDDLE_BUTTON : RIGHT_BUTTON);
215 midend_process_key(me, x, y, button);
219 void mouseup(int x, int y, int button)
221 button = (button == 0 ? LEFT_RELEASE :
222 button == 1 ? MIDDLE_RELEASE : RIGHT_RELEASE);
223 midend_process_key(me, x, y, button);
227 void mousemove(int x, int y, int buttons)
229 int button = (buttons & 2 ? MIDDLE_DRAG :
230 buttons & 4 ? RIGHT_DRAG : LEFT_DRAG);
231 midend_process_key(me, x, y, button);
236 * Keyboard handler called from JS.
238 void key(int keycode, int charcode, int shift, int ctrl)
242 keyevent = charcode & (ctrl ? 0x1F : 0xFF);
246 keyevent = '\177'; /* backspace */
249 keyevent = 13; /* return */
252 keyevent = CURSOR_LEFT;
255 keyevent = CURSOR_UP;
258 keyevent = CURSOR_RIGHT;
261 keyevent = CURSOR_DOWN;
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.
272 keyevent = MOD_NUM_KEYPAD | '1';
275 keyevent = MOD_NUM_KEYPAD | '3';
278 keyevent = MOD_NUM_KEYPAD | '7';
281 keyevent = MOD_NUM_KEYPAD | '9';
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);
288 /* not a key we care about */
292 if (shift && keyevent >= 0x100)
293 keyevent |= MOD_SHFT;
294 if (ctrl && keyevent >= 0x100)
295 keyevent |= MOD_CTRL;
297 midend_process_key(me, 0, 0, keyevent);
302 * Helper function called from several places to update the permalinks
303 * whenever a new game is created.
305 static void update_permalinks(void)
308 desc = midend_get_game_id(me);
309 seed = midend_get_random_seed(me);
310 js_update_permalinks(desc, seed);
316 * Callback from the midend when the game ids change, so we can update
319 static void ids_changed(void *ignored)
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
329 static void js_start_draw(void *handle)
331 js_canvas_start_draw();
334 static void js_clip(void *handle, int x, int y, int w, int h)
336 js_canvas_clip_rect(x, y, w, h);
339 static void js_unclip(void *handle)
344 static void js_draw_text(void *handle, int x, int y, int fonttype,
345 int fontsize, int align, int colour, char *text)
350 sprintf(fontstyle, "%dpx %s", fontsize,
351 fonttype == FONT_FIXED ? "monospace" : "sans-serif");
353 if (align & ALIGN_VCENTRE)
354 y += js_canvas_find_font_midpoint(fontsize, fontstyle);
356 if (align & ALIGN_HCENTRE)
358 else if (align & ALIGN_HRIGHT)
363 js_canvas_draw_text(x, y, halign, colour_strings[colour], fontstyle, text);
366 static void js_draw_rect(void *handle, int x, int y, int w, int h, int colour)
368 js_canvas_draw_rect(x, y, w, h, colour_strings[colour]);
371 static void js_draw_line(void *handle, int x1, int y1, int x2, int y2,
374 js_canvas_draw_line(x1, y1, x2, y2, 1, colour_strings[colour]);
377 static void js_draw_thick_line(void *handle, float thickness,
378 float x1, float y1, float x2, float y2,
381 js_canvas_draw_line(x1, y1, x2, y2, thickness, colour_strings[colour]);
384 static void js_draw_poly(void *handle, int *coords, int npoints,
385 int fillcolour, int outlinecolour)
387 js_canvas_draw_poly(coords, npoints,
388 fillcolour >= 0 ? colour_strings[fillcolour] : NULL,
389 colour_strings[outlinecolour]);
392 static void js_draw_circle(void *handle, int cx, int cy, int radius,
393 int fillcolour, int outlinecolour)
395 js_canvas_draw_circle(cx, cy, radius,
396 fillcolour >= 0 ? colour_strings[fillcolour] : NULL,
397 colour_strings[outlinecolour]);
401 int id; /* allocated on the js side */
402 int w, h; /* easier to retain here */
405 static blitter *js_blitter_new(void *handle, int w, int h)
407 blitter *bl = snew(blitter);
410 bl->id = js_canvas_new_blitter(w, h);
414 static void js_blitter_free(void *handle, blitter *bl)
416 js_canvas_free_blitter(bl->id);
420 static void trim_rect(int *x, int *y, int *w, int *h)
425 * Reduce the size of the copied rectangle to stop it going
426 * outside the bounds of the canvas.
429 /* Transform from x,y,w,h form into coordinates of all edges */
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);
441 /* Transform back into x,y,w,h to return */
448 static void js_blitter_save(void *handle, blitter *bl, int x, int y)
450 int w = bl->w, h = bl->h;
451 trim_rect(&x, &y, &w, &h);
453 js_canvas_copy_to_blitter(bl->id, x, y, w, h);
456 static void js_blitter_load(void *handle, blitter *bl, int x, int y)
458 int w = bl->w, h = bl->h;
459 trim_rect(&x, &y, &w, &h);
461 js_canvas_copy_from_blitter(bl->id, x, y, w, h);
464 static void js_draw_update(void *handle, int x, int y, int w, int h)
466 trim_rect(&x, &y, &w, &h);
468 js_canvas_draw_update(x, y, w, h);
471 static void js_end_draw(void *handle)
473 js_canvas_end_draw();
476 static void js_status_bar(void *handle, char *text)
478 js_canvas_set_statusbar(text);
481 static char *js_text_fallback(void *handle, const char *const *strings,
484 return dupstr(strings[0]); /* Emscripten has no trouble with UTF-8 */
487 const struct drawing_api js_drawing = {
503 NULL, NULL, NULL, NULL, NULL, NULL, /* {begin,end}_{doc,page,puzzle} */
504 NULL, NULL, /* line_width, line_dotted */
509 /* ----------------------------------------------------------------------
510 * Presets and game-configuration dialog support.
512 static game_params **presets;
513 static int custom_preset;
514 int have_presets_dropdown;
516 void select_appropriate_preset(void)
518 if (have_presets_dropdown) {
519 int preset = midend_which_preset(me);
520 js_select_preset(preset < 0 ? custom_preset : preset);
524 static config_item *cfg = NULL;
525 static int cfg_which;
528 * Set up a dialog box. This is pretty easy on the C side; most of the
529 * work is done in JS.
531 static void cfg_start(int which)
536 cfg = midend_get_config(me, which, &title);
539 js_dialog_init(title);
542 for (i = 0; cfg[i].type != C_END; i++) {
543 switch (cfg[i].type) {
545 js_dialog_string(i, cfg[i].name, cfg[i].sval);
548 js_dialog_boolean(i, cfg[i].name, cfg[i].ival);
551 js_dialog_choices(i, cfg[i].name, cfg[i].sval, cfg[i].ival);
560 * Callbacks from JS when the OK button is clicked, to return the
561 * final state of each control.
563 void dlg_return_sval(int index, const char *val)
565 sfree(cfg[index].sval);
566 cfg[index].sval = dupstr(val);
568 void dlg_return_ival(int index, int val)
570 cfg[index].ival = val;
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.
578 static void cfg_end(int use_results)
584 char *err = midend_set_config(me, cfg_which, cfg);
588 * The settings were unacceptable, so leave the config box
589 * open for the user to adjust them and try again.
594 * New settings are fine; start a new game and close the
597 select_appropriate_preset();
606 * User hit Cancel. Close the dialog, but also we must still
607 * reselect the right element of the dropdown list.
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.)
618 select_appropriate_preset();
625 /* ----------------------------------------------------------------------
626 * Called from JS when a command is given to the puzzle by clicking a
627 * button or control of some sort.
632 case 0: /* specific game ID */
635 case 1: /* random game seed */
638 case 2: /* game parameter dropdown changed */
640 int i = js_get_selected_preset();
641 if (i == custom_preset) {
643 * The user selected 'Custom', so launch the config
646 if (thegame.can_configure) /* (double-check just in case) */
647 cfg_start(CFG_SETTINGS);
650 * The user selected a preset, so just switch straight
653 midend_set_params(me, presets[i]);
662 case 3: /* OK clicked in a config box */
666 case 4: /* Cancel clicked in a config box */
670 case 5: /* New Game */
671 midend_process_key(me, 0, 0, 'n');
675 case 6: /* Restart */
676 midend_restart_game(me);
681 midend_process_key(me, 0, 0, 'u');
686 midend_process_key(me, 0, 0, 'r');
691 if (thegame.can_solve) {
692 char *msg = midend_solve(me);
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.
710 int main(int argc, char **argv)
717 * Instantiate a midend.
719 me = midend_new(NULL, &thegame, &js_drawing, NULL);
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.
727 if (argc > 1 && argv[1][0] == '#' && argv[1][1] != '\0')
728 param_err = midend_game_id(me, argv[1] + 1);
733 * Create either a random game or the specified one, and set the
734 * canvas size appropriately.
740 * Create a status bar, if needed.
742 if (midend_wants_statusbar(me))
743 js_canvas_make_statusbar();
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
751 custom_preset = midend_num_presets(me);
752 if (custom_preset == 0) {
754 * This puzzle doesn't have selectable game types at all.
755 * Completely remove the drop-down list from the page.
757 js_remove_type_dropdown();
758 have_presets_dropdown = FALSE;
762 presets = snewn(custom_preset, game_params *);
763 for (i = 0; i < custom_preset; i++) {
765 midend_fetch_preset(me, i, &name, &presets[i]);
768 if (thegame.can_configure)
769 js_add_preset(NULL); /* the 'Custom' entry in the dropdown */
771 have_presets_dropdown = TRUE;
774 * Now ensure the appropriate element of the presets menu
775 * starts off selected, in case it isn't the first one in the
778 select_appropriate_preset();
782 * Remove the Solve button if the game doesn't support it.
784 if (!thegame.can_solve)
785 js_remove_solve_button();
788 * Retrieve the game's colours, and convert them into #abcdef type
791 colours = midend_colours(me, &ncolours);
792 colour_strings = snewn(ncolours, char *);
793 for (i = 0; i < ncolours; i++) {
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);
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.
807 midend_request_id_changes(me, ids_changed, NULL);
810 * Draw the puzzle's initial state, and set up the permalinks and
811 * undo/redo greying out.
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
824 js_error_box(param_err);
827 * Done. Return to JS, and await callbacks!