chiark / gitweb /
Small refactor to relative_mouse_coords: now the functionality which
[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 var Module = {
39     'noInitialRun': true,
40     'noExitRuntime': true
41 };
42
43 // Variables used by js_canvas_find_font_midpoint().
44 var midpoint_test_str = "ABCDEFGHIKLMNOPRSTUVWXYZ0123456789";
45 var midpoint_cache = [];
46
47 // Variables used by js_activate_timer() and js_deactivate_timer().
48 var timer = null;
49 var timer_reference_date;
50
51 // void timer_callback(double tplus);
52 //
53 // Called every 20ms while timing is active.
54 var timer_callback;
55
56 // The status bar object, if we create one.
57 var statusbar = null;
58
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.
62 var blittercount = 0;
63 var blitters = [];
64
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;
72 var dlg_next_id = 0;
73 var dlg_return_funcs = null;
74
75 // void dlg_return_sval(int index, const char *val);
76 // void dlg_return_ival(int index, int val);
77 //
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;
81
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().
85 //
86 // gametypethiscustom is an option which indicates some custom game
87 // params you've already set up, and which will be auto-selected on
88 // return from the customisation dialog; gametypenewcustom is an
89 // option which you select to indicate that you want to bring up the
90 // customisation dialog and select a new configuration. Ideally I'd do
91 // this with just one option serving both purposes, but instead we
92 // have to do this a bit oddly because browsers don't send 'onchange'
93 // events for a select element if you reselect the same one - so if
94 // you've picked a custom setup and now want to change it, you need a
95 // way to specify that.
96 var gametypeselector = null, gametypeoptions = [];
97 var gametypethiscustom = null, gametypehiddencustom = null;
98
99 // The two anchors used to give permalinks to the current puzzle. Used
100 // by js_update_permalinks().
101 var permalink_seed, permalink_desc;
102
103 // The undo and redo buttons. Used by js_enable_undo_redo().
104 var undo_button, redo_button;
105
106 // Helper function to find the absolute position of a given DOM
107 // element on a page, by iterating upwards through the DOM finding
108 // each element's offset from its parent, and thus calculating the
109 // page-relative position of the target element.
110 function element_coords(element) {
111     var ex = 0, ey = 0;
112     while (element.offsetParent) {
113         ex += element.offsetLeft;
114         ey += element.offsetTop;
115         element = element.offsetParent;
116     }
117     return {x: ex, y:ey};
118 }
119
120 // Helper function which is passed a mouse event object and a DOM
121 // element, and returns the coordinates of the mouse event relative to
122 // the top left corner of the element by subtracting element_coords
123 // from event.page{X,Y}.
124 function relative_mouse_coords(event, element) {
125     var ecoords = element_coords(element);
126     return {x: event.pageX - ecoords.x,
127             y: event.pageY - ecoords.y};
128 }
129
130 // Init function called from body.onload.
131 function initPuzzle() {
132     // Construct the off-screen canvas used for double buffering.
133     onscreen_canvas = document.getElementById("puzzlecanvas");
134     offscreen_canvas = document.createElement("canvas");
135     offscreen_canvas.width = onscreen_canvas.width;
136     offscreen_canvas.height = onscreen_canvas.height;
137
138     // Stop right-clicks on the puzzle from popping up a context menu.
139     // We need those right-clicks!
140     onscreen_canvas.oncontextmenu = function(event) { return false; }
141
142     // Set up mouse handlers. We do a bit of tracking of the currently
143     // pressed mouse buttons, to avoid sending mousemoves with no
144     // button down (our puzzles don't want those events).
145     mousedown = Module.cwrap('mousedown', 'void',
146                              ['number', 'number', 'number']);
147     buttons_down = 0;
148     onscreen_canvas.onmousedown = function(event) {
149         var xy = relative_mouse_coords(event, onscreen_canvas);
150         mousedown(xy.x, xy.y, event.button);
151         buttons_down |= 1 << event.button;
152         onscreen_canvas.setCapture(true);
153     };
154     mousemove = Module.cwrap('mousemove', 'void',
155                              ['number', 'number', 'number']);
156     onscreen_canvas.onmousemove = function(event) {
157         if (buttons_down) {
158             var xy = relative_mouse_coords(event, onscreen_canvas);
159             mousemove(xy.x, xy.y, buttons_down);
160         }
161     };
162     mouseup = Module.cwrap('mouseup', 'void',
163                            ['number', 'number', 'number']);
164     onscreen_canvas.onmouseup = function(event) {
165         if (buttons_down & (1 << event.button)) {
166             buttons_down ^= 1 << event.button;
167             var xy = relative_mouse_coords(event, onscreen_canvas);
168             mouseup(xy.x, xy.y, event.button);
169         }
170     };
171
172     // Set up keyboard handlers. We do all the actual keyboard
173     // handling in onkeydown; but we also call event.preventDefault()
174     // in both the keydown and keypress handlers. This means that
175     // while the canvas itself has focus, _all_ keypresses go only to
176     // the puzzle - so users of this puzzle collection in other media
177     // can indulge their instinct to press ^R for redo, for example,
178     // without accidentally reloading the page.
179     key = Module.cwrap('key', 'void', ['number', 'number', 'string',
180                                        'string', 'number', 'number']);
181     onscreen_canvas.onkeydown = function(event) {
182         key(event.keyCode, event.charCode, event.key, event.char,
183             event.shiftKey ? 1 : 0, event.ctrlKey ? 1 : 0);
184         event.preventDefault();
185     };
186     onscreen_canvas.onkeypress = function(event) {
187         event.preventDefault();
188     };
189
190     // command() is a C function called to pass back events which
191     // don't fall into other categories like mouse and key events.
192     // Mostly those are button presses, but there's also one for the
193     // game-type dropdown having been changed.
194     command = Module.cwrap('command', 'void', ['number']);
195
196     // Event handlers for buttons and things, which call command().
197     document.getElementById("specific").onclick = function(event) {
198         // Ensure we don't accidentally process these events when a
199         // dialog is actually active, e.g. because the button still
200         // has keyboard focus
201         if (dlg_dimmer === null)
202             command(0);
203     };
204     document.getElementById("random").onclick = function(event) {
205         if (dlg_dimmer === null)
206             command(1);
207     };
208     document.getElementById("new").onclick = function(event) {
209         if (dlg_dimmer === null)
210             command(5);
211     };
212     document.getElementById("restart").onclick = function(event) {
213         if (dlg_dimmer === null)
214             command(6);
215     };
216     undo_button = document.getElementById("undo");
217     undo_button.onclick = function(event) {
218         if (dlg_dimmer === null)
219             command(7);
220     };
221     redo_button = document.getElementById("redo");
222     redo_button.onclick = function(event) {
223         if (dlg_dimmer === null)
224             command(8);
225     };
226     document.getElementById("solve").onclick = function(event) {
227         if (dlg_dimmer === null)
228             command(9);
229     };
230
231     gametypeselector = document.getElementById("gametype");
232     gametypeselector.onchange = function(event) {
233         if (dlg_dimmer === null)
234             command(2);
235     };
236
237     // In IE, the canvas doesn't automatically gain focus on a mouse
238     // click, so make sure it does
239     onscreen_canvas.addEventListener("mousedown", function(event) {
240         onscreen_canvas.focus();
241     });
242
243     // In our dialog boxes, Return and Escape should be like pressing
244     // OK and Cancel respectively
245     document.addEventListener("keydown", function(event) {
246
247         if (dlg_dimmer !== null && event.keyCode == 13) {
248             for (var i in dlg_return_funcs)
249                 dlg_return_funcs[i]();
250             command(3);
251         }
252
253         if (dlg_dimmer !== null && event.keyCode == 27)
254             command(4);
255     });
256
257     // Set up the function pointers we haven't already grabbed. 
258     dlg_return_sval = Module.cwrap('dlg_return_sval', 'void',
259                                    ['number','string']);
260     dlg_return_ival = Module.cwrap('dlg_return_ival', 'void',
261                                    ['number','number']);
262     timer_callback = Module.cwrap('timer_callback', 'void', ['number']);
263
264     // Save references to the two permalinks.
265     permalink_desc = document.getElementById("permalink-desc");
266     permalink_seed = document.getElementById("permalink-seed");
267
268     // Default to giving keyboard focus to the puzzle.
269     onscreen_canvas.focus();
270
271     // Run the C setup function, passing argv[1] as the fragment
272     // identifier (so that permalinks of the form puzzle.html#game-id
273     // can launch the specified id).
274     Module.arguments = [location.hash];
275     Module.run();
276
277     // And if we get here with everything having gone smoothly, i.e.
278     // we haven't crashed for one reason or another during setup, then
279     // it's probably safe to hide the 'sorry, no puzzle here' div and
280     // show the div containing the actual puzzle.
281     document.getElementById("apology").style.display = "none";
282     document.getElementById("puzzle").style.display = "inline";
283 }