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 <select> object implementing the game-type drop-down, and a
83 // list of the <option> objects inside it. Used by js_add_preset(),
84 // js_get_selected_preset() and js_select_preset().
86 // gametypehiddencustom is a second copy of the 'Custom' dropdown
87 // element, set to display:none. This is used by a bodge in emcclib.js
88 // (see comment in js_add_preset) to arrange that if the Custom
89 // element is (apparently) already selected, we still find out if the
90 // user selects it again.
91 var gametypeselector = null, gametypeoptions = [];
92 var gametypehiddencustom = null;
94 // The two anchors used to give permalinks to the current puzzle. Used
95 // by js_update_permalinks().
96 var permalink_seed, permalink_desc;
98 // The undo and redo buttons. Used by js_enable_undo_redo().
99 var undo_button, redo_button;
101 // Helper function which is passed a mouse event object and a DOM
102 // element, and returns the coordinates of the mouse event relative to
103 // the top left corner of the element by iterating upwards through the
104 // DOM finding each element's offset from its parent, and thus
105 // calculating the page-relative position of the target element so
106 // that we can subtract that from event.page{X,Y}.
107 function relative_mouse_coords(event, element) {
109 while (element.offsetParent) {
110 ex += element.offsetLeft;
111 ey += element.offsetTop;
112 element = element.offsetParent;
114 return {x: event.pageX - ex,
115 y: event.pageY - ey};
118 // Init function called from body.onload.
119 function initPuzzle() {
120 // Construct the off-screen canvas used for double buffering.
121 onscreen_canvas = document.getElementById("puzzlecanvas");
122 offscreen_canvas = document.createElement("canvas");
123 offscreen_canvas.width = onscreen_canvas.width;
124 offscreen_canvas.height = onscreen_canvas.height;
126 // Stop right-clicks on the puzzle from popping up a context menu.
127 // We need those right-clicks!
128 onscreen_canvas.oncontextmenu = function(event) { return false; }
130 // Set up mouse handlers. We do a bit of tracking of the currently
131 // pressed mouse buttons, to avoid sending mousemoves with no
132 // button down (our puzzles don't want those events).
133 mousedown = Module.cwrap('mousedown', 'void',
134 ['number', 'number', 'number']);
136 onscreen_canvas.onmousedown = function(event) {
137 var xy = relative_mouse_coords(event, onscreen_canvas);
138 mousedown(xy.x, xy.y, event.button);
139 buttons_down |= 1 << event.button;
140 onscreen_canvas.setCapture(true);
142 mousemove = Module.cwrap('mousemove', 'void',
143 ['number', 'number', 'number']);
144 onscreen_canvas.onmousemove = function(event) {
146 var xy = relative_mouse_coords(event, onscreen_canvas);
147 mousemove(xy.x, xy.y, buttons_down);
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, xy.y, event.button);
160 // Set up keyboard handlers. We do all the actual keyboard
161 // handling in onkeydown; but we also call event.preventDefault()
162 // in both the keydown and keypress handlers. This means that
163 // while the canvas itself has focus, _all_ keypresses go only to
164 // the puzzle - so users of this puzzle collection in other media
165 // can indulge their instinct to press ^R for redo, for example,
166 // without accidentally reloading the page.
167 key = Module.cwrap('key', 'void', ['number', 'number', 'string',
168 'string', 'number', 'number']);
169 onscreen_canvas.onkeydown = function(event) {
170 key(event.keyCode, event.charCode, event.key, event.char,
171 event.shiftKey ? 1 : 0, event.ctrlKey ? 1 : 0);
172 event.preventDefault();
174 onscreen_canvas.onkeypress = function(event) {
175 event.preventDefault();
178 // command() is a C function called to pass back events which
179 // don't fall into other categories like mouse and key events.
180 // Mostly those are button presses, but there's also one for the
181 // game-type dropdown having been changed.
182 command = Module.cwrap('command', 'void', ['number']);
184 // Event handlers for buttons and things, which call command().
185 document.getElementById("specific").onclick = function(event) {
186 // Ensure we don't accidentally process these events when a
187 // dialog is actually active, e.g. because the button still
188 // has keyboard focus
189 if (dlg_dimmer === null)
192 document.getElementById("random").onclick = function(event) {
193 if (dlg_dimmer === null)
196 document.getElementById("new").onclick = function(event) {
197 if (dlg_dimmer === null)
200 document.getElementById("restart").onclick = function(event) {
201 if (dlg_dimmer === null)
204 undo_button = document.getElementById("undo");
205 undo_button.onclick = function(event) {
206 if (dlg_dimmer === null)
209 redo_button = document.getElementById("redo");
210 redo_button.onclick = function(event) {
211 if (dlg_dimmer === null)
214 document.getElementById("solve").onclick = function(event) {
215 if (dlg_dimmer === null)
219 gametypeselector = document.getElementById("gametype");
220 gametypeselector.onchange = function(event) {
221 if (dlg_dimmer === null)
225 // In IE, the canvas doesn't automatically gain focus on a mouse
226 // click, so make sure it does
227 onscreen_canvas.addEventListener("mousedown", function(event) {
228 onscreen_canvas.focus();
231 // In our dialog boxes, Return and Escape should be like pressing
232 // OK and Cancel respectively
233 document.addEventListener("keydown", function(event) {
235 if (dlg_dimmer !== null && event.keyCode == 13) {
236 for (var i in dlg_return_funcs)
237 dlg_return_funcs[i]();
241 if (dlg_dimmer !== null && event.keyCode == 27)
245 // Set up the function pointers we haven't already grabbed.
246 dlg_return_sval = Module.cwrap('dlg_return_sval', 'void',
247 ['number','string']);
248 dlg_return_ival = Module.cwrap('dlg_return_ival', 'void',
249 ['number','number']);
250 timer_callback = Module.cwrap('timer_callback', 'void', ['number']);
252 // Save references to the two permalinks.
253 permalink_desc = document.getElementById("permalink-desc");
254 permalink_seed = document.getElementById("permalink-seed");
256 // Default to giving keyboard focus to the puzzle.
257 onscreen_canvas.focus();
259 // Run the C setup function, passing argv[1] as the fragment
260 // identifier (so that permalinks of the form puzzle.html#game-id
261 // can launch the specified id).
262 Module.arguments = [location.hash];
265 // And if we get here with everything having gone smoothly, i.e.
266 // we haven't crashed for one reason or another during setup, then
267 // it's probably safe to hide the 'sorry, no puzzle here' div and
268 // show the div containing the actual puzzle.
269 document.getElementById("apology").style.display = "none";
270 document.getElementById("puzzle").style.display = "inline";