chiark / gitweb /
Remove trailing commas at the ends of initialiser lists. IE 8 and 9
[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 // 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;
93
94 // The two anchors used to give permalinks to the current puzzle. Used
95 // by js_update_permalinks().
96 var permalink_seed, permalink_desc;
97
98 // The undo and redo buttons. Used by js_enable_undo_redo().
99 var undo_button, redo_button;
100
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) {
108     var ex = 0, ey = 0;
109     while (element.offsetParent) {
110         ex += element.offsetLeft;
111         ey += element.offsetTop;
112         element = element.offsetParent;
113     }
114     return {x: event.pageX - ex,
115             y: event.pageY - ey};
116 }
117
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;
125
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; }
129
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']);
135     buttons_down = 0;
136     onscreen_canvas.onmousedown = function(event) {
137         var xy = relative_mouse_coords(event, onscreen_canvas);
138         mousedown(xy.x - onscreen_canvas.offsetLeft,
139                   xy.y - onscreen_canvas.offsetTop,
140                   event.button);
141         buttons_down |= 1 << event.button;
142         onscreen_canvas.setCapture(true);
143     };
144     mousemove = Module.cwrap('mousemove', 'void',
145                              ['number', 'number', 'number']);
146     onscreen_canvas.onmousemove = function(event) {
147         if (buttons_down) {
148             var xy = relative_mouse_coords(event, onscreen_canvas);
149             mousemove(xy.x - onscreen_canvas.offsetLeft,
150                       xy.y - onscreen_canvas.offsetTop,
151                       buttons_down);
152         }
153     };
154     mouseup = Module.cwrap('mouseup', 'void',
155                            ['number', 'number', 'number']);
156     onscreen_canvas.onmouseup = function(event) {
157         if (buttons_down & (1 << event.button)) {
158             buttons_down ^= 1 << event.button;
159             var xy = relative_mouse_coords(event, onscreen_canvas);
160             mouseup(xy.x - onscreen_canvas.offsetLeft,
161                     xy.y - onscreen_canvas.offsetTop,
162                     event.button);
163         }
164     };
165
166     // Set up keyboard handlers. We expect ordinary keys (with a
167     // charCode) to be handled by onkeypress, but function keys
168     // (arrows etc) to be handled by onkeydown.
169     //
170     // We also call event.preventDefault() in both handlers. This
171     // means that while the canvas itself has focus, _all_ keypresses
172     // go only to the puzzle - so users of this puzzle collection in
173     // other media can indulge their instinct to press ^R for redo,
174     // for example, without accidentally reloading the page.
175     key = Module.cwrap('key', 'void',
176                        ['number', 'number', 'number', 'number']);
177     onscreen_canvas.onkeydown = function(event) {
178         key(event.keyCode, event.charCode,
179             event.shiftKey ? 1 : 0, event.ctrlKey ? 1 : 0);
180         event.preventDefault();
181     };
182     onscreen_canvas.onkeypress = function(event) {
183         if (event.charCode != 0)
184             key(event.keyCode, event.charCode,
185                 event.shiftKey ? 1 : 0, event.ctrlKey ? 1 : 0);
186         event.preventDefault();
187     };
188
189     // command() is a C function called to pass back events which
190     // don't fall into other categories like mouse and key events.
191     // Mostly those are button presses, but there's also one for the
192     // game-type dropdown having been changed.
193     command = Module.cwrap('command', 'void', ['number']);
194
195     // Event handlers for buttons and things, which call command().
196     document.getElementById("specific").onclick = function(event) {
197         // Ensure we don't accidentally process these events when a
198         // dialog is actually active, e.g. because the button still
199         // has keyboard focus
200         if (dlg_dimmer === null)
201             command(0);
202     };
203     document.getElementById("random").onclick = function(event) {
204         if (dlg_dimmer === null)
205             command(1);
206     };
207     document.getElementById("new").onclick = function(event) {
208         if (dlg_dimmer === null)
209             command(5);
210     };
211     document.getElementById("restart").onclick = function(event) {
212         if (dlg_dimmer === null)
213             command(6);
214     };
215     undo_button = document.getElementById("undo");
216     undo_button.onclick = function(event) {
217         if (dlg_dimmer === null)
218             command(7);
219     };
220     redo_button = document.getElementById("redo");
221     redo_button.onclick = function(event) {
222         if (dlg_dimmer === null)
223             command(8);
224     };
225     document.getElementById("solve").onclick = function(event) {
226         if (dlg_dimmer === null)
227             command(9);
228     };
229
230     gametypeselector = document.getElementById("gametype");
231     gametypeselector.onchange = function(event) {
232         if (dlg_dimmer === null)
233             command(2);
234     };
235
236     // In our dialog boxes, Return and Escape should be like pressing
237     // OK and Cancel respectively
238     document.addEventListener("keydown", function(event) {
239
240         if (dlg_dimmer !== null && event.keyCode == 13) {
241             for (var i in dlg_return_funcs)
242                 dlg_return_funcs[i]();
243             command(3);
244         }
245
246         if (dlg_dimmer !== null && event.keyCode == 27)
247             command(4);
248     });
249
250     // Set up the function pointers we haven't already grabbed. 
251     dlg_return_sval = Module.cwrap('dlg_return_sval', 'void',
252                                    ['number','string']);
253     dlg_return_ival = Module.cwrap('dlg_return_ival', 'void',
254                                    ['number','number']);
255     timer_callback = Module.cwrap('timer_callback', 'void', ['number']);
256
257     // Save references to the two permalinks.
258     permalink_desc = document.getElementById("permalink-desc");
259     permalink_seed = document.getElementById("permalink-seed");
260
261     // Default to giving keyboard focus to the puzzle.
262     onscreen_canvas.focus();
263
264     // Run the C setup function, passing argv[1] as the fragment
265     // identifier (so that permalinks of the form puzzle.html#game-id
266     // can launch the specified id).
267     Module.arguments = [location.hash];
268     Module.run();
269
270     // And if we get here with everything having gone smoothly, i.e.
271     // we haven't crashed for one reason or another during setup, then
272     // it's probably safe to hide the 'sorry, no puzzle here' div and
273     // show the div containing the actual puzzle.
274     document.getElementById("apology").style.display = "none";
275     document.getElementById("puzzle").style.display = "inline";
276 }