chiark / gitweb /
Fix borders on the HTML menu bar.
[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 = [];
86 var gametypeselectedindex = null;
87 var gametypesubmenus = [];
88
89 // The two anchors used to give permalinks to the current puzzle. Used
90 // by js_update_permalinks().
91 var permalink_seed, permalink_desc;
92
93 // The undo and redo buttons. Used by js_enable_undo_redo().
94 var undo_button, redo_button;
95
96 // A div element enclosing both the puzzle and its status bar, used
97 // for positioning the resize handle.
98 var resizable_div;
99
100 // Helper function to find the absolute position of a given DOM
101 // element on a page, by iterating upwards through the DOM finding
102 // each element's offset from its parent, and thus calculating the
103 // page-relative position of the target element.
104 function element_coords(element) {
105     var ex = 0, ey = 0;
106     while (element.offsetParent) {
107         ex += element.offsetLeft;
108         ey += element.offsetTop;
109         element = element.offsetParent;
110     }
111     return {x: ex, y:ey};
112 }
113
114 // Helper function which is passed a mouse event object and a DOM
115 // element, and returns the coordinates of the mouse event relative to
116 // the top left corner of the element by subtracting element_coords
117 // from event.page{X,Y}.
118 function relative_mouse_coords(event, element) {
119     var ecoords = element_coords(element);
120     return {x: event.pageX - ecoords.x,
121             y: event.pageY - ecoords.y};
122 }
123
124 // Enable and disable items in the CSS menus.
125 function disable_menu_item(item, disabledFlag) {
126     if (disabledFlag)
127         item.className = "disabled";
128     else
129         item.className = "";
130 }
131
132 // Dialog-box functions called from both C and JS.
133 function dialog_init(titletext) {
134     // Create an overlay on the page which darkens everything
135     // beneath it.
136     dlg_dimmer = document.createElement("div");
137     dlg_dimmer.style.width = "100%";
138     dlg_dimmer.style.height = "100%";
139     dlg_dimmer.style.background = '#000000';
140     dlg_dimmer.style.position = 'fixed';
141     dlg_dimmer.style.opacity = 0.3;
142     dlg_dimmer.style.top = dlg_dimmer.style.left = 0;
143     dlg_dimmer.style["z-index"] = 99;
144
145     // Now create a form which sits on top of that in turn.
146     dlg_form = document.createElement("form");
147     dlg_form.style.width = (window.innerWidth * 2 / 3) + "px";
148     dlg_form.style.opacity = 1;
149     dlg_form.style.background = '#ffffff';
150     dlg_form.style.color = '#000000';
151     dlg_form.style.position = 'absolute';
152     dlg_form.style.border = "2px solid black";
153     dlg_form.style.padding = "20px";
154     dlg_form.style.top = (window.innerHeight / 10) + "px";
155     dlg_form.style.left = (window.innerWidth / 6) + "px";
156     dlg_form.style["z-index"] = 100;
157
158     var title = document.createElement("p");
159     title.style.marginTop = "0px";
160     title.appendChild(document.createTextNode(titletext));
161     dlg_form.appendChild(title);
162
163     dlg_return_funcs = [];
164     dlg_next_id = 0;
165 }
166
167 function dialog_launch(ok_function, cancel_function) {
168     // Put in the OK and Cancel buttons at the bottom.
169     var button;
170
171     if (ok_function) {
172         button = document.createElement("input");
173         button.type = "button";
174         button.value = "OK";
175         button.onclick = ok_function;
176         dlg_form.appendChild(button);
177     }
178
179     if (cancel_function) {
180         button = document.createElement("input");
181         button.type = "button";
182         button.value = "Cancel";
183         button.onclick = cancel_function;
184         dlg_form.appendChild(button);
185     }
186
187     document.body.appendChild(dlg_dimmer);
188     document.body.appendChild(dlg_form);
189 }
190
191 function dialog_cleanup() {
192     document.body.removeChild(dlg_dimmer);
193     document.body.removeChild(dlg_form);
194     dlg_dimmer = dlg_form = null;
195     onscreen_canvas.focus();
196 }
197
198 // Init function called from body.onload.
199 function initPuzzle() {
200     // Construct the off-screen canvas used for double buffering.
201     onscreen_canvas = document.getElementById("puzzlecanvas");
202     offscreen_canvas = document.createElement("canvas");
203     offscreen_canvas.width = onscreen_canvas.width;
204     offscreen_canvas.height = onscreen_canvas.height;
205
206     // Stop right-clicks on the puzzle from popping up a context menu.
207     // We need those right-clicks!
208     onscreen_canvas.oncontextmenu = function(event) { return false; }
209
210     // Set up mouse handlers. We do a bit of tracking of the currently
211     // pressed mouse buttons, to avoid sending mousemoves with no
212     // button down (our puzzles don't want those events).
213     mousedown = Module.cwrap('mousedown', 'void',
214                              ['number', 'number', 'number']);
215     buttons_down = 0;
216     onscreen_canvas.onmousedown = function(event) {
217         var xy = relative_mouse_coords(event, onscreen_canvas);
218         mousedown(xy.x, xy.y, event.button);
219         buttons_down |= 1 << event.button;
220         onscreen_canvas.setCapture(true);
221     };
222     mousemove = Module.cwrap('mousemove', 'void',
223                              ['number', 'number', 'number']);
224     onscreen_canvas.onmousemove = function(event) {
225         if (buttons_down) {
226             var xy = relative_mouse_coords(event, onscreen_canvas);
227             mousemove(xy.x, xy.y, buttons_down);
228         }
229     };
230     mouseup = Module.cwrap('mouseup', 'void',
231                            ['number', 'number', 'number']);
232     onscreen_canvas.onmouseup = function(event) {
233         if (buttons_down & (1 << event.button)) {
234             buttons_down ^= 1 << event.button;
235             var xy = relative_mouse_coords(event, onscreen_canvas);
236             mouseup(xy.x, xy.y, event.button);
237         }
238     };
239
240     // Set up keyboard handlers. We do all the actual keyboard
241     // handling in onkeydown; but we also call event.preventDefault()
242     // in both the keydown and keypress handlers. This means that
243     // while the canvas itself has focus, _all_ keypresses go only to
244     // the puzzle - so users of this puzzle collection in other media
245     // can indulge their instinct to press ^R for redo, for example,
246     // without accidentally reloading the page.
247     key = Module.cwrap('key', 'void', ['number', 'number', 'string',
248                                        'string', 'number', 'number']);
249     onscreen_canvas.onkeydown = function(event) {
250         key(event.keyCode, event.charCode, event.key, event.char,
251             event.shiftKey ? 1 : 0, event.ctrlKey ? 1 : 0);
252         event.preventDefault();
253     };
254     onscreen_canvas.onkeypress = function(event) {
255         event.preventDefault();
256     };
257
258     // command() is a C function called to pass back events which
259     // don't fall into other categories like mouse and key events.
260     // Mostly those are button presses, but there's also one for the
261     // game-type dropdown having been changed.
262     command = Module.cwrap('command', 'void', ['number']);
263
264     // Event handlers for buttons and things, which call command().
265     document.getElementById("specific").onclick = function(event) {
266         // Ensure we don't accidentally process these events when a
267         // dialog is actually active, e.g. because the button still
268         // has keyboard focus
269         if (dlg_dimmer === null)
270             command(0);
271     };
272     document.getElementById("random").onclick = function(event) {
273         if (dlg_dimmer === null)
274             command(1);
275     };
276     document.getElementById("new").onclick = function(event) {
277         if (dlg_dimmer === null)
278             command(5);
279     };
280     document.getElementById("restart").onclick = function(event) {
281         if (dlg_dimmer === null)
282             command(6);
283     };
284     undo_button = document.getElementById("undo");
285     undo_button.onclick = function(event) {
286         if (dlg_dimmer === null)
287             command(7);
288     };
289     redo_button = document.getElementById("redo");
290     redo_button.onclick = function(event) {
291         if (dlg_dimmer === null)
292             command(8);
293     };
294     document.getElementById("solve").onclick = function(event) {
295         if (dlg_dimmer === null)
296             command(9);
297     };
298
299     // 'number' is used for C pointers
300     get_save_file = Module.cwrap('get_save_file', 'number', []);
301     free_save_file = Module.cwrap('free_save_file', 'void', ['number']);
302     load_game = Module.cwrap('load_game', 'void', ['string', 'number']);
303
304     document.getElementById("save").onclick = function(event) {
305         if (dlg_dimmer === null) {
306             var savefile_ptr = get_save_file();
307             var savefile_text = Pointer_stringify(savefile_ptr);
308             free_save_file(savefile_ptr);
309             dialog_init("Download saved-game file");
310             dlg_form.appendChild(document.createTextNode(
311                 "Click to download the "));
312             var a = document.createElement("a");
313             a.download = "puzzle.sav";
314             a.href = "data:application/octet-stream," +
315                 encodeURIComponent(savefile_text);
316             a.appendChild(document.createTextNode("saved-game file"));
317             dlg_form.appendChild(a);
318             dlg_form.appendChild(document.createTextNode("."));
319             dlg_form.appendChild(document.createElement("br"));
320             dialog_launch(function(event) {
321                 dialog_cleanup();
322             });
323         }
324     };
325
326     document.getElementById("load").onclick = function(event) {
327         if (dlg_dimmer === null) {
328             dialog_init("Upload saved-game file");
329             var input = document.createElement("input");
330             input.type = "file";
331             input.multiple = false;
332             dlg_form.appendChild(input);
333             dlg_form.appendChild(document.createElement("br"));
334             dialog_launch(function(event) {
335                 if (input.files.length == 1) {
336                     var file = input.files.item(0);
337                     var reader = new FileReader();
338                     reader.addEventListener("loadend", function() {
339                         var string = reader.result;
340                         load_game(string, string.length);
341                     });
342                     reader.readAsBinaryString(file);
343                 }
344                 dialog_cleanup();
345             }, function(event) {
346                 dialog_cleanup();
347             });
348         }
349     };
350
351     gametypelist = document.getElementById("gametype");
352     gametypesubmenus.push(gametypelist);
353
354     // In IE, the canvas doesn't automatically gain focus on a mouse
355     // click, so make sure it does
356     onscreen_canvas.addEventListener("mousedown", function(event) {
357         onscreen_canvas.focus();
358     });
359
360     // In our dialog boxes, Return and Escape should be like pressing
361     // OK and Cancel respectively
362     document.addEventListener("keydown", function(event) {
363
364         if (dlg_dimmer !== null && event.keyCode == 13) {
365             for (var i in dlg_return_funcs)
366                 dlg_return_funcs[i]();
367             command(3);
368         }
369
370         if (dlg_dimmer !== null && event.keyCode == 27)
371             command(4);
372     });
373
374     // Set up the function pointers we haven't already grabbed. 
375     dlg_return_sval = Module.cwrap('dlg_return_sval', 'void',
376                                    ['number','string']);
377     dlg_return_ival = Module.cwrap('dlg_return_ival', 'void',
378                                    ['number','number']);
379     timer_callback = Module.cwrap('timer_callback', 'void', ['number']);
380
381     // Save references to the two permalinks.
382     permalink_desc = document.getElementById("permalink-desc");
383     permalink_seed = document.getElementById("permalink-seed");
384
385     // Default to giving keyboard focus to the puzzle.
386     onscreen_canvas.focus();
387
388     // Create the resize handle.
389     var resize_handle = document.createElement("canvas");
390     resize_handle.width = 10;
391     resize_handle.height = 10;
392     {
393         var ctx = resize_handle.getContext("2d");
394         ctx.beginPath();
395         for (var i = 1; i <= 7; i += 3) {
396             ctx.moveTo(8.5, i + 0.5);
397             ctx.lineTo(i + 0.5, 8.5);
398         }
399         ctx.lineWidth = '1px';
400         ctx.lineCap = 'round';
401         ctx.lineJoin = 'round';
402         ctx.strokeStyle = '#000000';
403         ctx.stroke();
404     }
405     resizable_div = document.getElementById("resizable");
406     resizable_div.appendChild(resize_handle);
407     resize_handle.style.position = 'absolute';
408     resize_handle.style.zIndex = 98;
409     resize_handle.style.bottom = "0";
410     resize_handle.style.right = "0";
411     resize_handle.style.cursor = "se-resize";
412     resize_handle.title = "Drag to resize the puzzle. Right-click to restore the default size.";
413     var resize_xbase = null, resize_ybase = null, restore_pending = false;
414     var resize_xoffset = null, resize_yoffset = null;
415     var resize_puzzle = Module.cwrap('resize_puzzle',
416                                      'void', ['number', 'number']);
417     var restore_puzzle_size = Module.cwrap('restore_puzzle_size', 'void', []);
418     resize_handle.oncontextmenu = function(event) { return false; }
419     resize_handle.onmousedown = function(event) {
420         if (event.button == 0) {
421             var xy = element_coords(onscreen_canvas);
422             resize_xbase = xy.x + onscreen_canvas.width / 2;
423             resize_ybase = xy.y;
424             resize_xoffset = xy.x + onscreen_canvas.width - event.pageX;
425             resize_yoffset = xy.y + onscreen_canvas.height - event.pageY;
426         } else {
427             restore_pending = true;
428         }
429         resize_handle.setCapture(true);
430         event.preventDefault();
431     };
432     window.addEventListener("mousemove", function(event) {
433         if (resize_xbase !== null && resize_ybase !== null) {
434             resize_puzzle((event.pageX + resize_xoffset - resize_xbase) * 2,
435                           (event.pageY + resize_yoffset - resize_ybase));
436             event.preventDefault();
437             // Chrome insists on selecting text during a resize drag
438             // no matter what I do
439             if (window.getSelection)
440                 window.getSelection().removeAllRanges();
441             else
442                 document.selection.empty();        }
443     });
444     window.addEventListener("mouseup", function(event) {
445         if (resize_xbase !== null && resize_ybase !== null) {
446             resize_xbase = null;
447             resize_ybase = null;
448             onscreen_canvas.focus(); // return focus to the puzzle
449             event.preventDefault();
450         } else if (restore_pending) {
451             // If you have the puzzle at larger than normal size and
452             // then right-click to restore, I haven't found any way to
453             // stop Chrome and IE popping up a context menu on the
454             // revealed piece of document when you release the button
455             // except by putting the actual restore into a setTimeout.
456             // Gah.
457             setTimeout(function() {
458                 restore_pending = false;
459                 restore_puzzle_size();
460                 onscreen_canvas.focus();
461             }, 20);
462             event.preventDefault();
463         }
464     });
465
466     // Run the C setup function, passing argv[1] as the fragment
467     // identifier (so that permalinks of the form puzzle.html#game-id
468     // can launch the specified id).
469     Module.callMain([location.hash]);
470
471     // And if we get here with everything having gone smoothly, i.e.
472     // we haven't crashed for one reason or another during setup, then
473     // it's probably safe to hide the 'sorry, no puzzle here' div and
474     // show the div containing the actual puzzle.
475     document.getElementById("apology").style.display = "none";
476     document.getElementById("puzzle").style.display = "inline";
477 }