chiark / gitweb /
Javascript puzzles: switch to a CSS-based drop-down system.
[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 <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 = [], gametypecustom = null;
86 var gametypeselectedindex = null;
87
88 // The two anchors used to give permalinks to the current puzzle. Used
89 // by js_update_permalinks().
90 var permalink_seed, permalink_desc;
91
92 // The undo and redo buttons. Used by js_enable_undo_redo().
93 var undo_button, redo_button;
94
95 // A div element enclosing both the puzzle and its status bar, used
96 // for positioning the resize handle.
97 var resizable_div;
98
99 // Helper function to find the absolute position of a given DOM
100 // element on a page, by iterating upwards through the DOM finding
101 // each element's offset from its parent, and thus calculating the
102 // page-relative position of the target element.
103 function element_coords(element) {
104     var ex = 0, ey = 0;
105     while (element.offsetParent) {
106         ex += element.offsetLeft;
107         ey += element.offsetTop;
108         element = element.offsetParent;
109     }
110     return {x: ex, y:ey};
111 }
112
113 // Helper function which is passed a mouse event object and a DOM
114 // element, and returns the coordinates of the mouse event relative to
115 // the top left corner of the element by subtracting element_coords
116 // from event.page{X,Y}.
117 function relative_mouse_coords(event, element) {
118     var ecoords = element_coords(element);
119     return {x: event.pageX - ecoords.x,
120             y: event.pageY - ecoords.y};
121 }
122
123 // Enable and disable items in the CSS menus.
124 function disable_menu_item(item, disabledFlag) {
125     if (disabledFlag)
126         item.className = "disabled";
127     else
128         item.className = "";
129 }
130
131 // Init function called from body.onload.
132 function initPuzzle() {
133     // Construct the off-screen canvas used for double buffering.
134     onscreen_canvas = document.getElementById("puzzlecanvas");
135     offscreen_canvas = document.createElement("canvas");
136     offscreen_canvas.width = onscreen_canvas.width;
137     offscreen_canvas.height = onscreen_canvas.height;
138
139     // Stop right-clicks on the puzzle from popping up a context menu.
140     // We need those right-clicks!
141     onscreen_canvas.oncontextmenu = function(event) { return false; }
142
143     // Set up mouse handlers. We do a bit of tracking of the currently
144     // pressed mouse buttons, to avoid sending mousemoves with no
145     // button down (our puzzles don't want those events).
146     mousedown = Module.cwrap('mousedown', 'void',
147                              ['number', 'number', 'number']);
148     buttons_down = 0;
149     onscreen_canvas.onmousedown = function(event) {
150         var xy = relative_mouse_coords(event, onscreen_canvas);
151         mousedown(xy.x, xy.y, event.button);
152         buttons_down |= 1 << event.button;
153         onscreen_canvas.setCapture(true);
154     };
155     mousemove = Module.cwrap('mousemove', 'void',
156                              ['number', 'number', 'number']);
157     onscreen_canvas.onmousemove = function(event) {
158         if (buttons_down) {
159             var xy = relative_mouse_coords(event, onscreen_canvas);
160             mousemove(xy.x, xy.y, buttons_down);
161         }
162     };
163     mouseup = Module.cwrap('mouseup', 'void',
164                            ['number', 'number', 'number']);
165     onscreen_canvas.onmouseup = function(event) {
166         if (buttons_down & (1 << event.button)) {
167             buttons_down ^= 1 << event.button;
168             var xy = relative_mouse_coords(event, onscreen_canvas);
169             mouseup(xy.x, xy.y, event.button);
170         }
171     };
172
173     // Set up keyboard handlers. We do all the actual keyboard
174     // handling in onkeydown; but we also call event.preventDefault()
175     // in both the keydown and keypress handlers. This means that
176     // while the canvas itself has focus, _all_ keypresses go only to
177     // the puzzle - so users of this puzzle collection in other media
178     // can indulge their instinct to press ^R for redo, for example,
179     // without accidentally reloading the page.
180     key = Module.cwrap('key', 'void', ['number', 'number', 'string',
181                                        'string', 'number', 'number']);
182     onscreen_canvas.onkeydown = function(event) {
183         key(event.keyCode, event.charCode, event.key, event.char,
184             event.shiftKey ? 1 : 0, event.ctrlKey ? 1 : 0);
185         event.preventDefault();
186     };
187     onscreen_canvas.onkeypress = function(event) {
188         event.preventDefault();
189     };
190
191     // command() is a C function called to pass back events which
192     // don't fall into other categories like mouse and key events.
193     // Mostly those are button presses, but there's also one for the
194     // game-type dropdown having been changed.
195     command = Module.cwrap('command', 'void', ['number']);
196
197     // Event handlers for buttons and things, which call command().
198     document.getElementById("specific").onclick = function(event) {
199         // Ensure we don't accidentally process these events when a
200         // dialog is actually active, e.g. because the button still
201         // has keyboard focus
202         if (dlg_dimmer === null)
203             command(0);
204     };
205     document.getElementById("random").onclick = function(event) {
206         if (dlg_dimmer === null)
207             command(1);
208     };
209     document.getElementById("new").onclick = function(event) {
210         if (dlg_dimmer === null)
211             command(5);
212     };
213     document.getElementById("restart").onclick = function(event) {
214         if (dlg_dimmer === null)
215             command(6);
216     };
217     undo_button = document.getElementById("undo");
218     undo_button.onclick = function(event) {
219         if (dlg_dimmer === null)
220             command(7);
221     };
222     redo_button = document.getElementById("redo");
223     redo_button.onclick = function(event) {
224         if (dlg_dimmer === null)
225             command(8);
226     };
227     document.getElementById("solve").onclick = function(event) {
228         if (dlg_dimmer === null)
229             command(9);
230     };
231
232     gametypelist = document.getElementById("gametype");
233
234     // In IE, the canvas doesn't automatically gain focus on a mouse
235     // click, so make sure it does
236     onscreen_canvas.addEventListener("mousedown", function(event) {
237         onscreen_canvas.focus();
238     });
239
240     // In our dialog boxes, Return and Escape should be like pressing
241     // OK and Cancel respectively
242     document.addEventListener("keydown", function(event) {
243
244         if (dlg_dimmer !== null && event.keyCode == 13) {
245             for (var i in dlg_return_funcs)
246                 dlg_return_funcs[i]();
247             command(3);
248         }
249
250         if (dlg_dimmer !== null && event.keyCode == 27)
251             command(4);
252     });
253
254     // Set up the function pointers we haven't already grabbed. 
255     dlg_return_sval = Module.cwrap('dlg_return_sval', 'void',
256                                    ['number','string']);
257     dlg_return_ival = Module.cwrap('dlg_return_ival', 'void',
258                                    ['number','number']);
259     timer_callback = Module.cwrap('timer_callback', 'void', ['number']);
260
261     // Save references to the two permalinks.
262     permalink_desc = document.getElementById("permalink-desc");
263     permalink_seed = document.getElementById("permalink-seed");
264
265     // Default to giving keyboard focus to the puzzle.
266     onscreen_canvas.focus();
267
268     // Create the resize handle.
269     var resize_handle = document.createElement("canvas");
270     resize_handle.width = 10;
271     resize_handle.height = 10;
272     {
273         var ctx = resize_handle.getContext("2d");
274         ctx.beginPath();
275         for (var i = 1; i <= 7; i += 3) {
276             ctx.moveTo(8.5, i + 0.5);
277             ctx.lineTo(i + 0.5, 8.5);
278         }
279         ctx.lineWidth = '1px';
280         ctx.lineCap = 'round';
281         ctx.lineJoin = 'round';
282         ctx.strokeStyle = '#000000';
283         ctx.stroke();
284     }
285     resizable_div = document.getElementById("resizable");
286     resizable_div.appendChild(resize_handle);
287     resize_handle.style.position = 'absolute';
288     resize_handle.style.zIndex = 98;
289     resize_handle.style.bottom = "0";
290     resize_handle.style.right = "0";
291     resize_handle.style.cursor = "se-resize";
292     resize_handle.title = "Drag to resize the puzzle. Right-click to restore the default size.";
293     var resize_xbase = null, resize_ybase = null, restore_pending = false;
294     var resize_xoffset = null, resize_yoffset = null;
295     var resize_puzzle = Module.cwrap('resize_puzzle',
296                                      'void', ['number', 'number']);
297     var restore_puzzle_size = Module.cwrap('restore_puzzle_size', 'void', []);
298     resize_handle.oncontextmenu = function(event) { return false; }
299     resize_handle.onmousedown = function(event) {
300         if (event.button == 0) {
301             var xy = element_coords(onscreen_canvas);
302             resize_xbase = xy.x + onscreen_canvas.width / 2;
303             resize_ybase = xy.y;
304             resize_xoffset = xy.x + onscreen_canvas.width - event.pageX;
305             resize_yoffset = xy.y + onscreen_canvas.height - event.pageY;
306         } else {
307             restore_pending = true;
308         }
309         resize_handle.setCapture(true);
310         event.preventDefault();
311     };
312     window.addEventListener("mousemove", function(event) {
313         if (resize_xbase !== null && resize_ybase !== null) {
314             resize_puzzle((event.pageX + resize_xoffset - resize_xbase) * 2,
315                           (event.pageY + resize_yoffset - resize_ybase));
316             event.preventDefault();
317             // Chrome insists on selecting text during a resize drag
318             // no matter what I do
319             if (window.getSelection)
320                 window.getSelection().removeAllRanges();
321             else
322                 document.selection.empty();        }
323     });
324     window.addEventListener("mouseup", function(event) {
325         if (resize_xbase !== null && resize_ybase !== null) {
326             resize_xbase = null;
327             resize_ybase = null;
328             onscreen_canvas.focus(); // return focus to the puzzle
329             event.preventDefault();
330         } else if (restore_pending) {
331             // If you have the puzzle at larger than normal size and
332             // then right-click to restore, I haven't found any way to
333             // stop Chrome and IE popping up a context menu on the
334             // revealed piece of document when you release the button
335             // except by putting the actual restore into a setTimeout.
336             // Gah.
337             setTimeout(function() {
338                 restore_pending = false;
339                 restore_puzzle_size();
340                 onscreen_canvas.focus();
341             }, 20);
342             event.preventDefault();
343         }
344     });
345
346     // Run the C setup function, passing argv[1] as the fragment
347     // identifier (so that permalinks of the form puzzle.html#game-id
348     // can launch the specified id).
349     Module.callMain([location.hash]);
350
351     // And if we get here with everything having gone smoothly, i.e.
352     // we haven't crashed for one reason or another during setup, then
353     // it's probably safe to hide the 'sorry, no puzzle here' div and
354     // show the div containing the actual puzzle.
355     document.getElementById("apology").style.display = "none";
356     document.getElementById("puzzle").style.display = "inline";
357 }