chiark / gitweb /
Net: reference-count the barriers array.
[sgt-puzzles.git] / emccpre.js
index e2986da0fb4ccdac128f2aa13f29a3f8404790f0..50825556171e5442827ea93865d2ba22334a40d9 100644 (file)
@@ -2,7 +2,11 @@
  * emccpre.js: one of the Javascript components of an Emscripten-based
  * web/Javascript front end for Puzzles.
  *
- * The other parts of this system live in emcc.c and emcclib.js.
+ * The other parts of this system live in emcc.c and emcclib.js. It
+ * also depends on being run in the context of a web page containing
+ * an appropriate collection of bits and pieces (a canvas, some
+ * buttons and links etc), which is generated for each puzzle by the
+ * script html/jspage.pl.
  *
  * This file contains the Javascript code which is prefixed unmodified
  * to Emscripten's output via the --pre-js option. It declares all our
@@ -33,7 +37,7 @@ var update_xmin, update_xmax, update_ymin, update_ymax;
 // callbacks.
 var Module = {
     'noInitialRun': true,
-    'noExitRuntime': true,
+    'noExitRuntime': true
 };
 
 // Variables used by js_canvas_find_font_midpoint().
@@ -75,17 +79,12 @@ var dlg_return_funcs = null;
 // pass back the final value in each dialog control.
 var dlg_return_sval, dlg_return_ival;
 
-// The <select> object implementing the game-type drop-down, and a
-// list of the <option> objects inside it. Used by js_add_preset(),
+// The <ul> object implementing the game-type drop-down, and a list of
+// the <li> objects inside it. Used by js_add_preset(),
 // js_get_selected_preset() and js_select_preset().
-//
-// gametypehiddencustom is a second copy of the 'Custom' dropdown
-// element, set to display:none. This is used by a bodge in emcclib.js
-// (see comment in js_add_preset) to arrange that if the Custom
-// element is (apparently) already selected, we still find out if the
-// user selects it again.
-var gametypeselector = null, gametypeoptions = [];
-var gametypehiddencustom = null;
+var gametypelist = null, gametypeitems = [];
+var gametypeselectedindex = null;
+var gametypesubmenus = [];
 
 // The two anchors used to give permalinks to the current puzzle. Used
 // by js_update_permalinks().
@@ -94,21 +93,106 @@ var permalink_seed, permalink_desc;
 // The undo and redo buttons. Used by js_enable_undo_redo().
 var undo_button, redo_button;
 
-// Helper function which is passed a mouse event object and a DOM
-// element, and returns the coordinates of the mouse event relative to
-// the top left corner of the element by iterating upwards through the
-// DOM finding each element's offset from its parent, and thus
-// calculating the page-relative position of the target element so
-// that we can subtract that from event.page{X,Y}.
-function relative_mouse_coords(event, element) {
+// A div element enclosing both the puzzle and its status bar, used
+// for positioning the resize handle.
+var resizable_div;
+
+// Helper function to find the absolute position of a given DOM
+// element on a page, by iterating upwards through the DOM finding
+// each element's offset from its parent, and thus calculating the
+// page-relative position of the target element.
+function element_coords(element) {
     var ex = 0, ey = 0;
     while (element.offsetParent) {
         ex += element.offsetLeft;
         ey += element.offsetTop;
         element = element.offsetParent;
     }
-    return {x: event.pageX - ex,
-            y: event.pageY - ey};
+    return {x: ex, y:ey};
+}
+
+// Helper function which is passed a mouse event object and a DOM
+// element, and returns the coordinates of the mouse event relative to
+// the top left corner of the element by subtracting element_coords
+// from event.page{X,Y}.
+function relative_mouse_coords(event, element) {
+    var ecoords = element_coords(element);
+    return {x: event.pageX - ecoords.x,
+            y: event.pageY - ecoords.y};
+}
+
+// Enable and disable items in the CSS menus.
+function disable_menu_item(item, disabledFlag) {
+    if (disabledFlag)
+        item.className = "disabled";
+    else
+        item.className = "";
+}
+
+// Dialog-box functions called from both C and JS.
+function dialog_init(titletext) {
+    // Create an overlay on the page which darkens everything
+    // beneath it.
+    dlg_dimmer = document.createElement("div");
+    dlg_dimmer.style.width = "100%";
+    dlg_dimmer.style.height = "100%";
+    dlg_dimmer.style.background = '#000000';
+    dlg_dimmer.style.position = 'fixed';
+    dlg_dimmer.style.opacity = 0.3;
+    dlg_dimmer.style.top = dlg_dimmer.style.left = 0;
+    dlg_dimmer.style["z-index"] = 99;
+
+    // Now create a form which sits on top of that in turn.
+    dlg_form = document.createElement("form");
+    dlg_form.style.width = (window.innerWidth * 2 / 3) + "px";
+    dlg_form.style.opacity = 1;
+    dlg_form.style.background = '#ffffff';
+    dlg_form.style.color = '#000000';
+    dlg_form.style.position = 'absolute';
+    dlg_form.style.border = "2px solid black";
+    dlg_form.style.padding = "20px";
+    dlg_form.style.top = (window.innerHeight / 10) + "px";
+    dlg_form.style.left = (window.innerWidth / 6) + "px";
+    dlg_form.style["z-index"] = 100;
+
+    var title = document.createElement("p");
+    title.style.marginTop = "0px";
+    title.appendChild(document.createTextNode(titletext));
+    dlg_form.appendChild(title);
+
+    dlg_return_funcs = [];
+    dlg_next_id = 0;
+}
+
+function dialog_launch(ok_function, cancel_function) {
+    // Put in the OK and Cancel buttons at the bottom.
+    var button;
+
+    if (ok_function) {
+        button = document.createElement("input");
+        button.type = "button";
+        button.value = "OK";
+        button.onclick = ok_function;
+        dlg_form.appendChild(button);
+    }
+
+    if (cancel_function) {
+        button = document.createElement("input");
+        button.type = "button";
+        button.value = "Cancel";
+        button.onclick = cancel_function;
+        dlg_form.appendChild(button);
+    }
+
+    document.body.appendChild(dlg_dimmer);
+    document.body.appendChild(dlg_form);
+}
+
+function dialog_cleanup() {
+    document.body.removeChild(dlg_dimmer);
+    document.body.removeChild(dlg_form);
+    dlg_dimmer = dlg_form = null;
+    onscreen_canvas.focus();
 }
 
 // Init function called from body.onload.
@@ -131,9 +215,7 @@ function initPuzzle() {
     buttons_down = 0;
     onscreen_canvas.onmousedown = function(event) {
         var xy = relative_mouse_coords(event, onscreen_canvas);
-        mousedown(xy.x - onscreen_canvas.offsetLeft,
-                  xy.y - onscreen_canvas.offsetTop,
-                  event.button);
+        mousedown(xy.x, xy.y, event.button);
         buttons_down |= 1 << event.button;
         onscreen_canvas.setCapture(true);
     };
@@ -142,9 +224,7 @@ function initPuzzle() {
     onscreen_canvas.onmousemove = function(event) {
         if (buttons_down) {
             var xy = relative_mouse_coords(event, onscreen_canvas);
-            mousemove(xy.x - onscreen_canvas.offsetLeft,
-                      xy.y - onscreen_canvas.offsetTop,
-                      buttons_down);
+            mousemove(xy.x, xy.y, buttons_down);
         }
     };
     mouseup = Module.cwrap('mouseup', 'void',
@@ -153,32 +233,25 @@ function initPuzzle() {
         if (buttons_down & (1 << event.button)) {
             buttons_down ^= 1 << event.button;
             var xy = relative_mouse_coords(event, onscreen_canvas);
-            mouseup(xy.x - onscreen_canvas.offsetLeft,
-                    xy.y - onscreen_canvas.offsetTop,
-                    event.button);
+            mouseup(xy.x, xy.y, event.button);
         }
     };
 
-    // Set up keyboard handlers. We expect ordinary keys (with a
-    // charCode) to be handled by onkeypress, but function keys
-    // (arrows etc) to be handled by onkeydown.
-    //
-    // We also call event.preventDefault() in both handlers. This
-    // means that while the canvas itself has focus, _all_ keypresses
-    // go only to the puzzle - so users of this puzzle collection in
-    // other media can indulge their instinct to press ^R for redo,
-    // for example, without accidentally reloading the page.
-    key = Module.cwrap('key', 'void',
-                       ['number', 'number', 'number', 'number']);
+    // Set up keyboard handlers. We do all the actual keyboard
+    // handling in onkeydown; but we also call event.preventDefault()
+    // in both the keydown and keypress handlers. This means that
+    // while the canvas itself has focus, _all_ keypresses go only to
+    // the puzzle - so users of this puzzle collection in other media
+    // can indulge their instinct to press ^R for redo, for example,
+    // without accidentally reloading the page.
+    key = Module.cwrap('key', 'void', ['number', 'number', 'string',
+                                       'string', 'number', 'number']);
     onscreen_canvas.onkeydown = function(event) {
-        key(event.keyCode, event.charCode,
+        key(event.keyCode, event.charCode, event.key, event.char,
             event.shiftKey ? 1 : 0, event.ctrlKey ? 1 : 0);
         event.preventDefault();
     };
     onscreen_canvas.onkeypress = function(event) {
-        if (event.charCode != 0)
-            key(event.keyCode, event.charCode,
-                event.shiftKey ? 1 : 0, event.ctrlKey ? 1 : 0);
         event.preventDefault();
     };
 
@@ -223,12 +296,67 @@ function initPuzzle() {
             command(9);
     };
 
-    gametypeselector = document.getElementById("gametype");
-    gametypeselector.onchange = function(event) {
-        if (dlg_dimmer === null)
-            command(2);
+    // 'number' is used for C pointers
+    get_save_file = Module.cwrap('get_save_file', 'number', []);
+    free_save_file = Module.cwrap('free_save_file', 'void', ['number']);
+    load_game = Module.cwrap('load_game', 'void', ['string', 'number']);
+
+    document.getElementById("save").onclick = function(event) {
+        if (dlg_dimmer === null) {
+            var savefile_ptr = get_save_file();
+            var savefile_text = Pointer_stringify(savefile_ptr);
+            free_save_file(savefile_ptr);
+            dialog_init("Download saved-game file");
+            dlg_form.appendChild(document.createTextNode(
+                "Click to download the "));
+            var a = document.createElement("a");
+            a.download = "puzzle.sav";
+            a.href = "data:application/octet-stream," +
+                encodeURIComponent(savefile_text);
+            a.appendChild(document.createTextNode("saved-game file"));
+            dlg_form.appendChild(a);
+            dlg_form.appendChild(document.createTextNode("."));
+            dlg_form.appendChild(document.createElement("br"));
+            dialog_launch(function(event) {
+                dialog_cleanup();
+            });
+        }
     };
 
+    document.getElementById("load").onclick = function(event) {
+        if (dlg_dimmer === null) {
+            dialog_init("Upload saved-game file");
+            var input = document.createElement("input");
+            input.type = "file";
+            input.multiple = false;
+            dlg_form.appendChild(input);
+            dlg_form.appendChild(document.createElement("br"));
+            dialog_launch(function(event) {
+                if (input.files.length == 1) {
+                    var file = input.files.item(0);
+                    var reader = new FileReader();
+                    reader.addEventListener("loadend", function() {
+                        var string = reader.result;
+                        load_game(string, string.length);
+                    });
+                    reader.readAsBinaryString(file);
+                }
+                dialog_cleanup();
+            }, function(event) {
+                dialog_cleanup();
+            });
+        }
+    };
+
+    gametypelist = document.getElementById("gametype");
+    gametypesubmenus.push(gametypelist);
+
+    // In IE, the canvas doesn't automatically gain focus on a mouse
+    // click, so make sure it does
+    onscreen_canvas.addEventListener("mousedown", function(event) {
+        onscreen_canvas.focus();
+    });
+
     // In our dialog boxes, Return and Escape should be like pressing
     // OK and Cancel respectively
     document.addEventListener("keydown", function(event) {
@@ -257,11 +385,88 @@ function initPuzzle() {
     // Default to giving keyboard focus to the puzzle.
     onscreen_canvas.focus();
 
+    // Create the resize handle.
+    var resize_handle = document.createElement("canvas");
+    resize_handle.width = 10;
+    resize_handle.height = 10;
+    {
+        var ctx = resize_handle.getContext("2d");
+        ctx.beginPath();
+        for (var i = 1; i <= 7; i += 3) {
+            ctx.moveTo(8.5, i + 0.5);
+            ctx.lineTo(i + 0.5, 8.5);
+        }
+        ctx.lineWidth = '1px';
+        ctx.lineCap = 'round';
+        ctx.lineJoin = 'round';
+        ctx.strokeStyle = '#000000';
+        ctx.stroke();
+    }
+    resizable_div = document.getElementById("resizable");
+    resizable_div.appendChild(resize_handle);
+    resize_handle.style.position = 'absolute';
+    resize_handle.style.zIndex = 98;
+    resize_handle.style.bottom = "0";
+    resize_handle.style.right = "0";
+    resize_handle.style.cursor = "se-resize";
+    resize_handle.title = "Drag to resize the puzzle. Right-click to restore the default size.";
+    var resize_xbase = null, resize_ybase = null, restore_pending = false;
+    var resize_xoffset = null, resize_yoffset = null;
+    var resize_puzzle = Module.cwrap('resize_puzzle',
+                                     'void', ['number', 'number']);
+    var restore_puzzle_size = Module.cwrap('restore_puzzle_size', 'void', []);
+    resize_handle.oncontextmenu = function(event) { return false; }
+    resize_handle.onmousedown = function(event) {
+        if (event.button == 0) {
+            var xy = element_coords(onscreen_canvas);
+            resize_xbase = xy.x + onscreen_canvas.width / 2;
+            resize_ybase = xy.y;
+            resize_xoffset = xy.x + onscreen_canvas.width - event.pageX;
+            resize_yoffset = xy.y + onscreen_canvas.height - event.pageY;
+        } else {
+            restore_pending = true;
+        }
+        resize_handle.setCapture(true);
+        event.preventDefault();
+    };
+    window.addEventListener("mousemove", function(event) {
+        if (resize_xbase !== null && resize_ybase !== null) {
+            resize_puzzle((event.pageX + resize_xoffset - resize_xbase) * 2,
+                          (event.pageY + resize_yoffset - resize_ybase));
+            event.preventDefault();
+            // Chrome insists on selecting text during a resize drag
+            // no matter what I do
+            if (window.getSelection)
+                window.getSelection().removeAllRanges();
+            else
+                document.selection.empty();        }
+    });
+    window.addEventListener("mouseup", function(event) {
+        if (resize_xbase !== null && resize_ybase !== null) {
+            resize_xbase = null;
+            resize_ybase = null;
+            onscreen_canvas.focus(); // return focus to the puzzle
+            event.preventDefault();
+        } else if (restore_pending) {
+            // If you have the puzzle at larger than normal size and
+            // then right-click to restore, I haven't found any way to
+            // stop Chrome and IE popping up a context menu on the
+            // revealed piece of document when you release the button
+            // except by putting the actual restore into a setTimeout.
+            // Gah.
+            setTimeout(function() {
+                restore_pending = false;
+                restore_puzzle_size();
+                onscreen_canvas.focus();
+            }, 20);
+            event.preventDefault();
+        }
+    });
+
     // Run the C setup function, passing argv[1] as the fragment
     // identifier (so that permalinks of the form puzzle.html#game-id
     // can launch the specified id).
-    Module.arguments = [location.hash];
-    Module.run();
+    Module.callMain([location.hash]);
 
     // And if we get here with everything having gone smoothly, i.e.
     // we haven't crashed for one reason or another during setup, then