2 * emcclib.js: one of the Javascript components of an Emscripten-based
3 * web/Javascript front end for Puzzles.
5 * The other parts of this system live in emcc.c and emccpre.js.
7 * This file contains a set of Javascript functions which we insert
8 * into Emscripten's library object via the --js-library option; this
9 * allows us to provide JS code which can be called from the
10 * Emscripten-compiled C, mostly dealing with UI interaction of
14 mergeInto(LibraryManager.library, {
16 * void js_debug(const char *message);
18 * A function to write a diagnostic to the Javascript console.
19 * Unused in production, but handy in development.
21 js_debug: function(ptr) {
22 console.log(Pointer_stringify(ptr));
26 * void js_error_box(const char *message);
28 * A wrapper around Javascript's alert(), so the C code can print
29 * simple error message boxes (e.g. when invalid data is entered
30 * in a configuration dialog).
32 js_error_box: function(ptr) {
33 alert(Pointer_stringify(ptr));
37 * void js_remove_type_dropdown(void);
39 * Get rid of the drop-down list on the web page for selecting
40 * game presets. Called at setup time if the game back end
41 * provides neither presets nor configurability.
43 js_remove_type_dropdown: function() {
44 document.getElementById("gametype").style.display = "none";
48 * void js_remove_solve_button(void);
50 * Get rid of the Solve button on the web page. Called at setup
51 * time if the game doesn't support an in-game solve function.
53 js_remove_solve_button: function() {
54 document.getElementById("solve").style.display = "none";
58 * void js_add_preset(const char *name);
60 * Add a preset to the drop-down types menu. The provided text is
61 * the name of the preset. (The corresponding game_params stays on
62 * the C side and never comes out this far; we just pass a numeric
63 * index back to the C code when a selection is made.)
65 js_add_preset: function(ptr) {
66 var option = document.createElement("option");
67 option.value = Pointer_stringify(ptr);
68 option.innerHTML = Pointer_stringify(ptr);
69 gametypeselector.appendChild(option);
70 gametypeoptions.push(option);
74 * int js_get_selected_preset(void);
76 * Return the index of the currently selected value in the type
79 js_get_selected_preset: function() {
81 for (var i in gametypeoptions) {
82 if (gametypeoptions[i].selected) {
91 * void js_select_preset(int n);
93 * Cause a different value to be selected in the type dropdown
94 * (for when the user selects values from the Custom configurer
95 * which turn out to exactly match a preset).
97 js_select_preset: function(n) {
98 gametypeoptions[n].selected = true;
102 * void js_get_date_64(unsigned *p);
104 * Return the current date, in milliseconds since the epoch
105 * (Javascript's native format), as a 64-bit integer. Used to
106 * invent an initial random seed for puzzle generation.
108 js_get_date_64: function(ptr) {
109 var d = (new Date()).valueOf();
110 setValue(ptr, d, 'i64');
114 * void js_update_permalinks(const char *desc, const char *seed);
116 * Update the permalinks on the web page for a new game
117 * description and optional random seed. desc can never be NULL,
118 * but seed might be (if the game was generated by entering a
119 * descriptive id by hand), in which case we suppress display of
120 * the random seed permalink.
122 js_update_permalinks: function(desc, seed) {
123 desc = Pointer_stringify(desc);
124 permalink_desc.href = "#" + desc;
127 permalink_seed.style.display = "none";
129 seed = Pointer_stringify(seed);
130 permalink_seed.href = "#" + seed;
131 permalink_seed.style.display = "inline";
136 * void js_enable_undo_redo(int undo, int redo);
138 * Set the enabled/disabled states of the undo and redo buttons,
141 js_enable_undo_redo: function(undo, redo) {
142 undo_button.disabled = (undo == 0);
143 redo_button.disabled = (redo == 0);
147 * void js_activate_timer();
149 * Start calling the C timer_callback() function every 20ms.
151 js_activate_timer: function() {
152 if (timer === null) {
153 timer_reference_date = (new Date()).valueOf();
154 timer = setInterval(function() {
155 var now = (new Date()).valueOf();
156 timer_callback((now - timer_reference_date) / 1000.0);
157 timer_reference_date = now;
164 * void js_deactivate_timer();
166 * Stop calling the C timer_callback() function every 20ms.
168 js_deactivate_timer: function() {
169 if (timer !== null) {
170 clearInterval(timer);
176 * void js_canvas_start_draw(void);
178 * Prepare to do some drawing on the canvas.
180 js_canvas_start_draw: function() {
181 ctx = offscreen_canvas.getContext('2d');
182 update_xmin = update_xmax = update_ymin = update_ymax = undefined;
186 * void js_canvas_draw_update(int x, int y, int w, int h);
188 * Mark a rectangle of the off-screen canvas as needing to be
189 * copied to the on-screen one.
191 js_canvas_draw_update: function(x, y, w, h) {
193 * Currently we do this in a really simple way, just by taking
194 * the smallest rectangle containing all updates so far. We
195 * could instead keep the data in a richer form (e.g. retain
196 * multiple smaller rectangles needing update, and only redraw
197 * the whole thing beyond a certain threshold) but this will
200 if (update_xmin === undefined || update_xmin > x) update_xmin = x;
201 if (update_ymin === undefined || update_ymin > y) update_ymin = y;
202 if (update_xmax === undefined || update_xmax < x+w) update_xmax = x+w;
203 if (update_ymax === undefined || update_ymax < y+h) update_ymax = y+h;
207 * void js_canvas_end_draw(void);
209 * Finish the drawing, by actually copying the newly drawn stuff
210 * to the on-screen canvas.
212 js_canvas_end_draw: function() {
213 if (update_xmin !== undefined) {
214 var onscreen_ctx = onscreen_canvas.getContext('2d');
215 onscreen_ctx.drawImage(offscreen_canvas,
216 update_xmin, update_ymin,
217 update_xmax - update_xmin,
218 update_ymax - update_ymin,
219 update_xmin, update_ymin,
220 update_xmax - update_xmin,
221 update_ymax - update_ymin);
227 * void js_canvas_draw_rect(int x, int y, int w, int h,
228 * const char *colour);
232 js_canvas_draw_rect: function(x, y, w, h, colptr) {
233 ctx.fillStyle = Pointer_stringify(colptr);
234 ctx.fillRect(x, y, w, h);
238 * void js_canvas_clip_rect(int x, int y, int w, int h);
240 * Set a clipping rectangle.
242 js_canvas_clip_rect: function(x, y, w, h) {
245 ctx.rect(x, y, w, h);
250 * void js_canvas_unclip(void);
252 * Reset to no clipping.
254 js_canvas_unclip: function() {
259 * void js_canvas_draw_line(float x1, float y1, float x2, float y2,
260 * int width, const char *colour);
262 * Draw a line. We must adjust the coordinates by 0.5 because
263 * Javascript's canvas coordinates appear to be pixel corners,
264 * whereas we want pixel centres. Also, we manually draw the pixel
265 * at each end of the line, which our clients will expect but
266 * Javascript won't reliably do by default (in common with other
267 * Postscriptish drawing frameworks).
269 js_canvas_draw_line: function(x1, y1, x2, y2, width, colour) {
270 colour = Pointer_stringify(colour);
273 ctx.moveTo(x1 + 0.5, y1 + 0.5);
274 ctx.lineTo(x2 + 0.5, y2 + 0.5);
275 ctx.lineWidth = width;
278 ctx.strokeStyle = colour;
280 ctx.fillStyle = colour;
281 ctx.fillRect(x1, y1, 1, 1);
282 ctx.fillRect(x2, y2, 1, 1);
286 * void js_canvas_draw_poly(int *points, int npoints,
287 * const char *fillcolour,
288 * const char *outlinecolour);
292 js_canvas_draw_poly: function(pointptr, npoints, fill, outline) {
294 ctx.moveTo(getValue(pointptr , 'i32') + 0.5,
295 getValue(pointptr+4, 'i32') + 0.5);
296 for (var i = 1; i < npoints; i++)
297 ctx.lineTo(getValue(pointptr+8*i , 'i32') + 0.5,
298 getValue(pointptr+8*i+4, 'i32') + 0.5);
301 ctx.fillStyle = Pointer_stringify(fill);
307 ctx.strokeStyle = Pointer_stringify(outline);
312 * void js_canvas_draw_circle(int x, int y, int r,
313 * const char *fillcolour,
314 * const char *outlinecolour);
318 js_canvas_draw_circle: function(x, y, r, fill, outline) {
320 ctx.arc(x + 0.5, y + 0.5, r, 0, 2*Math.PI);
322 ctx.fillStyle = Pointer_stringify(fill);
328 ctx.strokeStyle = Pointer_stringify(outline);
333 * int js_canvas_find_font_midpoint(int height, const char *fontptr);
335 * Return the adjustment required for text displayed using
336 * ALIGN_VCENTRE. We want to place the midpoint between the
337 * baseline and the cap-height at the specified position; so this
338 * function returns the adjustment which, when added to the
339 * desired centre point, returns the y-coordinate at which you
340 * should put the baseline.
342 * There is no sensible method of querying this kind of font
343 * metric in Javascript, so instead we render a piece of test text
344 * to a throwaway offscreen canvas and then read the pixel data
345 * back out to find the highest and lowest pixels. That's good
346 * _enough_ (in that we only needed the answer to the nearest
347 * pixel anyway), but rather disgusting!
349 * Since this is a very expensive operation, we cache the results
350 * per (font,height) pair.
352 js_canvas_find_font_midpoint: function(height, font) {
353 font = Pointer_stringify(font);
355 // Reuse cached value if possible
356 if (midpoint_cache[font] !== undefined)
357 return midpoint_cache[font];
359 // Find the width of the string
360 var ctx1 = onscreen_canvas.getContext('2d');
362 var width = ctx1.measureText(midpoint_test_str).width;
364 // Construct a test canvas of appropriate size, initialise it to
365 // black, and draw the string on it in white
366 var measure_canvas = document.createElement('canvas');
367 var ctx2 = measure_canvas.getContext('2d');
368 ctx2.canvas.width = width;
369 ctx2.canvas.height = 2*height;
370 ctx2.fillStyle = "#000000";
371 ctx2.fillRect(0, 0, width, 2*height);
372 var baseline = (1.5*height) | 0;
373 ctx2.fillStyle = "#ffffff";
375 ctx2.fillText(midpoint_test_str, 0, baseline);
377 // Scan the contents of the test canvas to find the top and bottom
379 var pixels = ctx2.getImageData(0, 0, width, 2*height).data;
380 var ymin = 2*height, ymax = -1;
381 for (var y = 0; y < 2*height; y++) {
382 for (var x = 0; x < width; x++) {
383 if (pixels[4*(y*width+x)] != 0) {
384 if (ymin > y) ymin = y;
385 if (ymax < y) ymax = y;
391 var ret = (baseline - (ymin + ymax) / 2) | 0;
392 midpoint_cache[font] = ret;
397 * void js_canvas_draw_text(int x, int y, int halign,
398 * const char *colptr, const char *fontptr,
401 * Draw text. Vertical alignment has been taken care of on the C
402 * side, by optionally calling the above function. Horizontal
403 * alignment is handled here, since we can get the canvas draw
404 * function to do it for us with almost no extra effort.
406 js_canvas_draw_text: function(x, y, halign, colptr, fontptr, text) {
407 ctx.font = Pointer_stringify(fontptr);
408 ctx.fillStyle = Pointer_stringify(colptr);
409 ctx.textAlign = (halign == 0 ? 'left' :
410 halign == 1 ? 'center' : 'right');
411 ctx.textBaseline = 'alphabetic';
412 ctx.fillText(Pointer_stringify(text), x, y);
416 * int js_canvas_new_blitter(int w, int h);
418 * Create a new blitter object, which is just an offscreen canvas
419 * of the specified size.
421 js_canvas_new_blitter: function(w, h) {
422 var id = blittercount++;
423 blitters[id] = document.createElement("canvas");
424 blitters[id].width = w;
425 blitters[id].height = h;
429 * void js_canvas_free_blitter(int id);
431 * Free a blitter (or rather, destroy our reference to it so JS
432 * can garbage-collect it, and also enforce that we don't
433 * accidentally use it again afterwards).
435 js_canvas_free_blitter: function(id) {
440 * void js_canvas_copy_to_blitter(int id, int x, int y, int w, int h);
442 * Copy from the puzzle image to a blitter. The size is passed to
443 * us, partly so we don't have to remember the size of each
444 * blitter, but mostly so that the C side can adjust the copy
445 * rectangle in the case where it partially overlaps the edge of
448 js_canvas_copy_to_blitter: function(id, x, y, w, h) {
449 var blitter_ctx = blitters[id].getContext('2d');
450 blitter_ctx.drawImage(offscreen_canvas,
456 * void js_canvas_copy_from_blitter(int id, int x, int y, int w, int h);
458 * Copy from a blitter back to the puzzle image. As above, the
459 * size of the copied rectangle is passed to us from the C side
460 * and may already have been modified.
462 js_canvas_copy_from_blitter: function(id, x, y, w, h) {
463 ctx.drawImage(blitters[id],
469 * void js_canvas_make_statusbar(void);
471 * Cause a status bar to exist. Called at setup time if the puzzle
472 * back end turns out to want one.
474 js_canvas_make_statusbar: function() {
475 var statustd = document.getElementById("statusbarholder");
476 statusbar = document.createElement("div");
477 statusbar.style.overflow = "hidden";
478 statusbar.style.width = onscreen_canvas.width - 4;
479 statusbar.style.height = "1.2em";
480 statusbar.style.background = "#d8d8d8";
481 statusbar.style.borderLeft = '2px solid #c8c8c8';
482 statusbar.style.borderTop = '2px solid #c8c8c8';
483 statusbar.style.borderRight = '2px solid #e8e8e8';
484 statusbar.style.borderBottom = '2px solid #e8e8e8';
485 statusbar.appendChild(document.createTextNode(" "));
486 statustd.appendChild(statusbar);
490 * void js_canvas_set_statusbar(const char *text);
492 * Set the text in the status bar.
494 js_canvas_set_statusbar: function(ptr) {
495 var text = Pointer_stringify(ptr);
496 statusbar.replaceChild(document.createTextNode(text),
497 statusbar.lastChild);
501 * void js_canvas_set_size(int w, int h);
503 * Set the size of the puzzle canvas. Called at setup, and every
504 * time the user picks new puzzle settings requiring a different
507 js_canvas_set_size: function(w, h) {
508 onscreen_canvas.width = w;
509 offscreen_canvas.width = w;
510 if (statusbar !== null)
511 statusbar.style.width = w - 4;
513 onscreen_canvas.height = h;
514 offscreen_canvas.height = h;
518 * void js_dialog_init(const char *title);
520 * Begin constructing a 'dialog box' which will be popped up in an
521 * overlay on top of the rest of the puzzle web page.
523 js_dialog_init: function(titletext) {
524 // Create an overlay on the page which darkens everything
526 dlg_dimmer = document.createElement("div");
527 dlg_dimmer.style.width = "100%";
528 dlg_dimmer.style.height = "100%";
529 dlg_dimmer.style.background = '#000000';
530 dlg_dimmer.style.position = 'fixed';
531 dlg_dimmer.style.opacity = 0.3;
532 dlg_dimmer.style.top = dlg_dimmer.style.left = 0;
533 dlg_dimmer.style["z-index"] = 99;
535 // Now create a form which sits on top of that in turn.
536 dlg_form = document.createElement("form");
537 dlg_form.style.width = window.innerWidth * 2 / 3;
538 dlg_form.style.opacity = 1;
539 dlg_form.style.background = '#ffffff';
540 dlg_form.style.color = '#000000';
541 dlg_form.style.position = 'absolute';
542 dlg_form.style.border = "2px solid black";
543 dlg_form.style.padding = 20;
544 dlg_form.style.top = window.innerHeight / 10;
545 dlg_form.style.left = window.innerWidth / 6;
546 dlg_form.style["z-index"] = 100;
548 var title = document.createElement("p");
549 title.style.marginTop = "0px";
550 title.appendChild(document.createTextNode
551 (Pointer_stringify(titletext)));
552 dlg_form.appendChild(title);
554 dlg_return_funcs = [];
559 * void js_dialog_string(int i, const char *title, const char *initvalue);
561 * Add a string control (that is, an edit box) to the dialog under
564 js_dialog_string: function(index, title, initialtext) {
565 dlg_form.appendChild(document.createTextNode(Pointer_stringify(title)));
566 var editbox = document.createElement("input");
567 editbox.type = "text";
568 editbox.value = Pointer_stringify(initialtext);
569 dlg_form.appendChild(editbox);
570 dlg_form.appendChild(document.createElement("br"));
572 dlg_return_funcs.push(function() {
573 dlg_return_sval(index, editbox.value);
578 * void js_dialog_choices(int i, const char *title, const char *choicelist,
581 * Add a choices control (i.e. a drop-down list) to the dialog
582 * under construction. The 'choicelist' parameter is unchanged
583 * from the way the puzzle back end will have supplied it: i.e.
584 * it's still encoded as a single string whose first character
585 * gives the separator.
587 js_dialog_choices: function(index, title, choicelist, initvalue) {
588 dlg_form.appendChild(document.createTextNode(Pointer_stringify(title)));
589 var dropdown = document.createElement("select");
590 var choicestr = Pointer_stringify(choicelist);
591 var items = choicestr.slice(1).split(choicestr[0]);
593 for (var i in items) {
594 var option = document.createElement("option");
595 option.value = items[i];
596 option.innerHTML = items[i];
597 if (i == initvalue) option.selected = true;
598 dropdown.appendChild(option);
599 options.push(option);
601 dlg_form.appendChild(dropdown);
602 dlg_form.appendChild(document.createElement("br"));
604 dlg_return_funcs.push(function() {
606 for (var i in options) {
607 if (options[i].selected) {
612 dlg_return_ival(index, val);
617 * void js_dialog_boolean(int i, const char *title, int initvalue);
619 * Add a boolean control (a checkbox) to the dialog under
620 * construction. Checkboxes are generally expected to be sensitive
621 * on their label text as well as the box itself, so for this
622 * control we create an actual label rather than merely a text
623 * node (and hence we must allocate an id to the checkbox so that
624 * the label can refer to it).
626 js_dialog_boolean: function(index, title, initvalue) {
627 var checkbox = document.createElement("input");
628 checkbox.type = "checkbox";
629 checkbox.id = "cb" + String(dlg_next_id++);
630 checkbox.checked = (initvalue != 0);
631 dlg_form.appendChild(checkbox);
632 var checkboxlabel = document.createElement("label");
633 checkboxlabel.setAttribute("for", checkbox.id);
634 checkboxlabel.textContent = Pointer_stringify(title);
635 dlg_form.appendChild(checkboxlabel);
636 dlg_form.appendChild(document.createElement("br"));
638 dlg_return_funcs.push(function() {
639 dlg_return_ival(index, checkbox.checked ? 1 : 0);
644 * void js_dialog_launch(void);
646 * Finish constructing a dialog, and actually display it, dimming
647 * everything else on the page.
649 js_dialog_launch: function() {
650 // Put in the OK and Cancel buttons at the bottom.
653 button = document.createElement("input");
654 button.type = "button";
656 button.onclick = function(event) {
657 for (var i in dlg_return_funcs)
658 dlg_return_funcs[i]();
661 dlg_form.appendChild(button);
663 button = document.createElement("input");
664 button.type = "button";
665 button.value = "Cancel";
666 button.onclick = function(event) {
669 dlg_form.appendChild(button);
671 document.body.appendChild(dlg_dimmer);
672 document.body.appendChild(dlg_form);
676 * void js_dialog_cleanup(void);
678 * Stop displaying a dialog, and clean up the internal state
679 * associated with it.
681 js_dialog_cleanup: function() {
682 document.body.removeChild(dlg_dimmer);
683 document.body.removeChild(dlg_form);
684 dlg_dimmer = dlg_form = null;
685 onscreen_canvas.focus();
689 * void js_focus_canvas(void);
691 * Return keyboard focus to the puzzle canvas. Called after a
692 * puzzle-control button is pressed, which tends to have the side
693 * effect of taking focus away from the canvas.
695 js_focus_canvas: function() {
696 onscreen_canvas.focus();