<commit_before>console.log ("inside helloiostableview.js");

import { NSBundle, NSObject, NSRect } from '$pirouette/foundation';
import { chainCtor, instanceSelector, sig } from '$pirouette/objc';
import { GLKViewController, GLKCanvasView, GLKViewDrawableDepthFormat } from '$pirouette/glkit';
import * as ui from '$pirouette/uikit';

// the mdn samples use importScripts (old functionality from coffeekit) which doesn't exist in pirouette.
// import * as mdn_sample2 from './webgl-samples/sample2/sample';
// import * as mdn_sample3 from './webgl-samples/sample3/sample';
// import * as mdn_sample4 from './webgl-samples/sample4/sample';
// import * as mdn_sample5 from './webgl-samples/sample5/sample';

import * as j3d_cube    from './j3d/HelloCube';
import * as j3d_lights  from './j3d/HelloLights';
import * as j3d_scene   from './j3d/HelloScene';
import * as j3d_head    from './j3d/HelloHead';
import * as j3d_cubemap from './j3d/HelloCubemap';
import * as j3d_plasma  from './j3d/HelloPlasma';

let HelloIOSViewController = ui.UIViewController.extendClass("HelloIOSViewController", {});

let GLKCanvasViewController = GLKViewController.extendClass("GLKCanvasViewController", () => ({

    constructor: function (handle) {
      chainCtor(GLKCanvasViewController, this, arguments);
      if (!handle)
        this.initWithNibNameAndBundle(null, null);
    },

    loadView: instanceSelector().returns(() => sig.Void).impl(function() {
                this.view = new GLKCanvasView().initWithFrame(ui.UIScreen.mainScreen.bounds);
                this.view.drawableDepthFormat = GLKViewDrawableDepthFormat.depth16;
              })
}));

let TargetActionProxy1 = NSObject.extendClass("TargetActionProxy1", () => ({
    constructor: function(fn) {
      chainCtor(TargetActionProxy1, this);
      this.fn = fn;
    },

    proxyAction: instanceSelector("action").returns(() => sig.Void).impl (function (a1) { return this.fn(a1); })
}));

let HelloIOSAppDelegate = NSObject.extendClass("HelloIOSAppDelegate", () => ({

    constructor: function () {
      console.log ("made it to HelloIOSAppDelegate.ctor");
      chainCtor(HelloIOSAppDelegate, this, arguments);
    },

    runGLDemo: function(demoName, demo) {
	function uiAlertOnException(f) {
            try {
		f();
		return true;
            } catch (e) {
		console.log(e);
		new ui.UIAlertView().init("Exception in demo script", e, null, "Ok", null).show();
		return false;
            }
	};

	let glkcontroller = new GLKCanvasViewController;
	let canvas = glkcontroller.view;

	glkcontroller.delegate = {
	    update: typeof(demo.update) === "function" ? demo.update : () => void 0
	};

	canvas.delegate = {
	    drawInRect: demo.draw
	};

	if (demo.tap) {
	    let tapProxy = new TargetActionProxy1(demo.tap);
            canvas.addGestureRecognizer(new ui.UITapGestureRecognizer().initWithTarget(tapProxy, tapProxy.proxyAction));
	}

	demo.run(canvas);

	glkcontroller.title = "" + demoName;
	this.window.rootViewController.pushViewController(glkcontroller, true);
    },

    workerDemo: function() {
      let screenBounds = ui.UIScreen.mainScreen.bounds;
      let newcontroller = new HelloIOSViewController("HelloIOSViewController", null);
      let primeButton = ui.UIButton.buttonWithType(ui.UIButtonType.roundedRect);
      primeButton.title = "Click to generate primes";
      primeButton.frame = new NSRect(screenBounds.width / 2 - 100, screenBounds.height / 2 - 50, 200, 50);

      let primeTextField = new ui.UITextField().initWithFrame(new NSRect(0, screenBounds.height / 2 + 50, screenBounds.width, 50));
      primeTextField.textAlignment = ui.UITextAlignment.center;

      let primeCount = 0;

      let worker;

      primeButton.clicked = () => {
        if (worker) {
          primeButton = "Click to generate primes";
          primeTextField.text = "";
          worker.close();
          worker = null;
        } else {
          primeButton = "Click to stop";
/*
          worker = new Worker('./prime-worker');
          worker.onmessage = (msg) => {
            primeTextField.text = "Prime " + (++primeCount) + ": " + msg;
          };
*/
        }
      };

      newcontroller.title = "Web Workers";
      newcontroller.view.addSubviews(primeButton, primeTextField);
      this.window.rootViewController.pushViewController(newcontroller, true);
    },

    xhrDemo: function() {
      let screenBounds = ui.UIScreen.mainScreen.bounds;
      let newcontroller = new ui.UIViewController();
      newcontroller.view.backgroundColor = ui.UIColor.whiteColor;
      newcontroller.title = "XMLHttpRequest";

      let xhrButton = ui.UIButton.buttonWithType(ui.UIButtonType.roundedRect);
      xhrButton.title = "Click to fetch google.com";
      xhrButton.frame = new NSRect(screenBounds.width / 2 - 100, screenBounds.height / 2 - 50, 250, 50);

      let xhrTextView = new ui.UITextView().initWithFrame(new NSRect(0, screenBounds.height / 2 + 50, screenBounds.width, screenBounds.height - (screenBounds.height / 2 + 50)), null);
      xhrTextView.textAlignment = ui.UITextAlignment.center;

      xhrButton.clicked = () => {
	console.log ("clicked!");
        let xhr = new XMLHttpRequest;
        xhr.open("GET", "https://google.com/");
        xhr.onreadystatechange = () => {
	  console.log ("onreadystatechange!");
          if (xhr.readyState === 4) {
	      console.log ("response = " + xhr.responseText);
	      console.log ("status = " + xhr.statusText);
              xhrTextView.text = "response = " + xhr.responseText;
	  }
        };
	  console.log ("sending!");
        xhr.send();
      };
      newcontroller.view.addSubview(xhrButton);
      newcontroller.view.addSubview(xhrTextView);
      this.window.rootViewController.pushViewController(newcontroller, true);
    },

    didFinishLaunching: instanceSelector("application:didFinishLaunchingWithOptions:").impl(function() {
      console.log ("inside HelloIOAppDelegate.didFinishLaunching");
      this.window = new ui.UIWindow().initWithFrame(ui.UIScreen.mainScreen.bounds);

      let tableviewcontroller = new ui.UITableViewController().initWithStyle(ui.UITableViewStyle.plain);
      tableviewcontroller.title = "Pirouette Demos";

      let tableData = [ { title: "Web Workers",
                           rows: [ { title: "Primes in a button",  clicked: () => this.workerDemo() } ] },
                        { title: "XMLHttpRequest",
                           rows: [ { title: "Simple fetch",        clicked: () => this.xhrDemo() } ] },
                        { title: "WebGL",
                           rows: [
			       // { title: "MDN sample 2", 	   clicked: () => this.runGLDemo("sample2", mdn_sample2) },
                               // { title: "MDN sample 3", 	   clicked: () => this.runGLDemo("sample3", mdn_sample3) },
                               // { title: "MDN sample 4", 	   clicked: () => this.runGLDemo("sample4", mdn_sample4) },
                               // { title: "MDN sample 5", 	   clicked: () => this.runGLDemo("sample5", mdn_sample5) },
                               { title: "J3D Engine: Cube",    clicked: () => this.runGLDemo("Cube",    j3d_cube) },
                               { title: "J3D Engine: Lights",  clicked: () => this.runGLDemo("Lights",  j3d_lights) },
                               { title: "J3D Engine: Scene",   clicked: () => this.runGLDemo("Scene",   j3d_scene) },
                               { title: "J3D Engine: Head",    clicked: () => this.runGLDemo("Head",    j3d_head) },
                               { title: "J3D Engine: Cubemap", clicked: () => this.runGLDemo("Cubemap", j3d_cubemap) },
                               { title: "J3D Engine: Plasma",  clicked: () => this.runGLDemo("Plasma",  j3d_plasma) }
			   ] }
                      ];

      let pathToItem = (arr, pos, path) => {
        let item = arr[path.indexAtPosition(pos)];
        if (pos === (path.length - 1)) {
          return item;
        } else {
          return pathToItem(item.rows, pos + 1, path);
        }
      };
      tableviewcontroller.tableView.delegate = {
        didSelectRow:               (tv, path) => pathToItem(tableData, 0, path).clicked()
      };
      tableviewcontroller.tableView.dataSource = {
        numberOfSections:                   () => tableData.length,
        numberOfRowsInSection:   (tv, section) => tableData[section].rows.length,
        titleForHeaderInSection: (tv, section) => tableData[section].title,
        cellForRow:                 (tv, path) => {
          let cell = tv.dequeueReusableCellWithIdentifier("reuse") || new ui.UITableViewCell().initWithStyle(ui.UITableViewCellStyle.value1, "reuse");
          cell.textLabel.text = pathToItem(tableData, 0, path).title;
          return cell;
        }
      };

      let navController = new ui.UINavigationController().initWithRootViewController(tableviewcontroller);
      navController.toolbarHidden = ui.UIDevice.currentDevice.userInterfaceIdiom !== ui.UIUserInterfaceIdiom.pad;
      this.window.rootViewController = navController;

      this.window.makeKeyAndVisible();
      return true;
    })
}));

console.log ("before chdir");
process.chdir(NSBundle.mainBundle.bundlePath);
console.log ("after chdir");

console.log ("before UIApplication.main, delegate name = " + HelloIOSAppDelegate._ck_register);
ui.UIApplication.main(process.argv, null, "HelloIOSAppDelegate" /*HelloIOSAppDelegate._ck_register*/);
console.log ("UIApplication.main returned, wtf");
<commit_msg>re-order the imports so objc gets pulled in first.  need to figure this out, definitely<commit_after>console.log ("inside helloiostableview.js");

import { chainCtor, instanceSelector, sig } from '$pirouette/objc';
import { NSBundle, NSObject, NSRect } from '$pirouette/foundation';
import { GLKViewController, GLKCanvasView, GLKViewDrawableDepthFormat } from '$pirouette/glkit';
import * as ui from '$pirouette/uikit';

// the mdn samples use importScripts (old functionality from coffeekit) which doesn't exist in pirouette.
// import * as mdn_sample2 from './webgl-samples/sample2/sample';
// import * as mdn_sample3 from './webgl-samples/sample3/sample';
// import * as mdn_sample4 from './webgl-samples/sample4/sample';
// import * as mdn_sample5 from './webgl-samples/sample5/sample';

import * as j3d_cube    from './j3d/HelloCube';
import * as j3d_lights  from './j3d/HelloLights';
import * as j3d_scene   from './j3d/HelloScene';
import * as j3d_head    from './j3d/HelloHead';
import * as j3d_cubemap from './j3d/HelloCubemap';
import * as j3d_plasma  from './j3d/HelloPlasma';

let HelloIOSViewController = ui.UIViewController.extendClass("HelloIOSViewController", {});

let GLKCanvasViewController = GLKViewController.extendClass("GLKCanvasViewController", () => ({

    constructor: function (handle) {
      chainCtor(GLKCanvasViewController, this, arguments);
      if (!handle)
        this.initWithNibNameAndBundle(null, null);
    },

    loadView: instanceSelector().returns(() => sig.Void).impl(function() {
                this.view = new GLKCanvasView().initWithFrame(ui.UIScreen.mainScreen.bounds);
                this.view.drawableDepthFormat = GLKViewDrawableDepthFormat.depth16;
              })
}));

let TargetActionProxy1 = NSObject.extendClass("TargetActionProxy1", () => ({
    constructor: function(fn) {
      chainCtor(TargetActionProxy1, this);
      this.fn = fn;
    },

    proxyAction: instanceSelector("action").returns(() => sig.Void).impl (function (a1) { return this.fn(a1); })
}));

let HelloIOSAppDelegate = NSObject.extendClass("HelloIOSAppDelegate", () => ({

    constructor: function () {
      console.log ("made it to HelloIOSAppDelegate.ctor");
      chainCtor(HelloIOSAppDelegate, this, arguments);
    },

    runGLDemo: function(demoName, demo) {
	function uiAlertOnException(f) {
            try {
		f();
		return true;
            } catch (e) {
		console.log(e);
		new ui.UIAlertView().init("Exception in demo script", e, null, "Ok", null).show();
		return false;
            }
	};

	let glkcontroller = new GLKCanvasViewController;
	let canvas = glkcontroller.view;

	glkcontroller.delegate = {
	    update: typeof(demo.update) === "function" ? demo.update : () => void 0
	};

	canvas.delegate = {
	    drawInRect: demo.draw
	};

	if (demo.tap) {
	    let tapProxy = new TargetActionProxy1(demo.tap);
            canvas.addGestureRecognizer(new ui.UITapGestureRecognizer().initWithTarget(tapProxy, tapProxy.proxyAction));
	}

	demo.run(canvas);

	glkcontroller.title = "" + demoName;
	this.window.rootViewController.pushViewController(glkcontroller, true);
    },

    workerDemo: function() {
      let screenBounds = ui.UIScreen.mainScreen.bounds;
      let newcontroller = new HelloIOSViewController("HelloIOSViewController", null);
      let primeButton = ui.UIButton.buttonWithType(ui.UIButtonType.roundedRect);
      primeButton.title = "Click to generate primes";
      primeButton.frame = new NSRect(screenBounds.width / 2 - 100, screenBounds.height / 2 - 50, 200, 50);

      let primeTextField = new ui.UITextField().initWithFrame(new NSRect(0, screenBounds.height / 2 + 50, screenBounds.width, 50));
      primeTextField.textAlignment = ui.UITextAlignment.center;

      let primeCount = 0;

      let worker;

      primeButton.clicked = () => {
        if (worker) {
          primeButton = "Click to generate primes";
          primeTextField.text = "";
          worker.close();
          worker = null;
        } else {
          primeButton = "Click to stop";
/*
          worker = new Worker('./prime-worker');
          worker.onmessage = (msg) => {
            primeTextField.text = "Prime " + (++primeCount) + ": " + msg;
          };
*/
        }
      };

      newcontroller.title = "Web Workers";
      newcontroller.view.addSubviews(primeButton, primeTextField);
      this.window.rootViewController.pushViewController(newcontroller, true);
    },

    xhrDemo: function() {
      let screenBounds = ui.UIScreen.mainScreen.bounds;
      let newcontroller = new ui.UIViewController();
      newcontroller.view.backgroundColor = ui.UIColor.whiteColor;
      newcontroller.title = "XMLHttpRequest";

      let xhrButton = ui.UIButton.buttonWithType(ui.UIButtonType.roundedRect);
      xhrButton.title = "Click to fetch google.com";
      xhrButton.frame = new NSRect(screenBounds.width / 2 - 100, screenBounds.height / 2 - 50, 250, 50);

      let xhrTextView = new ui.UITextView().initWithFrame(new NSRect(0, screenBounds.height / 2 + 50, screenBounds.width, screenBounds.height - (screenBounds.height / 2 + 50)), null);
      xhrTextView.textAlignment = ui.UITextAlignment.center;

      xhrButton.clicked = () => {
	console.log ("clicked!");
        let xhr = new XMLHttpRequest;
        xhr.open("GET", "https://google.com/");
        xhr.onreadystatechange = () => {
	  console.log ("onreadystatechange!");
          if (xhr.readyState === 4) {
	      console.log ("response = " + xhr.responseText);
	      console.log ("status = " + xhr.statusText);
              xhrTextView.text = "response = " + xhr.responseText;
	  }
        };
	  console.log ("sending!");
        xhr.send();
      };
      newcontroller.view.addSubview(xhrButton);
      newcontroller.view.addSubview(xhrTextView);
      this.window.rootViewController.pushViewController(newcontroller, true);
    },

    didFinishLaunching: instanceSelector("application:didFinishLaunchingWithOptions:").impl(function() {
      console.log ("inside HelloIOAppDelegate.didFinishLaunching");
      this.window = new ui.UIWindow().initWithFrame(ui.UIScreen.mainScreen.bounds);

      let tableviewcontroller = new ui.UITableViewController().initWithStyle(ui.UITableViewStyle.plain);
      tableviewcontroller.title = "Pirouette Demos";

      let tableData = [ { title: "Web Workers",
                           rows: [ { title: "Primes in a button",  clicked: () => this.workerDemo() } ] },
                        { title: "XMLHttpRequest",
                           rows: [ { title: "Simple fetch",        clicked: () => this.xhrDemo() } ] },
                        { title: "WebGL",
                           rows: [
			       // { title: "MDN sample 2", 	   clicked: () => this.runGLDemo("sample2", mdn_sample2) },
                               // { title: "MDN sample 3", 	   clicked: () => this.runGLDemo("sample3", mdn_sample3) },
                               // { title: "MDN sample 4", 	   clicked: () => this.runGLDemo("sample4", mdn_sample4) },
                               // { title: "MDN sample 5", 	   clicked: () => this.runGLDemo("sample5", mdn_sample5) },
                               { title: "J3D Engine: Cube",    clicked: () => this.runGLDemo("Cube",    j3d_cube) },
                               { title: "J3D Engine: Lights",  clicked: () => this.runGLDemo("Lights",  j3d_lights) },
                               { title: "J3D Engine: Scene",   clicked: () => this.runGLDemo("Scene",   j3d_scene) },
                               { title: "J3D Engine: Head",    clicked: () => this.runGLDemo("Head",    j3d_head) },
                               { title: "J3D Engine: Cubemap", clicked: () => this.runGLDemo("Cubemap", j3d_cubemap) },
                               { title: "J3D Engine: Plasma",  clicked: () => this.runGLDemo("Plasma",  j3d_plasma) }
			   ] }
                      ];

      let pathToItem = (arr, pos, path) => {
        let item = arr[path.indexAtPosition(pos)];
        if (pos === (path.length - 1)) {
          return item;
        } else {
          return pathToItem(item.rows, pos + 1, path);
        }
      };
      tableviewcontroller.tableView.delegate = {
        didSelectRow:               (tv, path) => pathToItem(tableData, 0, path).clicked()
      };
      tableviewcontroller.tableView.dataSource = {
        numberOfSections:                   () => tableData.length,
        numberOfRowsInSection:   (tv, section) => tableData[section].rows.length,
        titleForHeaderInSection: (tv, section) => tableData[section].title,
        cellForRow:                 (tv, path) => {
          let cell = tv.dequeueReusableCellWithIdentifier("reuse") || new ui.UITableViewCell().initWithStyle(ui.UITableViewCellStyle.value1, "reuse");
          cell.textLabel.text = pathToItem(tableData, 0, path).title;
          return cell;
        }
      };

      let navController = new ui.UINavigationController().initWithRootViewController(tableviewcontroller);
      navController.toolbarHidden = ui.UIDevice.currentDevice.userInterfaceIdiom !== ui.UIUserInterfaceIdiom.pad;
      this.window.rootViewController = navController;

      this.window.makeKeyAndVisible();
      return true;
    })
}));

console.log ("before chdir");
process.chdir(NSBundle.mainBundle.bundlePath);
console.log ("after chdir");

console.log ("before UIApplication.main, delegate name = " + HelloIOSAppDelegate._ck_register);
ui.UIApplication.main(process.argv, null, "HelloIOSAppDelegate" /*HelloIOSAppDelegate._ck_register*/);
console.log ("UIApplication.main returned, wtf");
<|endoftext|>


<commit_before>/*
 * 140 medley
 *
 * This is a micro-framework or a collection of small, helpful utilities for
 * common javascript tasks.
 *
 * Size:
 *   Source:  8.6 kb
 *   Minified: 821 bytes
 *   gzipped: 504 bytes
 *
 * Features:
 *  - templating - t();
 *  - local storage - s();
 *  - bind/unbind events - b();
 *  - create DOM elements - m();
 *  - DOM selector - $();
 *  - Get cross-browser xhr - j();
 *
 *
 *           DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
 *                   Version 2, December 2004
 *
 * Copyright (C) 2011 Honza Pokorny <me@honza.ca>
 *
 * Everyone is permitted to copy and distribute verbatim or modified
 * copies of this license document, and changing it is allowed as long
 * as the name is changed.
 *
 *           DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
 *  TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
 *
 *
 *   0. You just DO WHAT THE FUCK YOU WANT TO.
 */

/*
 * Templating
 *
 * Usage:
 *  var hello = t("Hello, #{this.name || 'world'}!")
 *
 *  console.log( // => "Hello, Jed!"
 *    hello({name: "Jed"})
 *  )
 *
 *
 *
 *            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
 *                    Version 2, December 2004
 *
 * Copyright (C) 2011 Jed Schmidt <http://jed.is>
 *
 * Everyone is permitted to copy and distribute verbatim or modified
 * copies of this license document, and changing it is allowed as long
 * as the name is changed.
 *
 *            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
 *   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
 *
 *
 *    0. You just DO WHAT THE FUCK YOU WANT TO.
 *
 *  More: https://gist.github.com/964762
 */

var t = function(
  a, // the string source from which the template is compiled
  b  // the default `with` context of the template (optional)
){
  return function(
    c, // the object called as `this` in the template
    d  // the `with` context of this template call (optional)
  ){
    return a.replace(
      /#{([^}]*)}/g, // a regexp that finds the interpolated code: "#{}"
      function(
        a, // not used, only positional
        e  // the code matched by the interpolation
      ){
        return Function(
          "x",
          "with(x)return " + e // the result of the interpolated code
        ).call(
          c,    // pass the data object as `this`, with
          d     // the most
          || b  // specific
          || {} // context.
        )
      }
    )
  }
};

/*
 * LocalStorage
 *
 * Usage:
 *
 *
 *
 *            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
 *                    Version 2, December 2004
 *
 * Copyright (C) 2011 Jed Schmidt <http://jed.is>
 *
 * Everyone is permitted to copy and distribute verbatim or modified
 * copies of this license document, and changing it is allowed as long
 * as the name is changed.
 *
 *            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
 *   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
 *
 *
 *    0. You just DO WHAT THE FUCK YOU WANT TO.
 *
 *  More: https://gist.github.com/966030
 *
 */

var s = function(
  a, // placeholder for storage object
  b  // placeholder for JSON
){
  return b
    ? {                 // if JSON is supported
      get: function(    // provide a getter function
        c               // that takes a key
      ){
        return a[c] &&  // and if the key exists
          b.parse(a[c]) // parses and returns it,
      },

      set: function(     // and a setter function
        c,               // that takes a key
        d                // and a value
      ){
        a[c] =           // and sets
          b.stringify(d) // its serialization.
      }
    }
    : {}                 // if JSON isn't supported, provide a shim.
}(
  this.localStorage // use native localStorage if available
  || {},            // or an object otherwise
  JSON              // use native JSON (required)
)

/*
 * Bind/Unbind events
 *
 * Usage:
 *   var el = document.getElementyById('#container');
 *   b(el, 'click', function() {
 *     console.log('clicked');
 *   });
 *
 *
 *            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
 *                    Version 2, December 2004
 *
 * Copyright (C) 2011 Jed Schmidt <http://jed.is>
 *
 * Everyone is permitted to copy and distribute verbatim or modified
 * copies of this license document, and changing it is allowed as long
 * as the name is changed.
 *
 *            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
 *   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
 *
 *
 *    0. You just DO WHAT THE FUCK YOU WANT TO.
 *
 *  More: https://gist.github.com/968186
 *
 */

var p = function(
  a, // a DOM element
  b, // an event name such as "click"
  c, // (placeholder)
  d  // (placeholder)
){
  c = c || document; // use the document by default
  d = c[             // save the current onevent　handler
    b = "on" + b     // prepent the event name with "on"
  ];
  a = c[b] =                 // cache and replace the current handler
    function(e) {            // with a function that
      d = d && d(            // executes/caches the previous handler
        e = e || c.event     // with a cross-browser object,
      );

      return (a = a && b(e)) // and calls the passed function,
        ? b                  // returning the current handler if it rebinds
        : d                  // and the previous handler otherwise.
    };
  c = this // cache the window to fetch IE events
};

/*
 * Create DOM element
 *
 * Usage:
 *   var el = m('
Hello
');
 *   document.body.appendChild(el);
 *
 *
 *            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
 *                    Version 2, December 2004
 *
 * Copyright (C) 2011 Jed Schmidt <http://jed.is>
 *
 * Everyone is permitted to copy and distribute verbatim or modified
 * copies of this license document, and changing it is allowed as long
 * as the name is changed.
 *
 *            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
 *   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
 *
 *
 *    0. You just DO WHAT THE FUCK YOU WANT TO.
 *
 *  More: https://gist.github.com/966233
 *
 */

var m = function(
  a, // an HTML string
  b, // placeholder
  c  // placeholder
){
  b = document;                   // get the document,
  c = b.createElement("p");       // create a container element,
  c.innerHTML = a;                // write the HTML to it, and
  a = b.createDocumentFragment(); // create a fragment.

  while (                         // while
    b = c.firstChild              // the container element has a first child
  ) a.appendChild(b);             // append the child to the fragment,

  return a                        // and then return the fragment.
}

/*
 * DOM selector
 *
 * Usage:
 *   $('div');
 *   $('#name');
 *   $('.name');
 *
 *
 *            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
 *                    Version 2, December 2004
 *
 * Copyright (C) 2011 Jed Schmidt <http://jed.is>
 *
 * Everyone is permitted to copy and distribute verbatim or modified
 * copies of this license document, and changing it is allowed as long
 * as the name is changed.
 *
 *            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
 *   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
 *
 *
 *    0. You just DO WHAT THE FUCK YOU WANT TO.
 *
 *  More: https://gist.github.com/991057
 *
 */

var $ = function(
  a,                         // take a simple selector like "name", "#name", or ".name", and
  b                          // an optional context, and
){
  a = a.match(/^(\W)?(.*)/); // split the selector into name and symbol.
  return(                    // return an element or list, from within the scope of
    b                        // the passed context
    || document              // or document,
  )[
    "getElement" + (         // obtained by the appropriate method calculated by
      b = a[1]
        ? b == "#"
          ? "ById"           // the node by ID,
          : "sByClassName"   // the nodes by class name, or
        : "sByTagName"       // the nodes by tag name,
    )
  ](
    a[2]                     // called with the name.
  )
}

/*
 * Get cross browser xhr object
 *
 *
 *            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
 *                    Version 2, December 2004
 *
 * Copyright (C) 2011 Jed Schmidt <http://jed.is>
 *
 * Everyone is permitted to copy and distribute verbatim or modified
 * copies of this license document, and changing it is allowed as long
 * as the name is changed.
 *
 *            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
 *   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
 *
 *
 *    0. You just DO WHAT THE FUCK YOU WANT TO.
 *
 *  More: https://gist.github.com/993585
 *
 */

var j = function(
  a // cursor placeholder
){
  for(                     // for all a
    a=0;                   // from 0
    a<4;                   // to 4,
    a++                    // incrementing
  ) try {                  // try
    return a               // returning
      ? new ActiveXObject( // a new ActiveXObject
          [                // reflecting
            ,              // (elided)
            "Msxml2",      // the various
            "Msxml3",      // working
            "Microsoft"    // options
          ][a] +           // for Microsoft implementations, and
          ".XMLHTTP"       // the appropriate suffix,
        )                  // but make sure to
      : new XMLHttpRequest // try the w3c standard first, and
  }

  catch(e){}               // ignore when it fails.
}

<commit_msg>Make in-code license less obnoxious<commit_after>/*
 * 140 medley
 * (c) 2011 - Honza Pokorny
 * Licensed under the terms of the BSD license
 *
 * This is a micro-framework or a collection of small, helpful utilities for
 * common javascript tasks.
 *
 * Size:
 *   Source:  8.6 kb
 *   Minified: 821 bytes
 *   gzipped: 504 bytes
 *
 * Features:
 *  - templating - t();
 *  - local storage - s();
 *  - bind/unbind events - b();
 *  - create DOM elements - m();
 *  - DOM selector - $();
 *  - Get cross-browser xhr - j();
 *
 */

/*
 * Templating
 *
 * Usage:
 *  var hello = t("Hello, #{this.name || 'world'}!")
 *
 *  console.log( // => "Hello, Jed!"
 *    hello({name: "Jed"})
 *  )
 *
 * Copyright (C) 2011 Jed Schmidt <http://jed.is> - WTFPL
 * More: https://gist.github.com/964762
 */

var t = function(
  a, // the string source from which the template is compiled
  b  // the default `with` context of the template (optional)
){
  return function(
    c, // the object called as `this` in the template
    d  // the `with` context of this template call (optional)
  ){
    return a.replace(
      /#{([^}]*)}/g, // a regexp that finds the interpolated code: "#{}"
      function(
        a, // not used, only positional
        e  // the code matched by the interpolation
      ){
        return Function(
          "x",
          "with(x)return " + e // the result of the interpolated code
        ).call(
          c,    // pass the data object as `this`, with
          d     // the most
          || b  // specific
          || {} // context.
        )
      }
    )
  }
};

/*
 * LocalStorage
 *
 * Copyright (C) 2011 Jed Schmidt <http://jed.is> - WTFPL
 * More: https://gist.github.com/966030
 *
 */

var s = function(
  a, // placeholder for storage object
  b  // placeholder for JSON
){
  return b
    ? {                 // if JSON is supported
      get: function(    // provide a getter function
        c               // that takes a key
      ){
        return a[c] &&  // and if the key exists
          b.parse(a[c]) // parses and returns it,
      },

      set: function(     // and a setter function
        c,               // that takes a key
        d                // and a value
      ){
        a[c] =           // and sets
          b.stringify(d) // its serialization.
      }
    }
    : {}                 // if JSON isn't supported, provide a shim.
}(
  this.localStorage // use native localStorage if available
  || {},            // or an object otherwise
  JSON              // use native JSON (required)
)

/*
 * Bind/Unbind events
 *
 * Usage:
 *   var el = document.getElementyById('#container');
 *   b(el, 'click', function() {
 *     console.log('clicked');
 *   });
 *
 * Copyright (C) 2011 Jed Schmidt <http://jed.is> - WTFPL
 * More: https://gist.github.com/968186
 *
 */

var p = function(
  a, // a DOM element
  b, // an event name such as "click"
  c, // (placeholder)
  d  // (placeholder)
){
  c = c || document; // use the document by default
  d = c[             // save the current onevent　handler
    b = "on" + b     // prepent the event name with "on"
  ];
  a = c[b] =                 // cache and replace the current handler
    function(e) {            // with a function that
      d = d && d(            // executes/caches the previous handler
        e = e || c.event     // with a cross-browser object,
      );

      return (a = a && b(e)) // and calls the passed function,
        ? b                  // returning the current handler if it rebinds
        : d                  // and the previous handler otherwise.
    };
  c = this // cache the window to fetch IE events
};

/*
 * Create DOM element
 *
 * Usage:
 *   var el = m('
Hello
');
 *   document.body.appendChild(el);
 *
 *
 *            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
 *                    Version 2, December 2004
 *
 * Copyright (C) 2011 Jed Schmidt <http://jed.is> - WTFPL
 * More: https://gist.github.com/966233
 *
 */

var m = function(
  a, // an HTML string
  b, // placeholder
  c  // placeholder
){
  b = document;                   // get the document,
  c = b.createElement("p");       // create a container element,
  c.innerHTML = a;                // write the HTML to it, and
  a = b.createDocumentFragment(); // create a fragment.

  while (                         // while
    b = c.firstChild              // the container element has a first child
  ) a.appendChild(b);             // append the child to the fragment,

  return a                        // and then return the fragment.
}

/*
 * DOM selector
 *
 * Usage:
 *   $('div');
 *   $('#name');
 *   $('.name');
 *
 *
 * Copyright (C) 2011 Jed Schmidt <http://jed.is> - WTFPL
 * More: https://gist.github.com/991057
 *
 */

var $ = function(
  a,                         // take a simple selector like "name", "#name", or ".name", and
  b                          // an optional context, and
){
  a = a.match(/^(\W)?(.*)/); // split the selector into name and symbol.
  return(                    // return an element or list, from within the scope of
    b                        // the passed context
    || document              // or document,
  )[
    "getElement" + (         // obtained by the appropriate method calculated by
      b = a[1]
        ? b == "#"
          ? "ById"           // the node by ID,
          : "sByClassName"   // the nodes by class name, or
        : "sByTagName"       // the nodes by tag name,
    )
  ](
    a[2]                     // called with the name.
  )
}

/*
 * Get cross browser xhr object
 *
 *
 *            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
 *                    Version 2, December 2004
 *
 * Copyright (C) 2011 Jed Schmidt <http://jed.is>
 * More: https://gist.github.com/993585
 *
 */

var j = function(
  a // cursor placeholder
){
  for(                     // for all a
    a=0;                   // from 0
    a<4;                   // to 4,
    a++                    // incrementing
  ) try {                  // try
    return a               // returning
      ? new ActiveXObject( // a new ActiveXObject
          [                // reflecting
            ,              // (elided)
            "Msxml2",      // the various
            "Msxml3",      // working
            "Microsoft"    // options
          ][a] +           // for Microsoft implementations, and
          ".XMLHTTP"       // the appropriate suffix,
        )                  // but make sure to
      : new XMLHttpRequest // try the w3c standard first, and
  }

  catch(e){}               // ignore when it fails.
}

<|endoftext|>


<commit_before>export default class Shader {
  static add(string = "void main() {}", chunks) {
    for (const [key, chunk] of chunks) {
      switch (key) {
        case "start":
          string = string.replace(/^(#version .*?\n(\s*precision highp float;\s)?)?([\s\S]*)/, `$1\n${chunk}\n$3`);
          break;
        case "end":
          string = string.replace(/(}\s*$)/, `\n${chunk}\n$1`);
          break;
        case "main":
          string = string.replace(/(\bvoid\b +\bmain\b[\s\S]*?{\s*)/, `$1\n${chunk}\n`);
          break;
        default:
          string = string.replace(key, chunk);
      }
    }

    return string;
  }

  constructor({
    vertexShader = `#version 300 es
      void main() {
        gl_Position = vec4(0., 0., 0., 1.);
      }
    `,
    fragmentShader = `#version 300 es
      precision highp float;

      out vec4 fragColor;

      void main() {
        fragColor = vec4(1.);
      }
    `,
    dataTypeConctructors = {
      Vector2: class Vector2 extends Float32Array {
        constructor() {
          super(2);
        }
      },
      Vector3: class Vector3 extends Float32Array {
        constructor() {
          super(3);
        }
      },
      Vector4: class Vector4 extends Float32Array {
        constructor() {
          super(4);
        }
      },
      Matrix3: class Matrix3 extends Float32Array {
        constructor() {
          super([1, 0, 0, 0, 1, 0, 0, 0, 1]);
        }
      },
      Matrix4: class Matrix4 extends Float32Array {
        constructor() {
          super([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
        }
      },
      Texture: class Texture { },
      TextureCube: class TextureCube { },
    },
    uniforms = {},
    vertexShaderChunks = [],
    fragmentShaderChunks = [],
    shaders = [],
  } = {}) {
    this.uniforms = uniforms;
    this.uniformTypes = {};

    this._dataTypeConctructors = dataTypeConctructors;

    this.vertexShader = vertexShader;
    this.fragmentShader = fragmentShader;
    this._vertexShaderChunks = [];
    this._fragmentShaderChunks = [];

    this.add({ vertexShaderChunks, fragmentShaderChunks, uniforms });

    for (const shader of shaders) {
      this.add(shader);
    }
  }

  add({ vertexShaderChunks = [], fragmentShaderChunks = [], uniforms = {} } = {}) {
    this.vertexShader = Shader.add(this.vertexShader, vertexShaderChunks);
    this._vertexShaderChunks.push(...vertexShaderChunks);
    this.fragmentShader = Shader.add(this.fragmentShader, fragmentShaderChunks);
    this._fragmentShaderChunks.push(...fragmentShaderChunks);
    for (const key in uniforms) {
      this.uniforms[key] = uniforms[key];
    }
  }

  set vertexShader(value) {
    this._vertexShader = value;
    this._parseUniforms(this._vertexShader);
  }

  get vertexShader() {
    return this._vertexShader;
  }

  set fragmentShader(value) {
    this._fragmentShader = value;
    this._parseUniforms(this._fragmentShader);
  }

  get fragmentShader() {
    return this._fragmentShader;
  }

  get vertexShaderChunks() {
    return this._vertexShaderChunks;
  }

  get fragmentShaderChunks() {
    return this._fragmentShaderChunks;
  }

  _addUniform(name, type, arrayLength) {
    let value;
    let typeMatch;

    this.uniformTypes[name] = type;

    if (/float|double/.test(type)) {
      if (isNaN(arrayLength)) {
        value = 0;
      } else {
        value = new Array(arrayLength).fill(0);
      }
    } else if (/int|uint/.test(type)) {
      if (isNaN(arrayLength)) {
        value = 0;
      } else {
        value = new Array(arrayLength).fill(0);
      }
    } else if (/sampler2D/.test(type)) {
      if (isNaN(arrayLength)) {
        value = new this._dataTypeConctructors["Texture"]();
      } else {
        value = new Array(arrayLength).fill(undefined).map((value) => new this._dataTypeConctructors["Texture"]());
      }
    } else if (/samplerCube/.test(type)) {
      if (isNaN(arrayLength)) {
        value = new this._dataTypeConctructors["TextureCube"]();
      } else {
        value = new Array(arrayLength).fill(undefined).map((value) => new this._dataTypeConctructors["TextureCube"]());
      }
    } else if ((typeMatch = /(.?)vec(\d)/.exec(type))) {
      const vectorLength = typeMatch[2];
      if (isNaN(arrayLength)) {
        value = new this._dataTypeConctructors[`Vector${vectorLength}`]();
      } else {
        value = new Array(arrayLength).fill(undefined).map((value) => new this._dataTypeConctructors[`Vector${vectorLength}`]());
      }
    } else if ((typeMatch = /mat(\d)/.exec(type))) {
      const matrixLength = typeMatch[1];
      if (isNaN(arrayLength)) {
        value = new this._dataTypeConctructors[`Matrix${matrixLength}`]();
      } else {
        value = new Array(arrayLength).fill(undefined).map((value) => new this._dataTypeConctructors[`Matrix${matrixLength}`]());
      }
    } else {
      value = undefined;
    }

    this.uniforms[name] = value;
  }

  // Parse shader strings to extract uniforms

  _parseUniforms(string) {
    const structures = new Map();

    const structRegExp = /struct\s*(.*)\s*{\s*([\s\S]*?)}/g;
    const structMemberRegExp = /^\s*(.[^ ]+) (.[^ ;[\]]+)\[? *(\d+)? *\]?/gm;
    let structMatch;
    while ((structMatch = structRegExp.exec(string))) {
      const structName = structMatch[1];
      const structString = structMatch[2];

      const structure = {};
      let structMemberMatch;
      while ((structMemberMatch = structMemberRegExp.exec(structString))) {
        const [, type, name, arrayLengthStr] = structMemberMatch;
        const arrayLength = parseInt(arrayLengthStr);
        structure[name] = {
          type,
          arrayLength,
        };
      }

      structures.set(structName, structure);
    }

    const uniformsRegExp = /^\s*uniform (.[^ ]+) (.[^ ;[\]]+)\[? *(\d+)? *\]?/gm;
    let uniformMatch;
    while ((uniformMatch = uniformsRegExp.exec(string))) {
      const [, type, name, arrayLengthStr] = uniformMatch;

      const structure = structures.get(type);
      if (structure) {
        for (const key in structure) {
          this._addUniform(`${name}.${key}`, structure[key].type, structure[key].arrayLength);
        }
      } else {
        const arrayLength = parseInt(arrayLengthStr);
        this._addUniform(name, type, arrayLength);
      }
    }
  }
}
<commit_msg>fix Shader.js add uniform<commit_after>export default class Shader {
  static add(string = "void main() {}", chunks) {
    for (const [key, chunk] of chunks) {
      switch (key) {
        case "start":
          string = string.replace(/^(#version .*?\n(\s*precision highp float;\s)?)?([\s\S]*)/, `$1\n${chunk}\n$3`);
          break;
        case "end":
          string = string.replace(/(}\s*$)/, `\n${chunk}\n$1`);
          break;
        case "main":
          string = string.replace(/(\bvoid\b +\bmain\b[\s\S]*?{\s*)/, `$1\n${chunk}\n`);
          break;
        default:
          string = string.replace(key, chunk);
      }
    }

    return string;
  }

  constructor({
    vertexShader = `#version 300 es
      void main() {
        gl_Position = vec4(0., 0., 0., 1.);
      }
    `,
    fragmentShader = `#version 300 es
      precision highp float;

      out vec4 fragColor;

      void main() {
        fragColor = vec4(1.);
      }
    `,
    dataTypeConctructors = {
      Vector2: class Vector2 extends Float32Array {
        constructor() {
          super(2);
        }
      },
      Vector3: class Vector3 extends Float32Array {
        constructor() {
          super(3);
        }
      },
      Vector4: class Vector4 extends Float32Array {
        constructor() {
          super(4);
        }
      },
      Matrix3: class Matrix3 extends Float32Array {
        constructor() {
          super([1, 0, 0, 0, 1, 0, 0, 0, 1]);
        }
      },
      Matrix4: class Matrix4 extends Float32Array {
        constructor() {
          super([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
        }
      },
      Texture: class Texture { },
      TextureCube: class TextureCube { },
    },
    uniforms = {},
    vertexShaderChunks = [],
    fragmentShaderChunks = [],
    shaders = [],
  } = {}) {
    this.uniforms = uniforms;
    this.uniformTypes = {};

    this._dataTypeConctructors = dataTypeConctructors;

    this.vertexShader = vertexShader;
    this.fragmentShader = fragmentShader;
    this._vertexShaderChunks = [];
    this._fragmentShaderChunks = [];

    this.add({ vertexShaderChunks, fragmentShaderChunks, uniforms });

    for (const shader of shaders) {
      this.add(shader);
    }
  }

  add({ vertexShaderChunks = [], fragmentShaderChunks = [], uniforms = {} } = {}) {
    this.vertexShader = Shader.add(this.vertexShader, vertexShaderChunks);
    this._vertexShaderChunks.push(...vertexShaderChunks);
    this.fragmentShader = Shader.add(this.fragmentShader, fragmentShaderChunks);
    this._fragmentShaderChunks.push(...fragmentShaderChunks);
    for (const key in uniforms) {
      this.uniforms[key] = uniforms[key];
    }
  }

  set vertexShader(value) {
    this._vertexShader = value;
    this._parseUniforms(this._vertexShader);
  }

  get vertexShader() {
    return this._vertexShader;
  }

  set fragmentShader(value) {
    this._fragmentShader = value;
    this._parseUniforms(this._fragmentShader);
  }

  get fragmentShader() {
    return this._fragmentShader;
  }

  get vertexShaderChunks() {
    return this._vertexShaderChunks;
  }

  get fragmentShaderChunks() {
    return this._fragmentShaderChunks;
  }

  _addUniform(name, type, arrayLength) {
    if (this.uniforms[name] !== undefined) {
      return;
    }

    let value;
    let typeMatch;

    this.uniformTypes[name] = type;

    if (/float|double/.test(type)) {
      if (isNaN(arrayLength)) {
        value = 0;
      } else {
        value = new Array(arrayLength).fill(0);
      }
    } else if (/int|uint/.test(type)) {
      if (isNaN(arrayLength)) {
        value = 0;
      } else {
        value = new Array(arrayLength).fill(0);
      }
    } else if (/sampler2D/.test(type)) {
      if (isNaN(arrayLength)) {
        value = new this._dataTypeConctructors["Texture"]();
      } else {
        value = new Array(arrayLength).fill(undefined).map((value) => new this._dataTypeConctructors["Texture"]());
      }
    } else if (/samplerCube/.test(type)) {
      if (isNaN(arrayLength)) {
        value = new this._dataTypeConctructors["TextureCube"]();
      } else {
        value = new Array(arrayLength).fill(undefined).map((value) => new this._dataTypeConctructors["TextureCube"]());
      }
    } else if ((typeMatch = /(.?)vec(\d)/.exec(type))) {
      const vectorLength = typeMatch[2];
      if (isNaN(arrayLength)) {
        value = new this._dataTypeConctructors[`Vector${vectorLength}`]();
      } else {
        value = new Array(arrayLength).fill(undefined).map((value) => new this._dataTypeConctructors[`Vector${vectorLength}`]());
      }
    } else if ((typeMatch = /mat(\d)/.exec(type))) {
      const matrixLength = typeMatch[1];
      if (isNaN(arrayLength)) {
        value = new this._dataTypeConctructors[`Matrix${matrixLength}`]();
      } else {
        value = new Array(arrayLength).fill(undefined).map((value) => new this._dataTypeConctructors[`Matrix${matrixLength}`]());
      }
    } else {
      value = undefined;
    }

    this.uniforms[name] = value;
  }

  // Parse shader strings to extract uniforms

  _parseUniforms(string) {
    const structures = new Map();

    const structRegExp = /struct\s*(.*)\s*{\s*([\s\S]*?)}/g;
    const structMemberRegExp = /^\s*(.[^ ]+) (.[^ ;[\]]+)\[? *(\d+)? *\]?/gm;
    let structMatch;
    while ((structMatch = structRegExp.exec(string))) {
      const structName = structMatch[1];
      const structString = structMatch[2];

      const structure = {};
      let structMemberMatch;
      while ((structMemberMatch = structMemberRegExp.exec(structString))) {
        const [, type, name, arrayLengthStr] = structMemberMatch;
        const arrayLength = parseInt(arrayLengthStr);
        structure[name] = {
          type,
          arrayLength,
        };
      }

      structures.set(structName, structure);
    }

    const uniformsRegExp = /^\s*uniform (.[^ ]+) (.[^ ;[\]]+)\[? *(\d+)? *\]?/gm;
    let uniformMatch;
    while ((uniformMatch = uniformsRegExp.exec(string))) {
      const [, type, name, arrayLengthStr] = uniformMatch;

      const structure = structures.get(type);
      if (structure) {
        for (const key in structure) {
          this._addUniform(`${name}.${key}`, structure[key].type, structure[key].arrayLength);
        }
      } else {
        const arrayLength = parseInt(arrayLengthStr);
        this._addUniform(name, type, arrayLength);
      }
    }
  }
}
<|endoftext|>


<commit_before>var bower = require("bower");

var Path = require("path")
var fs = require("fs")
var Q = require("Q");
Q.longStackSupport = true;

_3scaffold = (function() {

  function _3scaffold() {}

  _3scaffold.setup= function (options){

    fs.mkdir( Path.join( process.cwd(), options.folder ), function(){} );
    fs.mkdir( Path.join( process.cwd(), options.folder , "apps" ), function(){} );
    fs.mkdir( Path.join( process.cwd(), options.folder , "apps", "dependencies" ), function(){} );
    fs.mkdir( Path.join( process.cwd(), options.folder , "tmp" ), function(){}) ;

    var templatesPath =  Path.join(Path.dirname(fs.realpathSync(__filename)), 'templates');

    console.log(templatesPath);

    var _3votJSON = require( Path.join(  templatesPath, "3vot.json" ));
    var gitIgnore = fs.readFileSync(  Path.join( templatesPath, ".gitignore" ), "utf-8");
    var pckJSON = require( Path.join( templatesPath, "package.json" ));

    _3votJSON.key = options.key;
    _3votJSON.profile = options.profile;

    fs.writeFileSync( Path.join(process.cwd(), options.folder, "3vot.json"), JSON.stringify(_3votJSON) );
    fs.writeFileSync( Path.join(process.cwd(), options.folder, "package.json"), JSON.stringify(pckJSON) );
    fs.writeFileSync( Path.join(process.cwd(), options.folder, ".gitignore"), gitIgnore );

  }

  return _3scaffold;

})();

module.exports = _3scaffold;<commit_msg>testing bin<commit_after>var bower = require("bower");

var Path = require("path")
var fs = require("fs")
var Q = require("Q");
Q.longStackSupport = true;

_3scaffold = (function() {

  function _3scaffold() {}

  _3scaffold.setup= function (options){

    fs.mkdir( Path.join( process.cwd(), options.folder ), function(){} );
    fs.mkdir( Path.join( process.cwd(), options.folder , "apps" ), function(){} );
    fs.mkdir( Path.join( process.cwd(), options.folder , "apps", "dependencies" ), function(){} );
    fs.mkdir( Path.join( process.cwd(), options.folder , "tmp" ), function(){}) ;

    var templatesPath =  Path.join(Path.dirname(fs.realpathSync(__filename)), './templates');

    console.log(templatesPath);

    var _3votJSON = require( Path.join(  templatesPath, "3vot.json" ));
    var gitIgnore = fs.readFileSync(  Path.join( templatesPath, ".gitignore" ), "utf-8");
    var pckJSON = require( Path.join( templatesPath, "package.json" ));

    _3votJSON.key = options.key;
    _3votJSON.profile = options.profile;

    fs.writeFileSync( Path.join(process.cwd(), options.folder, "3vot.json"), JSON.stringify(_3votJSON) );
    fs.writeFileSync( Path.join(process.cwd(), options.folder, "package.json"), JSON.stringify(pckJSON) );
    fs.writeFileSync( Path.join(process.cwd(), options.folder, ".gitignore"), gitIgnore );

  }

  return _3scaffold;

})();

module.exports = _3scaffold;<|endoftext|>


<commit_before>(function($, location, document, exports) {

  var view, router, model,

  loadComments = function(path, offset) {
    // clean things
    $('link').filter('[href*="disqus"]').remove();
    $('script').filter('[src*="disqus"]').remove();

    // change a few disqus variable before loading in
    exports.disqus_identifier = path;
    exports.disqus_url= path;
    exports.disqus_title = 'h5bp docs comment for ' + path;

    (function() {
      var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
      dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
      (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();
  };

  // modernizr history test
  var historyAble = !!(window.history && history.pushState);

  (function() {
    // doing it here to trigger this on non pushState able browsers too
    // we now prevent non pushState browsers from running the Backbone app
    // cause it may become tricky to deal with multiple location and so on
    // (/docs/ vs /docs/The-style/)

    var text = location.hash.replace(/^#/,''),
      parts, heading;

    // if no hash in url, does nothing
    if(!text) return;

    var links = $('.wikiconvertor-pages a');

    // also make sure we support `#thiskind#ofurl`
    parts = text.split(/(#|%23)/);
    heading = parts[1] ? ('#' + parts[parts.length - 1]) : '';

    // iterate through links and try to get a case unsensitive test with hash value
    var navlink = links.map(function() {
      var m = this.href.match(new RegExp(parts[0], 'i'));
      return m ? $(this).attr('href') : undefined;
    });

    // if navlink has elements, redirect to the first one, only when we're
    // at `/docs/` or `/docs`
    if (navlink.length && /\/docs\/?$/.test(location.pathname)) location.href = navlink[0] + heading;

  })();

  // no backbone for non push state :(
  if(!historyAble) return;

  var DocsPage = Backbone.Model.extend({
    url: function url() {
      var path = this.get('path');
      return (/^\//.test(path) ? '' : '/') + this.get('path');
    },

    parse: function(resp, xhr) {
      var m = this.get('path').match(/docs\/([^\/]+)\//),
      title = m ? m[1].replace(/-/g, ' ') : 'Home';
      return {
        title: title,
        content: $(resp).find('.wikiconvertor-content').html()
      };
    },

    // provide a sync impl for our Page Model
    sync: function(method, model, options) {
      $.ajax($.extend(options, {
        dataType: 'html',
        url: this.url()
      }));
      return this;
    }

  });

  var DocsView = Backbone.View.extend({
    el: '#body',

    events: {
      'click .wikiconvertor-pages a': 'clickHandler'
    },

    initialize: function() {
      _.bindAll(this, 'clickHandler', 'addHdrAttr', 'addPermalinks');

      // re-render when model changes
      this.model.bind('change:content', _.bind(this.render, this));
      this.model.bind('change:title', _.bind(this.updateTitle, this));

      // few dom references
      this.placeholder = this.$('.wikiconvertor-content');
      this.nav = this.$('.wikiconvertor-pages');
      this.scroller = this.options.scroll ? $('html,body') : undefined;
      this.active = this.$('.wikiconvertor-pages a[href="' + model.url() + '"]');
      this.active.closest('li').addClass('wikiconvertor-pages-active');

      // build headings and permalinks
      this.headings();
    },

    clickHandler: function clickHandler(e) {
      var target = $(e.target),
      url = target.closest('a').attr('href'),
      external = /\/\//.test(url),
      octothorpe = /#/.test(url);

      e.preventDefault();

      if(!external && !octothorpe) {
         this.active.closest('li').removeClass('wikiconvertor-pages-active');
         this.active = target.closest('li').addClass('wikiconvertor-pages-active');

         if(this.scroller) {
           this.scroller.animate({scrollTop: 0}, 500);
         }

         router.navigate(url, true);
       }
    },

    headings: function headings(text) {
      // # or ...
      var t = text || location.hash.replace(/^#/,''),
        hdr = this.placeholder.find(':header'),
        h;

      // First thing first deal with headings and add proper data-wiki-hdr attribute
      hdr
        .each(this.addHdrAttr)
        .each(this.addPermalinks);

      if(!t || !hdr.length) {
        return;
      }

      h = hdr.filter('#' + t);

      if(!h.length) {
        return;
      }

      this.scroller.animate({scrollTop: h.offset().top}, 0);
    },

    addPermalinks: function(i, header) {
      var t = $(header),
      hdr  = t.attr('id');
      $('#').appendTo(t);
    },

    addHdrAttr: function(i, header) {
      var t = $(header),
      text = t.text(),
      attr = text
        // First lower case all
        .toLowerCase()

        // Then replace any special character
        .replace(/[^a-z|A-Z|\d|\s|\-]/g, '')

        // Finally, replace all blank space by - delimiter
        .replace(/\s/g, '-');

      t.attr('id', attr);
    },

    render: function render() {
      $(this.placeholder).html(this.model.get('content'));
      this.headings();
      return this;
    },

    updateTitle: function() {
      document.title = document.title.replace(/[^|]+|/, this.model.get('title') + ' ');
    }
  });

  var DocsRouter = Backbone.Router.extend({
    routes: {
      // catch all
      '*path': 'changePage'
    },

    changePage: function changePage(path) {
      if(!path || path === model.get('path')) {
        return;
      }

      model
        .set({ path: path })
        .fetch({
          success: function() {
            // users gets comments by scolling to the bottom section

            // the only exception is when the page content is too small for that, in that case
            // load immediately

            if( view.nav.height() - 750 > view.placeholder.height() ) {
              loadComments(path);
            }
          }
        });
    }
  });

  $(function() {

    var disqus_thread = $('#disqus_thread'),
    win = $(window),
    doc = $(document),

    atBottom = function(offset) {
      offset = offset || 750;
      return win.scrollTop() > (doc.height() - win.height() - offset);
    };

    // create our app components
    model = new DocsPage({path: location.pathname.replace(/^\//, '')});
    view = new DocsView({model: model, scroll: true});
    router = new DocsRouter();

    Backbone.history.start({
      pushState: true
    });

    // listen to scrolling so that we detect when the bottom is reached
    // where we trigger disqus comments
    win.scroll(function() {
      var dsq = $('#disqus_thread');

      if(!atBottom()) return;

      // ok, user is reaching the page bottom, load comments, but only if it wasn't done before.
      // assume es5 trim method is there, since non pushstate browser would normally
      // not reach this code
      var prevent = dsq.html().trim();
      if(prevent) return;

      loadComments(model.get('path'));
    });

  });

})(this.jQuery, this.location, this.document, this);

<commit_msg>Optimize the eff out of the Disqus snippet.<commit_after>(function($, location, document, exports) {

  var view, router, model,

  loadComments = function(path, offset) {
    // clean things
    $('link').filter('[href*="disqus"]').remove();
    $('script').filter('[src*="disqus"]').remove();

    // change a few disqus variable before loading in
    exports.disqus_identifier = path;
    exports.disqus_url= path;
    exports.disqus_title = 'h5bp docs comment for ' + path;

    (function() {
      var dsq = document.createElement('script');
      dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
      (document.head || document.getElementsByTagName('head')[0] || document.body).appendChild(dsq);
    })();
  };

  // modernizr history test
  var historyAble = !!(window.history && history.pushState);

  (function() {
    // doing it here to trigger this on non pushState able browsers too
    // we now prevent non pushState browsers from running the Backbone app
    // cause it may become tricky to deal with multiple location and so on
    // (/docs/ vs /docs/The-style/)

    var text = location.hash.replace(/^#/,''),
      parts, heading;

    // if no hash in url, does nothing
    if(!text) return;

    var links = $('.wikiconvertor-pages a');

    // also make sure we support `#thiskind#ofurl`
    parts = text.split(/(#|%23)/);
    heading = parts[1] ? ('#' + parts[parts.length - 1]) : '';

    // iterate through links and try to get a case unsensitive test with hash value
    var navlink = links.map(function() {
      var m = this.href.match(new RegExp(parts[0], 'i'));
      return m ? $(this).attr('href') : undefined;
    });

    // if navlink has elements, redirect to the first one, only when we're
    // at `/docs/` or `/docs`
    if (navlink.length && /\/docs\/?$/.test(location.pathname)) location.href = navlink[0] + heading;

  })();

  // no backbone for non push state :(
  if(!historyAble) return;

  var DocsPage = Backbone.Model.extend({
    url: function url() {
      var path = this.get('path');
      return (/^\//.test(path) ? '' : '/') + this.get('path');
    },

    parse: function(resp, xhr) {
      var m = this.get('path').match(/docs\/([^\/]+)\//),
      title = m ? m[1].replace(/-/g, ' ') : 'Home';
      return {
        title: title,
        content: $(resp).find('.wikiconvertor-content').html()
      };
    },

    // provide a sync impl for our Page Model
    sync: function(method, model, options) {
      $.ajax($.extend(options, {
        dataType: 'html',
        url: this.url()
      }));
      return this;
    }

  });

  var DocsView = Backbone.View.extend({
    el: '#body',

    events: {
      'click .wikiconvertor-pages a': 'clickHandler'
    },

    initialize: function() {
      _.bindAll(this, 'clickHandler', 'addHdrAttr', 'addPermalinks');

      // re-render when model changes
      this.model.bind('change:content', _.bind(this.render, this));
      this.model.bind('change:title', _.bind(this.updateTitle, this));

      // few dom references
      this.placeholder = this.$('.wikiconvertor-content');
      this.nav = this.$('.wikiconvertor-pages');
      this.scroller = this.options.scroll ? $('html,body') : undefined;
      this.active = this.$('.wikiconvertor-pages a[href="' + model.url() + '"]');
      this.active.closest('li').addClass('wikiconvertor-pages-active');

      // build headings and permalinks
      this.headings();
    },

    clickHandler: function clickHandler(e) {
      var target = $(e.target),
      url = target.closest('a').attr('href'),
      external = /\/\//.test(url),
      octothorpe = /#/.test(url);

      e.preventDefault();

      if(!external && !octothorpe) {
         this.active.closest('li').removeClass('wikiconvertor-pages-active');
         this.active = target.closest('li').addClass('wikiconvertor-pages-active');

         if(this.scroller) {
           this.scroller.animate({scrollTop: 0}, 500);
         }

         router.navigate(url, true);
       }
    },

    headings: function headings(text) {
      // # or ...
      var t = text || location.hash.replace(/^#/,''),
        hdr = this.placeholder.find(':header'),
        h;

      // First thing first deal with headings and add proper data-wiki-hdr attribute
      hdr
        .each(this.addHdrAttr)
        .each(this.addPermalinks);

      if(!t || !hdr.length) {
        return;
      }

      h = hdr.filter('#' + t);

      if(!h.length) {
        return;
      }

      this.scroller.animate({scrollTop: h.offset().top}, 0);
    },

    addPermalinks: function(i, header) {
      var t = $(header),
      hdr  = t.attr('id');
      $('#').appendTo(t);
    },

    addHdrAttr: function(i, header) {
      var t = $(header),
      text = t.text(),
      attr = text
        // First lower case all
        .toLowerCase()

        // Then replace any special character
        .replace(/[^a-z|A-Z|\d|\s|\-]/g, '')

        // Finally, replace all blank space by - delimiter
        .replace(/\s/g, '-');

      t.attr('id', attr);
    },

    render: function render() {
      $(this.placeholder).html(this.model.get('content'));
      this.headings();
      return this;
    },

    updateTitle: function() {
      document.title = document.title.replace(/[^|]+|/, this.model.get('title') + ' ');
    }
  });

  var DocsRouter = Backbone.Router.extend({
    routes: {
      // catch all
      '*path': 'changePage'
    },

    changePage: function changePage(path) {
      if(!path || path === model.get('path')) {
        return;
      }

      model
        .set({ path: path })
        .fetch({
          success: function() {
            // users gets comments by scolling to the bottom section

            // the only exception is when the page content is too small for that, in that case
            // load immediately

            if( view.nav.height() - 750 > view.placeholder.height() ) {
              loadComments(path);
            }
          }
        });
    }
  });

  $(function() {

    var disqus_thread = $('#disqus_thread'),
    win = $(window),
    doc = $(document),

    atBottom = function(offset) {
      offset = offset || 750;
      return win.scrollTop() > (doc.height() - win.height() - offset);
    };

    // create our app components
    model = new DocsPage({path: location.pathname.replace(/^\//, '')});
    view = new DocsView({model: model, scroll: true});
    router = new DocsRouter();

    Backbone.history.start({
      pushState: true
    });

    // listen to scrolling so that we detect when the bottom is reached
    // where we trigger disqus comments
    win.scroll(function() {
      var dsq = $('#disqus_thread');

      if(!atBottom()) return;

      // ok, user is reaching the page bottom, load comments, but only if it wasn't done before.
      // assume es5 trim method is there, since non pushstate browser would normally
      // not reach this code
      var prevent = dsq.html().trim();
      if(prevent) return;

      loadComments(model.get('path'));
    });

  });

})(this.jQuery, this.location, this.document, this);

<|endoftext|>


<commit_before>function MenuBar(div) {
    this._div = div;
    this._initializeUI();
}

MenuBar.MenuItems = [
    {
        "id" : "core/project",
        "label" : "Project",
        "submenu" : [
            /*
            {
                "label": "Data Model",
                "submenu": [
                    {
                        "label": "Denormalize Records",
                        "click": function() { MenuBar.handlers.denormalizeRecords(); }
                    }
                ]
            },
            {},
            */
            {
                "id" : "core/rename-project",
                "label": "Rename...",
                "click": function() { MenuBar.handlers.renameProject(); }
            },
            {},
            {
                "id" : "core/export",
                "label": "Export Filtered Rows",
                "submenu": [
                    {
                        "id" : "core/export-tsv",
                        "label": "Tab-Separated Value",
                        "click": function() { MenuBar.handlers.exportRows("tsv", "tsv"); }
                    },
                    {
                        "id" : "core/export-csv",
                        "label": "Comma-Separated Value",
                        "click": function() { MenuBar.handlers.exportRows("csv", "csv"); }
                    },
                    {
                        "id" : "core/export-html-table",
                        "label": "HTML Table",
                        "click": function() { MenuBar.handlers.exportRows("html", "html"); }
                    },
                    {
                        "id" : "core/export-excel",
                        "label": "Excel",
                        "click": function() { MenuBar.handlers.exportRows("xls", "xls"); }
                    },
                    {},
                    {
                        "id" : "core/export-tripleloader",
                        "label": "Tripleloader",
                        "click": function() { MenuBar.handlers.exportTripleloader("tripleloader"); }
                    },
                    {
                        "id" : "core/export-mqlwrite",
                        "label": "MQLWrite",
                        "click": function() { MenuBar.handlers.exportTripleloader("mqlwrite"); }
                    },
                    {},
                    {
                        "id" : "core/export-templating",
                        "label": "Templating...",
                        "click": function() { new TemplatingExporterDialog(); }
                    }
                ]
            },
            {
                "id" : "core/export-project",
                "label": "Export Project",
                "click": function() { MenuBar.handlers.exportProject(); }
            }
        ]
    },
    {
        "id" : "core/schemas",
        "label" : "Schemas",
        "submenu" : [
            /*{
                "id" : "core/auto-schema-alignment",
                label: "Auto-Align with Freebase ...",
                click: function() { MenuBar.handlers.autoSchemaAlignment(); }
            },*/
            {
                "id" : "core/schema-alignment",
                label: "Edit Schema Aligment Skeleton ...",
                click: function() { MenuBar.handlers.editSchemaAlignment(false); }
            },
            {
                "id" : "core/reset-schema-alignment",
                label: "Reset Schema Alignment Skeleton ...",
                click: function() { MenuBar.handlers.editSchemaAlignment(true); }
            },
            {},
            {
                "id" : "core/load-info-freebase",
                label: "Load into Freebase ...",
                click: function() { MenuBar.handlers.loadIntoFreebase(); }
            }
        ]
    }
];

MenuBar._find = function(path, levels) {
    var menuItems = MenuBar.MenuItems;
    for (var p = 0; p < path.length && p < levels; p++) {
        var segment = path[p];
        var subMenuItems;

        for (var i = 0; i < menuItems.length; i++) {
            var menuItem = menuItems[i];
            if (menuItem.id == segment) {
                if ("submenu" in menuItem) {
                    subMenuItems = menuItem.submenu;
                } else {
                    return undefined;
                }
                break;
            }
        }

        if (subMenuItems) {
            menuItems = subMenuItems;
        } else {
            return undefined;
        }
    }

    return menuItems;
};

MenuBar.appendTo = function(path, what) {
    var menuItems = MenuBar._find(path, path.length);
    if (menuItems) {
        if (what instanceof Array) {
            $.merge(menuItems, what);
        } else {
            menuItems.push(what);
        }
    }
};

MenuBar.insertBefore = function(path, what) {
    var menuItems = MenuBar._find(path, path.length - 1);
    if ((menuItems) && path.length > 0) {
        var spliceArgs = [ 0, 0 ];
        if (what instanceof Array) {
            $.merge(spliceArgs, what);
        } else {
            spliceArgs.push(what);
        }

        var segment = path[path.length - 1];
        for (var i = 0; i < menuItems.length; i++) {
            var menuItem = menuItems[i];
            if (menuItem.id == segment) {
                spliceArgs[0] = i;
                break;
            }
        }

        Array.prototype.splice.apply(menuItems, spliceArgs);
    }
};

MenuBar.insertAfter = function(path, what) {
    var menuItems = MenuBar._find(path, path.length - 1);
    if ((menuItems) && path.length > 0) {
        var spliceArgs = [ menuItems.length, 0 ];
        if (what instanceof Array) {
            $.merge(spliceArgs, what);
        } else {
            spliceArgs.push(what);
        }

        var segment = path[path.length - 1];
        for (var i = 0; i < menuItems.length; i++) {
            var menuItem = menuItems[i];
            if (menuItem.id == segment) {
                spliceArgs[0] = i + 1;
                break;
            }
        }

        Array.prototype.splice.apply(menuItems, spliceArgs);
    }
};

MenuBar.handlers = {};

MenuBar.prototype.resize = function() {
};

MenuBar.prototype._initializeUI = function() {
    this._mode = "inactive";
    this._menuItemRecords = [];

    this._div.addClass("menu-bar").html(" ");
    this._innerDiv = $('

').addClass("menu-bar-inner").appendTo(this._div);

    var self = this;
    for (var i = 0; i < MenuBar.MenuItems.length; i++) {
        var menuItem = MenuBar.MenuItems[i];
        this._createTopLevelMenuItem(menuItem.label, menuItem.submenu);
    }
    this._wireAllMenuItemsInactive();
};

MenuBar.prototype._createTopLevelMenuItem = function(label, submenu) {
    var self = this;

    var menuItem = MenuSystem.createMenuItem().text(label).appendTo(this._innerDiv);

    this._menuItemRecords.push({
        menuItem: menuItem,
        show: function() {
            MenuSystem.dismissUntil(self._level);

            menuItem.addClass("menu-expanded");

            MenuSystem.createAndShowStandardMenu(
                submenu,
                this,
                {
                    horizontal: false,
                    onDismiss: function() {
                        menuItem.removeClass("menu-expanded");
                    }
                }
            );
        }
    });
};

MenuBar.prototype._wireMenuItemInactive = function(record) {
    var self = this;
    var click = function() {
        self._activateMenu();
        record.show.apply(record.menuItem[0]);
    };

    record.menuItem.click(function() {
        // because we're going to rewire the menu bar, we have to
        // make this asynchronous, or jquery event binding won't work.
        window.setTimeout(click, 100);
    });
};

MenuBar.prototype._wireAllMenuItemsInactive = function() {
    for (var i = 0; i < this._menuItemRecords.length; i++) {
        this._wireMenuItemInactive(this._menuItemRecords[i]);
    }
};

MenuBar.prototype._wireMenuItemActive = function(record) {
    record.menuItem.mouseover(function() {
        record.show.apply(this);
    });
};

MenuBar.prototype._wireAllMenuItemsActive = function() {
    for (var i = 0; i < this._menuItemRecords.length; i++) {
        this._wireMenuItemActive(this._menuItemRecords[i]);
    }
};

MenuBar.prototype._activateMenu = function() {
    var self = this;

    var top = this._innerDiv.offset().top;

    this._innerDiv.remove().css("top", top + "px");
    this._wireAllMenuItemsActive();
    this._mode = "active";

    this._level = MenuSystem.showMenu(this._innerDiv, function() {
        self._deactivateMenu();
    });
};

MenuBar.prototype._deactivateMenu = function() {
    this._innerDiv.remove()
        .css("z-index", "auto")
        .css("top", "0px")
        .appendTo(this._div);

    this._wireAllMenuItemsInactive();
    this._mode = "inactive";
};

MenuBar.prototype._doDenormalizeRecords = function() {
    Gridworks.postProcess(
        "denormalize",
        {},
        null,
        { modelsChanged: true }
    );
};

MenuBar.prototype._doExportTripleloader = function(format) {
    if (!theProject.overlayModels.freebaseProtograph) {
        alert(
            "You haven't done any schema alignment yet,\nso there is no triple to export.\n\n" +
            "Use the Schemas > Edit Schema Alignment Skeleton...\ncommand to align your data with Freebase schemas first."
        );
    } else {
        this._doExportRows(format, "txt");
    }
};

MenuBar.handlers.exportRows = function(format, ext) {
    var name = $.trim(theProject.metadata.name.replace(/\W/g, ' ')).replace(/\s+/g, '-');
    var form = document.createElement("form");
    $(form)
        .css("display", "none")
        .attr("method", "post")
        .attr("action", "/command/export-rows/" + name + "." + ext)
        .attr("target", "gridworks-export");

    $('<input />')
        .attr("name", "engine")
        .attr("value", JSON.stringify(ui.browsingEngine.getJSON()))
        .appendTo(form);
    $('<input />')
        .attr("name", "project")
        .attr("value", theProject.id)
        .appendTo(form);
    $('<input />')
        .attr("name", "format")
        .attr("value", format)
        .appendTo(form);

    document.body.appendChild(form);

    window.open("about:blank", "gridworks-export");
    form.submit();

    document.body.removeChild(form);
};

MenuBar.handlers.exportProject = function() {
    var name = $.trim(theProject.metadata.name.replace(/\W/g, ' ')).replace(/\s+/g, '-');
    var form = document.createElement("form");
    $(form)
        .css("display", "none")
        .attr("method", "post")
        .attr("action", "/command/export-project/" + name + ".gridworks.tar.gz")
        .attr("target", "gridworks-export");
    $('<input />')
        .attr("name", "project")
        .attr("value", theProject.id)
        .appendTo(form);

    document.body.appendChild(form);

    window.open("about:blank", "gridworks-export");
    form.submit();

    document.body.removeChild(form);
};

MenuBar.handlers.renameProject = function() {
    var name = window.prompt("Rename Project", theProject.metadata.name);
    if (name == null) {
        return;
    }

    name = $.trim(name);
    if (theProject.metadata.name == name || name.length == 0) {
        return;
    }

    $.ajax({
        type: "POST",
        url: "/command/rename-project",
        data: { "project" : theProject.id, "name" : name },
        dataType: "json",
        success: function (data) {
            if (data && typeof data.code != 'undefined' && data.code == "ok") {
                theProject.metadata.name = name;
                Gridworks.setTitle();
            } else {
                alert("Failed to rename project: " + data.message);
            }
        }
    });
};

MenuBar.handlers.autoSchemaAlignment = function() {
    //SchemaAlignment.autoAlign();
};

MenuBar.handlers.editSchemaAlignment = function(reset) {
    new SchemaAlignmentDialog(
        reset ? null : theProject.overlayModels.freebaseProtograph, function(newProtograph) {});
};

MenuBar.handlers.loadIntoFreebase = function() {
    new FreebaseLoadingDialog();
};

<commit_msg>Export as Tripleloader format command was broken by menu bar refactoring<commit_after>function MenuBar(div) {
    this._div = div;
    this._initializeUI();
}

MenuBar.MenuItems = [
    {
        "id" : "core/project",
        "label" : "Project",
        "submenu" : [
            /*
            {
                "label": "Data Model",
                "submenu": [
                    {
                        "label": "Denormalize Records",
                        "click": function() { MenuBar.handlers.denormalizeRecords(); }
                    }
                ]
            },
            {},
            */
            {
                "id" : "core/rename-project",
                "label": "Rename...",
                "click": function() { MenuBar.handlers.renameProject(); }
            },
            {},
            {
                "id" : "core/export",
                "label": "Export Filtered Rows",
                "submenu": [
                    {
                        "id" : "core/export-tsv",
                        "label": "Tab-Separated Value",
                        "click": function() { MenuBar.handlers.exportRows("tsv", "tsv"); }
                    },
                    {
                        "id" : "core/export-csv",
                        "label": "Comma-Separated Value",
                        "click": function() { MenuBar.handlers.exportRows("csv", "csv"); }
                    },
                    {
                        "id" : "core/export-html-table",
                        "label": "HTML Table",
                        "click": function() { MenuBar.handlers.exportRows("html", "html"); }
                    },
                    {
                        "id" : "core/export-excel",
                        "label": "Excel",
                        "click": function() { MenuBar.handlers.exportRows("xls", "xls"); }
                    },
                    {},
                    {
                        "id" : "core/export-tripleloader",
                        "label": "Tripleloader",
                        "click": function() { MenuBar.handlers.exportTripleloader("tripleloader"); }
                    },
                    {
                        "id" : "core/export-mqlwrite",
                        "label": "MQLWrite",
                        "click": function() { MenuBar.handlers.exportTripleloader("mqlwrite"); }
                    },
                    {},
                    {
                        "id" : "core/export-templating",
                        "label": "Templating...",
                        "click": function() { new TemplatingExporterDialog(); }
                    }
                ]
            },
            {
                "id" : "core/export-project",
                "label": "Export Project",
                "click": function() { MenuBar.handlers.exportProject(); }
            }
        ]
    },
    {
        "id" : "core/schemas",
        "label" : "Schemas",
        "submenu" : [
            /*{
                "id" : "core/auto-schema-alignment",
                label: "Auto-Align with Freebase ...",
                click: function() { MenuBar.handlers.autoSchemaAlignment(); }
            },*/
            {
                "id" : "core/schema-alignment",
                label: "Edit Schema Aligment Skeleton ...",
                click: function() { MenuBar.handlers.editSchemaAlignment(false); }
            },
            {
                "id" : "core/reset-schema-alignment",
                label: "Reset Schema Alignment Skeleton ...",
                click: function() { MenuBar.handlers.editSchemaAlignment(true); }
            },
            {},
            {
                "id" : "core/load-info-freebase",
                label: "Load into Freebase ...",
                click: function() { MenuBar.handlers.loadIntoFreebase(); }
            }
        ]
    }
];

MenuBar._find = function(path, levels) {
    var menuItems = MenuBar.MenuItems;
    for (var p = 0; p < path.length && p < levels; p++) {
        var segment = path[p];
        var subMenuItems;

        for (var i = 0; i < menuItems.length; i++) {
            var menuItem = menuItems[i];
            if (menuItem.id == segment) {
                if ("submenu" in menuItem) {
                    subMenuItems = menuItem.submenu;
                } else {
                    return undefined;
                }
                break;
            }
        }

        if (subMenuItems) {
            menuItems = subMenuItems;
        } else {
            return undefined;
        }
    }

    return menuItems;
};

MenuBar.appendTo = function(path, what) {
    var menuItems = MenuBar._find(path, path.length);
    if (menuItems) {
        if (what instanceof Array) {
            $.merge(menuItems, what);
        } else {
            menuItems.push(what);
        }
    }
};

MenuBar.insertBefore = function(path, what) {
    var menuItems = MenuBar._find(path, path.length - 1);
    if ((menuItems) && path.length > 0) {
        var spliceArgs = [ 0, 0 ];
        if (what instanceof Array) {
            $.merge(spliceArgs, what);
        } else {
            spliceArgs.push(what);
        }

        var segment = path[path.length - 1];
        for (var i = 0; i < menuItems.length; i++) {
            var menuItem = menuItems[i];
            if (menuItem.id == segment) {
                spliceArgs[0] = i;
                break;
            }
        }

        Array.prototype.splice.apply(menuItems, spliceArgs);
    }
};

MenuBar.insertAfter = function(path, what) {
    var menuItems = MenuBar._find(path, path.length - 1);
    if ((menuItems) && path.length > 0) {
        var spliceArgs = [ menuItems.length, 0 ];
        if (what instanceof Array) {
            $.merge(spliceArgs, what);
        } else {
            spliceArgs.push(what);
        }

        var segment = path[path.length - 1];
        for (var i = 0; i < menuItems.length; i++) {
            var menuItem = menuItems[i];
            if (menuItem.id == segment) {
                spliceArgs[0] = i + 1;
                break;
            }
        }

        Array.prototype.splice.apply(menuItems, spliceArgs);
    }
};

MenuBar.handlers = {};

MenuBar.prototype.resize = function() {
};

MenuBar.prototype._initializeUI = function() {
    this._mode = "inactive";
    this._menuItemRecords = [];

    this._div.addClass("menu-bar").html(" ");
    this._innerDiv = $('

').addClass("menu-bar-inner").appendTo(this._div);

    var self = this;
    for (var i = 0; i < MenuBar.MenuItems.length; i++) {
        var menuItem = MenuBar.MenuItems[i];
        this._createTopLevelMenuItem(menuItem.label, menuItem.submenu);
    }
    this._wireAllMenuItemsInactive();
};

MenuBar.prototype._createTopLevelMenuItem = function(label, submenu) {
    var self = this;

    var menuItem = MenuSystem.createMenuItem().text(label).appendTo(this._innerDiv);

    this._menuItemRecords.push({
        menuItem: menuItem,
        show: function() {
            MenuSystem.dismissUntil(self._level);

            menuItem.addClass("menu-expanded");

            MenuSystem.createAndShowStandardMenu(
                submenu,
                this,
                {
                    horizontal: false,
                    onDismiss: function() {
                        menuItem.removeClass("menu-expanded");
                    }
                }
            );
        }
    });
};

MenuBar.prototype._wireMenuItemInactive = function(record) {
    var self = this;
    var click = function() {
        self._activateMenu();
        record.show.apply(record.menuItem[0]);
    };

    record.menuItem.click(function() {
        // because we're going to rewire the menu bar, we have to
        // make this asynchronous, or jquery event binding won't work.
        window.setTimeout(click, 100);
    });
};

MenuBar.prototype._wireAllMenuItemsInactive = function() {
    for (var i = 0; i < this._menuItemRecords.length; i++) {
        this._wireMenuItemInactive(this._menuItemRecords[i]);
    }
};

MenuBar.prototype._wireMenuItemActive = function(record) {
    record.menuItem.mouseover(function() {
        record.show.apply(this);
    });
};

MenuBar.prototype._wireAllMenuItemsActive = function() {
    for (var i = 0; i < this._menuItemRecords.length; i++) {
        this._wireMenuItemActive(this._menuItemRecords[i]);
    }
};

MenuBar.prototype._activateMenu = function() {
    var self = this;

    var top = this._innerDiv.offset().top;

    this._innerDiv.remove().css("top", top + "px");
    this._wireAllMenuItemsActive();
    this._mode = "active";

    this._level = MenuSystem.showMenu(this._innerDiv, function() {
        self._deactivateMenu();
    });
};

MenuBar.prototype._deactivateMenu = function() {
    this._innerDiv.remove()
        .css("z-index", "auto")
        .css("top", "0px")
        .appendTo(this._div);

    this._wireAllMenuItemsInactive();
    this._mode = "inactive";
};

MenuBar.handlers.exportTripleloader = function(format) {
    if (!theProject.overlayModels.freebaseProtograph) {
        alert(
            "You haven't done any schema alignment yet,\nso there is no triple to export.\n\n" +
            "Use the Schemas > Edit Schema Alignment Skeleton...\ncommand to align your data with Freebase schemas first."
        );
    } else {
        MenuBar.handlers.exportRows(format, "txt");
    }
};

MenuBar.handlers.exportRows = function(format, ext) {
    var name = $.trim(theProject.metadata.name.replace(/\W/g, ' ')).replace(/\s+/g, '-');
    var form = document.createElement("form");
    $(form)
        .css("display", "none")
        .attr("method", "post")
        .attr("action", "/command/export-rows/" + name + "." + ext)
        .attr("target", "gridworks-export");

    $('<input />')
        .attr("name", "engine")
        .attr("value", JSON.stringify(ui.browsingEngine.getJSON()))
        .appendTo(form);
    $('<input />')
        .attr("name", "project")
        .attr("value", theProject.id)
        .appendTo(form);
    $('<input />')
        .attr("name", "format")
        .attr("value", format)
        .appendTo(form);

    document.body.appendChild(form);

    window.open("about:blank", "gridworks-export");
    form.submit();

    document.body.removeChild(form);
};

MenuBar.handlers.exportProject = function() {
    var name = $.trim(theProject.metadata.name.replace(/\W/g, ' ')).replace(/\s+/g, '-');
    var form = document.createElement("form");
    $(form)
        .css("display", "none")
        .attr("method", "post")
        .attr("action", "/command/export-project/" + name + ".gridworks.tar.gz")
        .attr("target", "gridworks-export");
    $('<input />')
        .attr("name", "project")
        .attr("value", theProject.id)
        .appendTo(form);

    document.body.appendChild(form);

    window.open("about:blank", "gridworks-export");
    form.submit();

    document.body.removeChild(form);
};

MenuBar.handlers.renameProject = function() {
    var name = window.prompt("Rename Project", theProject.metadata.name);
    if (name == null) {
        return;
    }

    name = $.trim(name);
    if (theProject.metadata.name == name || name.length == 0) {
        return;
    }

    $.ajax({
        type: "POST",
        url: "/command/rename-project",
        data: { "project" : theProject.id, "name" : name },
        dataType: "json",
        success: function (data) {
            if (data && typeof data.code != 'undefined' && data.code == "ok") {
                theProject.metadata.name = name;
                Gridworks.setTitle();
            } else {
                alert("Failed to rename project: " + data.message);
            }
        }
    });
};

MenuBar.handlers.autoSchemaAlignment = function() {
    //SchemaAlignment.autoAlign();
};

MenuBar.handlers.editSchemaAlignment = function(reset) {
    new SchemaAlignmentDialog(
        reset ? null : theProject.overlayModels.freebaseProtograph, function(newProtograph) {});
};

MenuBar.handlers.loadIntoFreebase = function() {
    new FreebaseLoadingDialog();
};

<|endoftext|>