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.
7 * This file contains the Javascript code which is prefixed unmodified
8 * to Emscripten's output via the --pre-js option. It declares all our
9 * global variables, and provides the puzzle init function and a
10 * couple of other helper functions.
13 // To avoid flicker while doing complicated drawing, we use two
14 // canvases, the same size. One is actually on the web page, and the
15 // other is off-screen. We do all our drawing on the off-screen one
16 // first, and then copy rectangles of it to the on-screen canvas in
17 // response to draw_update() calls by the game backend.
18 var onscreen_canvas, offscreen_canvas;
20 // A persistent drawing context for the offscreen canvas, to save
21 // constructing one per individual graphics operation.
24 // Bounding rectangle for the copy to the onscreen canvas that will be
25 // done at drawing end time. Updated by js_canvas_draw_update and used
26 // by js_canvas_end_draw.
27 var update_xmin, update_xmax, update_ymin, update_ymax;
29 // Module object for Emscripten. We fill in these parameters to ensure
30 // that Module.run() won't be called until we're ready (we want to do
31 // our own init stuff first), and that when main() returns nothing
32 // will get cleaned up so we remain able to call the puzzle's various
36 'noExitRuntime': true,
39 // Variables used by js_canvas_find_font_midpoint().
40 var midpoint_test_str = "ABCDEFGHIKLMNOPRSTUVWXYZ0123456789";
41 var midpoint_cache = [];
43 // Variables used by js_activate_timer() and js_deactivate_timer().
45 var timer_reference_date;
47 // void timer_callback(double tplus);
49 // Called every 20ms while timing is active.
52 // The status bar object, if we create one.
55 // Currently live blitters. We keep an integer id for each one on the
56 // JS side; the C side, which expects a blitter to look like a struct,
57 // simply defines the struct to contain that integer id.
61 // State for the dialog-box mechanism. dlg_dimmer and dlg_form are the
62 // page-darkening overlay and the actual dialog box respectively;
63 // dlg_next_id is used to allocate each checkbox a unique id to use
64 // for linking its label to it (see js_dialog_boolean);
65 // dlg_return_funcs is a list of JS functions to be called when the OK
66 // button is pressed, to pass the results back to C.
67 var dlg_dimmer = null, dlg_form = null;
69 var dlg_return_funcs = null;
71 // void dlg_return_sval(int index, const char *val);
72 // void dlg_return_ival(int index, int val);
74 // C-side entry points called by functions in dlg_return_funcs, to
75 // pass back the final value in each dialog control.
76 var dlg_return_sval, dlg_return_ival;
78 // The <select> object implementing the game-type drop-down, and a
79 // list of the <option> objects inside it. Used by js_add_preset(),
80 // js_get_selected_preset() and js_select_preset().
82 // gametypehiddencustom is a second copy of the 'Custom' dropdown
83 // element, set to display:none. This is used by a bodge in emcclib.js
84 // (see comment in js_add_preset) to arrange that if the Custom
85 // element is (apparently) already selected, we still find out if the
86 // user selects it again.
87 var gametypeselector = null, gametypeoptions = [];
88 var gametypehiddencustom = null;
90 // The two anchors used to give permalinks to the current puzzle. Used
91 // by js_update_permalinks().
92 var permalink_seed, permalink_desc;
94 // The undo and redo buttons. Used by js_enable_undo_redo().
95 var undo_button, redo_button;
97 // Helper function which is passed a mouse event object and a DOM
98 // element, and returns the coordinates of the mouse event relative to
99 // the top left corner of the element by iterating upwards through the
100 // DOM finding each element's offset from its parent, and thus
101 // calculating the page-relative position of the target element so
102 // that we can subtract that from event.page{X,Y}.
103 function relative_mouse_coords(event, element) {
105 while (element.offsetParent) {
106 ex += element.offsetLeft;
107 ey += element.offsetTop;
108 element = element.offsetParent;
110 return {x: event.pageX - ex,
111 y: event.pageY - ey};
114 // Init function called from body.onload.
115 function initPuzzle() {
116 // Construct the off-screen canvas used for double buffering.
117 onscreen_canvas = document.getElementById("puzzlecanvas");
118 offscreen_canvas = document.createElement("canvas");
119 offscreen_canvas.width = onscreen_canvas.width;
120 offscreen_canvas.height = onscreen_canvas.height;
122 // Stop right-clicks on the puzzle from popping up a context menu.
123 // We need those right-clicks!
124 onscreen_canvas.oncontextmenu = function(event) { return false; }
126 // Set up mouse handlers. We do a bit of tracking of the currently
127 // pressed mouse buttons, to avoid sending mousemoves with no
128 // button down (our puzzles don't want those events).
129 mousedown = Module.cwrap('mousedown', 'void',
130 ['number', 'number', 'number']);
132 onscreen_canvas.onmousedown = function(event) {
133 var xy = relative_mouse_coords(event, onscreen_canvas);
134 mousedown(xy.x - onscreen_canvas.offsetLeft,
135 xy.y - onscreen_canvas.offsetTop,
137 buttons_down |= 1 << event.button;
138 onscreen_canvas.setCapture(true);
140 mousemove = Module.cwrap('mousemove', 'void',
141 ['number', 'number', 'number']);
142 onscreen_canvas.onmousemove = function(event) {
144 var xy = relative_mouse_coords(event, onscreen_canvas);
145 mousemove(xy.x - onscreen_canvas.offsetLeft,
146 xy.y - onscreen_canvas.offsetTop,
150 mouseup = Module.cwrap('mouseup', 'void',
151 ['number', 'number', 'number']);
152 onscreen_canvas.onmouseup = function(event) {
153 if (buttons_down & (1 << event.button)) {
154 buttons_down ^= 1 << event.button;
155 var xy = relative_mouse_coords(event, onscreen_canvas);
156 mouseup(xy.x - onscreen_canvas.offsetLeft,
157 xy.y - onscreen_canvas.offsetTop,
162 // Set up keyboard handlers. We expect ordinary keys (with a
163 // charCode) to be handled by onkeypress, but function keys
164 // (arrows etc) to be handled by onkeydown.
166 // We also call event.preventDefault() in both handlers. This
167 // means that while the canvas itself has focus, _all_ keypresses
168 // go only to the puzzle - so users of this puzzle collection in
169 // other media can indulge their instinct to press ^R for redo,
170 // for example, without accidentally reloading the page.
171 key = Module.cwrap('key', 'void',
172 ['number', 'number', 'number', 'number']);
173 onscreen_canvas.onkeydown = function(event) {
174 key(event.keyCode, event.charCode,
175 event.shiftKey ? 1 : 0, event.ctrlKey ? 1 : 0);
176 event.preventDefault();
178 onscreen_canvas.onkeypress = function(event) {
179 if (event.charCode != 0)
180 key(event.keyCode, event.charCode,
181 event.shiftKey ? 1 : 0, event.ctrlKey ? 1 : 0);
182 event.preventDefault();
185 // command() is a C function called to pass back events which
186 // don't fall into other categories like mouse and key events.
187 // Mostly those are button presses, but there's also one for the
188 // game-type dropdown having been changed.
189 command = Module.cwrap('command', 'void', ['number']);
191 // Event handlers for buttons and things, which call command().
192 document.getElementById("specific").onclick = function(event) {
193 // Ensure we don't accidentally process these events when a
194 // dialog is actually active, e.g. because the button still
195 // has keyboard focus
196 if (dlg_dimmer === null)
199 document.getElementById("random").onclick = function(event) {
200 if (dlg_dimmer === null)
203 document.getElementById("new").onclick = function(event) {
204 if (dlg_dimmer === null)
207 document.getElementById("restart").onclick = function(event) {
208 if (dlg_dimmer === null)
211 undo_button = document.getElementById("undo");
212 undo_button.onclick = function(event) {
213 if (dlg_dimmer === null)
216 redo_button = document.getElementById("redo");
217 redo_button.onclick = function(event) {
218 if (dlg_dimmer === null)
221 document.getElementById("solve").onclick = function(event) {
222 if (dlg_dimmer === null)
226 gametypeselector = document.getElementById("gametype");
227 gametypeselector.onchange = function(event) {
228 if (dlg_dimmer === null)
232 // In our dialog boxes, Return and Escape should be like pressing
233 // OK and Cancel respectively
234 document.addEventListener("keydown", function(event) {
236 if (dlg_dimmer !== null && event.keyCode == 13) {
237 for (var i in dlg_return_funcs)
238 dlg_return_funcs[i]();
242 if (dlg_dimmer !== null && event.keyCode == 27)
246 // Set up the function pointers we haven't already grabbed.
247 dlg_return_sval = Module.cwrap('dlg_return_sval', 'void',
248 ['number','string']);
249 dlg_return_ival = Module.cwrap('dlg_return_ival', 'void',
250 ['number','number']);
251 timer_callback = Module.cwrap('timer_callback', 'void', ['number']);
253 // Save references to the two permalinks.
254 permalink_desc = document.getElementById("permalink-desc");
255 permalink_seed = document.getElementById("permalink-seed");
257 // Default to giving keyboard focus to the puzzle.
258 onscreen_canvas.focus();
260 // Run the C setup function, passing argv[1] as the fragment
261 // identifier (so that permalinks of the form puzzle.html#game-id
262 // can launch the specified id).
263 Module.arguments = [location.hash];
266 // And if we get here with everything having gone smoothly, i.e.
267 // we haven't crashed for one reason or another during setup, then
268 // it's probably safe to hide the 'sorry, no puzzle here' div and
269 // show the div containing the actual puzzle.
270 document.getElementById("apology").style.display = "none";
271 document.getElementById("puzzle").style.display = "inline";