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 * - I should think about whether these webified puzzles can support
25 * touchscreen-based tablet browsers (assuming there are any that
26 * can cope with the reasonably modern JS and run it fast enough to
29 * - think about making use of localStorage. It might be useful to
30 * let the user save games into there as an alternative to disk
31 * files - disk files are all very well for getting the save right
32 * out of your browser to (e.g.) email to me as a bug report, but
33 * for just resuming a game you were in the middle of, you'd
34 * probably rather have a nice simple 'quick save' and 'quick load'
35 * button pair. Also, that might be a useful place to store
36 * preferences, if I ever get round to writing a preferences UI.
38 * - some CSS to make the button bar and configuration dialogs a
39 * little less ugly would probably not go amiss.
41 * - this is a downright silly idea, but it does occur to me that if
42 * I were to write a PDF output driver for the Puzzles printing
43 * API, then I might be able to implement a sort of 'printing'
44 * feature in this front end, using data: URIs again. (Ask the user
45 * exactly what they want printed, then construct an appropriate
46 * PDF and embed it in a gigantic data: URI. Then they can print
47 * that using whatever they normally use to print PDFs!)
58 * Extern references to Javascript functions provided in emcclib.js.
60 extern void js_debug(const char *);
61 extern void js_error_box(const char *message);
62 extern void js_remove_type_dropdown(void);
63 extern void js_remove_solve_button(void);
64 extern void js_add_preset(int menuid, const char *name, int value);
65 extern int js_add_preset_submenu(int menuid, const char *name);
66 extern int js_get_selected_preset(void);
67 extern void js_select_preset(int n);
68 extern void js_get_date_64(unsigned *p);
69 extern void js_update_permalinks(const char *desc, const char *seed);
70 extern void js_enable_undo_redo(int undo, int redo);
71 extern void js_activate_timer();
72 extern void js_deactivate_timer();
73 extern void js_canvas_start_draw(void);
74 extern void js_canvas_draw_update(int x, int y, int w, int h);
75 extern void js_canvas_end_draw(void);
76 extern void js_canvas_draw_rect(int x, int y, int w, int h,
78 extern void js_canvas_clip_rect(int x, int y, int w, int h);
79 extern void js_canvas_unclip(void);
80 extern void js_canvas_draw_line(float x1, float y1, float x2, float y2,
81 int width, const char *colour);
82 extern void js_canvas_draw_poly(int *points, int npoints,
83 const char *fillcolour,
84 const char *outlinecolour);
85 extern void js_canvas_draw_circle(int x, int y, int r,
86 const char *fillcolour,
87 const char *outlinecolour);
88 extern int js_canvas_find_font_midpoint(int height, const char *fontptr);
89 extern void js_canvas_draw_text(int x, int y, int halign,
90 const char *colptr, const char *fontptr,
92 extern int js_canvas_new_blitter(int w, int h);
93 extern void js_canvas_free_blitter(int id);
94 extern void js_canvas_copy_to_blitter(int id, int x, int y, int w, int h);
95 extern void js_canvas_copy_from_blitter(int id, int x, int y, int w, int h);
96 extern void js_canvas_make_statusbar(void);
97 extern void js_canvas_set_statusbar(const char *text);
98 extern void js_canvas_set_size(int w, int h);
100 extern void js_dialog_init(const char *title);
101 extern void js_dialog_string(int i, const char *title, const char *initvalue);
102 extern void js_dialog_choices(int i, const char *title, const char *choicelist,
104 extern void js_dialog_boolean(int i, const char *title, int initvalue);
105 extern void js_dialog_launch(void);
106 extern void js_dialog_cleanup(void);
107 extern void js_focus_canvas(void);
110 * Call JS to get the date, and use that to initialise our random
111 * number generator to invent the first game seed.
113 void get_random_seed(void **randseed, int *randseedsize)
115 unsigned *ret = snewn(2, unsigned);
118 *randseedsize = 2*sizeof(unsigned);
122 * Fatal error, called in cases of complete despair such as when
123 * malloc() has returned NULL.
125 void fatal(char *fmt, ...)
130 strcpy(buf, "puzzle fatal error: ");
133 vsnprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), fmt, ap);
139 void debug_printf(char *fmt, ...)
144 vsnprintf(buf, sizeof(buf), fmt, ap);
150 * Helper function that makes it easy to test strings that might be
153 int strnullcmp(const char *a, const char *b)
155 if (a == NULL || b == NULL)
156 return a != NULL ? +1 : b != NULL ? -1 : 0;
161 * HTMLish names for the colours allocated by the puzzle.
163 char **colour_strings;
167 * The global midend object.
171 /* ----------------------------------------------------------------------
174 int timer_active = FALSE;
175 void deactivate_timer(frontend *fe)
177 js_deactivate_timer();
178 timer_active = FALSE;
180 void activate_timer(frontend *fe)
187 void timer_callback(double tplus)
190 midend_timer(me, tplus);
193 /* ----------------------------------------------------------------------
194 * Helper functions to resize the canvas, and variables to remember
195 * its size for other functions (e.g. trimming blitter rectangles).
197 static int canvas_w, canvas_h;
199 /* Called when we resize as a result of changing puzzle settings */
200 static void resize(void)
204 midend_size(me, &w, &h, FALSE);
205 js_canvas_set_size(w, h);
210 /* Called from JS when the user uses the resize handle */
211 void resize_puzzle(int w, int h)
213 midend_size(me, &w, &h, TRUE);
214 if (canvas_w != w || canvas_h != h) {
215 js_canvas_set_size(w, h);
218 midend_force_redraw(me);
222 /* Called from JS when the user uses the restore button */
223 void restore_puzzle_size(int w, int h)
225 midend_reset_tilesize(me);
227 midend_force_redraw(me);
231 * HTML doesn't give us a default frontend colour of its own, so we
232 * just make up a lightish grey ourselves.
234 void frontend_default_colour(frontend *fe, float *output)
236 output[0] = output[1] = output[2] = 0.9F;
240 * Helper function called from all over the place to ensure the undo
241 * and redo buttons get properly enabled and disabled after every move
242 * or undo or new-game event.
244 static void update_undo_redo(void)
246 js_enable_undo_redo(midend_can_undo(me), midend_can_redo(me));
250 * Mouse event handlers called from JS.
252 void mousedown(int x, int y, int button)
254 button = (button == 0 ? LEFT_BUTTON :
255 button == 1 ? MIDDLE_BUTTON : RIGHT_BUTTON);
256 midend_process_key(me, x, y, button);
260 void mouseup(int x, int y, int button)
262 button = (button == 0 ? LEFT_RELEASE :
263 button == 1 ? MIDDLE_RELEASE : RIGHT_RELEASE);
264 midend_process_key(me, x, y, button);
268 void mousemove(int x, int y, int buttons)
270 int button = (buttons & 2 ? MIDDLE_DRAG :
271 buttons & 4 ? RIGHT_DRAG : LEFT_DRAG);
272 midend_process_key(me, x, y, button);
277 * Keyboard handler called from JS.
279 void key(int keycode, int charcode, const char *key, const char *chr,
284 if (!strnullcmp(key, "Backspace") || !strnullcmp(key, "Del") ||
285 keycode == 8 || keycode == 46) {
286 keyevent = 127; /* Backspace / Delete */
287 } else if (!strnullcmp(key, "Enter") || keycode == 13) {
288 keyevent = 13; /* return */
289 } else if (!strnullcmp(key, "Left") || keycode == 37) {
290 keyevent = CURSOR_LEFT;
291 } else if (!strnullcmp(key, "Up") || keycode == 38) {
292 keyevent = CURSOR_UP;
293 } else if (!strnullcmp(key, "Right") || keycode == 39) {
294 keyevent = CURSOR_RIGHT;
295 } else if (!strnullcmp(key, "Down") || keycode == 40) {
296 keyevent = CURSOR_DOWN;
297 } else if (!strnullcmp(key, "End") || keycode == 35) {
299 * We interpret Home, End, PgUp and PgDn as numeric keypad
300 * controls regardless of whether they're the ones on the
301 * numeric keypad (since we can't tell). The effect of
302 * this should only be that the non-numeric-pad versions
303 * of those keys generate directions in 8-way movement
304 * puzzles like Cube and Inertia.
306 keyevent = MOD_NUM_KEYPAD | '1';
307 } else if (!strnullcmp(key, "PageDown") || keycode==34) {
308 keyevent = MOD_NUM_KEYPAD | '3';
309 } else if (!strnullcmp(key, "Home") || keycode==36) {
310 keyevent = MOD_NUM_KEYPAD | '7';
311 } else if (!strnullcmp(key, "PageUp") || keycode==33) {
312 keyevent = MOD_NUM_KEYPAD | '9';
313 } else if (shift && ctrl && (keycode & 0x1F) == 26) {
315 } else if (chr && chr[0] && !chr[1]) {
316 keyevent = chr[0] & 0xFF;
317 } else if (keycode >= 96 && keycode < 106) {
318 keyevent = MOD_NUM_KEYPAD | ('0' + keycode - 96);
319 } else if (keycode >= 65 && keycode <= 90) {
320 keyevent = keycode + (shift ? 0 : 32);
321 } else if (keycode >= 48 && keycode <= 57) {
323 } else if (keycode == 32) { /* space / CURSOR_SELECT2 */
328 if (shift && (keyevent >= 0x100 && !IS_UI_FAKE_KEY(keyevent)))
329 keyevent |= MOD_SHFT;
331 if (ctrl && !IS_UI_FAKE_KEY(keyevent)) {
332 if (keyevent >= 0x100)
333 keyevent |= MOD_CTRL;
338 midend_process_key(me, 0, 0, keyevent);
344 * Helper function called from several places to update the permalinks
345 * whenever a new game is created.
347 static void update_permalinks(void)
350 desc = midend_get_game_id(me);
351 seed = midend_get_random_seed(me);
352 js_update_permalinks(desc, seed);
358 * Callback from the midend when the game ids change, so we can update
361 static void ids_changed(void *ignored)
366 /* ----------------------------------------------------------------------
367 * Implementation of the drawing API by calling Javascript canvas
368 * drawing functions. (Well, half of it; the other half is on the JS
371 static void js_start_draw(void *handle)
373 js_canvas_start_draw();
376 static void js_clip(void *handle, int x, int y, int w, int h)
378 js_canvas_clip_rect(x, y, w, h);
381 static void js_unclip(void *handle)
386 static void js_draw_text(void *handle, int x, int y, int fonttype,
387 int fontsize, int align, int colour, char *text)
392 sprintf(fontstyle, "%dpx %s", fontsize,
393 fonttype == FONT_FIXED ? "monospace" : "sans-serif");
395 if (align & ALIGN_VCENTRE)
396 y += js_canvas_find_font_midpoint(fontsize, fontstyle);
398 if (align & ALIGN_HCENTRE)
400 else if (align & ALIGN_HRIGHT)
405 js_canvas_draw_text(x, y, halign, colour_strings[colour], fontstyle, text);
408 static void js_draw_rect(void *handle, int x, int y, int w, int h, int colour)
410 js_canvas_draw_rect(x, y, w, h, colour_strings[colour]);
413 static void js_draw_line(void *handle, int x1, int y1, int x2, int y2,
416 js_canvas_draw_line(x1, y1, x2, y2, 1, colour_strings[colour]);
419 static void js_draw_thick_line(void *handle, float thickness,
420 float x1, float y1, float x2, float y2,
423 js_canvas_draw_line(x1, y1, x2, y2, thickness, colour_strings[colour]);
426 static void js_draw_poly(void *handle, int *coords, int npoints,
427 int fillcolour, int outlinecolour)
429 js_canvas_draw_poly(coords, npoints,
430 fillcolour >= 0 ? colour_strings[fillcolour] : NULL,
431 colour_strings[outlinecolour]);
434 static void js_draw_circle(void *handle, int cx, int cy, int radius,
435 int fillcolour, int outlinecolour)
437 js_canvas_draw_circle(cx, cy, radius,
438 fillcolour >= 0 ? colour_strings[fillcolour] : NULL,
439 colour_strings[outlinecolour]);
443 int id; /* allocated on the js side */
444 int w, h; /* easier to retain here */
447 static blitter *js_blitter_new(void *handle, int w, int h)
449 blitter *bl = snew(blitter);
452 bl->id = js_canvas_new_blitter(w, h);
456 static void js_blitter_free(void *handle, blitter *bl)
458 js_canvas_free_blitter(bl->id);
462 static void trim_rect(int *x, int *y, int *w, int *h)
467 * Reduce the size of the copied rectangle to stop it going
468 * outside the bounds of the canvas.
471 /* Transform from x,y,w,h form into coordinates of all edges */
477 /* Clip each coordinate at both extremes of the canvas */
478 x0 = (x0 < 0 ? 0 : x0 > canvas_w ? canvas_w : x0);
479 x1 = (x1 < 0 ? 0 : x1 > canvas_w ? canvas_w : x1);
480 y0 = (y0 < 0 ? 0 : y0 > canvas_h ? canvas_h : y0);
481 y1 = (y1 < 0 ? 0 : y1 > canvas_h ? canvas_h : y1);
483 /* Transform back into x,y,w,h to return */
490 static void js_blitter_save(void *handle, blitter *bl, int x, int y)
492 int w = bl->w, h = bl->h;
493 trim_rect(&x, &y, &w, &h);
495 js_canvas_copy_to_blitter(bl->id, x, y, w, h);
498 static void js_blitter_load(void *handle, blitter *bl, int x, int y)
500 int w = bl->w, h = bl->h;
501 trim_rect(&x, &y, &w, &h);
503 js_canvas_copy_from_blitter(bl->id, x, y, w, h);
506 static void js_draw_update(void *handle, int x, int y, int w, int h)
508 trim_rect(&x, &y, &w, &h);
510 js_canvas_draw_update(x, y, w, h);
513 static void js_end_draw(void *handle)
515 js_canvas_end_draw();
518 static void js_status_bar(void *handle, char *text)
520 js_canvas_set_statusbar(text);
523 static char *js_text_fallback(void *handle, const char *const *strings,
526 return dupstr(strings[0]); /* Emscripten has no trouble with UTF-8 */
529 const struct drawing_api js_drawing = {
545 NULL, NULL, NULL, NULL, NULL, NULL, /* {begin,end}_{doc,page,puzzle} */
546 NULL, NULL, /* line_width, line_dotted */
551 /* ----------------------------------------------------------------------
552 * Presets and game-configuration dialog support.
554 static game_params **presets;
556 int have_presets_dropdown;
558 void populate_js_preset_menu(int menuid, struct preset_menu *menu)
561 for (i = 0; i < menu->n_entries; i++) {
562 struct preset_menu_entry *entry = &menu->entries[i];
564 presets[entry->id] = entry->params;
565 js_add_preset(menuid, entry->title, entry->id);
567 int js_submenu = js_add_preset_submenu(menuid, entry->title);
568 populate_js_preset_menu(js_submenu, entry->submenu);
573 void select_appropriate_preset(void)
575 if (have_presets_dropdown) {
576 int preset = midend_which_preset(me);
577 js_select_preset(preset < 0 ? -1 : preset);
581 static config_item *cfg = NULL;
582 static int cfg_which;
585 * Set up a dialog box. This is pretty easy on the C side; most of the
586 * work is done in JS.
588 static void cfg_start(int which)
593 cfg = midend_get_config(me, which, &title);
596 js_dialog_init(title);
599 for (i = 0; cfg[i].type != C_END; i++) {
600 switch (cfg[i].type) {
602 js_dialog_string(i, cfg[i].name, cfg[i].sval);
605 js_dialog_boolean(i, cfg[i].name, cfg[i].ival);
608 js_dialog_choices(i, cfg[i].name, cfg[i].sval, cfg[i].ival);
617 * Callbacks from JS when the OK button is clicked, to return the
618 * final state of each control.
620 void dlg_return_sval(int index, const char *val)
622 sfree(cfg[index].sval);
623 cfg[index].sval = dupstr(val);
625 void dlg_return_ival(int index, int val)
627 cfg[index].ival = val;
631 * Called when the user clicks OK or Cancel. use_results will be TRUE
632 * or FALSE respectively, in those cases. We terminate the dialog box,
633 * unless the user selected an invalid combination of parameters.
635 static void cfg_end(int use_results)
641 char *err = midend_set_config(me, cfg_which, cfg);
645 * The settings were unacceptable, so leave the config box
646 * open for the user to adjust them and try again.
651 * New settings are fine; start a new game and close the
654 select_appropriate_preset();
663 * User hit Cancel. Close the dialog, but also we must still
664 * reselect the right element of the dropdown list.
666 * (Because: imagine you have a preset selected, and then you
667 * select Custom from the list, but change your mind and hit
668 * Esc. The Custom option will now still be selected in the
669 * list, whereas obviously it should show the preset you still
670 * _actually_ have selected. Worse still, it'll be the visible
671 * rather than invisible Custom option - see the comment in
672 * js_add_preset in emcclib.js - so you won't even be able to
673 * select Custom without a faffy workaround.)
675 select_appropriate_preset();
682 /* ----------------------------------------------------------------------
683 * Called from JS when a command is given to the puzzle by clicking a
684 * button or control of some sort.
689 case 0: /* specific game ID */
692 case 1: /* random game seed */
695 case 2: /* game parameter dropdown changed */
697 int i = js_get_selected_preset();
700 * The user selected 'Custom', so launch the config
703 if (thegame.can_configure) /* (double-check just in case) */
704 cfg_start(CFG_SETTINGS);
707 * The user selected a preset, so just switch straight
710 assert(i < npresets);
711 midend_set_params(me, presets[i]);
717 select_appropriate_preset();
721 case 3: /* OK clicked in a config box */
725 case 4: /* Cancel clicked in a config box */
729 case 5: /* New Game */
730 midend_process_key(me, 0, 0, UI_NEWGAME);
734 case 6: /* Restart */
735 midend_restart_game(me);
740 midend_process_key(me, 0, 0, UI_UNDO);
745 midend_process_key(me, 0, 0, UI_REDO);
750 if (thegame.can_solve) {
751 char *msg = midend_solve(me);
761 /* ----------------------------------------------------------------------
762 * Called from JS to prepare a save-game file, and free one after it's
766 struct savefile_write_ctx {
771 static void savefile_write(void *vctx, void *buf, int len)
773 struct savefile_write_ctx *ctx = (struct savefile_write_ctx *)vctx;
775 memcpy(ctx->buffer + ctx->pos, buf, len);
779 char *get_save_file(void)
781 struct savefile_write_ctx ctx;
784 /* First pass, to count up the size */
787 midend_serialise(me, savefile_write, &ctx);
790 /* Second pass, to actually write out the data */
791 ctx.buffer = snewn(size, char);
793 midend_serialise(me, savefile_write, &ctx);
794 assert(ctx.pos == size);
799 void free_save_file(char *buffer)
804 struct savefile_read_ctx {
809 static int savefile_read(void *vctx, void *buf, int len)
811 struct savefile_read_ctx *ctx = (struct savefile_read_ctx *)vctx;
812 if (ctx->len_remaining < len)
814 memcpy(buf, ctx->buffer, len);
815 ctx->len_remaining -= len;
820 void load_game(const char *buffer, int len)
822 struct savefile_read_ctx ctx;
826 ctx.len_remaining = len;
827 err = midend_deserialise(me, savefile_read, &ctx);
832 select_appropriate_preset();
838 /* ----------------------------------------------------------------------
839 * Setup function called at page load time. It's called main() because
840 * that's the most convenient thing in Emscripten, but it's not main()
841 * in the usual sense of bounding the program's entire execution.
842 * Instead, this function returns once the initial puzzle is set up
843 * and working, and everything thereafter happens by means of JS event
844 * handlers sending us callbacks.
846 int main(int argc, char **argv)
853 * Instantiate a midend.
855 me = midend_new(NULL, &thegame, &js_drawing, NULL);
858 * Chuck in the HTML fragment ID if we have one (trimming the
859 * leading # off the front first). If that's invalid, we retain
860 * the error message and will display it at the end, after setting
861 * up a random puzzle as usual.
863 if (argc > 1 && argv[1][0] == '#' && argv[1][1] != '\0')
864 param_err = midend_game_id(me, argv[1] + 1);
869 * Create either a random game or the specified one, and set the
870 * canvas size appropriately.
876 * Create a status bar, if needed.
878 if (midend_wants_statusbar(me))
879 js_canvas_make_statusbar();
882 * Set up the game-type dropdown with presets and/or the Custom
886 struct preset_menu *menu = midend_get_presets(me, &npresets);
887 presets = snewn(npresets, game_params *);
888 for (i = 0; i < npresets; i++)
891 populate_js_preset_menu(0, menu);
893 if (thegame.can_configure)
894 js_add_preset(0, "Custom", -1);
896 have_presets_dropdown = TRUE;
899 * Now ensure the appropriate element of the presets menu
900 * starts off selected, in case it isn't the first one in the
903 select_appropriate_preset();
907 * Remove the Solve button if the game doesn't support it.
909 if (!thegame.can_solve)
910 js_remove_solve_button();
913 * Retrieve the game's colours, and convert them into #abcdef type
916 colours = midend_colours(me, &ncolours);
917 colour_strings = snewn(ncolours, char *);
918 for (i = 0; i < ncolours; i++) {
920 sprintf(col, "#%02x%02x%02x",
921 (unsigned)(0.5 + 255 * colours[i*3+0]),
922 (unsigned)(0.5 + 255 * colours[i*3+1]),
923 (unsigned)(0.5 + 255 * colours[i*3+2]));
924 colour_strings[i] = dupstr(col);
928 * Request notification when the game ids change (e.g. if the user
929 * presses 'n', and also when Mines supersedes its game
930 * description), so that we can proactively update the permalink.
932 midend_request_id_changes(me, ids_changed, NULL);
935 * Draw the puzzle's initial state, and set up the permalinks and
936 * undo/redo greying out.
943 * If we were given an erroneous game ID in argv[1], now's the
944 * time to put up the error box about it, after we've fully set up
945 * a random puzzle. Then when the user clicks 'ok', we have a
949 js_error_box(param_err);
952 * Done. Return to JS, and await callbacks!