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 gametypelist = document.getElementById("gametype");
300 gametypesubmenus.push(gametypelist);
302 // In IE, the canvas doesn't automatically gain focus on a mouse
303 // click, so make sure it does
304 onscreen_canvas.addEventListener("mousedown", function(event) {
305 onscreen_canvas.focus();
308 // In our dialog boxes, Return and Escape should be like pressing
309 // OK and Cancel respectively
310 document.addEventListener("keydown", function(event) {
312 if (dlg_dimmer !== null && event.keyCode == 13) {
313 for (var i in dlg_return_funcs)
314 dlg_return_funcs[i]();
318 if (dlg_dimmer !== null && event.keyCode == 27)
322 // Set up the function pointers we haven't already grabbed.
323 dlg_return_sval = Module.cwrap('dlg_return_sval', 'void',
324 ['number','string']);
325 dlg_return_ival = Module.cwrap('dlg_return_ival', 'void',
326 ['number','number']);
327 timer_callback = Module.cwrap('timer_callback', 'void', ['number']);
329 // Save references to the two permalinks.
330 permalink_desc = document.getElementById("permalink-desc");
331 permalink_seed = document.getElementById("permalink-seed");
333 // Default to giving keyboard focus to the puzzle.
334 onscreen_canvas.focus();
336 // Create the resize handle.
337 var resize_handle = document.createElement("canvas");
338 resize_handle.width = 10;
339 resize_handle.height = 10;
341 var ctx = resize_handle.getContext("2d");
343 for (var i = 1; i <= 7; i += 3) {
344 ctx.moveTo(8.5, i + 0.5);
345 ctx.lineTo(i + 0.5, 8.5);
347 ctx.lineWidth = '1px';
348 ctx.lineCap = 'round';
349 ctx.lineJoin = 'round';
350 ctx.strokeStyle = '#000000';
353 resizable_div = document.getElementById("resizable");
354 resizable_div.appendChild(resize_handle);
355 resize_handle.style.position = 'absolute';
356 resize_handle.style.zIndex = 98;
357 resize_handle.style.bottom = "0";
358 resize_handle.style.right = "0";
359 resize_handle.style.cursor = "se-resize";
360 resize_handle.title = "Drag to resize the puzzle. Right-click to restore the default size.";
361 var resize_xbase = null, resize_ybase = null, restore_pending = false;
362 var resize_xoffset = null, resize_yoffset = null;
363 var resize_puzzle = Module.cwrap('resize_puzzle',
364 'void', ['number', 'number']);
365 var restore_puzzle_size = Module.cwrap('restore_puzzle_size', 'void', []);
366 resize_handle.oncontextmenu = function(event) { return false; }
367 resize_handle.onmousedown = function(event) {
368 if (event.button == 0) {
369 var xy = element_coords(onscreen_canvas);
370 resize_xbase = xy.x + onscreen_canvas.width / 2;
372 resize_xoffset = xy.x + onscreen_canvas.width - event.pageX;
373 resize_yoffset = xy.y + onscreen_canvas.height - event.pageY;
375 restore_pending = true;
377 resize_handle.setCapture(true);
378 event.preventDefault();
380 window.addEventListener("mousemove", function(event) {
381 if (resize_xbase !== null && resize_ybase !== null) {
382 resize_puzzle((event.pageX + resize_xoffset - resize_xbase) * 2,
383 (event.pageY + resize_yoffset - resize_ybase));
384 event.preventDefault();
385 // Chrome insists on selecting text during a resize drag
386 // no matter what I do
387 if (window.getSelection)
388 window.getSelection().removeAllRanges();
390 document.selection.empty(); }
392 window.addEventListener("mouseup", function(event) {
393 if (resize_xbase !== null && resize_ybase !== null) {
396 onscreen_canvas.focus(); // return focus to the puzzle
397 event.preventDefault();
398 } else if (restore_pending) {
399 // If you have the puzzle at larger than normal size and
400 // then right-click to restore, I haven't found any way to
401 // stop Chrome and IE popping up a context menu on the
402 // revealed piece of document when you release the button
403 // except by putting the actual restore into a setTimeout.
405 setTimeout(function() {
406 restore_pending = false;
407 restore_puzzle_size();
408 onscreen_canvas.focus();
410 event.preventDefault();
414 // Run the C setup function, passing argv[1] as the fragment
415 // identifier (so that permalinks of the form puzzle.html#game-id
416 // can launch the specified id).
417 Module.callMain([location.hash]);
419 // And if we get here with everything having gone smoothly, i.e.
420 // we haven't crashed for one reason or another during setup, then
421 // it's probably safe to hide the 'sorry, no puzzle here' div and
422 // show the div containing the actual puzzle.
423 document.getElementById("apology").style.display = "none";
424 document.getElementById("puzzle").style.display = "inline";