2 * emccpre.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 emcclib.js. It
6 * also depends on being run in the context of a web page containing
7 * an appropriate collection of bits and pieces (a canvas, some
8 * buttons and links etc), which is generated for each puzzle by the
9 * script html/jspage.pl.
11 * This file contains the Javascript code which is prefixed unmodified
12 * to Emscripten's output via the --pre-js option. It declares all our
13 * global variables, and provides the puzzle init function and a
14 * couple of other helper functions.
17 // To avoid flicker while doing complicated drawing, we use two
18 // canvases, the same size. One is actually on the web page, and the
19 // other is off-screen. We do all our drawing on the off-screen one
20 // first, and then copy rectangles of it to the on-screen canvas in
21 // response to draw_update() calls by the game backend.
22 var onscreen_canvas, offscreen_canvas;
24 // A persistent drawing context for the offscreen canvas, to save
25 // constructing one per individual graphics operation.
28 // Bounding rectangle for the copy to the onscreen canvas that will be
29 // done at drawing end time. Updated by js_canvas_draw_update and used
30 // by js_canvas_end_draw.
31 var update_xmin, update_xmax, update_ymin, update_ymax;
33 // Module object for Emscripten. We fill in these parameters to ensure
34 // that Module.run() won't be called until we're ready (we want to do
35 // our own init stuff first), and that when main() returns nothing
36 // will get cleaned up so we remain able to call the puzzle's various
43 // Variables used by js_canvas_find_font_midpoint().
44 var midpoint_test_str = "ABCDEFGHIKLMNOPRSTUVWXYZ0123456789";
45 var midpoint_cache = [];
47 // Variables used by js_activate_timer() and js_deactivate_timer().
49 var timer_reference_date;
51 // void timer_callback(double tplus);
53 // Called every 20ms while timing is active.
56 // The status bar object, if we create one.
59 // Currently live blitters. We keep an integer id for each one on the
60 // JS side; the C side, which expects a blitter to look like a struct,
61 // simply defines the struct to contain that integer id.
65 // State for the dialog-box mechanism. dlg_dimmer and dlg_form are the
66 // page-darkening overlay and the actual dialog box respectively;
67 // dlg_next_id is used to allocate each checkbox a unique id to use
68 // for linking its label to it (see js_dialog_boolean);
69 // dlg_return_funcs is a list of JS functions to be called when the OK
70 // button is pressed, to pass the results back to C.
71 var dlg_dimmer = null, dlg_form = null;
73 var dlg_return_funcs = null;
75 // void dlg_return_sval(int index, const char *val);
76 // void dlg_return_ival(int index, int val);
78 // C-side entry points called by functions in dlg_return_funcs, to
79 // pass back the final value in each dialog control.
80 var dlg_return_sval, dlg_return_ival;
82 // The <ul> object implementing the game-type drop-down, and a list of
83 // the <li> objects inside it. Used by js_add_preset(),
84 // js_get_selected_preset() and js_select_preset().
85 var gametypelist = null, gametypeitems = [];
86 var gametypeselectedindex = null;
87 var gametypesubmenus = [];
89 // The two anchors used to give permalinks to the current puzzle. Used
90 // by js_update_permalinks().
91 var permalink_seed, permalink_desc;
93 // The undo and redo buttons. Used by js_enable_undo_redo().
94 var undo_button, redo_button;
96 // A div element enclosing both the puzzle and its status bar, used
97 // for positioning the resize handle.
100 // Helper function to find the absolute position of a given DOM
101 // element on a page, by iterating upwards through the DOM finding
102 // each element's offset from its parent, and thus calculating the
103 // page-relative position of the target element.
104 function element_coords(element) {
106 while (element.offsetParent) {
107 ex += element.offsetLeft;
108 ey += element.offsetTop;
109 element = element.offsetParent;
111 return {x: ex, y:ey};
114 // Helper function which is passed a mouse event object and a DOM
115 // element, and returns the coordinates of the mouse event relative to
116 // the top left corner of the element by subtracting element_coords
117 // from event.page{X,Y}.
118 function relative_mouse_coords(event, element) {
119 var ecoords = element_coords(element);
120 return {x: event.pageX - ecoords.x,
121 y: event.pageY - ecoords.y};
124 // Enable and disable items in the CSS menus.
125 function disable_menu_item(item, disabledFlag) {
127 item.className = "disabled";
132 // Dialog-box functions called from both C and JS.
133 function dialog_init(titletext) {
134 // Create an overlay on the page which darkens everything
136 dlg_dimmer = document.createElement("div");
137 dlg_dimmer.style.width = "100%";
138 dlg_dimmer.style.height = "100%";
139 dlg_dimmer.style.background = '#000000';
140 dlg_dimmer.style.position = 'fixed';
141 dlg_dimmer.style.opacity = 0.3;
142 dlg_dimmer.style.top = dlg_dimmer.style.left = 0;
143 dlg_dimmer.style["z-index"] = 99;
145 // Now create a form which sits on top of that in turn.
146 dlg_form = document.createElement("form");
147 dlg_form.style.width = (window.innerWidth * 2 / 3) + "px";
148 dlg_form.style.opacity = 1;
149 dlg_form.style.background = '#ffffff';
150 dlg_form.style.color = '#000000';
151 dlg_form.style.position = 'absolute';
152 dlg_form.style.border = "2px solid black";
153 dlg_form.style.padding = "20px";
154 dlg_form.style.top = (window.innerHeight / 10) + "px";
155 dlg_form.style.left = (window.innerWidth / 6) + "px";
156 dlg_form.style["z-index"] = 100;
158 var title = document.createElement("p");
159 title.style.marginTop = "0px";
160 title.appendChild(document.createTextNode(titletext));
161 dlg_form.appendChild(title);
163 dlg_return_funcs = [];
167 function dialog_launch(ok_function, cancel_function) {
168 // Put in the OK and Cancel buttons at the bottom.
172 button = document.createElement("input");
173 button.type = "button";
175 button.onclick = ok_function;
176 dlg_form.appendChild(button);
179 if (cancel_function) {
180 button = document.createElement("input");
181 button.type = "button";
182 button.value = "Cancel";
183 button.onclick = cancel_function;
184 dlg_form.appendChild(button);
187 document.body.appendChild(dlg_dimmer);
188 document.body.appendChild(dlg_form);
191 function dialog_cleanup() {
192 document.body.removeChild(dlg_dimmer);
193 document.body.removeChild(dlg_form);
194 dlg_dimmer = dlg_form = null;
195 onscreen_canvas.focus();
198 // Init function called from body.onload.
199 function initPuzzle() {
200 // Construct the off-screen canvas used for double buffering.
201 onscreen_canvas = document.getElementById("puzzlecanvas");
202 offscreen_canvas = document.createElement("canvas");
203 offscreen_canvas.width = onscreen_canvas.width;
204 offscreen_canvas.height = onscreen_canvas.height;
206 // Stop right-clicks on the puzzle from popping up a context menu.
207 // We need those right-clicks!
208 onscreen_canvas.oncontextmenu = function(event) { return false; }
210 // Set up mouse handlers. We do a bit of tracking of the currently
211 // pressed mouse buttons, to avoid sending mousemoves with no
212 // button down (our puzzles don't want those events).
213 mousedown = Module.cwrap('mousedown', 'void',
214 ['number', 'number', 'number']);
216 onscreen_canvas.onmousedown = function(event) {
217 var xy = relative_mouse_coords(event, onscreen_canvas);
218 mousedown(xy.x, xy.y, event.button);
219 buttons_down |= 1 << event.button;
220 onscreen_canvas.setCapture(true);
222 mousemove = Module.cwrap('mousemove', 'void',
223 ['number', 'number', 'number']);
224 onscreen_canvas.onmousemove = function(event) {
226 var xy = relative_mouse_coords(event, onscreen_canvas);
227 mousemove(xy.x, xy.y, buttons_down);
230 mouseup = Module.cwrap('mouseup', 'void',
231 ['number', 'number', 'number']);
232 onscreen_canvas.onmouseup = function(event) {
233 if (buttons_down & (1 << event.button)) {
234 buttons_down ^= 1 << event.button;
235 var xy = relative_mouse_coords(event, onscreen_canvas);
236 mouseup(xy.x, xy.y, event.button);
240 // Set up keyboard handlers. We do all the actual keyboard
241 // handling in onkeydown; but we also call event.preventDefault()
242 // in both the keydown and keypress handlers. This means that
243 // while the canvas itself has focus, _all_ keypresses go only to
244 // the puzzle - so users of this puzzle collection in other media
245 // can indulge their instinct to press ^R for redo, for example,
246 // without accidentally reloading the page.
247 key = Module.cwrap('key', 'void', ['number', 'number', 'string',
248 'string', 'number', 'number']);
249 onscreen_canvas.onkeydown = function(event) {
250 key(event.keyCode, event.charCode, event.key, event.char,
251 event.shiftKey ? 1 : 0, event.ctrlKey ? 1 : 0);
252 event.preventDefault();
254 onscreen_canvas.onkeypress = function(event) {
255 event.preventDefault();
258 // command() is a C function called to pass back events which
259 // don't fall into other categories like mouse and key events.
260 // Mostly those are button presses, but there's also one for the
261 // game-type dropdown having been changed.
262 command = Module.cwrap('command', 'void', ['number']);
264 // Event handlers for buttons and things, which call command().
265 document.getElementById("specific").onclick = function(event) {
266 // Ensure we don't accidentally process these events when a
267 // dialog is actually active, e.g. because the button still
268 // has keyboard focus
269 if (dlg_dimmer === null)
272 document.getElementById("random").onclick = function(event) {
273 if (dlg_dimmer === null)
276 document.getElementById("new").onclick = function(event) {
277 if (dlg_dimmer === null)
280 document.getElementById("restart").onclick = function(event) {
281 if (dlg_dimmer === null)
284 undo_button = document.getElementById("undo");
285 undo_button.onclick = function(event) {
286 if (dlg_dimmer === null)
289 redo_button = document.getElementById("redo");
290 redo_button.onclick = function(event) {
291 if (dlg_dimmer === null)
294 document.getElementById("solve").onclick = function(event) {
295 if (dlg_dimmer === null)
299 // 'number' is used for C pointers
300 get_save_file = Module.cwrap('get_save_file', 'number', []);
301 free_save_file = Module.cwrap('free_save_file', 'void', ['number']);
302 load_game = Module.cwrap('load_game', 'void', ['string', 'number']);
304 document.getElementById("save").onclick = function(event) {
305 if (dlg_dimmer === null) {
306 var savefile_ptr = get_save_file();
307 var savefile_text = Pointer_stringify(savefile_ptr);
308 free_save_file(savefile_ptr);
309 dialog_init("Download saved-game file");
310 dlg_form.appendChild(document.createTextNode(
311 "Click to download the "));
312 var a = document.createElement("a");
313 a.download = "puzzle.sav";
314 a.href = "data:application/octet-stream," +
315 encodeURIComponent(savefile_text);
316 a.appendChild(document.createTextNode("saved-game file"));
317 dlg_form.appendChild(a);
318 dlg_form.appendChild(document.createTextNode("."));
319 dlg_form.appendChild(document.createElement("br"));
320 dialog_launch(function(event) {
326 document.getElementById("load").onclick = function(event) {
327 if (dlg_dimmer === null) {
328 dialog_init("Upload saved-game file");
329 var input = document.createElement("input");
331 input.multiple = false;
332 dlg_form.appendChild(input);
333 dlg_form.appendChild(document.createElement("br"));
334 dialog_launch(function(event) {
335 if (input.files.length == 1) {
336 var file = input.files.item(0);
337 var reader = new FileReader();
338 reader.addEventListener("loadend", function() {
339 var string = reader.result;
340 load_game(string, string.length);
342 reader.readAsBinaryString(file);
351 gametypelist = document.getElementById("gametype");
352 gametypesubmenus.push(gametypelist);
354 // In IE, the canvas doesn't automatically gain focus on a mouse
355 // click, so make sure it does
356 onscreen_canvas.addEventListener("mousedown", function(event) {
357 onscreen_canvas.focus();
360 // In our dialog boxes, Return and Escape should be like pressing
361 // OK and Cancel respectively
362 document.addEventListener("keydown", function(event) {
364 if (dlg_dimmer !== null && event.keyCode == 13) {
365 for (var i in dlg_return_funcs)
366 dlg_return_funcs[i]();
370 if (dlg_dimmer !== null && event.keyCode == 27)
374 // Set up the function pointers we haven't already grabbed.
375 dlg_return_sval = Module.cwrap('dlg_return_sval', 'void',
376 ['number','string']);
377 dlg_return_ival = Module.cwrap('dlg_return_ival', 'void',
378 ['number','number']);
379 timer_callback = Module.cwrap('timer_callback', 'void', ['number']);
381 // Save references to the two permalinks.
382 permalink_desc = document.getElementById("permalink-desc");
383 permalink_seed = document.getElementById("permalink-seed");
385 // Default to giving keyboard focus to the puzzle.
386 onscreen_canvas.focus();
388 // Create the resize handle.
389 var resize_handle = document.createElement("canvas");
390 resize_handle.width = 10;
391 resize_handle.height = 10;
393 var ctx = resize_handle.getContext("2d");
395 for (var i = 1; i <= 7; i += 3) {
396 ctx.moveTo(8.5, i + 0.5);
397 ctx.lineTo(i + 0.5, 8.5);
399 ctx.lineWidth = '1px';
400 ctx.lineCap = 'round';
401 ctx.lineJoin = 'round';
402 ctx.strokeStyle = '#000000';
405 resizable_div = document.getElementById("resizable");
406 resizable_div.appendChild(resize_handle);
407 resize_handle.style.position = 'absolute';
408 resize_handle.style.zIndex = 98;
409 resize_handle.style.bottom = "0";
410 resize_handle.style.right = "0";
411 resize_handle.style.cursor = "se-resize";
412 resize_handle.title = "Drag to resize the puzzle. Right-click to restore the default size.";
413 var resize_xbase = null, resize_ybase = null, restore_pending = false;
414 var resize_xoffset = null, resize_yoffset = null;
415 var resize_puzzle = Module.cwrap('resize_puzzle',
416 'void', ['number', 'number']);
417 var restore_puzzle_size = Module.cwrap('restore_puzzle_size', 'void', []);
418 resize_handle.oncontextmenu = function(event) { return false; }
419 resize_handle.onmousedown = function(event) {
420 if (event.button == 0) {
421 var xy = element_coords(onscreen_canvas);
422 resize_xbase = xy.x + onscreen_canvas.width / 2;
424 resize_xoffset = xy.x + onscreen_canvas.width - event.pageX;
425 resize_yoffset = xy.y + onscreen_canvas.height - event.pageY;
427 restore_pending = true;
429 resize_handle.setCapture(true);
430 event.preventDefault();
432 window.addEventListener("mousemove", function(event) {
433 if (resize_xbase !== null && resize_ybase !== null) {
434 resize_puzzle((event.pageX + resize_xoffset - resize_xbase) * 2,
435 (event.pageY + resize_yoffset - resize_ybase));
436 event.preventDefault();
437 // Chrome insists on selecting text during a resize drag
438 // no matter what I do
439 if (window.getSelection)
440 window.getSelection().removeAllRanges();
442 document.selection.empty(); }
444 window.addEventListener("mouseup", function(event) {
445 if (resize_xbase !== null && resize_ybase !== null) {
448 onscreen_canvas.focus(); // return focus to the puzzle
449 event.preventDefault();
450 } else if (restore_pending) {
451 // If you have the puzzle at larger than normal size and
452 // then right-click to restore, I haven't found any way to
453 // stop Chrome and IE popping up a context menu on the
454 // revealed piece of document when you release the button
455 // except by putting the actual restore into a setTimeout.
457 setTimeout(function() {
458 restore_pending = false;
459 restore_puzzle_size();
460 onscreen_canvas.focus();
462 event.preventDefault();
466 // Run the C setup function, passing argv[1] as the fragment
467 // identifier (so that permalinks of the form puzzle.html#game-id
468 // can launch the specified id).
469 Module.callMain([location.hash]);
471 // And if we get here with everything having gone smoothly, i.e.
472 // we haven't crashed for one reason or another during setup, then
473 // it's probably safe to hide the 'sorry, no puzzle here' div and
474 // show the div containing the actual puzzle.
475 document.getElementById("apology").style.display = "none";
476 document.getElementById("puzzle").style.display = "inline";