chiark / gitweb /
wasm/js/emscripten: Fix page loading race
[sgt-puzzles.git] / emccpre.js
1 /*
2  * emccpre.js: one of the Javascript components of an Emscripten-based
3  * web/Javascript front end for Puzzles.
4  *
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.
10  *
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.
15  */
16
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;
23
24 // A persistent drawing context for the offscreen canvas, to save
25 // constructing one per individual graphics operation.
26 var ctx;
27
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;
32
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
37 // callbacks.
38 //
39 //
40 // Page loading order:
41 //
42 // 1. The browser starts reading *.html (which comes from jspage.pl)
43 // 2. It finds the <script> tag.  This is marked defer, so the
44 //    browser will start fetching and parsing it, but not execute it
45 //    until the page has loaded.
46 //
47 // Now the browser is loading *.html and *.js in parallel.  The
48 // html is rendered as we go, and the js is deferred.
49 //
50 // 3. The HTML finishes loading.  The browser is about to fire the
51 //    `DOMContentLoaded` event (ie `onload`) but before that, it
52 //    actually runs the deferred JS.  THis consists of
53 //
54 //    (i) emccpre.js (this file).  This sets up various JS variables
55 //      including the emscripten Module object.
56 //
57 //    (ii) emscripten's JS.  This starts the WASM loading.
58 //
59 //    (iii) emccpost.js.  This calls initPuzzle, which is defined here
60 //      in this file.  initPuzzle:
61 //
62 //      (a) finds various DOM elements and bind them to variables,
63 //      which depend on the HTML having loaded (it has).
64 //
65 //      (b) makes various `cwrap` calls into the emscripten module to
66 //      set up hooks; this depends on the emscripten JS having been
67 //      loaded (it has).
68 //
69 //      (c) Makes the call to emscripten's
70 //      Module.onRuntimeInitialized, which sets the callback for when
71 //      the WASM has finished loading and initialising.  This has to
72 //      come before the WASM finishes loading, or we'll miss the
73 //      callback.  We are executing synchronously here in the same JS
74 //      file as started the WASM loading, so that is guaranteed.
75 //
76 // When this JS execution is complete, the browser fires the `onload`
77 // event.  This is ignored.  It continues loading the WASM.
78 //
79 // 4. The WASM loading and initialisation completes.  The
80 //    onRuntimeInitialised callback calls into emscripten-generated
81 //    WASM to call the C `main`, to actually start the puzzle.
82
83 var Module = {
84     'noInitialRun': true,
85     'noExitRuntime': true
86 };
87
88 // Variables used by js_canvas_find_font_midpoint().
89 var midpoint_test_str = "ABCDEFGHIKLMNOPRSTUVWXYZ0123456789";
90 var midpoint_cache = [];
91
92 // Variables used by js_activate_timer() and js_deactivate_timer().
93 var timer = null;
94 var timer_reference_date;
95
96 // void timer_callback(double tplus);
97 //
98 // Called every 20ms while timing is active.
99 var timer_callback;
100
101 // The status bar object, if we create one.
102 var statusbar = null;
103
104 // Currently live blitters. We keep an integer id for each one on the
105 // JS side; the C side, which expects a blitter to look like a struct,
106 // simply defines the struct to contain that integer id.
107 var blittercount = 0;
108 var blitters = [];
109
110 // State for the dialog-box mechanism. dlg_dimmer and dlg_form are the
111 // page-darkening overlay and the actual dialog box respectively;
112 // dlg_next_id is used to allocate each checkbox a unique id to use
113 // for linking its label to it (see js_dialog_boolean);
114 // dlg_return_funcs is a list of JS functions to be called when the OK
115 // button is pressed, to pass the results back to C.
116 var dlg_dimmer = null, dlg_form = null;
117 var dlg_next_id = 0;
118 var dlg_return_funcs = null;
119
120 // void dlg_return_sval(int index, const char *val);
121 // void dlg_return_ival(int index, int val);
122 //
123 // C-side entry points called by functions in dlg_return_funcs, to
124 // pass back the final value in each dialog control.
125 var dlg_return_sval, dlg_return_ival;
126
127 // The <ul> object implementing the game-type drop-down, and a list of
128 // the <li> objects inside it. Used by js_add_preset(),
129 // js_get_selected_preset() and js_select_preset().
130 var gametypelist = null, gametypeitems = [];
131 var gametypeselectedindex = null;
132 var gametypesubmenus = [];
133
134 // The two anchors used to give permalinks to the current puzzle. Used
135 // by js_update_permalinks().
136 var permalink_seed, permalink_desc;
137
138 // The undo and redo buttons. Used by js_enable_undo_redo().
139 var undo_button, redo_button;
140
141 // A div element enclosing both the puzzle and its status bar, used
142 // for positioning the resize handle.
143 var resizable_div;
144
145 // Helper function to find the absolute position of a given DOM
146 // element on a page, by iterating upwards through the DOM finding
147 // each element's offset from its parent, and thus calculating the
148 // page-relative position of the target element.
149 function element_coords(element) {
150     var ex = 0, ey = 0;
151     while (element.offsetParent) {
152         ex += element.offsetLeft;
153         ey += element.offsetTop;
154         element = element.offsetParent;
155     }
156     return {x: ex, y:ey};
157 }
158
159 // Helper function which is passed a mouse event object and a DOM
160 // element, and returns the coordinates of the mouse event relative to
161 // the top left corner of the element by subtracting element_coords
162 // from event.page{X,Y}.
163 function relative_mouse_coords(event, element) {
164     var ecoords = element_coords(element);
165     return {x: event.pageX - ecoords.x,
166             y: event.pageY - ecoords.y};
167 }
168
169 // Enable and disable items in the CSS menus.
170 function disable_menu_item(item, disabledFlag) {
171     if (disabledFlag)
172         item.className = "disabled";
173     else
174         item.className = "";
175 }
176
177 // Dialog-box functions called from both C and JS.
178 function dialog_init(titletext) {
179     // Create an overlay on the page which darkens everything
180     // beneath it.
181     dlg_dimmer = document.createElement("div");
182     dlg_dimmer.style.width = "100%";
183     dlg_dimmer.style.height = "100%";
184     dlg_dimmer.style.background = '#000000';
185     dlg_dimmer.style.position = 'fixed';
186     dlg_dimmer.style.opacity = 0.3;
187     dlg_dimmer.style.top = dlg_dimmer.style.left = 0;
188     dlg_dimmer.style["z-index"] = 99;
189
190     // Now create a form which sits on top of that in turn.
191     dlg_form = document.createElement("form");
192     dlg_form.style.width = (window.innerWidth * 2 / 3) + "px";
193     dlg_form.style.opacity = 1;
194     dlg_form.style.background = '#ffffff';
195     dlg_form.style.color = '#000000';
196     dlg_form.style.position = 'absolute';
197     dlg_form.style.border = "2px solid black";
198     dlg_form.style.padding = "20px";
199     dlg_form.style.top = (window.innerHeight / 10) + "px";
200     dlg_form.style.left = (window.innerWidth / 6) + "px";
201     dlg_form.style["z-index"] = 100;
202
203     var title = document.createElement("p");
204     title.style.marginTop = "0px";
205     title.appendChild(document.createTextNode(titletext));
206     dlg_form.appendChild(title);
207
208     dlg_return_funcs = [];
209     dlg_next_id = 0;
210 }
211
212 function dialog_launch(ok_function, cancel_function) {
213     // Put in the OK and Cancel buttons at the bottom.
214     var button;
215
216     if (ok_function) {
217         button = document.createElement("input");
218         button.type = "button";
219         button.value = "OK";
220         button.onclick = ok_function;
221         dlg_form.appendChild(button);
222     }
223
224     if (cancel_function) {
225         button = document.createElement("input");
226         button.type = "button";
227         button.value = "Cancel";
228         button.onclick = cancel_function;
229         dlg_form.appendChild(button);
230     }
231
232     document.body.appendChild(dlg_dimmer);
233     document.body.appendChild(dlg_form);
234 }
235
236 function dialog_cleanup() {
237     document.body.removeChild(dlg_dimmer);
238     document.body.removeChild(dlg_form);
239     dlg_dimmer = dlg_form = null;
240     onscreen_canvas.focus();
241 }
242
243 // Init function called from body.onload.
244 function initPuzzle() {
245     // Construct the off-screen canvas used for double buffering.
246     onscreen_canvas = document.getElementById("puzzlecanvas");
247     offscreen_canvas = document.createElement("canvas");
248     offscreen_canvas.width = onscreen_canvas.width;
249     offscreen_canvas.height = onscreen_canvas.height;
250
251     // Stop right-clicks on the puzzle from popping up a context menu.
252     // We need those right-clicks!
253     onscreen_canvas.oncontextmenu = function(event) { return false; }
254
255     // Set up mouse handlers. We do a bit of tracking of the currently
256     // pressed mouse buttons, to avoid sending mousemoves with no
257     // button down (our puzzles don't want those events).
258     mousedown = Module.cwrap('mousedown', 'void',
259                              ['number', 'number', 'number']);
260
261     button_phys2log = [null, null, null];
262     buttons_down = function() {
263         var i, toret = 0;
264         for (i = 0; i < 3; i++)
265             if (button_phys2log[i] !== null)
266                 toret |= 1 << button_phys2log[i];
267         return toret;
268     };
269
270     onscreen_canvas.onmousedown = function(event) {
271         if (event.button >= 3)
272             return;
273
274         var xy = relative_mouse_coords(event, onscreen_canvas);
275         var logbutton = event.button;
276         if (event.shiftKey)
277             logbutton = 1;   // Shift-click overrides to middle button
278         else if (event.ctrlKey)
279             logbutton = 2;   // Ctrl-click overrides to right button
280
281         mousedown(xy.x, xy.y, logbutton);
282         button_phys2log[event.button] = logbutton;
283
284         onscreen_canvas.setCapture(true);
285     };
286     mousemove = Module.cwrap('mousemove', 'void',
287                              ['number', 'number', 'number']);
288     onscreen_canvas.onmousemove = function(event) {
289         var down = buttons_down();
290         if (down) {
291             var xy = relative_mouse_coords(event, onscreen_canvas);
292             mousemove(xy.x, xy.y, down);
293         }
294     };
295     mouseup = Module.cwrap('mouseup', 'void',
296                            ['number', 'number', 'number']);
297     onscreen_canvas.onmouseup = function(event) {
298         if (event.button >= 3)
299             return;
300
301         if (button_phys2log[event.button] !== null) {
302             var xy = relative_mouse_coords(event, onscreen_canvas);
303             mouseup(xy.x, xy.y, button_phys2log[event.button]);
304             button_phys2log[event.button] = null;
305         }
306     };
307
308     // Set up keyboard handlers. We do all the actual keyboard
309     // handling in onkeydown; but we also call event.preventDefault()
310     // in both the keydown and keypress handlers. This means that
311     // while the canvas itself has focus, _all_ keypresses go only to
312     // the puzzle - so users of this puzzle collection in other media
313     // can indulge their instinct to press ^R for redo, for example,
314     // without accidentally reloading the page.
315     key = Module.cwrap('key', 'void', ['number', 'number', 'string',
316                                        'string', 'number', 'number']);
317     onscreen_canvas.onkeydown = function(event) {
318         key(event.keyCode, event.charCode, event.key, event.char,
319             event.shiftKey ? 1 : 0, event.ctrlKey ? 1 : 0);
320         event.preventDefault();
321     };
322     onscreen_canvas.onkeypress = function(event) {
323         event.preventDefault();
324     };
325
326     // command() is a C function called to pass back events which
327     // don't fall into other categories like mouse and key events.
328     // Mostly those are button presses, but there's also one for the
329     // game-type dropdown having been changed.
330     command = Module.cwrap('command', 'void', ['number']);
331
332     // Event handlers for buttons and things, which call command().
333     document.getElementById("specific").onclick = function(event) {
334         // Ensure we don't accidentally process these events when a
335         // dialog is actually active, e.g. because the button still
336         // has keyboard focus
337         if (dlg_dimmer === null)
338             command(0);
339     };
340     document.getElementById("random").onclick = function(event) {
341         if (dlg_dimmer === null)
342             command(1);
343     };
344     document.getElementById("new").onclick = function(event) {
345         if (dlg_dimmer === null)
346             command(5);
347     };
348     document.getElementById("restart").onclick = function(event) {
349         if (dlg_dimmer === null)
350             command(6);
351     };
352     undo_button = document.getElementById("undo");
353     undo_button.onclick = function(event) {
354         if (dlg_dimmer === null)
355             command(7);
356     };
357     redo_button = document.getElementById("redo");
358     redo_button.onclick = function(event) {
359         if (dlg_dimmer === null)
360             command(8);
361     };
362     document.getElementById("solve").onclick = function(event) {
363         if (dlg_dimmer === null)
364             command(9);
365     };
366
367     // 'number' is used for C pointers
368     get_save_file = Module.cwrap('get_save_file', 'number', []);
369     free_save_file = Module.cwrap('free_save_file', 'void', ['number']);
370     load_game = Module.cwrap('load_game', 'void', ['string', 'number']);
371
372     document.getElementById("save").onclick = function(event) {
373         if (dlg_dimmer === null) {
374             var savefile_ptr = get_save_file();
375             var savefile_text = Pointer_stringify(savefile_ptr);
376             free_save_file(savefile_ptr);
377             dialog_init("Download saved-game file");
378             dlg_form.appendChild(document.createTextNode(
379                 "Click to download the "));
380             var a = document.createElement("a");
381             a.download = "puzzle.sav";
382             a.href = "data:application/octet-stream," +
383                 encodeURIComponent(savefile_text);
384             a.appendChild(document.createTextNode("saved-game file"));
385             dlg_form.appendChild(a);
386             dlg_form.appendChild(document.createTextNode("."));
387             dlg_form.appendChild(document.createElement("br"));
388             dialog_launch(function(event) {
389                 dialog_cleanup();
390             });
391         }
392     };
393
394     document.getElementById("load").onclick = function(event) {
395         if (dlg_dimmer === null) {
396             dialog_init("Upload saved-game file");
397             var input = document.createElement("input");
398             input.type = "file";
399             input.multiple = false;
400             dlg_form.appendChild(input);
401             dlg_form.appendChild(document.createElement("br"));
402             dialog_launch(function(event) {
403                 if (input.files.length == 1) {
404                     var file = input.files.item(0);
405                     var reader = new FileReader();
406                     reader.addEventListener("loadend", function() {
407                         var string = reader.result;
408                         load_game(string, string.length);
409                     });
410                     reader.readAsBinaryString(file);
411                 }
412                 dialog_cleanup();
413             }, function(event) {
414                 dialog_cleanup();
415             });
416         }
417     };
418
419     gametypelist = document.getElementById("gametype");
420     gametypesubmenus.push(gametypelist);
421
422     // In IE, the canvas doesn't automatically gain focus on a mouse
423     // click, so make sure it does
424     onscreen_canvas.addEventListener("mousedown", function(event) {
425         onscreen_canvas.focus();
426     });
427
428     // In our dialog boxes, Return and Escape should be like pressing
429     // OK and Cancel respectively
430     document.addEventListener("keydown", function(event) {
431
432         if (dlg_dimmer !== null && event.keyCode == 13) {
433             for (var i in dlg_return_funcs)
434                 dlg_return_funcs[i]();
435             command(3);
436         }
437
438         if (dlg_dimmer !== null && event.keyCode == 27)
439             command(4);
440     });
441
442     // Set up the function pointers we haven't already grabbed. 
443     dlg_return_sval = Module.cwrap('dlg_return_sval', 'void',
444                                    ['number','string']);
445     dlg_return_ival = Module.cwrap('dlg_return_ival', 'void',
446                                    ['number','number']);
447     timer_callback = Module.cwrap('timer_callback', 'void', ['number']);
448
449     // Save references to the two permalinks.
450     permalink_desc = document.getElementById("permalink-desc");
451     permalink_seed = document.getElementById("permalink-seed");
452
453     // Default to giving keyboard focus to the puzzle.
454     onscreen_canvas.focus();
455
456     // Create the resize handle.
457     var resize_handle = document.createElement("canvas");
458     resize_handle.width = 10;
459     resize_handle.height = 10;
460     {
461         var ctx = resize_handle.getContext("2d");
462         ctx.beginPath();
463         for (var i = 1; i <= 7; i += 3) {
464             ctx.moveTo(8.5, i + 0.5);
465             ctx.lineTo(i + 0.5, 8.5);
466         }
467         ctx.lineWidth = '1px';
468         ctx.lineCap = 'round';
469         ctx.lineJoin = 'round';
470         ctx.strokeStyle = '#000000';
471         ctx.stroke();
472     }
473     resizable_div = document.getElementById("resizable");
474     resizable_div.appendChild(resize_handle);
475     resize_handle.style.position = 'absolute';
476     resize_handle.style.zIndex = 98;
477     resize_handle.style.bottom = "0";
478     resize_handle.style.right = "0";
479     resize_handle.style.cursor = "se-resize";
480     resize_handle.title = "Drag to resize the puzzle. Right-click to restore the default size.";
481     var resize_xbase = null, resize_ybase = null, restore_pending = false;
482     var resize_xoffset = null, resize_yoffset = null;
483     var resize_puzzle = Module.cwrap('resize_puzzle',
484                                      'void', ['number', 'number']);
485     var restore_puzzle_size = Module.cwrap('restore_puzzle_size', 'void', []);
486     resize_handle.oncontextmenu = function(event) { return false; }
487     resize_handle.onmousedown = function(event) {
488         if (event.button == 0) {
489             var xy = element_coords(onscreen_canvas);
490             resize_xbase = xy.x + onscreen_canvas.width / 2;
491             resize_ybase = xy.y;
492             resize_xoffset = xy.x + onscreen_canvas.width - event.pageX;
493             resize_yoffset = xy.y + onscreen_canvas.height - event.pageY;
494         } else {
495             restore_pending = true;
496         }
497         resize_handle.setCapture(true);
498         event.preventDefault();
499     };
500     window.addEventListener("mousemove", function(event) {
501         if (resize_xbase !== null && resize_ybase !== null) {
502             resize_puzzle((event.pageX + resize_xoffset - resize_xbase) * 2,
503                           (event.pageY + resize_yoffset - resize_ybase));
504             event.preventDefault();
505             // Chrome insists on selecting text during a resize drag
506             // no matter what I do
507             if (window.getSelection)
508                 window.getSelection().removeAllRanges();
509             else
510                 document.selection.empty();        }
511     });
512     window.addEventListener("mouseup", function(event) {
513         if (resize_xbase !== null && resize_ybase !== null) {
514             resize_xbase = null;
515             resize_ybase = null;
516             onscreen_canvas.focus(); // return focus to the puzzle
517             event.preventDefault();
518         } else if (restore_pending) {
519             // If you have the puzzle at larger than normal size and
520             // then right-click to restore, I haven't found any way to
521             // stop Chrome and IE popping up a context menu on the
522             // revealed piece of document when you release the button
523             // except by putting the actual restore into a setTimeout.
524             // Gah.
525             setTimeout(function() {
526                 restore_pending = false;
527                 restore_puzzle_size();
528                 onscreen_canvas.focus();
529             }, 20);
530             event.preventDefault();
531         }
532     });
533
534     Module.onRuntimeInitialized = function() {
535         // Run the C setup function, passing argv[1] as the fragment
536         // identifier (so that permalinks of the form puzzle.html#game-id
537         // can launch the specified id).
538         Module.callMain([location.hash]);
539
540         // And if we get here with everything having gone smoothly, i.e.
541         // we haven't crashed for one reason or another during setup, then
542         // it's probably safe to hide the 'sorry, no puzzle here' div and
543         // show the div containing the actual puzzle.
544         document.getElementById("apology").style.display = "none";
545         document.getElementById("puzzle").style.display = "inline";
546     };
547 }