code stringlengths 2 1.05M |
|---|
'use babel';
import { Vue } from 'use-vue';
import { requirePackages } from 'atom-utils';
import StateMachine from 'javascript-state-machine';
import './module/use-vue-config';
import {
DEV,
NAME,
} from './module/constant';
import console from './module/console';
// TODO: autoToggle feature is not finished yet
// it seemed to config the package options failed
let { autoToggle } = !!atom.config.get(`${ NAME.kebab }`);
// TODO: defaults true
autoToggle = true;
console.log('autoToggle => ', autoToggle);
let addInfo = ( detail ) => atom.notifications.addInfo(`${ NAME }`, { detail });
let showTips = () => addInfo(`Plugin require "tree-view".`);
Vue.prototype.$dispatch = function ( event, payload ) {
return new Promise(( resolve ) => {
this.$emit(`${ event }`, resolve, payload);
});
};
class TreeViewSearchBar {
/**
* Plugin Active State
* @type {Boolean}
*/
active = false;
/**
* Plugin Commands Collection
* @type {Object}
*/
commands = {};
/**
* Define Finite State Machine Model
* @type {StateMachine}
* @type {String} Status | "Null" | "Dependent" | "Created" | "Actived" | "Disabled" | "Destroyed" |
* @type {String} Event | "Setup" | "Create" | "Activate" | "Deactivate" | "Destroy" | "Teardown" |
*/
fsm = StateMachine.create({
initial : 'Null',
error : null,
events : [
{
from : 'Null',
name : 'Setup',
to : 'Dependent',
},
{
from : 'Dependent',
name : 'Create',
to : 'Created',
},
{
from : ['Created', 'Disabled'],
name : 'Activate',
to : 'Actived',
},
{
from : 'Actived',
name : 'Deactivate',
to : 'Disabled',
},
{
from : ['Disabled', 'Actived', 'Created', 'Dependent'],
name : 'Destroy',
to : 'Destroyed',
},
{
from : 'Destroyed',
name : 'Teardown',
to : 'Null',
},
],
});
constructor () {
if (DEV) {
window.test = this;
this.Vue = Vue;
}
/**
* Setup Stage
*/
this.on('Setup', async () => {
console.log('event => Setup');
let [{ treeView }] = await requirePackages('tree-view');
Vue.prototype.$treeView = treeView;
if (treeView && treeView.isVisible()) {
this.emit('Create');
} else {
showTips();
this.add('search-bar:toggle', showTips);
let sid;
let ensureTreeViewVisible = () => {
console.log('ensureTreeViewVisible');
clearTimeout(sid);
// TODO: nextTick can not wait for the true moment when the treeView isVisible
// process.nextTick(() => {
// if (treeView && treeView.isVisible() && atom.project.rootDirectories.length) {
// this.emit('Create');
// }
// });
// HACK: loop check until create success
let loop = async () => {
let [{ treeView }] = await requirePackages('tree-view');
Vue.prototype.$treeView = treeView;
if (treeView && treeView.isVisible() && atom.project.rootDirectories.length) {
this.emit('Create');
} else {
sid = setTimeout(loop, 100);
}
};
sid = setTimeout(loop, 100);
};
// HACK: it seems to never hit the event tree-view:show / toggle when tree-view show or toggle in atom 1.21
this.add('tree-view:show', ensureTreeViewVisible);
this.add('tree-view:toggle', ensureTreeViewVisible);
let projectListener = atom.project.onDidChangePaths(ensureTreeViewVisible);
this.on('leaveDependent', () => {
console.log('event => leaveDependent');
this.remove(
'tree-view:show',
'tree-view:toggle',
'search-bar:toggle',
);
projectListener.disposalAction();
});
}
});
/**
* Create Stage
*/
this.on('Create', async () => {
console.log('event => Create');
let treeView = Vue.prototype.$treeView;
atom.notifications.addSuccess(`${ NAME }`, {
detail : 'Plugin is running!',
});
/**
* Vue instance
* @type {Vue|null}
*/
let vm = null;
if (DEV) {
Object.defineProperty(this, 'vm', {
get () {
return vm;
},
});
}
/**
* Plugin Placeholder
* @type {Element}
*/
let element = document.createElement('div');
/**
* Activate Stage
*/
this.on('Activate', async () => {
console.log('Activate');
if (vm) {
await vm.$dispatch('show');
} else {
// HACK: it seems not working in atom 1.21
// if (DEV) {
// let path = require('path');
// let files = [
// './views/app.vue',
// ];
// let Module = module.constructor;
// for (let file of files) {
// Module._cache[path.join(__dirname, file)] = null;
// }
// }
let app = require('./views/app.vue');
vm = new Vue(app);
treeView.element.parentNode.insertBefore(element, treeView.element);
vm.$mount(element);
}
console.log('app => show');
});
/**
* Destroy Vue instance
* @type {Function}
*/
let clean = async () => {
if (vm) {
await vm.$dispatch('hide');
vm = null;
}
console.log('app => hide');
};
/**
* Deactivate Stage
*/
this.on('Deactivate', () => {
console.log('Deactivate');
clean();
});
/**
* Destroy Stage
*/
this.on('Destroy', () => {
console.log('Destroy');
// clean();
});
/**
* ensure Tree View visible
* @param {Function} callback
* @return {Function} handler
*/
let requireTreeView = ( callback ) => {
return () => {
if (treeView.isVisible()) {
callback();
} else {
showTips();
}
};
};
this.add('search-bar:show', requireTreeView(() => {
this.emit('Activate');
}));
this.add('search-bar:hide', requireTreeView(() => {
this.emit('Deactivate');
}));
this.add('search-bar:focus', requireTreeView(() => {
this.emit('Activate');
vm.$emit('focus');
}));
this.add('search-bar:toggle', requireTreeView(() => {
let current = this.fsm.current;
this.emit('Activate');
if (current === this.fsm.current) {
this.emit('Deactivate');
}
}));
/**
* autoToggle
*/
if (autoToggle) {
this.emit('Activate');
}
});
/**
* Teardown Stage
*/
this.on('Teardown', () => {
console.log('event => Teardown');
this.remove(
'tree-view:show',
'tree-view:toggle',
'search-bar:show',
'search-bar:hide',
'search-bar:focus',
'search-bar:toggle',
);
});
}
/**
* Plugin Active State
* @return {Boolean} active
*/
isActive () {
return this.active;
}
/**
* Atom Activate Hook
*/
activate ( state ) {
if (this.active) return;
this.active = true;
/**
* Setup Plugin
*/
this.emit('Setup');
}
/**
* Atom Deactivate Hook
*/
deactivate () {
if (!this.active) return;
this.active = false;
/**
* Teardown Plugin
*/
this.emit('Teardown');
}
/**
* Bind State Machine Event
* @param {String} event
* @param {Function} handler
*/
on ( event, handler ) {
this.fsm[`on${ event }`] = function ( name, from, to, payload ) {
let event = { name, from, to };
return handler.call(this, event, payload);
};
}
/**
* Emit State Machine Event
* @param {String} event
* @param {Any} payload
*/
emit ( event, payload ) {
if (this.fsm.can(event)) {
this.fsm[event](payload);
}
}
/**
* Add Atom Command
* @param {String} command
* @param {Function} handler
*/
add ( command, handler ) {
console.log(`add => ${ command }`);
this.dispose(
command,
atom.commands.add(
'atom-workspace',
{
[command] : handler,
},
),
);
}
/**
* Remove Atom Command
* @param {String} command
*/
remove ( ...commands ) {
for (let command of commands) {
console.log(`remove => ${ command }`);
this.dispose(command);
}
}
/**
* Add or Remove Atom Command
* @param {String} command
* @param {Function} handler
*/
dispose ( command, handler ) {
let composition = this.commands[command];
if (composition) {
composition.dispose();
if (handler) {
this.commands[command] = handler;
}
}
}
}
export default new TreeViewSearchBar;
|
var flashlight = {
_on: false,
toggle: function(arg) {
if (flashlight._on) {
flashlight.off();
} else {
flashlight.on(arg);
}
flashlight._on = !flashlight._on;
},
isOn: function() {
return flashlight._on;
},
_checkAvailability: function() {
if (!this.isAvailable()) {
throw new Error("A flashlight is not available on this device. " +
"Check for availability with isAvailable().");
}
}
};
module.exports = flashlight;
|
window.onload = function() {
var init = function () {
var selectphoto = document.getElementById('selectphoto');
var registerForm = document.getElementById('registerForm');
var registerRemainder = document.getElementById('register-remainder');
var imgSrc = "img/photo/photo"+parseInt(Math.random()*9+1)+".jpg";
registerForm.elements[0].value = imgSrc;
var container = document.createDocumentFragment();
for (var i = 0; i < 3; i++)
for (var j = 0; j < 3; j++) {
var newImg = document.createElement('img');
newImg.src = "img/photo/photo"+(3*j+i+1)+".jpg";
newImg.className = "register-photo register-row"+i+" register-col"+j;
container.appendChild(newImg);
}
selectphoto.appendChild(container);
selectphoto.addEventListener('click', function(e) {
e = e || window.event;//这一行及下一行是为兼容IE8及以下版本
var target = e.target || e.srcElement;
if(e.target && e.target.nodeName == 'IMG') {
var photos = document.getElementsByClassName('register-photo');
for (var i in photos) {
var tmp = String(photos[i].className);
photos[i].className = tmp.replace(' register-img-active', '');
}
e.target.className += " register-img-active";
imgSrc = e.target.getAttribute("src");
registerForm.elements[0].value = imgSrc;
}
});
function validator(username, password, repeatpassword) {
var tmp = registerForm.elements;
for (var i in tmp) {
if(tmp[i].value === '') {
registerRemainder.innerText = '输入内容不能为空';
return false;
}
}
// if (/^[a-zA-Z0-9]{1,12}$/.test(tmp[1].value) !== true) {
// registerRemainder.innerText = '请输入1到12位由字母和数字组成的昵称';
// return false;
// }
if (tmp[1].value.length <1 || tmp[1].value.length > 16) {
registerRemainder.innerText = '请输入1到16位长度的昵称';
return false;
}
if (/^[a-zA-Z0-9]{6,16}$/.test(tmp[2].value) !== true) {
registerRemainder.innerText = '请输入6到16位由字母和数字组成的密码';
return false;
}
if (tmp[2].value != tmp[3].value) {
registerRemainder.innerText = '输入的密码不一致';
return false;
}
}
registerForm.onsubmit = function() {
return validator();
};
};
init();
}; |
'use strict';
angular.module('MyBootstrApp') // declare which module this controller should attach to
.controller('MainCtrl', function($scope){ // create our Main Controller
$scope.demo = "AngularUI Bootstrap"
})
|
'use strict';
var util = require('util');
var db = require('./db').getConnection();
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var crypto = require('crypto');
var userSchema = new Schema({
username: { type: String, required: true },
hash: { type: String, required: true },
salt: { type: String, required: true },
isAdmin: { type: Boolean, required: true, default: false }
});
userSchema.methods.verifyPassword = function(password, callback) {
if(!password)
return callback(null, false);
var originalHash = this.hash;
User.hashPassword(password, this.salt, function(error, hash, salt) {
if(error)
return callback(error);
callback(null, hash === originalHash);
});
};
userSchema.statics.verifyUser = function(username, password, callback) {
if(!username || !password)
return callback('No username or password provided')
this.findOne({ username: new RegExp('^'+username+'$', "i") }, function(error, user) {
if(error) {
callback(error);
} else if(user) {
user.verifyPassword(password, function(error, validated) {
callback(error, (validated) ? user : false);
});
} else {
callback(null, false);
}
})
};
userSchema.statics.hashPassword = function(plainPassword, salt, callback) {
// Make salt optional
if(callback === undefined && salt instanceof Function) {
callback = salt;
salt = undefined;
}
if(typeof salt === 'string') {
salt = new Buffer(salt, 'hex');
}
var calcHash = function() {
crypto.pbkdf2(plainPassword, salt, 10000, 64, function(err, key) {
if(err)
return callback(err);
callback(null, key.toString('hex'), salt.toString('hex'));
})
};
if(!salt) {
crypto.randomBytes(64, function(err, gensalt) {
if(err)
return callback(err);
salt = gensalt;
calcHash();
});
} else {
calcHash();
}
};
userSchema.statics.serializeUser = function(user, done) {
done(null, user.id);
};
userSchema.statics.deserializeUser = function(id, done) {
User.findById(id, done);
};
userSchema.statics.createUser = function(username, password, admin, callback) {
if(!username || !password)
return callback('No username or password provided')
this.findOne({ username: new RegExp('^'+username+'$', "i") }, function(error, user) {
if(error) {
callback(error);
} else if(!user) {
User.hashPassword(password, function(error, hash, salt) {
if(error)
return callback(error);
var newUser = new User({
username: username,
hash: hash,
salt: salt,
isAdmin: admin
});
newUser.save(callback);
});
} else {
callback('This user already exists');
}
})
};
var User = db.model('Users', userSchema);
module.exports.User = User; |
function Nounours(element,time)
{
this.element = element;
this.time = time;
this.timer;
this.reset = function()
{
element.classList.add("nounours_conteneur");
var self = this;
//on clean si le slider est déja lancé
var before = element.getElementsByClassName("before")[0] || null;
if(before != null )
{
before.parentElement.removeChild(before);
}
var after = element.getElementsByClassName("after")[0] || null;
if(after != null )
{
after.parentElement.removeChild(after);
}
clearInterval(this.timer);
var images = Array.from(this.element.childNodes).filter(self.elementValide);
//on verifie qu'il y a bien des images
if(images.length > 1)
{
//creation de la fleche gauche
var before = document.createElement("div");
before.classList.add("before");
element.insertBefore(before, element.childNodes[0]);
before.addEventListener("click",this.precedent,false);
//creation de la flèche droite
var after = document.createElement("div");
after.classList.add("after");
element.appendChild(after);
after.addEventListener("click",this.suivant,false);
//on demmare l'animation
this.selection(images[0]);
if(time > 0)
this.timer = setInterval(this.suivant,time);
}
else
{
console.error("no images in nounours slider !! ");
}
}
//fait l'animation
this.selection = (imageEnCours) =>
{
//récuperation de l'image suivante
var self = this;
realChilNodes = Array.from(this.element.childNodes).filter(self.elementValide);
imageSuivant = imageEnCours.nextElementSibling;
if(! this.elementValide(imageSuivant))//si le suivant est une fleche on prend la premièr image aussi
imageSuivant = realChilNodes[1];//on prend le 2eme element (le 1er c'est la fleche)
//récupération de l'image précédente
imagePrecedent = imageEnCours.previousElementSibling;
if(! this.elementValide(imagePrecedent))//si il y en a pas ou si le precedent est une fleche on prend la dernière
{
imagePrecedent = this.dernierElement(realChilNodes);
}
//on fait les oprations si l'élément est bien une image
if(this.elementValide(imageEnCours))
{
for(var className of ["nounours_suivant", "nounours_precedent", "nounours_encours"]){
for(var ele of Array.from(this.element.getElementsByClassName(className)))
{
ele.classList.remove(className);
}
}
imageSuivant.classList.add("nounours_suivant");
imageEnCours.classList.add("nounours_encours");
imagePrecedent.classList.add("nounours_precedent");
}
else // sinon on prend l'élément suivant
{
this.selection(imageSuivant);
}
}
this.suivant = () =>
{
this.selection(this.element.getElementsByClassName("nounours_suivant")[0]);
clearInterval(this.timer);
if(time > 0)
this.timer = setInterval(this.suivant,time);
}
this.precedent = () =>
{
this.selection(this.element.getElementsByClassName("nounours_precedent")[0]);
clearInterval(this.timer);
if(time > 0)
this.timer = setInterval(this.suivant,time);
}
this.dernierElement= function(collection)
{
return collection[collection.length -1] || null;
}
this.elementValide = function(ele)
{
if(ele == null)
{
return false
}
else
{ try
{
var isBefore = ele.classList.contains("before");
}
catch(err)
{
var isBefore = false;
}
try
{
var isAfter = ele.classList.contains("after");
}
catch(err)
{
var isBefore = false;
}
var bool = !((ele.nodeName == "#text") || isAfter || isBefore);
//console.log(ele);
//console.log(bool);
return bool;
}
}
}
|
"use strict";
DataUtility.insertAll('Location', {
'debug.fuckpit': {
name:'The Fuckpit',
brief:"Description of the fuckpit. Brief as in you're being given a briefing, not short.",
view:`${appPath}/stories/debug/views/locations/fuckpit.html` },
});
|
'use strict';
var Grid = require('gridfs-stream');
// The Package is passed automatically as first parameter
module.exports = function(Admin, app, auth, database, circles) {
var gfs = new Grid(database.connection.connections[0].db, database.connection.mongo);
var mean = require('meanio');
var requiresAdmin = circles.controller.hasCircle('admin');
//Setting up the users api
var users = require('../controllers/users');
app.get('/api/admin/users', requiresAdmin, users.all);
app.post('/api/admin/users', requiresAdmin, users.create);
app.put('/api/admin/users/:userId', requiresAdmin, users.update);
app.delete('/api/admin/users/:userId', requiresAdmin, users.destroy);
//Setting up the themes api
// var themes = require('../controllers/themes');
// app.get('/api/admin/themes', requiresAdmin, function(req, res) {
// themes.save(req, res, gfs);
// });
// app.get('/api/admin/themes/defaultTheme', requiresAdmin, function(req, res) {
// themes.defaultTheme(req, res, gfs);
// });
app.get('/api/admin/modules', requiresAdmin, function(req, res) {
//var modules = mean.exportable_modules_list;
//res.jsonp(modules);
//for (var index in mean.resolved) {
// //console.log(mean.resolved);
// if (mean.resolved[index].result) console.log(mean.resolved[index].result.loadedmodule);
//}
});
// var settings = require('../controllers/settings');
// app.get('/api/admin/settings', requiresAdmin, settings.get);
// app.put('/api/admin/settings', requiresAdmin, settings.save);
var moduleSettings = require('../controllers/module-settings');
app.get('/api/admin/moduleSettings/:name', requiresAdmin, moduleSettings.get);
app.post('/api/admin/moduleSettings/:name', requiresAdmin, moduleSettings.save);
app.put('/api/admin/moduleSettings/:name', requiresAdmin, moduleSettings.update);
};
|
// This class is written to handle basic animation item with default canvas
$dh.Require(["ctrl/richcanvas","util/animation","util/color"]);
$dh.isLoaded("ctrl/animitem", true);
$dh.newClass("DHAnimItem", DHRichCanvas, DHMotion, {
init: function(container, props) {
DHRichCanvas.prototype.init.apply(this, [container, props]);
if (container && !container.tagName) {
props = container;
}
this.initAnimation(props);
this.draw(props);
},
/**
* Set animation destination
*/
setAnimDes: function(animDes) {
this.setAnimation(animDes);
},
/**
* Set animation destination by delta
*/
setAnimDelta: function(animDelta) {
this.setAnimation(animDelta, null, null, true);
},
/**
* Initialize animation properties
*/
initAnimation: function(props) {
// Val is percentage
var self = this;
this.setPropValue = function(val) {
for (var p in self.animDelta) {
if (p.toLowerCase().match(/color/)) {
var r = Math.floor(self.animStart[p].r + self.animDelta[p].r * val / 100);
var g = Math.floor(self.animStart[p].g + self.animDelta[p].g * val / 100);
var b = Math.floor(self.animStart[p].b + self.animDelta[p].b * val / 100);
r = (r> 255)? 255: (r < 0 ? 0: r);
g = (g> 255)? 255: (g < 0 ? 0: g);
b = (b> 255)? 255: (b < 0 ? 0: b);
self[p]= "rgb("+r+","+g+","+b+")";
} else {
self[p] = Math.floor(self.animStart[p] + self.animDelta[p] * val / 100);
}
}
self.draw();
self.onAnimation(val);
self.raise("onanimation", val);
}
this.addEv("onstart", function() {self.onAnimStart();self.raise("onanimstart");} );
this.addEv("onstop", function() {self.onAnimStop();self.raise("onanimstop");} );
this.targetObj = this.canvas;
this.setParams(props.exeFunc, props.duration);
// Set default anim values
this.animStart = this.animStart || props;
this.canvas.style.position = "absolute";
// By default, all given options will become Item's properties
this.animDelta = this.animDelta || {};
//$dh.set(this.animDelta, this.animStart);
// Compatible with old version -- not really tidy but works
this.animation = this;
$dh.preventLeak(this, "animation");
},
/**
* Draw object using specified properties.
* If _deltaFlag_ is true, des is treated as difference (delta)
*/
draw: function(des, duration , exeFunc, _deltaFlag_) {
if ($dh.isNil(duration)) {
if ($dh.isNil(des)) des = {}; // On animation
for (var p in this.animStart) { // For redraw at anytime
if ($dh.isNil(des[p])) des[p] = this[p];
}
this.setProps(des);
}
else {
this.setAnimation(des, duration, exeFunc, _deltaFlag_);
this.start();
}
},
drawDelta: function(delta, duration, exeFunc) {
this.draw(delta, duration, exeFunc, true);
},
// If _deltaFlag_ is true, don't need to calculate animDelta
setAnimation: function(des, duration, exeFunc, _deltaFlag_) {
this.setParams(exeFunc || DHMotion.AnimEffects.strongEaseOut, duration);
des = des || {};
this.animDelta = _deltaFlag_ ? des : {};
this.animStart = {};
for (var p in des) { // Save animation's start status & calculate difference
this.animStart[p] = this.getProp(p);
// Special process for color
if (p.toLowerCase().match(/color/)) {
this.animStart[p] = $dh.color.getRGBHash(this.animStart[p]);
des[p] = $dh.color.getRGBHash(des[p]);
}
if (!_deltaFlag_) {
try {
if (p.toLowerCase().match(/color/)) {
this.animDelta[p] = {};
this.animDelta[p].r = des[p].r - this.animStart[p].r;
this.animDelta[p].g = des[p].g - this.animStart[p].g;
this.animDelta[p].b = des[p].b - this.animStart[p].b;
}
else
this.animDelta[p] = des[p] - this.animStart[p];
} catch (_error_) {}
}
}
},
onAnimation: function() {},
onAnimStart: function() { },
onAnimStop: function() { }
});
|
// All code points with the `Uppercase` derived core property as per Unicode v6.3.0:
[
0x41,
0x42,
0x43,
0x44,
0x45,
0x46,
0x47,
0x48,
0x49,
0x4A,
0x4B,
0x4C,
0x4D,
0x4E,
0x4F,
0x50,
0x51,
0x52,
0x53,
0x54,
0x55,
0x56,
0x57,
0x58,
0x59,
0x5A,
0xC0,
0xC1,
0xC2,
0xC3,
0xC4,
0xC5,
0xC6,
0xC7,
0xC8,
0xC9,
0xCA,
0xCB,
0xCC,
0xCD,
0xCE,
0xCF,
0xD0,
0xD1,
0xD2,
0xD3,
0xD4,
0xD5,
0xD6,
0xD8,
0xD9,
0xDA,
0xDB,
0xDC,
0xDD,
0xDE,
0x100,
0x102,
0x104,
0x106,
0x108,
0x10A,
0x10C,
0x10E,
0x110,
0x112,
0x114,
0x116,
0x118,
0x11A,
0x11C,
0x11E,
0x120,
0x122,
0x124,
0x126,
0x128,
0x12A,
0x12C,
0x12E,
0x130,
0x132,
0x134,
0x136,
0x139,
0x13B,
0x13D,
0x13F,
0x141,
0x143,
0x145,
0x147,
0x14A,
0x14C,
0x14E,
0x150,
0x152,
0x154,
0x156,
0x158,
0x15A,
0x15C,
0x15E,
0x160,
0x162,
0x164,
0x166,
0x168,
0x16A,
0x16C,
0x16E,
0x170,
0x172,
0x174,
0x176,
0x178,
0x179,
0x17B,
0x17D,
0x181,
0x182,
0x184,
0x186,
0x187,
0x189,
0x18A,
0x18B,
0x18E,
0x18F,
0x190,
0x191,
0x193,
0x194,
0x196,
0x197,
0x198,
0x19C,
0x19D,
0x19F,
0x1A0,
0x1A2,
0x1A4,
0x1A6,
0x1A7,
0x1A9,
0x1AC,
0x1AE,
0x1AF,
0x1B1,
0x1B2,
0x1B3,
0x1B5,
0x1B7,
0x1B8,
0x1BC,
0x1C4,
0x1C7,
0x1CA,
0x1CD,
0x1CF,
0x1D1,
0x1D3,
0x1D5,
0x1D7,
0x1D9,
0x1DB,
0x1DE,
0x1E0,
0x1E2,
0x1E4,
0x1E6,
0x1E8,
0x1EA,
0x1EC,
0x1EE,
0x1F1,
0x1F4,
0x1F6,
0x1F7,
0x1F8,
0x1FA,
0x1FC,
0x1FE,
0x200,
0x202,
0x204,
0x206,
0x208,
0x20A,
0x20C,
0x20E,
0x210,
0x212,
0x214,
0x216,
0x218,
0x21A,
0x21C,
0x21E,
0x220,
0x222,
0x224,
0x226,
0x228,
0x22A,
0x22C,
0x22E,
0x230,
0x232,
0x23A,
0x23B,
0x23D,
0x23E,
0x241,
0x243,
0x244,
0x245,
0x246,
0x248,
0x24A,
0x24C,
0x24E,
0x370,
0x372,
0x376,
0x386,
0x388,
0x389,
0x38A,
0x38C,
0x38E,
0x38F,
0x391,
0x392,
0x393,
0x394,
0x395,
0x396,
0x397,
0x398,
0x399,
0x39A,
0x39B,
0x39C,
0x39D,
0x39E,
0x39F,
0x3A0,
0x3A1,
0x3A3,
0x3A4,
0x3A5,
0x3A6,
0x3A7,
0x3A8,
0x3A9,
0x3AA,
0x3AB,
0x3CF,
0x3D2,
0x3D3,
0x3D4,
0x3D8,
0x3DA,
0x3DC,
0x3DE,
0x3E0,
0x3E2,
0x3E4,
0x3E6,
0x3E8,
0x3EA,
0x3EC,
0x3EE,
0x3F4,
0x3F7,
0x3F9,
0x3FA,
0x3FD,
0x3FE,
0x3FF,
0x400,
0x401,
0x402,
0x403,
0x404,
0x405,
0x406,
0x407,
0x408,
0x409,
0x40A,
0x40B,
0x40C,
0x40D,
0x40E,
0x40F,
0x410,
0x411,
0x412,
0x413,
0x414,
0x415,
0x416,
0x417,
0x418,
0x419,
0x41A,
0x41B,
0x41C,
0x41D,
0x41E,
0x41F,
0x420,
0x421,
0x422,
0x423,
0x424,
0x425,
0x426,
0x427,
0x428,
0x429,
0x42A,
0x42B,
0x42C,
0x42D,
0x42E,
0x42F,
0x460,
0x462,
0x464,
0x466,
0x468,
0x46A,
0x46C,
0x46E,
0x470,
0x472,
0x474,
0x476,
0x478,
0x47A,
0x47C,
0x47E,
0x480,
0x48A,
0x48C,
0x48E,
0x490,
0x492,
0x494,
0x496,
0x498,
0x49A,
0x49C,
0x49E,
0x4A0,
0x4A2,
0x4A4,
0x4A6,
0x4A8,
0x4AA,
0x4AC,
0x4AE,
0x4B0,
0x4B2,
0x4B4,
0x4B6,
0x4B8,
0x4BA,
0x4BC,
0x4BE,
0x4C0,
0x4C1,
0x4C3,
0x4C5,
0x4C7,
0x4C9,
0x4CB,
0x4CD,
0x4D0,
0x4D2,
0x4D4,
0x4D6,
0x4D8,
0x4DA,
0x4DC,
0x4DE,
0x4E0,
0x4E2,
0x4E4,
0x4E6,
0x4E8,
0x4EA,
0x4EC,
0x4EE,
0x4F0,
0x4F2,
0x4F4,
0x4F6,
0x4F8,
0x4FA,
0x4FC,
0x4FE,
0x500,
0x502,
0x504,
0x506,
0x508,
0x50A,
0x50C,
0x50E,
0x510,
0x512,
0x514,
0x516,
0x518,
0x51A,
0x51C,
0x51E,
0x520,
0x522,
0x524,
0x526,
0x531,
0x532,
0x533,
0x534,
0x535,
0x536,
0x537,
0x538,
0x539,
0x53A,
0x53B,
0x53C,
0x53D,
0x53E,
0x53F,
0x540,
0x541,
0x542,
0x543,
0x544,
0x545,
0x546,
0x547,
0x548,
0x549,
0x54A,
0x54B,
0x54C,
0x54D,
0x54E,
0x54F,
0x550,
0x551,
0x552,
0x553,
0x554,
0x555,
0x556,
0x10A0,
0x10A1,
0x10A2,
0x10A3,
0x10A4,
0x10A5,
0x10A6,
0x10A7,
0x10A8,
0x10A9,
0x10AA,
0x10AB,
0x10AC,
0x10AD,
0x10AE,
0x10AF,
0x10B0,
0x10B1,
0x10B2,
0x10B3,
0x10B4,
0x10B5,
0x10B6,
0x10B7,
0x10B8,
0x10B9,
0x10BA,
0x10BB,
0x10BC,
0x10BD,
0x10BE,
0x10BF,
0x10C0,
0x10C1,
0x10C2,
0x10C3,
0x10C4,
0x10C5,
0x10C7,
0x10CD,
0x1E00,
0x1E02,
0x1E04,
0x1E06,
0x1E08,
0x1E0A,
0x1E0C,
0x1E0E,
0x1E10,
0x1E12,
0x1E14,
0x1E16,
0x1E18,
0x1E1A,
0x1E1C,
0x1E1E,
0x1E20,
0x1E22,
0x1E24,
0x1E26,
0x1E28,
0x1E2A,
0x1E2C,
0x1E2E,
0x1E30,
0x1E32,
0x1E34,
0x1E36,
0x1E38,
0x1E3A,
0x1E3C,
0x1E3E,
0x1E40,
0x1E42,
0x1E44,
0x1E46,
0x1E48,
0x1E4A,
0x1E4C,
0x1E4E,
0x1E50,
0x1E52,
0x1E54,
0x1E56,
0x1E58,
0x1E5A,
0x1E5C,
0x1E5E,
0x1E60,
0x1E62,
0x1E64,
0x1E66,
0x1E68,
0x1E6A,
0x1E6C,
0x1E6E,
0x1E70,
0x1E72,
0x1E74,
0x1E76,
0x1E78,
0x1E7A,
0x1E7C,
0x1E7E,
0x1E80,
0x1E82,
0x1E84,
0x1E86,
0x1E88,
0x1E8A,
0x1E8C,
0x1E8E,
0x1E90,
0x1E92,
0x1E94,
0x1E9E,
0x1EA0,
0x1EA2,
0x1EA4,
0x1EA6,
0x1EA8,
0x1EAA,
0x1EAC,
0x1EAE,
0x1EB0,
0x1EB2,
0x1EB4,
0x1EB6,
0x1EB8,
0x1EBA,
0x1EBC,
0x1EBE,
0x1EC0,
0x1EC2,
0x1EC4,
0x1EC6,
0x1EC8,
0x1ECA,
0x1ECC,
0x1ECE,
0x1ED0,
0x1ED2,
0x1ED4,
0x1ED6,
0x1ED8,
0x1EDA,
0x1EDC,
0x1EDE,
0x1EE0,
0x1EE2,
0x1EE4,
0x1EE6,
0x1EE8,
0x1EEA,
0x1EEC,
0x1EEE,
0x1EF0,
0x1EF2,
0x1EF4,
0x1EF6,
0x1EF8,
0x1EFA,
0x1EFC,
0x1EFE,
0x1F08,
0x1F09,
0x1F0A,
0x1F0B,
0x1F0C,
0x1F0D,
0x1F0E,
0x1F0F,
0x1F18,
0x1F19,
0x1F1A,
0x1F1B,
0x1F1C,
0x1F1D,
0x1F28,
0x1F29,
0x1F2A,
0x1F2B,
0x1F2C,
0x1F2D,
0x1F2E,
0x1F2F,
0x1F38,
0x1F39,
0x1F3A,
0x1F3B,
0x1F3C,
0x1F3D,
0x1F3E,
0x1F3F,
0x1F48,
0x1F49,
0x1F4A,
0x1F4B,
0x1F4C,
0x1F4D,
0x1F59,
0x1F5B,
0x1F5D,
0x1F5F,
0x1F68,
0x1F69,
0x1F6A,
0x1F6B,
0x1F6C,
0x1F6D,
0x1F6E,
0x1F6F,
0x1FB8,
0x1FB9,
0x1FBA,
0x1FBB,
0x1FC8,
0x1FC9,
0x1FCA,
0x1FCB,
0x1FD8,
0x1FD9,
0x1FDA,
0x1FDB,
0x1FE8,
0x1FE9,
0x1FEA,
0x1FEB,
0x1FEC,
0x1FF8,
0x1FF9,
0x1FFA,
0x1FFB,
0x2102,
0x2107,
0x210B,
0x210C,
0x210D,
0x2110,
0x2111,
0x2112,
0x2115,
0x2119,
0x211A,
0x211B,
0x211C,
0x211D,
0x2124,
0x2126,
0x2128,
0x212A,
0x212B,
0x212C,
0x212D,
0x2130,
0x2131,
0x2132,
0x2133,
0x213E,
0x213F,
0x2145,
0x2160,
0x2161,
0x2162,
0x2163,
0x2164,
0x2165,
0x2166,
0x2167,
0x2168,
0x2169,
0x216A,
0x216B,
0x216C,
0x216D,
0x216E,
0x216F,
0x2183,
0x24B6,
0x24B7,
0x24B8,
0x24B9,
0x24BA,
0x24BB,
0x24BC,
0x24BD,
0x24BE,
0x24BF,
0x24C0,
0x24C1,
0x24C2,
0x24C3,
0x24C4,
0x24C5,
0x24C6,
0x24C7,
0x24C8,
0x24C9,
0x24CA,
0x24CB,
0x24CC,
0x24CD,
0x24CE,
0x24CF,
0x2C00,
0x2C01,
0x2C02,
0x2C03,
0x2C04,
0x2C05,
0x2C06,
0x2C07,
0x2C08,
0x2C09,
0x2C0A,
0x2C0B,
0x2C0C,
0x2C0D,
0x2C0E,
0x2C0F,
0x2C10,
0x2C11,
0x2C12,
0x2C13,
0x2C14,
0x2C15,
0x2C16,
0x2C17,
0x2C18,
0x2C19,
0x2C1A,
0x2C1B,
0x2C1C,
0x2C1D,
0x2C1E,
0x2C1F,
0x2C20,
0x2C21,
0x2C22,
0x2C23,
0x2C24,
0x2C25,
0x2C26,
0x2C27,
0x2C28,
0x2C29,
0x2C2A,
0x2C2B,
0x2C2C,
0x2C2D,
0x2C2E,
0x2C60,
0x2C62,
0x2C63,
0x2C64,
0x2C67,
0x2C69,
0x2C6B,
0x2C6D,
0x2C6E,
0x2C6F,
0x2C70,
0x2C72,
0x2C75,
0x2C7E,
0x2C7F,
0x2C80,
0x2C82,
0x2C84,
0x2C86,
0x2C88,
0x2C8A,
0x2C8C,
0x2C8E,
0x2C90,
0x2C92,
0x2C94,
0x2C96,
0x2C98,
0x2C9A,
0x2C9C,
0x2C9E,
0x2CA0,
0x2CA2,
0x2CA4,
0x2CA6,
0x2CA8,
0x2CAA,
0x2CAC,
0x2CAE,
0x2CB0,
0x2CB2,
0x2CB4,
0x2CB6,
0x2CB8,
0x2CBA,
0x2CBC,
0x2CBE,
0x2CC0,
0x2CC2,
0x2CC4,
0x2CC6,
0x2CC8,
0x2CCA,
0x2CCC,
0x2CCE,
0x2CD0,
0x2CD2,
0x2CD4,
0x2CD6,
0x2CD8,
0x2CDA,
0x2CDC,
0x2CDE,
0x2CE0,
0x2CE2,
0x2CEB,
0x2CED,
0x2CF2,
0xA640,
0xA642,
0xA644,
0xA646,
0xA648,
0xA64A,
0xA64C,
0xA64E,
0xA650,
0xA652,
0xA654,
0xA656,
0xA658,
0xA65A,
0xA65C,
0xA65E,
0xA660,
0xA662,
0xA664,
0xA666,
0xA668,
0xA66A,
0xA66C,
0xA680,
0xA682,
0xA684,
0xA686,
0xA688,
0xA68A,
0xA68C,
0xA68E,
0xA690,
0xA692,
0xA694,
0xA696,
0xA722,
0xA724,
0xA726,
0xA728,
0xA72A,
0xA72C,
0xA72E,
0xA732,
0xA734,
0xA736,
0xA738,
0xA73A,
0xA73C,
0xA73E,
0xA740,
0xA742,
0xA744,
0xA746,
0xA748,
0xA74A,
0xA74C,
0xA74E,
0xA750,
0xA752,
0xA754,
0xA756,
0xA758,
0xA75A,
0xA75C,
0xA75E,
0xA760,
0xA762,
0xA764,
0xA766,
0xA768,
0xA76A,
0xA76C,
0xA76E,
0xA779,
0xA77B,
0xA77D,
0xA77E,
0xA780,
0xA782,
0xA784,
0xA786,
0xA78B,
0xA78D,
0xA790,
0xA792,
0xA7A0,
0xA7A2,
0xA7A4,
0xA7A6,
0xA7A8,
0xA7AA,
0xFF21,
0xFF22,
0xFF23,
0xFF24,
0xFF25,
0xFF26,
0xFF27,
0xFF28,
0xFF29,
0xFF2A,
0xFF2B,
0xFF2C,
0xFF2D,
0xFF2E,
0xFF2F,
0xFF30,
0xFF31,
0xFF32,
0xFF33,
0xFF34,
0xFF35,
0xFF36,
0xFF37,
0xFF38,
0xFF39,
0xFF3A,
0x10400,
0x10401,
0x10402,
0x10403,
0x10404,
0x10405,
0x10406,
0x10407,
0x10408,
0x10409,
0x1040A,
0x1040B,
0x1040C,
0x1040D,
0x1040E,
0x1040F,
0x10410,
0x10411,
0x10412,
0x10413,
0x10414,
0x10415,
0x10416,
0x10417,
0x10418,
0x10419,
0x1041A,
0x1041B,
0x1041C,
0x1041D,
0x1041E,
0x1041F,
0x10420,
0x10421,
0x10422,
0x10423,
0x10424,
0x10425,
0x10426,
0x10427,
0x1D400,
0x1D401,
0x1D402,
0x1D403,
0x1D404,
0x1D405,
0x1D406,
0x1D407,
0x1D408,
0x1D409,
0x1D40A,
0x1D40B,
0x1D40C,
0x1D40D,
0x1D40E,
0x1D40F,
0x1D410,
0x1D411,
0x1D412,
0x1D413,
0x1D414,
0x1D415,
0x1D416,
0x1D417,
0x1D418,
0x1D419,
0x1D434,
0x1D435,
0x1D436,
0x1D437,
0x1D438,
0x1D439,
0x1D43A,
0x1D43B,
0x1D43C,
0x1D43D,
0x1D43E,
0x1D43F,
0x1D440,
0x1D441,
0x1D442,
0x1D443,
0x1D444,
0x1D445,
0x1D446,
0x1D447,
0x1D448,
0x1D449,
0x1D44A,
0x1D44B,
0x1D44C,
0x1D44D,
0x1D468,
0x1D469,
0x1D46A,
0x1D46B,
0x1D46C,
0x1D46D,
0x1D46E,
0x1D46F,
0x1D470,
0x1D471,
0x1D472,
0x1D473,
0x1D474,
0x1D475,
0x1D476,
0x1D477,
0x1D478,
0x1D479,
0x1D47A,
0x1D47B,
0x1D47C,
0x1D47D,
0x1D47E,
0x1D47F,
0x1D480,
0x1D481,
0x1D49C,
0x1D49E,
0x1D49F,
0x1D4A2,
0x1D4A5,
0x1D4A6,
0x1D4A9,
0x1D4AA,
0x1D4AB,
0x1D4AC,
0x1D4AE,
0x1D4AF,
0x1D4B0,
0x1D4B1,
0x1D4B2,
0x1D4B3,
0x1D4B4,
0x1D4B5,
0x1D4D0,
0x1D4D1,
0x1D4D2,
0x1D4D3,
0x1D4D4,
0x1D4D5,
0x1D4D6,
0x1D4D7,
0x1D4D8,
0x1D4D9,
0x1D4DA,
0x1D4DB,
0x1D4DC,
0x1D4DD,
0x1D4DE,
0x1D4DF,
0x1D4E0,
0x1D4E1,
0x1D4E2,
0x1D4E3,
0x1D4E4,
0x1D4E5,
0x1D4E6,
0x1D4E7,
0x1D4E8,
0x1D4E9,
0x1D504,
0x1D505,
0x1D507,
0x1D508,
0x1D509,
0x1D50A,
0x1D50D,
0x1D50E,
0x1D50F,
0x1D510,
0x1D511,
0x1D512,
0x1D513,
0x1D514,
0x1D516,
0x1D517,
0x1D518,
0x1D519,
0x1D51A,
0x1D51B,
0x1D51C,
0x1D538,
0x1D539,
0x1D53B,
0x1D53C,
0x1D53D,
0x1D53E,
0x1D540,
0x1D541,
0x1D542,
0x1D543,
0x1D544,
0x1D546,
0x1D54A,
0x1D54B,
0x1D54C,
0x1D54D,
0x1D54E,
0x1D54F,
0x1D550,
0x1D56C,
0x1D56D,
0x1D56E,
0x1D56F,
0x1D570,
0x1D571,
0x1D572,
0x1D573,
0x1D574,
0x1D575,
0x1D576,
0x1D577,
0x1D578,
0x1D579,
0x1D57A,
0x1D57B,
0x1D57C,
0x1D57D,
0x1D57E,
0x1D57F,
0x1D580,
0x1D581,
0x1D582,
0x1D583,
0x1D584,
0x1D585,
0x1D5A0,
0x1D5A1,
0x1D5A2,
0x1D5A3,
0x1D5A4,
0x1D5A5,
0x1D5A6,
0x1D5A7,
0x1D5A8,
0x1D5A9,
0x1D5AA,
0x1D5AB,
0x1D5AC,
0x1D5AD,
0x1D5AE,
0x1D5AF,
0x1D5B0,
0x1D5B1,
0x1D5B2,
0x1D5B3,
0x1D5B4,
0x1D5B5,
0x1D5B6,
0x1D5B7,
0x1D5B8,
0x1D5B9,
0x1D5D4,
0x1D5D5,
0x1D5D6,
0x1D5D7,
0x1D5D8,
0x1D5D9,
0x1D5DA,
0x1D5DB,
0x1D5DC,
0x1D5DD,
0x1D5DE,
0x1D5DF,
0x1D5E0,
0x1D5E1,
0x1D5E2,
0x1D5E3,
0x1D5E4,
0x1D5E5,
0x1D5E6,
0x1D5E7,
0x1D5E8,
0x1D5E9,
0x1D5EA,
0x1D5EB,
0x1D5EC,
0x1D5ED,
0x1D608,
0x1D609,
0x1D60A,
0x1D60B,
0x1D60C,
0x1D60D,
0x1D60E,
0x1D60F,
0x1D610,
0x1D611,
0x1D612,
0x1D613,
0x1D614,
0x1D615,
0x1D616,
0x1D617,
0x1D618,
0x1D619,
0x1D61A,
0x1D61B,
0x1D61C,
0x1D61D,
0x1D61E,
0x1D61F,
0x1D620,
0x1D621,
0x1D63C,
0x1D63D,
0x1D63E,
0x1D63F,
0x1D640,
0x1D641,
0x1D642,
0x1D643,
0x1D644,
0x1D645,
0x1D646,
0x1D647,
0x1D648,
0x1D649,
0x1D64A,
0x1D64B,
0x1D64C,
0x1D64D,
0x1D64E,
0x1D64F,
0x1D650,
0x1D651,
0x1D652,
0x1D653,
0x1D654,
0x1D655,
0x1D670,
0x1D671,
0x1D672,
0x1D673,
0x1D674,
0x1D675,
0x1D676,
0x1D677,
0x1D678,
0x1D679,
0x1D67A,
0x1D67B,
0x1D67C,
0x1D67D,
0x1D67E,
0x1D67F,
0x1D680,
0x1D681,
0x1D682,
0x1D683,
0x1D684,
0x1D685,
0x1D686,
0x1D687,
0x1D688,
0x1D689,
0x1D6A8,
0x1D6A9,
0x1D6AA,
0x1D6AB,
0x1D6AC,
0x1D6AD,
0x1D6AE,
0x1D6AF,
0x1D6B0,
0x1D6B1,
0x1D6B2,
0x1D6B3,
0x1D6B4,
0x1D6B5,
0x1D6B6,
0x1D6B7,
0x1D6B8,
0x1D6B9,
0x1D6BA,
0x1D6BB,
0x1D6BC,
0x1D6BD,
0x1D6BE,
0x1D6BF,
0x1D6C0,
0x1D6E2,
0x1D6E3,
0x1D6E4,
0x1D6E5,
0x1D6E6,
0x1D6E7,
0x1D6E8,
0x1D6E9,
0x1D6EA,
0x1D6EB,
0x1D6EC,
0x1D6ED,
0x1D6EE,
0x1D6EF,
0x1D6F0,
0x1D6F1,
0x1D6F2,
0x1D6F3,
0x1D6F4,
0x1D6F5,
0x1D6F6,
0x1D6F7,
0x1D6F8,
0x1D6F9,
0x1D6FA,
0x1D71C,
0x1D71D,
0x1D71E,
0x1D71F,
0x1D720,
0x1D721,
0x1D722,
0x1D723,
0x1D724,
0x1D725,
0x1D726,
0x1D727,
0x1D728,
0x1D729,
0x1D72A,
0x1D72B,
0x1D72C,
0x1D72D,
0x1D72E,
0x1D72F,
0x1D730,
0x1D731,
0x1D732,
0x1D733,
0x1D734,
0x1D756,
0x1D757,
0x1D758,
0x1D759,
0x1D75A,
0x1D75B,
0x1D75C,
0x1D75D,
0x1D75E,
0x1D75F,
0x1D760,
0x1D761,
0x1D762,
0x1D763,
0x1D764,
0x1D765,
0x1D766,
0x1D767,
0x1D768,
0x1D769,
0x1D76A,
0x1D76B,
0x1D76C,
0x1D76D,
0x1D76E,
0x1D790,
0x1D791,
0x1D792,
0x1D793,
0x1D794,
0x1D795,
0x1D796,
0x1D797,
0x1D798,
0x1D799,
0x1D79A,
0x1D79B,
0x1D79C,
0x1D79D,
0x1D79E,
0x1D79F,
0x1D7A0,
0x1D7A1,
0x1D7A2,
0x1D7A3,
0x1D7A4,
0x1D7A5,
0x1D7A6,
0x1D7A7,
0x1D7A8,
0x1D7CA
]; |
import Keen from '../../../lib/server';
import config from '../helpers/client-config';
describe('.deferEvent(s) methods', () => {
let client1;
beforeEach(() => {
Keen.enabled = false;
client1 = new Keen({
projectId: config.projectId,
writeKey: config.writeKey,
requestType: 'xhr',
host: config.host,
protocol: config.protocol
});
});
it('should have a queue', () => {
expect(client1.queue).toBeInstanceOf(Object);
});
it('should overwrite capacity and interval settings with accessor methods', () => {
client1.queueCapacity(10);
client1.queueInterval(11);
expect(client1.queue.config.capacity).toBe(10);
expect(client1.queue.config.interval).toBe(11);
});
it('should push individual deferred events into a queue', () => {
client1.deferEvent('deferred event', { test: 'data' });
expect(client1.queue.events['deferred event']).toBeInstanceOf(Array);
expect(client1.queue.events['deferred event'][0]).toEqual({ test: 'data' });
});
it('should push sets of deferred events into a queue', () => {
client1.deferEvents({
'deferred event': [{ test: 'data' }, { test: 'none' }],
'another event': [{ test: 'data' }]
});
expect(client1.queue.events['deferred event']).toBeInstanceOf(Array);
expect(client1.queue.events['another event']).toBeInstanceOf(Array);
expect(client1.queue.events['deferred event'][0]).toEqual({ test: 'data' });
expect(client1.queue.events['deferred event'][1]).toEqual({ test: 'none' });
expect(client1.queue.events['another event'][0]).toEqual({ test: 'data' });
});
it('should attempt to record events from the queue at given interval', () => {
client1.queueInterval(1);
client1.on('recordDeferredEvents', (data) => {
expect(data).toBeInstanceOf(Object);
expect(data['deferred event']).toBeInstanceOf(Array);
expect(data['another event']).toBeInstanceOf(Array);
expect(data['deferred event'][0]).toEqual({ test: 'data' });
expect(data['deferred event'][1]).toEqual({ test: 'none' });
expect(data['another event'][0]).toEqual({ test: 'data' });
});
client1.deferEvents({
'deferred event': [{ test: 'data' }, { test: 'none' }],
'another event': [{ test: 'data' }]
});
});
it('should attempt to record events from the queue when capacity is met', () => {
client1.queueCapacity(3);
client1.on('recordDeferredEvents', (data) => {
expect(data).toBeInstanceOf(Object);
expect(data['deferred event']).toBeInstanceOf(Array);
expect(data['another event']).toBeInstanceOf(Array);
expect(data['deferred event'][0]).toEqual({ test: 'data' });
expect(data['deferred event'][1]).toEqual({ test: 'none' });
expect(data['another event'][0]).toEqual({ test: 'data' });
});
client1.deferEvents({
'deferred event': [{ test: 'data' }, { test: 'none' }],
'another event': [{ test: 'data' }]
});
});
it('should attempt to record events when .recordDeferredEvents is called', () => {
client1.on('recordDeferredEvents', (data) => {
expect(data).toBeInstanceOf(Object);
expect(data['deferred event']).toBeInstanceOf(Array);
expect(data['another event']).toBeInstanceOf(Array);
expect(data['deferred event'][0]).toEqual({ test: 'data' });
expect(data['deferred event'][1]).toEqual({ test: 'none' });
expect(data['another event'][0]).toEqual({ test: 'data' });
});
client1.deferEvents({
'deferred event': [{ test: 'data' }, { test: 'none' }],
'another event': [{ test: 'data' }]
});
client1.recordDeferredEvents();
});
it('should not have an internal queue timer until an event is added to the queue', () => {
expect(client1.queue.timer).toBe(null);
client1.deferEvent('single-deferred-event', { prop: true });
expect(client1.queue.timer).not.toBe(null);
});
it('should not have an internal queue timer until multiple events are added to the queue', () => {
expect(client1.queue.timer).toBe(null);
client1.deferEvents({
'deferred event': [{ test: 'data' }, { test: 'none' }],
'another event': [{ test: 'data' }]
});
expect(client1.queue.timer).not.toBe(null);
});
it('should clear internal queue timer when .queueInterval() is set to 0', () => {
expect(client1.queue.timer).toBe(null);
client1.deferEvent('single-deferred-event', { prop: true });
expect(client1.queue.timer).not.toBe(null);
client1.queueInterval(0);
expect(client1.queue.timer).toBe(null);
});
});
|
// # Custom Middleware
// The following custom middleware functions are all unit testable, and have accompanying unit tests in
// middleware_spec.js
var _ = require('underscore'),
express = require('express'),
busboy = require('./ghost-busboy'),
config = require('../config'),
path = require('path'),
api = require('../api'),
expressServer,
ONE_HOUR_MS = 60 * 60 * 1000;
function isBlackListedFileType(file) {
var blackListedFileTypes = ['.hbs', '.md', '.json'],
ext = path.extname(file);
return _.contains(blackListedFileTypes, ext);
}
function cacheServer(server) {
expressServer = server;
}
var middleware = {
// ### Auth Middleware
// Authenticate a request by redirecting to login if not logged in.
// We strip /ghost/ out of the redirect parameter for neatness
auth: function (req, res, next) {
if (!req.session.user) {
var reqPath = req.path.replace(/^\/ghost\/?/gi, ''),
redirect = '',
msg;
return api.notifications.browse().then(function (notifications) {
if (reqPath !== '') {
msg = {
type: 'error',
message: 'Please Sign In',
status: 'passive',
id: 'failedauth'
};
// let's only add the notification once
if (!_.contains(_.pluck(notifications, 'id'), 'failedauth')) {
api.notifications.add(msg);
}
redirect = '?r=' + encodeURIComponent(reqPath);
}
return res.redirect(config.paths().subdir + '/ghost/signin/' + redirect);
});
}
next();
},
// ## AuthApi Middleware
// Authenticate a request to the API by responding with a 401 and json error details
authAPI: function (req, res, next) {
if (!req.session.user) {
// TODO: standardize error format/codes/messages
res.json(401, { error: 'Please sign in' });
return;
}
next();
},
// Check if we're logged in, and if so, redirect people back to dashboard
// Login and signup forms in particular
redirectToDashboard: function (req, res, next) {
if (req.session.user) {
return res.redirect(config.paths().subdir + '/ghost/');
}
next();
},
// While we're here, let's clean up on aisle 5
// That being ghost.notifications, and let's remove the passives from there
// plus the local messages, as they have already been added at this point
// otherwise they'd appear one too many times
cleanNotifications: function (req, res, next) {
/*jslint unparam:true*/
api.notifications.browse().then(function (notifications) {
_.each(notifications, function (notification) {
if (notification.status === 'passive') {
api.notifications.destroy(notification);
}
});
next();
});
},
// ### CacheControl Middleware
// provide sensible cache control headers
cacheControl: function (options) {
/*jslint unparam:true*/
var profiles = {
'public': 'public, max-age=0',
'private': 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0'
},
output;
if (_.isString(options) && profiles.hasOwnProperty(options)) {
output = profiles[options];
}
return function cacheControlHeaders(req, res, next) {
if (output) {
res.set({'Cache-Control': output});
}
next();
};
},
// ### whenEnabled Middleware
// Selectively use middleware
// From https://github.com/senchalabs/connect/issues/676#issuecomment-9569658
whenEnabled: function (setting, fn) {
return function settingEnabled(req, res, next) {
// Set from server/middleware/index.js for now
if (expressServer.enabled(setting)) {
fn(req, res, next);
} else {
next();
}
};
},
staticTheme: function () {
return function blackListStatic(req, res, next) {
if (isBlackListedFileType(req.url)) {
return next();
}
return middleware.forwardToExpressStatic(req, res, next);
};
},
// to allow unit testing
forwardToExpressStatic: function (req, res, next) {
api.settings.read('activeTheme').then(function (activeTheme) {
// For some reason send divides the max age number by 1000
express['static'](path.join(config.paths().themePath, activeTheme.value), {maxAge: ONE_HOUR_MS})(req, res, next);
});
},
conditionalCSRF: function (req, res, next) {
var csrf = express.csrf();
// CSRF is needed for admin only
if (res.isAdmin) {
csrf(req, res, next);
return;
}
next();
},
busboy: busboy
};
module.exports = middleware;
module.exports.cacheServer = cacheServer; |
(function () {
"use strict";
angular.module('app.widgets', [
'ui.bootstrap',
'ngFileUpload',
'multipleSelection'
]);
})(); |
function getGridTable() {
return this.tcmGridTableSelector || (this.tcmGridTableSelector = $("#TCMGridTable"));
}
function HolidaysHelper(year) {
this.year = year || new Date().getFullYear();
this.calculatePascua();
this.parsers = {};
this.dates = [];
}
HolidaysHelper.DayOfWeek = {};
HolidaysHelper.DaysArray = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
for (var i = 0, lengthD = HolidaysHelper.DaysArray.length; i < lengthD; ++i) {
HolidaysHelper.DayOfWeek[HolidaysHelper.DaysArray[i]] = i;
}
HolidaysHelper.Months = {};
HolidaysHelper.MonthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
for (var j = 0, lengthM = HolidaysHelper.MonthNames.length; j < lengthM; ++j) {
HolidaysHelper.Months[HolidaysHelper.MonthNames[j]] = j;
}
HolidaysHelper.prototype.nextWeekDay = function (weekDay, realDate, daysToAdd, backward) {
var date = new Date(realDate.getTime()),
dayAddition = (backward ? -1 : 1);
if (daysToAdd) {
date.setDate(date.getDate() + daysToAdd);
}
while (date.getDay() !== weekDay) {
date.setDate(date.getDate() + dayAddition);
}
return date;
};
HolidaysHelper.prototype.previousWeekDay = function (weekDay, date, daysToAdd) {
return this.nextWeekDay(weekDay, date, daysToAdd, true);
};
HolidaysHelper.prototype.addDate = function (date, data) {
this.dates.push({date: date, data: data});
};
HolidaysHelper.prototype.addParser = function (name, parser) {
this.parsers[name] = parser;
};
HolidaysHelper.prototype.getHolidays = function (parserName) {
var parser;
if (parserName && this.parsers.hasOwnProperty(parserName)) {
parser = this.parsers[parserName];
} else {
parser = function (date) {
return date;
};
}
return this.dates.sort(function (a, b) {
return a.date > b.date ? 1 : -1;
}).map(function (date) {
return parser(date.date, date.data);
});
};
HolidaysHelper.prototype.calculatePascua = function () {
var a, b, c, d, e;
var year = this.year, m = 24, n = 5;
switch (true) {
case (year >= 1583 && year <= 1699):
m = 22;
n = 2;
break;
case(year >= 1700 && year <= 1799) :
m = 23;
n = 3;
break;
case (year >= 1800 && year <= 1899) :
m = 23;
n = 4;
break;
case (year >= 1900 && year <= 2099) :
m = 24;
n = 5;
break;
case (year >= 2100 && year <= 2199) :
m = 24;
n = 6;
break;
case (year >= 2200 && year <= 2299) :
m = 25;
n = 0;
break;
}
a = year % 19;
b = year % 4;
c = year % 7;
d = ((a * 19) + m) % 30;
e = ((2 * b) + (4 * c) + (6 * d) + n) % 7;
var day = d + e;
if (day < 10)
return (this.pascua = new Date(year, HolidaysHelper.Months.March, day + 22));
else {
if (day == 26)
day = 19;
else if (day == 25 && d == 28 && e == 6 && a > 10)
day = 18;
else
day -= 9;
return (this.pascua = new Date(year, HolidaysHelper.Months.April, day));
}
};
|
'use strict';
// MODULES //
var test = require( 'tape' );
var urls = require( './../lib' );
// TESTS //
test( 'main export is a function', function test( t ) {
t.ok( typeof urls === 'function', 'main export is a function' );
t.end();
});
test( 'an `options` argument is required', function test( t ) {
t.throws( foo, TypeError, 'throws error' );
t.end();
function foo() {
urls();
}
});
test( 'a repository `owner` must be specified', function test( t ) {
t.throws( foo, TypeError, 'throws error' );
t.end();
function foo() {
urls({
'repo': 'beep'
});
}
});
test( 'a repository name must be specified', function test( t ) {
t.throws( foo, TypeError, 'throws error' );
t.end();
function foo() {
urls({
'owner': 'beep'
});
}
});
test( 'the function returns an object containing `image` and `url` fields', function test( t ) {
var out = urls({
'owner': 'beep',
'repo': 'boop'
});
t.equal( typeof out.image, 'string', 'image field is a string' );
t.equal( typeof out.url, 'string', 'url field is a string' );
t.end();
});
test( 'the `image` field corresponds to a shields.io badge url', function test( t ) {
var out = urls({
'owner': 'beep',
'repo': 'boop'
});
t.equal( out.image, 'https://img.shields.io/github/stars/beep/boop.svg?style=social&label=Star&link=https://github.com/beep/boop&link=https://github.com/beep/boop/stargazers', 'image url' );
t.end();
});
test( 'the `url` field corresponds to the repository url on Github', function test( t ) {
var out = urls({
'owner': 'beep',
'repo': 'boop'
});
t.equal( out.url, 'https://github.com/beep/boop', 'Github url' );
t.end();
});
test( 'the default social action is `star`', function test( t ) {
var out = urls({
'owner': 'beep',
'repo': 'boop'
});
t.equal( out.image, 'https://img.shields.io/github/stars/beep/boop.svg?style=social&label=Star&link=https://github.com/beep/boop&link=https://github.com/beep/boop/stargazers', 'image url' );
t.end();
});
test( 'the social action can be specified', function test( t ) {
var out;
// Fork:
out = urls({
'owner': 'beep',
'repo': 'boop',
'action': 'fork'
});
t.equal( out.image, 'https://img.shields.io/github/forks/beep/boop.svg?style=social&label=Fork&link=https://github.com/beep/boop&link=https://github.com/beep/boop/network', 'image url' );
// Watch:
out = urls({
'owner': 'beep',
'repo': 'boop',
'action': 'watch'
});
t.equal( out.image, 'https://img.shields.io/github/watchers/beep/boop.svg?style=social&label=Watch&link=https://github.com/beep/boop&link=https://github.com/beep/boop/watchers', 'image url' );
// Star:
out = urls({
'owner': 'beep',
'repo': 'boop',
'action': 'star'
});
t.equal( out.image, 'https://img.shields.io/github/stars/beep/boop.svg?style=social&label=Star&link=https://github.com/beep/boop&link=https://github.com/beep/boop/stargazers', 'image url' );
t.end();
});
test( 'the default badge style is `social`', function test( t ) {
var out = urls({
'owner': 'beep',
'repo': 'boop'
});
t.equal( out.image, 'https://img.shields.io/github/stars/beep/boop.svg?style=social&label=Star&link=https://github.com/beep/boop&link=https://github.com/beep/boop/stargazers', 'image url' );
t.end();
});
test( 'the badge style can be specified', function test( t ) {
var out = urls({
'owner': 'beep',
'repo': 'boop',
'style': 'flat'
});
t.equal( out.image, 'https://img.shields.io/github/stars/beep/boop.svg?style=flat&label=stars', 'image url' );
t.end();
});
test( 'the default badge format is `svg`', function test( t ) {
var out = urls({
'owner': 'beep',
'repo': 'boop'
});
t.equal( out.image, 'https://img.shields.io/github/stars/beep/boop.svg?style=social&label=Star&link=https://github.com/beep/boop&link=https://github.com/beep/boop/stargazers', 'image url' );
t.end();
});
test( 'the badge format can be specified', function test( t ) {
var out = urls({
'owner': 'beep',
'repo': 'boop',
'format': 'png'
});
t.equal( out.image, 'https://img.shields.io/github/stars/beep/boop.png?style=social&label=Star&link=https://github.com/beep/boop&link=https://github.com/beep/boop/stargazers', 'image url' );
t.end();
});
|
viewController.prototype.loadBaseMesh = function (mesh, ext, onsuccess, onerror) {
var http_request = new XMLHttpRequest();
var url = "base_mesh.php?mesh="+mesh+"&ext="+ext;
var vc_id = ""+this.id;
http_request.onreadystatechange = handle_json.bind(this);
http_request.open("GET", url, true);
http_request.send(null);
function handle_json() {
var vc = this;
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var json_data = http_request.responseText;
var json = JSON.parse(json_data);
var i;
for (var i = 0; i< json.vertices.length; i++ ){
vc.mesh.geometry.vertices.push( new THREE.Vertex( new THREE.Vector3(json.vertices[i][0], json.vertices[i][1], json.vertices[i][2] )) );
}
for (var i = 0; i< json.faces.length; i++ ){
vc.mesh.geometry.faces.push( new THREE.Face3( json.faces[i][0], json.faces[i][1], json.faces[i][2] ) );
}
vc.initView();
onsuccess();
} else {
alert('Server connection error.');
onerror();
}
http_request = null;
}
}
}
|
import TaskModel from '../../../../database/models/task-model'
var createTask = require('../create-task')
var sut_createTask = createTask.default
describe('database', () => {
describe('controllers', () => {
describe('task controller',() => {
describe('create task', () => {
it ('should reject if the created task model throws an exception', (done) => {
// arrange
var taskId = 'task id'
var options = { taskId }
var somethingWentWrong = new Error('error creating model')
var createModel = root.sandbox.stub(TaskModel, 'create').throws(somethingWentWrong)
// act
var promise = sut_createTask(options)
// assert
promise.catch((error) => {
expect(createModel).to.have.been.calledWith({ taskId })
expect(error).to.equal(somethingWentWrong)
done()
})
})
it ('should resolve if the task model is created', (done) => {
// arrange
var taskId = 'task id'
var options = { taskId }
var taskModel = {
taskId,
save : () => Promise.resolve(taskModel)
}
var createModel = root.sandbox.stub(TaskModel, 'create').returns(taskModel)
// act
var promise = sut_createTask(options)
// assert
promise.then((result) => {
expect(createModel).to.have.been.calledWith({ taskId })
expect(result).to.equal(taskModel)
done()
}).catch(done)
})
it ('should reject if the task model cannot be saved', (done) => {
// arrange
var taskId = 'task id'
var options = { taskId }
var taskModel = {
taskId,
save : () => Promise.reject('error saving')
}
var createModel = root.sandbox.stub(TaskModel, 'create').returns(taskModel)
var saveSpy = sinon.spy(taskModel, 'save')
// act
var promise = sut_createTask(options)
// assert
promise.catch((error) => {
expect(createModel).to.have.been.calledWith({ taskId })
expect(saveSpy).to.have.been.called
expect(error).to.equal('error saving')
done()
})
})
it ('should reject if the created task model throws an exception', (done) => {
// arrange
var taskId = 'task id'
var options = { taskId }
var somethingWentWrong = new Error('error creating model')
var createModel = root.sandbox.stub(TaskModel, 'create').throws(somethingWentWrong)
// act
var promise = sut_createTask(options)
// assert
promise.catch((error) => {
expect(createModel).to.have.been.calledWith({ taskId })
expect(error).to.equal(somethingWentWrong)
done()
})
})
it ('should throw exception if the task id is null', () => {
var options = null
expect(createTask.default.bind(createTask, options)).to.throw('taskId cannot be null')
})
})
})
})
}) |
angular.module('tragile.sprints')
.controller('SprintEntryCtrl', function SprintEntryCtrl ($scope, api, sprint, Project, Status, Ticket){
$scope.sprint = sprint;
Project.get(sprint.project).then(function(project){
$scope.projectCodeName = project.code_name;
});
Status.getAll(sprint.project).then(function(statuses){
var groups = {};
_.each(statuses, function(status){
groups[status.id] = [];
});
Ticket.getByProjectCodeName(sprint.project['code_name']).then(function(tickets){
_.each(tickets, function(ticket){
ticket.fetchAllData();
groups[ticket.status].push(ticket);
});
$scope.groups = groups;
$scope.statuses = statuses;
});
});
$scope.dropCallback = function (event, ui, statusId) {
_.each($scope.groups[statusId], function (ticket) {
if (ticket.status !== statusId) {
var newTicket = api.copy(ticket);
newTicket.status = statusId;
newTicket.save();
}
});
};
});
|
/**
* Function that returns default values.
* Used because Object.assign does a shallow instead of a deep copy.
* Using [].push will add to the base array, so a require will alter
* the base array output.
*/
'use strict';
const path = require('path');
const srcPath = path.join(__dirname, '/../src');
const dfltPort = 8000;
/**
* Get the default modules object for webpack
* @return {Object}
*/
function getDefaultModules() {
return {
preLoaders: [
{
test: /\.(js|jsx)$/,
include: srcPath,
loader: 'eslint-loader'
}
],
loaders: [
{
test: /\.css$/,
loader: 'style-loader!css-loader!autoprefixer-loader?{browsers:["last 2 version","firefox 15"]}'
},
{
test: /\.scss/,
loader: 'style-loader!css-loader!autoprefixer-loader?{browsers:["last 2 version","firefox 15"]}!sass-loader?outputStyle=expanded'
},
{
test: /\.json$/,
loader: 'json-loader'
},
{
test: /\.(png|jpg|gif|woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader?limit=8192'
},
{
test: /\.(mp4|ogg|svg)$/,
loader: 'file-loader'
}
]
};
}
module.exports = {
srcPath: srcPath,
publicPath: 'assets/',
port: dfltPort,
getDefaultModules: getDefaultModules
};
|
import React, { Component } from 'react'; //eslint-disable-line no-unused-vars
import Transition from '../base/Transition'; //eslint-disable-line no-unused-vars
const ZvuiModalFade = props =>
<Transition
{...props}
className={'fade'}
enteredClassName={'in'}
enteringClassName={'in'}
/>;
export default ZvuiModalFade;
|
import AddPost from '../../components/posts/AddPost';
import withNavigationBar from '../../components/app/NavigationBar';
import getAddPostContainer from '../../../common/containers/posts/AddPostContainer';
export default getAddPostContainer(AddPost, withNavigationBar);
|
module.exports.getTemplate = (type = 'class', name) => {
const template = []
if (type === 'route') {
template.push(
`/* eslint-disable */`,
`/* tslint:disable: max-line-length */\n`,
`import { loadComponent } from 'utils'\n`,
`export const routes: Route[] = [`,
`\t{`,
`\t\tpath: 'page',`,
`\t\tcomponent: loadComponent(() =>`,
`\t\t\timport(\n\t\t\t\t/* webpackChunkName: "${name}", webpackMode: "lazy-once", webpackPrefetch: true */\n\t\t\t\t'./'\n\t\t\t)`,
`\t\t),`,
`\t\ttitle: 'Page title',`,
`\t\tdescription: 'Page description',`,
`\t}`,
`]\n`,
)
}
if (type === 'styles') {
template.push(
`@import 'styles/_global.scss';\n`,
`.radio {`,
`\tcolor: $c-black;`,
`}\n`,
)
}
if (type === 'function') {
template.push(
`import * as React from 'react'\n`,
`import * as css from './styles.scss'`,
`import { classes } from 'helpers'`,
`import { P } from './types'`,
`import { StyledDiv } from './styled'\n`,
`const cx = classes.bind(css)\n`,
`export default function ${name} ({ className = '' }: P) {`,
`\treturn <StyledDiv className={cx({ test: true }, className)} />`,
`}\n`,
`export { ${name} }\n`,
)
}
if (type === 'class') {
template.push(
`import * as React from 'react'\n`,
`import * as css from './styles.scss'`,
`import { classes } from 'helpers'`,
`import { P, S } from './types'`,
`import { StyledDiv, StyledButton } from './styled'\n`,
`const cx = classes.bind(css)\n`,
`export default class ${name} extends React.Component<P, S> {\n`,
`\tstatic defaultProps = {`,
`\t\tvalue: '',`,
`\t\tinteger: false,`,
`\t}\n`,
`\tref: any = React.createRef()\n`,
`\tstate = {`,
`\t\tvalue: '',`,
`\t}\n`,
`\tstatic getDerivedStateFromProps (props: P, state: S) {`,
`\t\tif (state.value !== props.value) {`,
`\t\t\treturn {`,
`\t\t\t\t...state,`,
`\t\t\t\t...props,`,
`\t\t\t}`,
`\t\t}`,
`\t\treturn null`,
`\t}\n`,
`\tshouldComponentUpdate (props: P) {`,
`\t\tconst { value } = this.props`,
`\t\treturn !(value === props.value)`,
`\t}\n`,
`\tcomponentDidMount () {`,
`\t\tconsole.log('componentDidMount')`,
`\t}\n`,
`\tcomponentDidUpdate (props: P, state: S) {`,
`\t\tconsole.log('du', props, state)`,
`\t}\n`,
`\tcomponentWillUnmount () {}\n`,
`\thandleClick = (e: any) => {`,
`\t\tthis.setState((state: S) => ({ ...state, value: e.target.value }))\n`,
`\t\tif (this.props.handleClick) {`,
`\t\t\tthis.props.handleClick(e)`,
`\t\t}`,
`\t}\n`,
`\trender () {`,
`\t\tconst { className } = this.props\n`,
`\t\treturn (`,
`\t\t\t<StyledDiv className={cx({ test: true }, className)}>`,
`\t\t\t\t<StyledButton onClick={this.handleClick} />`,
`\t\t\t</StyledDiv>`,
`\t\t)`,
`\t}\n`,
`}\n`,
`export { ${name} }\n`,
)
}
if (['types.class', 'types.function'].indexOf(type) >= 0) {
template.push(
`export interface P {`,
`\timg: any;`,
`\tvalue: string;`,
`\tenum?: 'button' | 'text';`,
`\twidth?: number;`,
`\tsimple?: boolean;`,
`\thandleChange?: (e: Event) => void | boolean;`,
`\tchildren?: JSX.Element[] | JSX.Element | any;`,
`}\n`,
)
}
if (type === 'types.class') {
template.push(
`export interface S {`,
`\tvalue?: string | number;`,
`}\n`,
)
}
if (type === 'styled') {
template.push(
`import styled, { css } from 'styled-components'`,
`import CommonStyles from 'theme/common-styles'\n`,
`export const StyledDiv = styled.div\``,
`\t\${CommonStyles.themeColor};`,
`\tbackground: transparent;`,
`\tborder-radius: 3px;`,
`\tborder: 2px solid palevioletred;`,
`\tcolor: palevioletred;`,
`\toutline: 0;`,
`\tcursor: pointer;`,
`\tmargin: 0.5em 1em;`,
`\tpadding: 0.25em 1em;\n`,
`\t&:hover {`,
`\t\tborder-color: #f00;`,
`\t\tbackground-color: #f00;`,
`\t}\n`,
`\t\${(props: any) => props.primary && css\``,
`\t\tbackground: palevioletred;`,
`\t\tcolor: white;`,
`\t\`}`,
`\`\n`,
`export const StyledButton = styled.button\`\`\n`,
)
}
return template.join('\n').replace(/\t/g, ' ')
}
module.exports.folderName = (str) => {
return str.replace(/\s+/g, '-').toLowerCase();
}
module.exports.componentName = (str) => {
return str.replace(/(\b\w)/gi, (m) => m.toUpperCase()).replace(/\s+/g, '').replace(/-/g, '');
}
|
/*
* bella
* https://github.com/chrisenytc/bella
*
* Copyright (c) 2014, Christopher EnyTC
* Licensed under the MIT license.
*/
'use strict';
/*
* Module Dependencies
*/
var hat = require('hat'),
rack = hat.rack(),
_ = require('underscore');
/**
* @class Bella
*
* @constructor
*
* Constructor responsible for provide a bootstrap
*
* @example
*
* app.use(bella.init(mongoose, {connection: conn, uri: dbUri, status: true, model: userModel}));
*
* @param {Object} mongoose Mongoose instance
* @param {Object} options Options for Bella
* @return {Function} Returns a middleware
*/
exports.init = function Bella(mongoose, options) {
//Create Mongoose Schema
var Schema = mongoose.Schema,
db = options.connection;
//Create Mongoose connection
if (options.uri) {
mongoose.connect(options.uri, function(err) {
if (err) {
throw err;
}
});
//Get connection
db = mongoose.connection;
}
//Create Mongoose Model
var PermissionSchema = new Schema({
access_token: {
type: String,
required: true,
unique: true
},
ip: {
type: String,
required: true
},
domain: {
type: String,
required: true
},
permissions: {
type: Array,
default: ['user']
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
//Set default permissions
exports.enableStatus = options.status || false;
exports.UserModel = options.model || db.model('User');
exports.PermissionModel = db.model('Permission', PermissionSchema);
//Return a middleware
return function init(req, res, next) {
next();
};
};
/**
* Method responsible for creating the access_tokens to be used by the authentication system
*
* @example
*
* bella.create(req.user, ['user', 'create_article'], '127.0.0.1', 'example.com', function(err, access_token) {
* console.log('Token: ' + access_token);
* });
*
* @method create
* @param {Object} user A user
* @param {String} permissions A array list of permissions
* @param {String} ip A new Ip
* @param {String} domain A new Domain
* @param {Function} cb A callback with the error and a new access_token
* @return {Function} Returns a callback
*/
exports.create = function create(user, permissions, ip, domain, cb) {
//Fallback
cb = cb || function() {};
//Make a new access_token with this data
var access_token = rack();
//Create new User with this data
var permissionAuth = new exports.PermissionModel({
access_token: access_token,
ip: ip,
domain: domain,
permissions: permissions,
user: user
});
//Save this token in database
try {
permissionAuth.save(function(err) {
//If error throw this error
if (err) {
throw err;
} else {
//Return a callback with access_token
cb(null, access_token);
}
});
} catch (e) {
cb(e, null);
}
};
/**
* Method responsible for removing users
*
* @example
*
* bella.remove('YOUR ACCESS TOKEN', function(err, access_token) {
* console.log('Token: ' + access_token + 'Deleted');
* });
*
* @method remove
* @param {String} access_token A Access Token generated by create method
* @param {Function} cb A callback with the error
* @return {Function} Returns a callback
*/
exports.remove = function remove(access_token, cb) {
//Fallback
cb = cb || function() {};
//delete this user on database
try {
exports.PermissionModel.remove({
access_token: access_token
}, function(err) {
//If error throw this error
if (err) {
throw err;
} else {
//Return a callback with access_token
cb(null, access_token);
}
});
} catch (e) {
//Return a callback with access_token
cb(e, null);
}
};
/**
* Method responsible for authenticating access the API.
* Only users with Access Token, Domain and IP authenticated can access the API.
*
* @example
*
* app.configure(function() {
* app.use(bella.init(mongoose, {connection: conn, uri: dbUri, status: true, model: userModel}));
* app.use(bella.authenticate());
* });
*
* //OR
*
* app.get('/users', bella.authenticate('user'), ctrl);
*
* @method authenticate
* @param {String} permission The required permission
* @return {Function} Returns a middleware
*/
exports.authenticate = function authenticate(permission) {
//Save this scope
var that = exports;
// return a middleware
return function authenticate(req, res, next) {
//Callback
function callback(msg) {
//Access denied
if (typeof msg === 'string') {
msg = msg;
} else {
msg = msg.message;
}
res.jsonp(401, {
metadata: {
status: 401,
msg: 'Unauthorized'
},
response: {
msg: 'Bad Authentication. You do not have permission to access the API.',
error: msg
}
});
}
//Check if all permissions exists
function inPermissionList(list, permission) {
return _.contains(list, permission);
}
//Check if user exists
return that.UserModel.findOne({
access_token: req.query.access_token
}).exec(function(err, data) {
if (err) {
return callback(err);
}
if (!data) {
return that.PermissionModel.findOne({
access_token: req.query.access_token
}).populate('user')
.exec(function(pErr, pData) {
if (pErr) {
return callback(pErr);
}
if (!pData) {
return callback('access_token not found');
}
if (req.host !== pData.domain || req.ip !== pData.ip) {
return callback('The IP or domain is different from registered for this access_token');
}
if (!inPermissionList(pData.permissions, permission)) {
return callback('This access_token not have the permissions to continue the request.');
}
//Create permissionData
req.user = pData;
req.profile = pData;
return next();
});
}
if (that.enableStatus) {
if (!data.status) {
return callback('Inactive User');
}
}
if (!inPermissionList(data.permissions, permission)) {
return callback('This access_token not have the permissions to continue the request.');
}
//Create userData
req.user = data;
req.profile = data;
//Access granted
return next();
});
};
};
|
QUnit.config.notrycatch = true;
QUnit.config.noglobals = true;
QUnit.module('hier', {
afterEach: function() {
hier.clear();
}
});
// path errors
QUnit.test('path error if it does not start with slash', function(assert) {
assert.raises(function() {
hier.add('node', 'elem', function() {});
}, /start with a slash/);
});
QUnit.test('path error at empty string nodes', function(assert) {
assert.raises(function() {
hier.add('//', 'elem', function() {});
}, /well-formed path/);
});
QUnit.test('path error at empty string', function(assert) {
assert.raises(function() {
hier.add('', 'elem', function() {});
}, /empty path/);
});
// add
QUnit.test('add a node', function(assert) {
hier.add('/node', '#qunit-fixture', function() {});
assert.equal(hier.show(), '(root (node))');
});
QUnit.test('add nested nodes', function(assert) {
hier.add('/node', '#qunit-fixture', function(elem) {
elem.innerHTML = '<div id="nested"></div><div id="another"></div>';
});
hier.add('/node/nested', '#nested', function() {});
hier.add('/node/another', '#another', function() {});
assert.equal(hier.show(), '(root (node (nested) (another)))');
});
QUnit.test('add invokes the update func', function(assert) {
hier.add('/node', '#qunit-fixture', function(elem) {
assert.equal(elem, document.querySelector('#qunit-fixture'));
});
});
QUnit.test('add invokes the update func with params', function(assert) {
hier.add('/node', '#qunit-fixture', function(elem, param) {
assert.equal(elem, document.querySelector('#qunit-fixture'));
assert.equal(param, 'param');
}, 'param');
});
QUnit.test('add an added node does nothing', function(assert) {
hier.add('/node', '#qunit-fixture', function() {});
hier.add('/node', '#qunit-fixture', function() {});
assert.equal(hier.show(), '(root (node))');
});
QUnit.test('add an added node updates only if needed', function(assert) {
var calledWith = [];
var update = function(elem, param) { calledWith.push(param); };
var params = [true, false, 42, NaN, '', 'string'];
var i;
for(i = 0; i < params.length; i++) {
hier.add('/node', '#qunit-fixture', update, params[i]);
hier.add('/node', '#qunit-fixture', update, params[i]);
}
assert.deepEqual(calledWith, params);
});
QUnit.test('add an added node updates, object param', function(assert) {
var counter = 0;
var update = function(elem, param) { counter += 1; };
hier.add('/node', '#qunit-fixture', update, {});
hier.add('/node', '#qunit-fixture', update, {});
hier.add('/node', '#qunit-fixture', update, {answer: 42});
hier.add('/node', '#qunit-fixture', update, {answer: 42});
assert.equal(counter, 4);
});
QUnit.test('add error at short add without reg', function(assert) {
assert.raises(function() {
hier.add('/node');
}, /find in registry/);
});
QUnit.test('add returns the return of the update func', function(assert) {
var update = function(elem) { return 42; };
assert.equal(hier.add('/node', '#qunit-fixture', update), 42);
assert.equal(hier.add('/node', '#qunit-fixture', update), 42);
});
// remove
QUnit.test('remove a node', function(assert) {
hier.add('/node', '#qunit-fixture', function() {});
hier.remove('/node');
assert.equal(hier.show(), '(root)');
});
QUnit.test('remove a nested node', function(assert) {
hier.add('/node', '#qunit-fixture', function(elem) {
elem.innerHTML = '<div id="nested"></div>';
});
hier.add('/node/nested', '#nested', function() {});
hier.remove('/node/nested');
assert.equal(hier.show(), '(root (node))');
});
QUnit.test('remove a parent node', function(assert) {
hier.add('/node', '#qunit-fixture', function(elem) {
elem.innerHTML = '<div id="nested"></div>';
});
hier.add('/node/nested', '#nested', function() {});
hier.remove('/node');
assert.equal(hier.show(), '(root)');
});
// update
QUnit.test('update invokes the update func', function(assert) {
assert.expect(2);
var update = function(elem) {
assert.equal(elem, document.querySelector('#qunit-fixture'));
};
hier.add('/node', '#qunit-fixture', update);
hier.update('/node');
});
QUnit.test('update invokes the update func with params', function(assert) {
assert.expect(4);
var update = function(elem, param) {
assert.equal(elem, document.querySelector('#qunit-fixture'));
assert.equal(param, 'param');
};
hier.add('/node', '#qunit-fixture', update, 'param');
hier.update('/node', 'param');
});
QUnit.test('update error at non-existing node', function(assert) {
hier.add('/node', '#qunit-fixture', function() {});
assert.raises(function() {
hier.update('/another');
}, /could not find path/i);
});
QUnit.test('update removes the children nodes', function(assert) {
hier.add('/node', '#qunit-fixture', function(elem) {
elem.innerHTML = '<div id="nested"></div>';
});
hier.add('/node/nested', '#nested', function() {});
hier.update('/node');
assert.equal(hier.show(), '(root (node))');
assert.equal(hier.has('/node/nested'), false);
});
QUnit.test('update returns the return of the update func', function(assert) {
var update = function(elem) { return 42; };
hier.add('/node', '#qunit-fixture', update);
assert.equal(hier.update('/node'), 42);
});
// has
QUnit.test('has checks correctly', function(assert) {
assert.equal(hier.has('/node'), false);
hier.add('/node', '#qunit-fixture', function() {});
assert.equal(hier.has('/node'), true);
hier.remove('/node');
assert.equal(hier.has('/node'), false);
});
QUnit.test('has is not confused by reg', function(assert) {
hier.reg('/node', '#qunit-fixture', function() {});
assert.equal(hier.has('/node'), false);
hier.add('/node');
assert.equal(hier.has('/node'), true);
hier.remove('/node');
assert.equal(hier.has('/node'), false);
});
// reg
QUnit.test('reg a node and add', function(assert) {
hier.reg('/node', '#qunit-fixture', function() {});
assert.equal(hier.show(), '(root)');
hier.add('/node');
assert.equal(hier.show(), '(root (node))');
});
QUnit.test('reg a nested node and add', function(assert) {
hier.reg('/node/nested', '#nested', function() {});
assert.equal(hier.show(), '(root)');
hier.add('/node', '#qunit-fixture', function(elem) {
elem.innerHTML = '<div id="nested"></div>';
});
assert.equal(hier.show(), '(root (node))');
hier.add('/node/nested');
assert.equal(hier.show(), '(root (node (nested)))');
});
QUnit.test('reg a node and add with params', function(assert) {
hier.reg('/node', '#qunit-fixture', function(elem, param) {
assert.equal(elem, document.querySelector('#qunit-fixture'));
assert.equal(param, 'param');
});
hier.add('/node', 'param');
});
QUnit.test('add an added regged node updates only if needed', function(assert) {
var calledWith = [];
var update = function(elem, param) { calledWith.push(param); };
var params = [true, false, 42, NaN, '', 'string'];
var i;
hier.reg('/node', '#qunit-fixture', update);
for(i = 0; i < params.length; i++) {
hier.add('/node', params[i]);
hier.add('/node', params[i]);
}
assert.deepEqual(calledWith, params);
});
QUnit.test('add a regged node returns correctly', function(assert) {
hier.reg('/node', '#qunit-fixture', function(elem) { return 42; });
assert.equal(hier.add('/node'), 42);
});
// on
QUnit.test('hook error at empty string', function(assert) {
assert.raises(function() {
hier.on('', function() {});
}, /could not identify hook/i);
});
QUnit.test('hook error at non-existent hook', function(assert) {
assert.raises(function() {
hier.on('hook', function() {});
}, /could not identify hook/i);
assert.raises(function() {
hier.on(undefined, function() {});
}, /could not identify hook/i);
assert.raises(function() {
hier.on(null, function() {});
}, /could not identify hook/i);
});
QUnit.test('pre-init works with one node', function(assert) {
assert.expect(3);
hier.on('pre-init', function(path, elem, param) {
assert.equal(path, '/node');
assert.equal(elem, document.getElementById('qunit-fixture'));
assert.equal(param, 42);
});
hier.add('/node', '#qunit-fixture', function() {}, 42);
hier.off('pre-init');
hier.add('/node', '#qunit-fixture', function() {}, 42);
});
QUnit.test('post-init works with one node', function(assert) {
assert.expect(3);
hier.on('post-init', function(path, elem, view) {
assert.equal(path, '/node');
assert.equal(elem, document.getElementById('qunit-fixture'));
assert.equal(view, 42);
});
hier.add('/node', '#qunit-fixture', function() { return 42; });
hier.off('post-init');
hier.add('/node', '#qunit-fixture', function() { return 42; });
});
QUnit.test('pre-empty works with one node', function(assert) {
assert.expect(3);
hier.add('/node', '#qunit-fixture', function() { return 42; });
hier.on('pre-empty', function(path, elem, view) {
assert.equal(path, '/node');
assert.equal(elem, document.getElementById('qunit-fixture'));
assert.equal(view, 42);
});
hier.remove('/node');
hier.add('/node', '#qunit-fixture', function() { return 42; });
hier.off('pre-empty');
hier.remove('/node');
});
QUnit.test('pre-empty hooks in before children are removed', function(assert) {
assert.expect(4);
hier.add('/node', '#qunit-fixture', function(elem) {
elem.innerHTML = '<div id="nested"></div>';
});
hier.add('/node/nested', '#nested', function() {});
hier.on('pre-empty', function(path, elem, view) {
assert.equal(hier.has('/node'), true);
assert.equal(hier.has('/node/nested'), true);
});
hier.remove('/node');
});
QUnit.test('pre-empty works when adding an added node that updates', function(assert) {
var update = function(elem, param) { return param; };
assert.expect(2);
hier.on('pre-empty', function(path, elem, view) {
assert.equal(path, '/node');
assert.equal(view, 'a');
});
hier.add('/node', '#qunit-fixture', update, 'a');
hier.add('/node', '#qunit-fixture', update, 'a');
hier.add('/node', '#qunit-fixture', update, 'b');
hier.add('/node', '#qunit-fixture', update, 'b');
});
QUnit.test('pre-remove works with one node', function(assert) {
assert.expect(3);
hier.add('/node', '#qunit-fixture', function() { return 42; });
hier.on('pre-remove', function(path, elem, view) {
assert.equal(path, '/node');
assert.equal(elem, document.getElementById('qunit-fixture'));
assert.equal(view, 42);
});
hier.remove('/node');
hier.add('/node', '#qunit-fixture', function() { return 42; });
hier.off('pre-remove');
hier.remove('/node');
});
QUnit.test('pre-remove hooks in after children are removed', function(assert) {
assert.expect(4);
hier.add('/node', '#qunit-fixture', function(elem) {
elem.innerHTML = '<div id="nested"></div>';
});
hier.add('/node/nested', '#nested', function() {});
hier.on('pre-remove', function(path, elem, view) {
if(path == '/node/nested') {
assert.equal(hier.has('/node'), true);
assert.equal(hier.has('/node/nested'), true);
} else if(path == '/node') {
assert.equal(hier.has('/node'), true);
assert.equal(hier.has('/node/nested'), false);
}
});
hier.remove('/node');
});
QUnit.test('pre-remove works when adding an added node that updates', function(assert) {
var update = function(elem, param) { return param; };
assert.expect(3);
hier.on('pre-remove', function(path, elem, view) {
assert.equal(path, '/node');
assert.equal(elem, document.getElementById('qunit-fixture'));
assert.equal(view, 'a');
});
hier.add('/node', '#qunit-fixture', update, 'a');
hier.add('/node', '#qunit-fixture', update, 'a');
hier.add('/node', '#qunit-fixture', update, 'b');
hier.add('/node', '#qunit-fixture', update, 'b');
});
QUnit.test('post-remove works with one node', function(assert) {
assert.expect(1);
hier.add('/node', '#qunit-fixture', function() {});
hier.on('post-remove', function(path) {
assert.equal(path, '/node');
});
hier.remove('/node');
hier.off('post-remove');
hier.add('/node', '#qunit-fixture', function() {});
hier.remove('/node');
});
// show
QUnit.test('show root on its own', function(assert) {
assert.equal(hier.show(), '(root)');
});
|
let lignes = 50;
let phrase = "Je ne recopierai pas l'exemple de Valentin";
document.addEventListener('DOMContentLoaded', function () {
let tableau = document.getElementById('tableau');
for (let index = 0; index < lignes; index++) {
tableau.insertAdjacentHTML("beforeend", `${phrase}<br />`);
}
}); |
if(typeof exports === 'object') {
var assert = require("assert");
var alasql = require('..');
var DOMStorage = require("dom-storage");
global.localStorage = new DOMStorage("./test381.json", { strict: false, ws: '' });
};
/*
This sample beased on this article:
http://stackoverflow.com/questions/30442969/group-by-in-angularjs
*/
describe('Test 384 - NOT NULL error when copying from another table issue #471', function() {
it('1. CREATE DATABASE',function(done){
alasql('CREATE DATABASE test384;USE test384');
done();
});
it('3. Create table issue - many statements', function(done){
alasql.options.modifier = "MATRIX";
alasql('CREATE TABLE tab3 (pk INTEGER NOT NULL)');
alasql('CREATE TABLE tab4 (pk INTEGER NOT NULL)');
alasql('INSERT INTO tab3 VALUES(3)');
alasql('INSERT INTO tab4 SELECT * FROM tab3');
var res = alasql('SELECT * FROM tab3');
assert.deepEqual(res,[[3]]);
done();
});
if(false) {
it('2. Create table issue - one statement', function(done){
alasql.options.modifier = "MATRIX";
alasql(function(){/*
CREATE TABLE tab0 (pk INTEGER NOT NULL);
CREATE TABLE tab1 (pk INTEGER NOT NULL);
INSERT INTO tab0 VALUES(3);
INSERT INTO tab1 SELECT * FROM tab0;
*/});
var res = alasql('SELECT * FROM tab3');
assert.deepEqual(res,[[3]]);
done();
});
}
it('99. DROP DATABASE',function(done){
alasql.options.modifier = undefined;
alasql('DROP DATABASE test384');
done();
});
});
|
cc.Class({
extends: cc.Component,
properties: {
direct:1,
tipbg:cc.Node,
light:cc.Node,
title:cc.Node,
frame1:cc.Node,
frame2:cc.Node,
prog:cc.ProgressBar,
icon:cc.Node,
l_gunlv:cc.Label,
l_pay:cc.Label,
l_cost:cc.Label,
islock:{
default:true, // 1弹出未达到条件 2弹出达到条件
visible:false
},
sx:{
default:0,
visible:false
},
tx:{
default:0,
visible:false
},
out:{ //是否弹出了
default:false,
visible:false
},
_enable:true,
},
// use this for initialization
onLoad: function () {
this.node.on('setdirect',function(event){
this.direct = event.detail.direct;
if(this.direct==2) {//右
this.node.x = cc.Canvas.instance.node.width/2 -42 ;
this.tipbg.x = -60;
}else{
this.node.x = -cc.Canvas.instance.node.width/2 + 42;
this.tipbg.x = 60;
this.tipbg.scaleX = -1;
//反向内容
// this.frame1.x-=95;
//this.frame2.x-=95;
this.title.scaleX = -1;
this.frame1.scaleX = -1;
this.frame2.scaleX = -1;
}
},this);
//设置 状态和文字
this.node.on('setstatus',function(event){
this.islock = event.detail.islock;
if(!this.islock )
{
this.light.active = true;
this.light.runAction(cc.repeatForever( cc.sequence(cc.fadeIn(0.8),cc.fadeOut(0.8) )));
}
else
this.light.active = false;
},this);
this.icon.on('touchend',function(){
if(!this._enable) return;
this._enable = false;
var bx=-175;
if(this.direct==1) bx= -bx;
if(this.out) bx = -bx;
var that = this;
var frame;
if(this.islock) frame = this.frame1;
else frame = this.frame2;
frame.active = !frame.active;
this.title.active = !this.title.active;
this.tipbg.runAction( cc.sequence(cc.moveBy(0.3,bx,0),cc.callFunc(function(){
that.out = !that.out;
that._enable = true;
})));
},this);
this.frame2.on('touchend',function(){
//点击解锁炮台
});
this.prog.progress = 2/10;
},
// called every frame, uncomment this function to activate update callback
// update: function (dt) {
// },
});
|
'use strict';
var Backbone = require('backbone');
var $ = require('jquery');
var Work = require('../models/Work');
var WorkView = require('../views/WorkView');
var WorkCollection = require('../models/WorkCollection');
var WorkCollectionView = require('../views/WorkCollectionView');
module.exports = Backbone.Router.extend({
routes: {
'works/:id': 'show',
'works': 'index'
},
show: function(id){
},
start: function(){
Backbone.history.start({pushState: true});
},
index: function() {
this.workList.fetch();
$('#Contact').replaceWith(this.workListView.el);
},
initialize: function() {
console.log("work router.js");
this.workList = new WorkCollection();
this.workListView = new WorkCollectionView({collection: this.workList});
}
});
|
/*! jQuery UI - v1.10.3 - 2013-09-23
* http://jqueryui.com
* Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(e){e.datepicker.regional.uk={closeText:"Закрити",prevText:"<",nextText:">",currentText:"Сьогодні",monthNames:["Січень","Лютий","Березень","Квітень","Травень","Червень","Липень","Серпень","Вересень","Жовтень","Листопад","Грудень"],monthNamesShort:["Січ","Лют","Бер","Кві","Тра","Чер","Лип","Сер","Вер","Жов","Лис","Гру"],dayNames:["неділя","понеділок","вівторок","середа","четвер","п’ятниця","субота"],dayNamesShort:["нед","пнд","вів","срд","чтв","птн","сбт"],dayNamesMin:["Нд","Пн","Вт","Ср","Чт","Пт","Сб"],weekHeader:"Тиж",dateFormat:"dd/mm/yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional.uk)}); |
// ==========================================================================
// SC.Statechart Unit Test
// ==========================================================================
/*globals SC statechart State */
var TestState;
var obj1, rootState1, stateA, stateB;
var obj2, rootState2, stateC, stateD;
module("SC.Statechart: invokeStateMethod Tests", {
setup: function() {
TestState = SC.State.extend({
testInvokedCount: 0,
arg1: undefined,
arg2: undefined,
returnValue: undefined,
testInvoked: function() {
return this.get('testInvokedCount') > 0;
}.property('testInvokedCount'),
test: function(arg1, arg2) {
this.set('testInvokedCount', this.get('testInvokedCount') + 1);
this.set('arg1', arg1);
this.set('arg2', arg2);
if (this.get('returnValue') !== undefined) {
return this.get('returnValue');
}
}
});
obj1 = SC.Object.extend(SC.StatechartManager, {
initialState: 'stateA',
rootStateExample: TestState.design({
testX: function(arg1, arg2) {
this.set('testInvokedCount', this.get('testInvokedCount') + 1);
this.set('arg1', arg1);
this.set('arg2', arg2);
if (this.get('returnValue') !== undefined) {
return this.get('returnValue');
}
}
}),
stateA: TestState.design(),
stateB: TestState.design()
});
obj1 = obj1.create();
rootState1 = obj1.get('rootState');
stateA = obj1.getState('stateA');
stateB = obj1.getState('stateB');
obj2 = SC.Object.extend(SC.StatechartManager, {
statesAreConcurrent: YES,
rootStateExample: TestState.design({
testX: function(arg1, arg2) {
this.set('testInvokedCount', this.get('testInvokedCount') + 1);
this.set('arg1', arg1);
this.set('arg2', arg2);
if (this.get('returnValue') !== undefined) {
return this.get('returnValue');
}
}
}),
stateC: TestState.design(),
stateD: TestState.design()
});
obj2 = obj2.create();
rootState2 = obj2.get('rootState');
stateC = obj2.getState('stateC');
stateD = obj2.getState('stateD');
},
teardown: function() {
TestState = obj1 = rootState1 = stateA = stateB = null;
obj2 = rootState2 = stateC = stateD = null;
}
});
test("check obj1 - invoke method test1", function() {
var result = obj1.invokeStateMethod('test1');
ok(!rootState1.get('testInvoked'), "root state test method should not have been invoked");
ok(!stateA.get('testInvoked'), "state A's test method should not have been invoked");
ok(!stateB.get('testInvoked'), "state B's test method should not have been invoked");
});
test("check obj1 - invoke method test, current state A, no args, no return value", function() {
var result = obj1.invokeStateMethod('test');
equals(stateA.get('testInvokedCount'), 1, "state A's test method should have been invoked once");
equals(stateA.get('arg1'), undefined, "state A's arg1 method should be undefined");
equals(stateA.get('arg2'), undefined, "state A's arg2 method should be undefined");
equals(result, undefined, "returned result should be undefined");
ok(!rootState1.get('testInvoked'), "root state's test method should not have been invoked");
ok(!stateB.get('testInvoked'), "state B's test method should not have been invoked");
});
test("check obj1 - invoke method test, current state A, one args, no return value", function() {
var result = obj1.invokeStateMethod('test', "frozen");
ok(stateA.get('testInvoked'), "state A's test method should have been invoked");
equals(stateA.get('arg1'), "frozen", "state A's arg1 method should be 'frozen'");
equals(stateA.get('arg2'), undefined, "state A's arg2 method should be undefined");
ok(!rootState1.get('testInvoked'), "root state's test method should not have been invoked");
ok(!stateB.get('testInvoked'), "state B's test method should not have been invoked");
});
test("check obj1 - invoke method test, current state A, two args, no return value", function() {
var result = obj1.invokeStateMethod('test', 'frozen', 'canuck');
ok(stateA.get('testInvoked'), "state A's test method should have been invoked");
equals(stateA.get('arg1'), "frozen", "state A's arg1 method should be 'frozen'");
equals(stateA.get('arg2'), "canuck", "state A's arg2 method should be undefined");
ok(!rootState1.get('testInvoked'), "root state's test method should not have been invoked");
ok(!stateB.get('testInvoked'), "state B's test method should not have been invoked");
});
test("check obj1 - invoke method test, current state A, no args, return value", function() {
stateA.set('returnValue', 100);
var result = obj1.invokeStateMethod('test');
ok(stateA.get('testInvoked'), "state A's test method should have been invoked");
equals(result, 100, "returned result should be 100");
ok(!rootState1.get('testInvoked'), "root state's test method should not have been invoked");
ok(!stateB.get('testInvoked'), "state B's test method should not have been invoked");
});
test("check obj1 - invoke method test, current state B, two args, return value", function() {
stateB.set('returnValue', 100);
obj1.gotoState(stateB);
ok(stateB.get('isCurrentState'), "state B should be curren state");
var result = obj1.invokeStateMethod('test', 'frozen', 'canuck');
ok(!stateA.get('testInvoked'), "state A's test method should not have been invoked");
equals(stateB.get('testInvokedCount'), 1, "state B's test method should have been invoked once");
equals(stateB.get('arg1'), 'frozen', "state B's arg1 method should be 'frozen'");
equals(stateB.get('arg2'), 'canuck', "state B's arg2 method should be 'canuck'");
equals(result, 100, "returned result should be 100");
ok(!rootState1.get('testInvoked'), "root state's test method should not have been invoked");
});
test("check obj1 - invoke method test, current state A, use callback", function() {
var callbackState, callbackResult;
obj1.invokeStateMethod('test', function(state, result) {
callbackState = state;
callbackResult = result;
});
ok(stateA.get('testInvoked'), "state A's test method should have been invoked");
ok(!stateB.get('testInvoked'), "state B's test method should not have been invoked");
equals(callbackState, stateA, "state should be state A");
equals(callbackResult, undefined, "result should be undefined");
ok(!rootState1.get('testInvoked'), "root state's test method should not have been invoked");
});
test("check obj1- invoke method test, current state B, use callback", function() {
var callbackState, callbackResult;
obj1.gotoState(stateB);
stateB.set('returnValue', 100);
obj1.invokeStateMethod('test', function(state, result) {
callbackState = state;
callbackResult = result;
});
ok(!stateA.get('testInvoked'), "state A's test method should not have been invoked");
ok(stateB.get('testInvoked'), "state B's test method should have been invoked");
equals(callbackState, stateB, "state should be state B");
equals(callbackResult, 100, "result should be 100");
ok(!rootState1.get('testInvoked'), "root state's test method should not have been invoked");
});
test("check obj1 - invoke method testX", function() {
rootState1.set('returnValue', 100);
var result = obj1.invokeStateMethod('testX');
equals(rootState1.get('testInvokedCount'), 1, "root state's testX method should not have been invoked once");
equals(result, 100, "result should have value 100");
ok(!stateA.get('testInvoked'), "state A's test method should have been invoked");
ok(!stateB.get('testInvoked'), "state B's test method should not have been invoked");
});
test("check obj2 - invoke method test1", function() {
var result = obj2.invokeStateMethod('test1');
ok(!rootState2.get('testInvoked'), "root state test method should not have been invoked");
ok(!stateC.get('testInvoked'), "state A's test method should not have been invoked");
ok(!stateD.get('testInvoked'), "state B's test method should not have been invoked");
});
test("check obj2 - invoke test, no args, no return value", function() {
var result = obj2.invokeStateMethod('test');
equals(stateC.get('testInvokedCount'), 1, "state C's test method should have been invoked once");
equals(stateD.get('testInvokedCount'), 1, "state D's test method should have been invoked once");
ok(!rootState1.get('testInvoked'), "root state test method should not have been invoked");
equals(stateC.get('arg1'), undefined, "state C's arg1 method should be undefined");
equals(stateC.get('arg2'), undefined, "state C's arg2 method should be undefined");
equals(stateD.get('arg1'), undefined, "state D's arg1 method should be undefined");
equals(stateD.get('arg2'), undefined, "state D's arg2 method should be undefined");
equals(result, undefined, "returned result should be undefined");
});
test("check obj2 - invoke test, two args, return value, callback", function() {
var numCallbacks = 0,
callbackInfo = {};
stateC.set('returnValue', 100);
stateD.set('returnValue', 200);
var result = obj2.invokeStateMethod('test', 'frozen', 'canuck', function(state, result) {
numCallbacks += 1;
callbackInfo['state' + numCallbacks] = state;
callbackInfo['result' + numCallbacks] = result;
});
ok(!rootState1.get('testInvoked'), "root state test method should not have been invoked");
equals(stateC.get('testInvokedCount'), 1, "state C's test method should have been invoked once");
equals(stateD.get('testInvokedCount'), 1, "state D's test method should have been invoked once");
equals(stateC.get('arg1'), 'frozen', "state C's arg1 method should be 'frozen'");
equals(stateC.get('arg2'), 'canuck', "state C's arg2 method should be 'canuck'");
equals(stateD.get('arg1'), 'frozen', "state D's arg1 method should be 'frozen'");
equals(stateD.get('arg2'), 'canuck', "state D's arg2 method should be 'canuck'");
equals(numCallbacks, 2, "callback should have been invoked twice");
equals(callbackInfo['state1'], stateC, "first callback state arg should be state C");
equals(callbackInfo['result1'], 100, "first callback result arg should be 100");
equals(callbackInfo['state2'], stateD, "second callback state arg should be state D");
equals(callbackInfo['result2'], 200, "second callback result arg should be 200");
equals(result, undefined, "returned result should be undefined");
});
test("check obj2 - invoke method testX", function() {
rootState2.set('returnValue', 100);
var result = obj2.invokeStateMethod('testX');
equals(rootState2.get('testInvokedCount'), 1, "root state's testX method should not have been invoked once");
equals(result, 100, "result should have value 100");
ok(!stateA.get('testInvoked'), "state A's test method should have been invoked");
ok(!stateB.get('testInvoked'), "state B's test method should not have been invoked");
}); |
if(process.env.NODE_ENV !== 'production'){
require("./mock");
}
import { getAwait, postAwait } from '@/utils/request'
export async function getTableData(params) {
const url = `/gateway/org/back/institutionService/query`
return await postAwait(url, params)
}
export async function updateState(params) {
const url = `/gateway/org/back/institutionService/logicDelIns`
return await postAwait(url, params)
}
export async function queryIns(params) {
const url = `/gateway/org/back/institutionService/queryIns`
return await postAwait(url, params)
}
export async function submitOrgForm(params) {
const url = `/gateway/org/back/institutionService/addIns`
return await postAwait(url, params)
}
|
var LevelEditor = function() {
};
var editor = new LevelEditor();
//Input.mouseDown.Register();
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = groupsopen;
var _exec = require('./_exec');
var _exec2 = _interopRequireDefault(_exec);
var _validate = require('./_validate');
var _validate2 = _interopRequireDefault(_validate);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// this file was generated by ./scripts/generate-web-api
function groupsopen(params, callback) {
var ns = 'groups.open';
var err = (0, _validate2.default)(ns, params);
if (err) {
callback(err);
} else {
(0, _exec2.default)(ns, params, callback);
}
}
module.exports = exports['default']; |
import cloneDeep from 'lodash/cloneDeep';
import * as actionCreators from './../action-creators';
import constants from './../../constants';
// import debug from './../../../debug';
// const log = debug('inline-edit/association-modal/orchestrators/update-association-description');
export default async (dispatch, relationship, event, item) => {
const items = cloneDeep(relationship.items);
const currentItem = items.find((anItem) => anItem.id === item.id);
currentItem.relnDescription = event.target.value;
constants.setDirty();
dispatch(actionCreators.updateItems(items));
};
|
/* gss-engine - version 1.0.2-beta (2014-05-06) - http://gridstylesheets.org */
;(function(){
/**
* Require the given path.
*
* @param {String} path
* @return {Object} exports
* @api public
*/
function require(path, parent, orig) {
var resolved = require.resolve(path);
// lookup failed
if (null == resolved) {
orig = orig || path;
parent = parent || 'root';
var err = new Error('Failed to require "' + orig + '" from "' + parent + '"');
err.path = orig;
err.parent = parent;
err.require = true;
throw err;
}
var module = require.modules[resolved];
// perform real require()
// by invoking the module's
// registered function
if (!module._resolving && !module.exports) {
var mod = {};
mod.exports = {};
mod.client = mod.component = true;
module._resolving = true;
module.call(this, mod.exports, require.relative(resolved), mod);
delete module._resolving;
module.exports = mod.exports;
}
return module.exports;
}
/**
* Registered modules.
*/
require.modules = {};
/**
* Registered aliases.
*/
require.aliases = {};
/**
* Resolve `path`.
*
* Lookup:
*
* - PATH/index.js
* - PATH.js
* - PATH
*
* @param {String} path
* @return {String} path or null
* @api private
*/
require.resolve = function(path) {
if (path.charAt(0) === '/') path = path.slice(1);
var paths = [
path,
path + '.js',
path + '.json',
path + '/index.js',
path + '/index.json'
];
for (var i = 0; i < paths.length; i++) {
var path = paths[i];
if (require.modules.hasOwnProperty(path)) return path;
if (require.aliases.hasOwnProperty(path)) return require.aliases[path];
}
};
/**
* Normalize `path` relative to the current path.
*
* @param {String} curr
* @param {String} path
* @return {String}
* @api private
*/
require.normalize = function(curr, path) {
var segs = [];
if ('.' != path.charAt(0)) return path;
curr = curr.split('/');
path = path.split('/');
for (var i = 0; i < path.length; ++i) {
if ('..' == path[i]) {
curr.pop();
} else if ('.' != path[i] && '' != path[i]) {
segs.push(path[i]);
}
}
return curr.concat(segs).join('/');
};
/**
* Register module at `path` with callback `definition`.
*
* @param {String} path
* @param {Function} definition
* @api private
*/
require.register = function(path, definition) {
require.modules[path] = definition;
};
/**
* Alias a module definition.
*
* @param {String} from
* @param {String} to
* @api private
*/
require.alias = function(from, to) {
if (!require.modules.hasOwnProperty(from)) {
throw new Error('Failed to alias "' + from + '", it does not exist');
}
require.aliases[to] = from;
};
/**
* Return a require function relative to the `parent` path.
*
* @param {String} parent
* @return {Function}
* @api private
*/
require.relative = function(parent) {
var p = require.normalize(parent, '..');
/**
* lastIndexOf helper.
*/
function lastIndexOf(arr, obj) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) return i;
}
return -1;
}
/**
* The relative require() itself.
*/
function localRequire(path) {
var resolved = localRequire.resolve(path);
return require(resolved, parent, path);
}
/**
* Resolve relative to the parent.
*/
localRequire.resolve = function(path) {
var c = path.charAt(0);
if ('/' == c) return path.slice(1);
if ('.' == c) return require.normalize(p, path);
// resolve deps by returning
// the dep in the nearest "deps"
// directory
var segs = parent.split('/');
var i = lastIndexOf(segs, 'deps') + 1;
if (!i) i = 0;
path = segs.slice(0, i + 1).join('/') + '/deps/' + path;
return path;
};
/**
* Check if module is defined at `path`.
*/
localRequire.exists = function(path) {
return require.modules.hasOwnProperty(localRequire.resolve(path));
};
return localRequire;
};
require.register("the-gss-preparser/lib/gss-preparser.js", function(exports, require, module){
module.exports = (function(){
/*
* Generated by PEG.js 0.7.0.
*
* http://pegjs.majda.cz/
*/
function quote(s) {
/*
* ECMA-262, 5th ed., 7.8.4: All characters may appear literally in a
* string literal except for the closing quote character, backslash,
* carriage return, line separator, paragraph separator, and line feed.
* Any character may appear in the form of an escape sequence.
*
* For portability, we also escape escape all control and non-ASCII
* characters. Note that "\0" and "\v" escape sequences are not used
* because JSHint does not like the first and IE the second.
*/
return '"' + s
.replace(/\\/g, '\\\\') // backslash
.replace(/"/g, '\\"') // closing quote character
.replace(/\x08/g, '\\b') // backspace
.replace(/\t/g, '\\t') // horizontal tab
.replace(/\n/g, '\\n') // line feed
.replace(/\f/g, '\\f') // form feed
.replace(/\r/g, '\\r') // carriage return
.replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g, escape)
+ '"';
}
var result = {
/*
* Parses the input with a generated parser. If the parsing is successfull,
* returns a value explicitly or implicitly specified by the grammar from
* which the parser was generated (see |PEG.buildParser|). If the parsing is
* unsuccessful, throws |PEG.parser.SyntaxError| describing the error.
*/
parse: function(input, startRule) {
var parseFunctions = {
"statements": parse_statements,
"statement": parse_statement,
"nestedStatement": parse_nestedStatement,
"nestedStatements": parse_nestedStatements,
"ccss": parse_ccss,
"ccssStartChar": parse_ccssStartChar,
"ccssOp": parse_ccssOp,
"ContextualCCSSLine": parse_ContextualCCSSLine,
"cssLine": parse_cssLine,
"vfl": parse_vfl,
"gtl": parse_gtl,
"cssBlock": parse_cssBlock,
"Ruleset": parse_Ruleset,
"Directive": parse_Directive,
"DirectiveName": parse_DirectiveName,
"BlockedStatements": parse_BlockedStatements,
"SelectorList": parse_SelectorList,
"SelectorListEnd": parse_SelectorListEnd,
"Selector": parse_Selector,
"comment": parse_comment,
"_": parse__,
"__": parse___,
"space": parse_space,
"anychar": parse_anychar,
"multitoend": parse_multitoend,
"anytoend": parse_anytoend,
"TextToColon": parse_TextToColon,
"TextToSemicolon": parse_TextToSemicolon,
"_terminators": parse__terminators,
"LineTerminator": parse_LineTerminator
};
if (startRule !== undefined) {
if (parseFunctions[startRule] === undefined) {
throw new Error("Invalid rule name: " + quote(startRule) + ".");
}
} else {
startRule = "statements";
}
var pos = 0;
var reportFailures = 0;
var rightmostFailuresPos = 0;
var rightmostFailuresExpected = [];
function padLeft(input, padding, length) {
var result = input;
var padLength = length - input.length;
for (var i = 0; i < padLength; i++) {
result = padding + result;
}
return result;
}
function escape(ch) {
var charCode = ch.charCodeAt(0);
var escapeChar;
var length;
if (charCode <= 0xFF) {
escapeChar = 'x';
length = 2;
} else {
escapeChar = 'u';
length = 4;
}
return '\\' + escapeChar + padLeft(charCode.toString(16).toUpperCase(), '0', length);
}
function matchFailed(failure) {
if (pos < rightmostFailuresPos) {
return;
}
if (pos > rightmostFailuresPos) {
rightmostFailuresPos = pos;
rightmostFailuresExpected = [];
}
rightmostFailuresExpected.push(failure);
}
function parse_statements() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = [];
result1 = parse_LineTerminator();
while (result1 !== null) {
result0.push(result1);
result1 = parse_LineTerminator();
}
if (result0 !== null) {
result2 = parse_statement();
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
result2 = parse_statement();
}
} else {
result1 = null;
}
if (result1 !== null) {
result2 = [];
result3 = parse_LineTerminator();
while (result3 !== null) {
result2.push(result3);
result3 = parse_LineTerminator();
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, s) {return s})(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
result0 = parse__();
}
return result0;
}
function parse_statement() {
var result0;
reportFailures++;
result0 = parse_Ruleset();
if (result0 === null) {
result0 = parse_ccss();
if (result0 === null) {
result0 = parse_Directive();
if (result0 === null) {
result0 = parse_cssLine();
}
}
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("Statement");
}
return result0;
}
function parse_nestedStatement() {
var result0;
reportFailures++;
result0 = parse_Ruleset();
if (result0 === null) {
result0 = parse_ccss();
if (result0 === null) {
result0 = parse_Directive();
if (result0 === null) {
result0 = parse_ContextualCCSSLine();
if (result0 === null) {
result0 = parse_cssLine();
}
}
}
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("Nested Statement");
}
return result0;
}
function parse_nestedStatements() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = [];
result1 = parse_LineTerminator();
while (result1 !== null) {
result0.push(result1);
result1 = parse_LineTerminator();
}
if (result0 !== null) {
result1 = [];
result2 = parse_nestedStatement();
while (result2 !== null) {
result1.push(result2);
result2 = parse_nestedStatement();
}
if (result1 !== null) {
result2 = [];
result3 = parse_LineTerminator();
while (result3 !== null) {
result2.push(result3);
result3 = parse_LineTerminator();
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, s) {return s})(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
result0 = parse__();
}
return result0;
}
function parse_ccss() {
var result0, result1, result2, result3, result4, result5, result6, result7, result8;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
result0 = parse__();
if (result0 !== null) {
result2 = parse_ccssStartChar();
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
result2 = parse_ccssStartChar();
}
} else {
result1 = null;
}
if (result1 !== null) {
result2 = parse__();
if (result2 !== null) {
result3 = parse_ccssOp();
if (result3 !== null) {
result4 = parse_anytoend();
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, ccss) {
return {type:'constraint', cssText: p.stringify(ccss)};
})(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
result0 = parse__();
if (result0 !== null) {
if (input.charCodeAt(pos) === 64) {
result1 = "@";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result1 !== null) {
if (input.substr(pos, 5) === "-gss-") {
result2 = "-gss-";
pos += 5;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"-gss-\"");
}
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
if (input.substr(pos, 4) === "stay") {
result3 = "stay";
pos += 4;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"stay\"");
}
}
if (result3 !== null) {
result4 = parse_anytoend();
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, stay) {
return {type:'constraint', cssText: p.stringify(stay)};
})(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
result0 = parse__();
if (result0 !== null) {
if (input.charCodeAt(pos) === 64) {
result1 = "@";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result1 !== null) {
if (input.substr(pos, 5) === "-gss-") {
result2 = "-gss-";
pos += 5;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"-gss-\"");
}
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
if (input.substr(pos, 5) === "chain") {
result3 = "chain";
pos += 5;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"chain\"");
}
}
if (result3 !== null) {
result4 = parse_anytoend();
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, chain) {
return {type:'constraint', cssText: p.stringify(chain)};
})(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
result0 = parse__();
if (result0 !== null) {
if (input.charCodeAt(pos) === 64) {
result1 = "@";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result1 !== null) {
if (input.substr(pos, 5) === "-gss-") {
result2 = "-gss-";
pos += 5;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"-gss-\"");
}
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
if (input.substr(pos, 8) === "for-each") {
result3 = "for-each";
pos += 8;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"for-each\"");
}
}
if (result3 === null) {
if (input.substr(pos, 7) === "for-all") {
result3 = "for-all";
pos += 7;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"for-all\"");
}
}
}
if (result3 !== null) {
if (/^[^`]/.test(input.charAt(pos))) {
result5 = input.charAt(pos);
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("[^`]");
}
}
if (result5 !== null) {
result4 = [];
while (result5 !== null) {
result4.push(result5);
if (/^[^`]/.test(input.charAt(pos))) {
result5 = input.charAt(pos);
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("[^`]");
}
}
}
} else {
result4 = null;
}
if (result4 !== null) {
if (input.substr(pos, 3) === "```") {
result5 = "```";
pos += 3;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\"```\"");
}
}
if (result5 !== null) {
if (/^[^`]/.test(input.charAt(pos))) {
result7 = input.charAt(pos);
pos++;
} else {
result7 = null;
if (reportFailures === 0) {
matchFailed("[^`]");
}
}
if (result7 !== null) {
result6 = [];
while (result7 !== null) {
result6.push(result7);
if (/^[^`]/.test(input.charAt(pos))) {
result7 = input.charAt(pos);
pos++;
} else {
result7 = null;
if (reportFailures === 0) {
matchFailed("[^`]");
}
}
}
} else {
result6 = null;
}
if (result6 !== null) {
if (input.substr(pos, 3) === "```") {
result7 = "```";
pos += 3;
} else {
result7 = null;
if (reportFailures === 0) {
matchFailed("\"```\"");
}
}
if (result7 !== null) {
result8 = parse_anytoend();
if (result8 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, forlooper) {
return {type:'constraint', cssText: p.stringify(forlooper)};
})(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
}
}
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("CCSS");
}
return result0;
}
function parse_ccssStartChar() {
var result0;
if (/^[a-zA-Z0-9_#.[\]\-""' *+\/$^~%\\()~]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z0-9_#.[\\]\\-\"\"' *+\\/$^~%\\\\()~]");
}
}
if (result0 === null) {
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
}
return result0;
}
function parse_ccssOp() {
var result0;
if (input.substr(pos, 2) === ">=") {
result0 = ">=";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\">=\"");
}
}
if (result0 === null) {
if (input.substr(pos, 2) === "==") {
result0 = "==";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"==\"");
}
}
if (result0 === null) {
if (input.substr(pos, 2) === "<=") {
result0 = "<=";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"<=\"");
}
}
if (result0 === null) {
if (input.substr(pos, 2) === "=>") {
result0 = "=>";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"=>\"");
}
}
if (result0 === null) {
if (input.substr(pos, 2) === "=<") {
result0 = "=<";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"=<\"");
}
}
}
}
}
}
return result0;
}
function parse_ContextualCCSSLine() {
var result0, result1, result2, result3, result4, result5, result6;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
result0 = parse__();
if (result0 !== null) {
if (/^[a-zA-Z0-9\-_$]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z0-9\\-_$]");
}
}
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
if (/^[a-zA-Z0-9\-_$]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z0-9\\-_$]");
}
}
}
} else {
result1 = null;
}
if (result1 !== null) {
result2 = parse__();
if (result2 !== null) {
if (input.charCodeAt(pos) === 58) {
result3 = ":";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result3 !== null) {
result4 = parse__();
if (result4 !== null) {
result5 = parse_ccssOp();
if (result5 !== null) {
result6 = parse_anytoend();
if (result6 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, prop, op, tail) {
return {type:'constraint', cssText: "::["+p.trim(prop)+"]"+" "+op+" "+p.stringify(tail)};
})(pos0, result0[1], result0[5], result0[6]);
}
if (result0 === null) {
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("Contextual CCSS Statement");
}
return result0;
}
function parse_cssLine() {
var result0, result1, result2;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
result0 = parse__();
if (result0 !== null) {
result1 = parse_TextToColon();
if (result1 !== null) {
result2 = parse_TextToSemicolon();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, key, val) { return {type:'style', key:key, val:val}; })(pos0, result0[1], result0[2]);
}
if (result0 === null) {
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("CSS Line");
}
return result0;
}
function parse_vfl() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse__();
if (result0 !== null) {
if (input.substr(pos, 6) === "@-gss-") {
result1 = "@-gss-";
pos += 6;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"@-gss-\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 64) {
result1 = "@";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
}
if (result1 !== null) {
if (input.substr(pos, 10) === "horizontal") {
result2 = "horizontal";
pos += 10;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"horizontal\"");
}
}
if (result2 === null) {
if (input.substr(pos, 8) === "vertical") {
result2 = "vertical";
pos += 8;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"vertical\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 104) {
result2 = "h";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"h\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 118) {
result2 = "v";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"v\"");
}
}
}
}
}
if (result2 !== null) {
result3 = parse_anytoend();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, vfl) { return ['vfl', parser.stringify(vfl)]; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_gtl() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse__();
if (result0 !== null) {
if (input.substr(pos, 6) === "@-gss-") {
result1 = "@-gss-";
pos += 6;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"@-gss-\"");
}
}
if (result1 !== null) {
if (input.substr(pos, 6) === "layout") {
result2 = "layout";
pos += 6;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"layout\"");
}
}
if (result2 === null) {
if (input.substr(pos, 8) === "template") {
result2 = "template";
pos += 8;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"template\"");
}
}
}
if (result2 !== null) {
result3 = parse_multitoend();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, gtl) { return ['gtl', parser.stringify(gtl)]; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_cssBlock() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result1 = parse_anychar();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_anychar();
}
} else {
result0 = null;
}
if (result0 !== null) {
result1 = parse_multitoend();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, block) { return ['css', parser.stringify(block)]; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Ruleset() {
var result0, result1, result2;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
result0 = parse__();
if (result0 !== null) {
result1 = parse_SelectorList();
if (result1 !== null) {
result2 = parse_BlockedStatements();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, sel, s) {
return {type:'ruleset',selectors:sel,rules:s};
})(pos0, result0[1], result0[2]);
}
if (result0 === null) {
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("Ruleset");
}
return result0;
}
function parse_Directive() {
var result0, result1, result2;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
result0 = parse_DirectiveName();
if (result0 !== null) {
result1 = [];
if (/^[^@{};]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[^@{};]");
}
}
while (result2 !== null) {
result1.push(result2);
if (/^[^@{};]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[^@{};]");
}
}
}
if (result1 !== null) {
result2 = parse_BlockedStatements();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, name, terms, s) {
var o;
o = {type:'directive',name:p.trim(name),terms:p.trim(terms)};
if (!!s) {o.rules = s;}
return o;
})(pos0, result0[0], result0[1], result0[2]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
result0 = parse_DirectiveName();
if (result0 !== null) {
result1 = parse_TextToSemicolon();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, name, terms) {
var o;
o = {type:'directive',name:p.trim(name),terms:p.trim(terms)};
return o;
})(pos0, result0[0], result0[1]);
}
if (result0 === null) {
pos = pos0;
}
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("Directive");
}
return result0;
}
function parse_DirectiveName() {
var result0, result1, result2, result3;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
result0 = parse__();
if (result0 !== null) {
if (input.charCodeAt(pos) === 64) {
result1 = "@";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result1 !== null) {
if (/^[a-zA-Z0-9\-_$]/.test(input.charAt(pos))) {
result3 = input.charAt(pos);
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z0-9\\-_$]");
}
}
if (result3 !== null) {
result2 = [];
while (result3 !== null) {
result2.push(result3);
if (/^[a-zA-Z0-9\-_$]/.test(input.charAt(pos))) {
result3 = input.charAt(pos);
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z0-9\\-_$]");
}
}
}
} else {
result2 = null;
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, name) {return p.trim(name);})(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("Directive Name");
}
return result0;
}
function parse_BlockedStatements() {
var result0, result1, result2, result3, result4, result5, result6, result7, result8;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
result0 = parse__();
if (result0 !== null) {
if (input.charCodeAt(pos) === 123) {
result1 = "{";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"{\"");
}
}
if (result1 !== null) {
result2 = parse__();
if (result2 !== null) {
result3 = parse_nestedStatements();
if (result3 !== null) {
result4 = parse__();
if (result4 !== null) {
if (input.charCodeAt(pos) === 125) {
result5 = "}";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\"}\"");
}
}
if (result5 !== null) {
result6 = parse__();
if (result6 !== null) {
result7 = [];
result8 = parse_LineTerminator();
while (result8 !== null) {
result7.push(result8);
result8 = parse_LineTerminator();
}
if (result7 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, s) {return s;})(pos0, result0[3]);
}
if (result0 === null) {
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("Statement Blocks");
}
return result0;
}
function parse_SelectorList() {
var result0, result1, result2;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
result0 = parse_Selector();
if (result0 !== null) {
result1 = [];
result2 = parse_SelectorListEnd();
while (result2 !== null) {
result1.push(result2);
result2 = parse_SelectorListEnd();
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, sel, sels) {return [sel].concat(sels)})(pos0, result0[0], result0[1]);
}
if (result0 === null) {
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("SelectorList");
}
return result0;
}
function parse_SelectorListEnd() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse__();
if (result0 !== null) {
if (input.charCodeAt(pos) === 44) {
result1 = ",";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result1 !== null) {
result2 = parse_Selector();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, sel) {return sel})(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Selector() {
var result0, result1, result2;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
result0 = parse__();
if (result0 !== null) {
if (/^[^@{},;]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[^@{},;]");
}
}
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
if (/^[^@{},;]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[^@{},;]");
}
}
}
} else {
result1 = null;
}
if (result1 !== null) {
result2 = parse__();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, sel) {return sel.join("").trim()})(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("Selector");
}
return result0;
}
function parse_comment() {
var result0, result1, result2, result3, result4, result5, result6, result7, result8;
var pos0, pos1, pos2;
reportFailures++;
pos0 = pos;
pos1 = pos;
result0 = parse__();
if (result0 !== null) {
if (input.substr(pos, 2) === "/*") {
result1 = "/*";
pos += 2;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"/*\"");
}
}
if (result1 !== null) {
result2 = [];
if (/^[^*]/.test(input.charAt(pos))) {
result3 = input.charAt(pos);
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("[^*]");
}
}
while (result3 !== null) {
result2.push(result3);
if (/^[^*]/.test(input.charAt(pos))) {
result3 = input.charAt(pos);
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("[^*]");
}
}
}
if (result2 !== null) {
if (input.charCodeAt(pos) === 42) {
result4 = "*";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result4 !== null) {
result3 = [];
while (result4 !== null) {
result3.push(result4);
if (input.charCodeAt(pos) === 42) {
result4 = "*";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
}
} else {
result3 = null;
}
if (result3 !== null) {
result4 = [];
pos2 = pos;
if (/^[^\/*]/.test(input.charAt(pos))) {
result5 = input.charAt(pos);
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("[^\\/*]");
}
}
if (result5 !== null) {
result6 = [];
if (/^[^*]/.test(input.charAt(pos))) {
result7 = input.charAt(pos);
pos++;
} else {
result7 = null;
if (reportFailures === 0) {
matchFailed("[^*]");
}
}
while (result7 !== null) {
result6.push(result7);
if (/^[^*]/.test(input.charAt(pos))) {
result7 = input.charAt(pos);
pos++;
} else {
result7 = null;
if (reportFailures === 0) {
matchFailed("[^*]");
}
}
}
if (result6 !== null) {
if (input.charCodeAt(pos) === 42) {
result8 = "*";
pos++;
} else {
result8 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result8 !== null) {
result7 = [];
while (result8 !== null) {
result7.push(result8);
if (input.charCodeAt(pos) === 42) {
result8 = "*";
pos++;
} else {
result8 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
}
} else {
result7 = null;
}
if (result7 !== null) {
result5 = [result5, result6, result7];
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
while (result5 !== null) {
result4.push(result5);
pos2 = pos;
if (/^[^\/*]/.test(input.charAt(pos))) {
result5 = input.charAt(pos);
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("[^\\/*]");
}
}
if (result5 !== null) {
result6 = [];
if (/^[^*]/.test(input.charAt(pos))) {
result7 = input.charAt(pos);
pos++;
} else {
result7 = null;
if (reportFailures === 0) {
matchFailed("[^*]");
}
}
while (result7 !== null) {
result6.push(result7);
if (/^[^*]/.test(input.charAt(pos))) {
result7 = input.charAt(pos);
pos++;
} else {
result7 = null;
if (reportFailures === 0) {
matchFailed("[^*]");
}
}
}
if (result6 !== null) {
if (input.charCodeAt(pos) === 42) {
result8 = "*";
pos++;
} else {
result8 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result8 !== null) {
result7 = [];
while (result8 !== null) {
result7.push(result8);
if (input.charCodeAt(pos) === 42) {
result8 = "*";
pos++;
} else {
result8 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
}
} else {
result7 = null;
}
if (result7 !== null) {
result5 = [result5, result6, result7];
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
}
if (result4 !== null) {
if (input.charCodeAt(pos) === 47) {
result5 = "/";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result5 !== null) {
result6 = parse__();
if (result6 !== null) {
result7 = [];
result8 = parse_LineTerminator();
while (result8 !== null) {
result7.push(result8);
result8 = parse_LineTerminator();
}
if (result7 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return ""})(pos0);
}
if (result0 === null) {
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("Comment");
}
return result0;
}
function parse__() {
var result0, result1;
result0 = [];
result1 = parse_space();
while (result1 !== null) {
result0.push(result1);
result1 = parse_space();
}
return result0;
}
function parse___() {
var result0, result1;
result1 = parse_space();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_space();
}
} else {
result0 = null;
}
return result0;
}
function parse_space() {
var result0;
reportFailures++;
if (input.charCodeAt(pos) === 32) {
result0 = " ";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\" \"");
}
}
if (result0 === null) {
if (/^[\t]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\t]");
}
}
if (result0 === null) {
if (/^[\xA0]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\xA0]");
}
}
}
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("Space");
}
return result0;
}
function parse_anychar() {
var result0;
if (/^[a-zA-Z0-9 .,#:+?!^=()_\-$*\/\\""']/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z0-9 .,#:+?!^=()_\\-$*\\/\\\\\"\"']");
}
}
return result0;
}
function parse_multitoend() {
var result0, result1, result2, result3, result4;
var pos0;
reportFailures++;
pos0 = pos;
result0 = [];
if (/^[^}]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[^}]");
}
}
while (result1 !== null) {
result0.push(result1);
if (/^[^}]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[^}]");
}
}
}
if (result0 !== null) {
if (input.charCodeAt(pos) === 125) {
result1 = "}";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"}\"");
}
}
if (result1 !== null) {
result2 = parse__();
if (result2 !== null) {
result3 = [];
result4 = parse_LineTerminator();
while (result4 !== null) {
result3.push(result4);
result4 = parse_LineTerminator();
}
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("multitoend");
}
return result0;
}
function parse_anytoend() {
var result0, result1, result2, result3, result4;
var pos0;
reportFailures++;
pos0 = pos;
result0 = [];
if (/^[^;]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[^;]");
}
}
while (result1 !== null) {
result0.push(result1);
if (/^[^;]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[^;]");
}
}
}
if (result0 !== null) {
if (input.charCodeAt(pos) === 59) {
result1 = ";";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result1 !== null) {
result2 = parse__();
if (result2 !== null) {
result3 = [];
result4 = parse_LineTerminator();
while (result4 !== null) {
result3.push(result4);
result4 = parse_LineTerminator();
}
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("anytoend");
}
return result0;
}
function parse_TextToColon() {
var result0, result1, result2, result3, result4;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
if (/^[^:{}]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[^:{}]");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (/^[^:{}]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[^:{}]");
}
}
}
} else {
result0 = null;
}
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse__();
if (result2 !== null) {
result3 = [];
result4 = parse_LineTerminator();
while (result4 !== null) {
result3.push(result4);
result4 = parse_LineTerminator();
}
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, text) {return p.stringify(text)})(pos0, result0[0]);
}
if (result0 === null) {
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("TextToColon");
}
return result0;
}
function parse_TextToSemicolon() {
var result0, result1, result2, result3, result4;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
if (/^[^;{}]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[^;{}]");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (/^[^;{}]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[^;{}]");
}
}
}
} else {
result0 = null;
}
if (result0 !== null) {
if (input.charCodeAt(pos) === 59) {
result1 = ";";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result1 !== null) {
result2 = parse__();
if (result2 !== null) {
result3 = [];
result4 = parse_LineTerminator();
while (result4 !== null) {
result3.push(result4);
result4 = parse_LineTerminator();
}
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, text) {return p.stringify(text)})(pos0, result0[0]);
}
if (result0 === null) {
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("TextToSemicolon");
}
return result0;
}
function parse__terminators() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse__();
if (result0 !== null) {
result1 = [];
result2 = parse_LineTerminator();
while (result2 !== null) {
result1.push(result2);
result2 = parse_LineTerminator();
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_LineTerminator() {
var result0, result1;
var pos0;
reportFailures++;
pos0 = pos;
if (/^[\n\r\u2028\u2029]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\n\\r\\u2028\\u2029]");
}
}
if (result0 === null) {
if (input.substr(pos, 2) === "\r\n") {
result0 = "\r\n";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\r\\n\"");
}
}
}
if (result0 !== null) {
result1 = parse__();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
result0 = parse_comment();
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("LineTerminator");
}
return result0;
}
function cleanupExpected(expected) {
expected.sort();
var lastExpected = null;
var cleanExpected = [];
for (var i = 0; i < expected.length; i++) {
if (expected[i] !== lastExpected) {
cleanExpected.push(expected[i]);
lastExpected = expected[i];
}
}
return cleanExpected;
}
function computeErrorPosition() {
/*
* The first idea was to use |String.split| to break the input up to the
* error position along newlines and derive the line and column from
* there. However IE's |split| implementation is so broken that it was
* enough to prevent it.
*/
var line = 1;
var column = 1;
var seenCR = false;
for (var i = 0; i < Math.max(pos, rightmostFailuresPos); i++) {
var ch = input.charAt(i);
if (ch === "\n") {
if (!seenCR) { line++; }
column = 1;
seenCR = false;
} else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") {
line++;
column = 1;
seenCR = true;
} else {
column++;
seenCR = false;
}
}
return { line: line, column: column };
}
var p, parser, flatten, idPrefix;
p = parser = this;
String.prototype.trim = String.prototype.trim || function trim() { return this.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); };
flatten = parser.flatten = function (array, isShallow) {
var index = -1,
length = array ? array.length : 0,
result = [];
while (++index < length) {
var value = array[index];
if (value instanceof Array) {
Array.prototype.push.apply(result, isShallow ? value : flatten(value));
}
else {
result.push(value);
}
}
return result;
}
p.results = [];
p.stringify = function (array) {
return flatten(array).join("").trim();
};
p.trim = function (x) {
if (typeof x === "string") {return x.trim();}
if (x instanceof Array) {return x.join("").trim();}
return ""
};
parser.error = function (m,l,c) {
if (!!l && !!c) {
m = m + " {line:" + l + ", col:" + c + "}";
}
console.error(m);
return m;
};
var result = parseFunctions[startRule]();
/*
* The parser is now in one of the following three states:
*
* 1. The parser successfully parsed the whole input.
*
* - |result !== null|
* - |pos === input.length|
* - |rightmostFailuresExpected| may or may not contain something
*
* 2. The parser successfully parsed only a part of the input.
*
* - |result !== null|
* - |pos < input.length|
* - |rightmostFailuresExpected| may or may not contain something
*
* 3. The parser did not successfully parse any part of the input.
*
* - |result === null|
* - |pos === 0|
* - |rightmostFailuresExpected| contains at least one failure
*
* All code following this comment (including called functions) must
* handle these states.
*/
if (result === null || pos !== input.length) {
var offset = Math.max(pos, rightmostFailuresPos);
var found = offset < input.length ? input.charAt(offset) : null;
var errorPosition = computeErrorPosition();
throw new this.SyntaxError(
cleanupExpected(rightmostFailuresExpected),
found,
offset,
errorPosition.line,
errorPosition.column
);
}
return result;
},
/* Returns the parser source code. */
toSource: function() { return this._source; }
};
/* Thrown when a parser encounters a syntax error. */
result.SyntaxError = function(expected, found, offset, line, column) {
function buildMessage(expected, found) {
var expectedHumanized, foundHumanized;
switch (expected.length) {
case 0:
expectedHumanized = "end of input";
break;
case 1:
expectedHumanized = expected[0];
break;
default:
expectedHumanized = expected.slice(0, expected.length - 1).join(", ")
+ " or "
+ expected[expected.length - 1];
}
foundHumanized = found ? quote(found) : "end of input";
return "Expected " + expectedHumanized + " but " + foundHumanized + " found.";
}
this.name = "SyntaxError";
this.expected = expected;
this.found = found;
this.message = buildMessage(expected, found);
this.offset = offset;
this.line = line;
this.column = column;
};
result.SyntaxError.prototype = Error.prototype;
return result;
})();
});
require.register("the-gss-ccss-compiler/lib/ccss-compiler.js", function(exports, require, module){
module.exports = (function(){
/*
* Generated by PEG.js 0.7.0.
*
* http://pegjs.majda.cz/
*/
function quote(s) {
/*
* ECMA-262, 5th ed., 7.8.4: All characters may appear literally in a
* string literal except for the closing quote character, backslash,
* carriage return, line separator, paragraph separator, and line feed.
* Any character may appear in the form of an escape sequence.
*
* For portability, we also escape escape all control and non-ASCII
* characters. Note that "\0" and "\v" escape sequences are not used
* because JSHint does not like the first and IE the second.
*/
return '"' + s
.replace(/\\/g, '\\\\') // backslash
.replace(/"/g, '\\"') // closing quote character
.replace(/\x08/g, '\\b') // backspace
.replace(/\t/g, '\\t') // horizontal tab
.replace(/\n/g, '\\n') // line feed
.replace(/\f/g, '\\f') // form feed
.replace(/\r/g, '\\r') // carriage return
.replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g, escape)
+ '"';
}
var result = {
/*
* Parses the input with a generated parser. If the parsing is successfull,
* returns a value explicitly or implicitly specified by the grammar from
* which the parser was generated (see |PEG.buildParser|). If the parsing is
* unsuccessful, throws |PEG.parser.SyntaxError| describing the error.
*/
parse: function(input, startRule) {
var parseFunctions = {
"start": parse_start,
"Statement": parse_Statement,
"AndOrExpression": parse_AndOrExpression,
"AndOrOp": parse_AndOrOp,
"ConditionalExpression": parse_ConditionalExpression,
"CondOperator": parse_CondOperator,
"LinearConstraint": parse_LinearConstraint,
"LinearConstraintOperator": parse_LinearConstraintOperator,
"ConstraintAdditiveExpression": parse_ConstraintAdditiveExpression,
"AdditiveExpression": parse_AdditiveExpression,
"AdditiveOperator": parse_AdditiveOperator,
"ConstraintMultiplicativeExpression": parse_ConstraintMultiplicativeExpression,
"MultiplicativeExpression": parse_MultiplicativeExpression,
"MultiplicativeOperator": parse_MultiplicativeOperator,
"ConstraintPrimaryExpression": parse_ConstraintPrimaryExpression,
"PrimaryExpression": parse_PrimaryExpression,
"Measure": parse_Measure,
"Var": parse_Var,
"VarNames": parse_VarNames,
"NameChars": parse_NameChars,
"NameCharsWithSpace": parse_NameCharsWithSpace,
"Literal": parse_Literal,
"Integer": parse_Integer,
"Real": parse_Real,
"SignedInteger": parse_SignedInteger,
"SourceCharacter": parse_SourceCharacter,
"WhiteSpace": parse_WhiteSpace,
"LineTerminator": parse_LineTerminator,
"LineTerminatorSequence": parse_LineTerminatorSequence,
"EOS": parse_EOS,
"EOF": parse_EOF,
"Comment": parse_Comment,
"MultiLineComment": parse_MultiLineComment,
"MultiLineCommentNoLineTerminator": parse_MultiLineCommentNoLineTerminator,
"SingleLineComment": parse_SingleLineComment,
"_": parse__,
"__": parse___,
"Selector": parse_Selector,
"QuerySelectorChars": parse_QuerySelectorChars,
"ReservedPseudos": parse_ReservedPseudos,
"StrengthAndWeight": parse_StrengthAndWeight,
"Weight": parse_Weight,
"Strength": parse_Strength,
"Virtual": parse_Virtual,
"VirtualName": parse_VirtualName,
"Stay": parse_Stay,
"StayVars": parse_StayVars,
"StayStart": parse_StayStart,
"Conditional": parse_Conditional,
"ForEach": parse_ForEach,
"JavaScript": parse_JavaScript,
"ForLooperType": parse_ForLooperType,
"Chain": parse_Chain,
"Chainer": parse_Chainer,
"HeadExp": parse_HeadExp,
"TailExp": parse_TailExp,
"ChainMath": parse_ChainMath,
"ChainEq": parse_ChainEq
};
if (startRule !== undefined) {
if (parseFunctions[startRule] === undefined) {
throw new Error("Invalid rule name: " + quote(startRule) + ".");
}
} else {
startRule = "start";
}
var pos = 0;
var reportFailures = 0;
var rightmostFailuresPos = 0;
var rightmostFailuresExpected = [];
function padLeft(input, padding, length) {
var result = input;
var padLength = length - input.length;
for (var i = 0; i < padLength; i++) {
result = padding + result;
}
return result;
}
function escape(ch) {
var charCode = ch.charCodeAt(0);
var escapeChar;
var length;
if (charCode <= 0xFF) {
escapeChar = 'x';
length = 2;
} else {
escapeChar = 'u';
length = 4;
}
return '\\' + escapeChar + padLeft(charCode.toString(16).toUpperCase(), '0', length);
}
function matchFailed(failure) {
if (pos < rightmostFailuresPos) {
return;
}
if (pos > rightmostFailuresPos) {
rightmostFailuresPos = pos;
rightmostFailuresExpected = [];
}
rightmostFailuresExpected.push(failure);
}
function parse_start() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse___();
if (result0 !== null) {
result1 = [];
result2 = parse_Statement();
while (result2 !== null) {
result1.push(result2);
result2 = parse_Statement();
}
if (result1 !== null) {
result2 = parse___();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, statements) { return (parser.getResults()); })(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Statement() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_LinearConstraint();
if (result0 !== null) {
result1 = parse_EOS();
if (result1 !== null) {
result2 = parse___();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, exp) { return exp; })(pos0, result0[0]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
result0 = parse_Virtual();
if (result0 !== null) {
result1 = parse_EOS();
if (result1 !== null) {
result2 = parse___();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, virtual) { return virtual; })(pos0, result0[0]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
result0 = parse_Conditional();
if (result0 !== null) {
result1 = parse_EOS();
if (result1 !== null) {
result2 = parse___();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, cond) { return cond; })(pos0, result0[0]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
result0 = parse_Stay();
if (result0 !== null) {
result1 = parse_EOS();
if (result1 !== null) {
result2 = parse___();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, stay) { return stay; })(pos0, result0[0]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
result0 = parse_Chain();
if (result0 !== null) {
result1 = parse_EOS();
if (result1 !== null) {
result2 = parse___();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, chain) { return chain; })(pos0, result0[0]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
result0 = parse_ForEach();
if (result0 !== null) {
result1 = parse_EOS();
if (result1 !== null) {
result2 = parse___();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, js) { return js; })(pos0, result0[0]);
}
if (result0 === null) {
pos = pos0;
}
}
}
}
}
}
return result0;
}
function parse_AndOrExpression() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_ConditionalExpression();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse___();
if (result2 !== null) {
result3 = parse_AndOrOp();
if (result3 !== null) {
result4 = parse___();
if (result4 !== null) {
result5 = parse_ConditionalExpression();
if (result5 !== null) {
result2 = [result2, result3, result4, result5];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse___();
if (result2 !== null) {
result3 = parse_AndOrOp();
if (result3 !== null) {
result4 = parse___();
if (result4 !== null) {
result5 = parse_ConditionalExpression();
if (result5 !== null) {
result2 = [result2, result3, result4, result5];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, head, tail) {
var result = head;
for (var i = 0; i < tail.length; i++) {
result = [
tail[i][1],
result,
tail[i][3]
];
}
return result;
})(pos0, result0[0], result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_AndOrOp() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 3) === "AND") {
result0 = "AND";
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"AND\"");
}
}
if (result0 === null) {
if (input.substr(pos, 3) === "and") {
result0 = "and";
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"and\"");
}
}
if (result0 === null) {
if (input.substr(pos, 3) === "And") {
result0 = "And";
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"And\"");
}
}
if (result0 === null) {
if (input.substr(pos, 2) === "&&") {
result0 = "&&";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"&&\"");
}
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) { return "&&" })(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.substr(pos, 2) === "OR") {
result0 = "OR";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"OR\"");
}
}
if (result0 === null) {
if (input.substr(pos, 2) === "or") {
result0 = "or";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"or\"");
}
}
if (result0 === null) {
if (input.substr(pos, 2) === "Or") {
result0 = "Or";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"Or\"");
}
}
if (result0 === null) {
if (input.substr(pos, 2) === "||") {
result0 = "||";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"||\"");
}
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) { return "||" })(pos0);
}
if (result0 === null) {
pos = pos0;
}
}
return result0;
}
function parse_ConditionalExpression() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_AdditiveExpression();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse___();
if (result2 !== null) {
result3 = parse_CondOperator();
if (result3 !== null) {
result4 = parse___();
if (result4 !== null) {
result5 = parse_AdditiveExpression();
if (result5 !== null) {
result2 = [result2, result3, result4, result5];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse___();
if (result2 !== null) {
result3 = parse_CondOperator();
if (result3 !== null) {
result4 = parse___();
if (result4 !== null) {
result5 = parse_AdditiveExpression();
if (result5 !== null) {
result2 = [result2, result3, result4, result5];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, head, tail) {
var result = head;
for (var i = 0; i < tail.length; i++) {
result = [
tail[i][1],
result,
tail[i][3]
];
}
return result;
})(pos0, result0[0], result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_CondOperator() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 2) === "==") {
result0 = "==";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"==\"");
}
}
if (result0 !== null) {
result0 = (function(offset) { return "?==" })(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.substr(pos, 2) === "<=") {
result0 = "<=";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"<=\"");
}
}
if (result0 === null) {
if (input.substr(pos, 2) === "=<") {
result0 = "=<";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"=<\"");
}
}
}
if (result0 !== null) {
result0 = (function(offset) { return "?<=" })(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.substr(pos, 2) === ">=") {
result0 = ">=";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\">=\"");
}
}
if (result0 === null) {
if (input.substr(pos, 2) === "=>") {
result0 = "=>";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"=>\"");
}
}
}
if (result0 !== null) {
result0 = (function(offset) { return "?>=" })(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.charCodeAt(pos) === 60) {
result0 = "<";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"<\"");
}
}
if (result0 !== null) {
result0 = (function(offset) { return "?<" })(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.charCodeAt(pos) === 62) {
result0 = ">";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\">\"");
}
}
if (result0 !== null) {
result0 = (function(offset) { return "?>" })(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.substr(pos, 2) === "!=") {
result0 = "!=";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"!=\"");
}
}
if (result0 !== null) {
result0 = (function(offset) { return "?!=" })(pos0);
}
if (result0 === null) {
pos = pos0;
}
}
}
}
}
}
return result0;
}
function parse_LinearConstraint() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_ConstraintAdditiveExpression();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse___();
if (result2 !== null) {
result3 = parse_LinearConstraintOperator();
if (result3 !== null) {
result4 = parse___();
if (result4 !== null) {
result5 = parse_ConstraintAdditiveExpression();
if (result5 !== null) {
result2 = [result2, result3, result4, result5];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse___();
if (result2 !== null) {
result3 = parse_LinearConstraintOperator();
if (result3 !== null) {
result4 = parse___();
if (result4 !== null) {
result5 = parse_ConstraintAdditiveExpression();
if (result5 !== null) {
result2 = [result2, result3, result4, result5];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result2 = parse___();
if (result2 !== null) {
result3 = parse_StrengthAndWeight();
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, e1, tail, s) {
var eq, e2;
if (s.length === 0) {s = [];}
for (var i = 0; i < tail.length; i++) {
eq = tail[i][1];
e2 = tail[i][3];
parser.addC([
eq,
e1,
e2
].concat(s));
e1 = e2;
}
return "LineaerExpression";
})(pos0, result0[0], result0[1], result0[3]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_LinearConstraintOperator() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 2) === "==") {
result0 = "==";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"==\"");
}
}
if (result0 !== null) {
result0 = (function(offset) { return "eq" })(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.substr(pos, 2) === "<=") {
result0 = "<=";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"<=\"");
}
}
if (result0 === null) {
if (input.substr(pos, 2) === "=<") {
result0 = "=<";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"=<\"");
}
}
}
if (result0 !== null) {
result0 = (function(offset) { return "lte" })(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.substr(pos, 2) === ">=") {
result0 = ">=";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\">=\"");
}
}
if (result0 === null) {
if (input.substr(pos, 2) === "=>") {
result0 = "=>";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"=>\"");
}
}
}
if (result0 !== null) {
result0 = (function(offset) { return "gte" })(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.charCodeAt(pos) === 60) {
result0 = "<";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"<\"");
}
}
if (result0 !== null) {
result0 = (function(offset) { return "lt" })(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.charCodeAt(pos) === 62) {
result0 = ">";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\">\"");
}
}
if (result0 !== null) {
result0 = (function(offset) { return "gt" })(pos0);
}
if (result0 === null) {
pos = pos0;
}
}
}
}
}
return result0;
}
function parse_ConstraintAdditiveExpression() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_ConstraintMultiplicativeExpression();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse___();
if (result2 !== null) {
result3 = parse_AdditiveOperator();
if (result3 !== null) {
result4 = parse___();
if (result4 !== null) {
result5 = parse_ConstraintMultiplicativeExpression();
if (result5 !== null) {
result2 = [result2, result3, result4, result5];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse___();
if (result2 !== null) {
result3 = parse_AdditiveOperator();
if (result3 !== null) {
result4 = parse___();
if (result4 !== null) {
result5 = parse_ConstraintMultiplicativeExpression();
if (result5 !== null) {
result2 = [result2, result3, result4, result5];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, head, tail) {
var result = head;
for (var i = 0; i < tail.length; i++) {
result = [
tail[i][1],
result,
tail[i][3]
];
}
return result;
})(pos0, result0[0], result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_AdditiveExpression() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_MultiplicativeExpression();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse___();
if (result2 !== null) {
result3 = parse_AdditiveOperator();
if (result3 !== null) {
result4 = parse___();
if (result4 !== null) {
result5 = parse_MultiplicativeExpression();
if (result5 !== null) {
result2 = [result2, result3, result4, result5];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse___();
if (result2 !== null) {
result3 = parse_AdditiveOperator();
if (result3 !== null) {
result4 = parse___();
if (result4 !== null) {
result5 = parse_MultiplicativeExpression();
if (result5 !== null) {
result2 = [result2, result3, result4, result5];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, head, tail) {
var result = head;
for (var i = 0; i < tail.length; i++) {
result = [
tail[i][1],
result,
tail[i][3]
];
}
return result;
})(pos0, result0[0], result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_AdditiveOperator() {
var result0;
var pos0;
pos0 = pos;
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 !== null) {
result0 = (function(offset) { return "plus" })(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.charCodeAt(pos) === 45) {
result0 = "-";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result0 !== null) {
result0 = (function(offset) { return "minus" })(pos0);
}
if (result0 === null) {
pos = pos0;
}
}
return result0;
}
function parse_ConstraintMultiplicativeExpression() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_ConstraintPrimaryExpression();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse___();
if (result2 !== null) {
result3 = parse_MultiplicativeOperator();
if (result3 !== null) {
result4 = parse___();
if (result4 !== null) {
result5 = parse_ConstraintPrimaryExpression();
if (result5 !== null) {
result2 = [result2, result3, result4, result5];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse___();
if (result2 !== null) {
result3 = parse_MultiplicativeOperator();
if (result3 !== null) {
result4 = parse___();
if (result4 !== null) {
result5 = parse_ConstraintPrimaryExpression();
if (result5 !== null) {
result2 = [result2, result3, result4, result5];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, head, tail) {
var result = head;
for (var i = 0; i < tail.length; i++) {
result = [
tail[i][1],
result,
tail[i][3]
];
}
return result;
})(pos0, result0[0], result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_MultiplicativeExpression() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_PrimaryExpression();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse___();
if (result2 !== null) {
result3 = parse_MultiplicativeOperator();
if (result3 !== null) {
result4 = parse___();
if (result4 !== null) {
result5 = parse_PrimaryExpression();
if (result5 !== null) {
result2 = [result2, result3, result4, result5];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse___();
if (result2 !== null) {
result3 = parse_MultiplicativeOperator();
if (result3 !== null) {
result4 = parse___();
if (result4 !== null) {
result5 = parse_PrimaryExpression();
if (result5 !== null) {
result2 = [result2, result3, result4, result5];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, head, tail) {
var result = head;
for (var i = 0; i < tail.length; i++) {
result = [
tail[i][1],
result,
tail[i][3]
];
}
return result;
})(pos0, result0[0], result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_MultiplicativeOperator() {
var result0;
var pos0;
pos0 = pos;
if (input.charCodeAt(pos) === 42) {
result0 = "*";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result0 !== null) {
result0 = (function(offset) {return "multiply"})(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.charCodeAt(pos) === 47) {
result0 = "/";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result0 !== null) {
result0 = (function(offset) {return "divide"})(pos0);
}
if (result0 === null) {
pos = pos0;
}
}
return result0;
}
function parse_ConstraintPrimaryExpression() {
var result0, result1, result2, result3, result4;
var pos0, pos1;
result0 = parse_Measure();
if (result0 === null) {
result0 = parse_Var();
if (result0 === null) {
result0 = parse_Literal();
if (result0 === null) {
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 40) {
result0 = "(";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result0 !== null) {
result1 = parse___();
if (result1 !== null) {
result2 = parse_ConstraintAdditiveExpression();
if (result2 !== null) {
result3 = parse___();
if (result3 !== null) {
if (input.charCodeAt(pos) === 41) {
result4 = ")";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, expression) { return expression; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
}
}
}
return result0;
}
function parse_PrimaryExpression() {
var result0, result1, result2, result3, result4;
var pos0, pos1;
result0 = parse_Measure();
if (result0 === null) {
result0 = parse_Var();
if (result0 === null) {
result0 = parse_Literal();
if (result0 === null) {
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 40) {
result0 = "(";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result0 !== null) {
result1 = parse___();
if (result1 !== null) {
result2 = parse_AndOrExpression();
if (result2 !== null) {
result3 = parse___();
if (result3 !== null) {
if (input.charCodeAt(pos) === 41) {
result4 = ")";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, expression) { return expression; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
}
}
}
return result0;
}
function parse_Measure() {
var result0, result1, result2, result3, result4;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 8) === "measure(") {
result0 = "measure(";
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"measure(\"");
}
}
if (result0 !== null) {
result1 = parse___();
if (result1 !== null) {
result2 = parse_Var();
if (result2 !== null) {
result3 = parse___();
if (result3 !== null) {
if (input.charCodeAt(pos) === 41) {
result4 = ")";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, v) { return p.processMeasure(["measure",v]);})(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("measure");
}
return result0;
}
function parse_Var() {
var result0, result1, result2, result3;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
result0 = parse_Selector();
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
if (input.charCodeAt(pos) === 91) {
result1 = "[";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result1 !== null) {
result3 = parse_NameChars();
if (result3 !== null) {
result2 = [];
while (result3 !== null) {
result2.push(result3);
result3 = parse_NameChars();
}
} else {
result2 = null;
}
if (result2 !== null) {
if (input.charCodeAt(pos) === 93) {
result3 = "]";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, sel, v) {
var result, id, _id1, _id2;
v = v.join("");
// if bound to dom query
if (sel.length !== 0) {
parser.add$(sel.selector);
// normalize var names when query bound
if (v === 'left') {
v = 'x';
} else if (v === 'top') {
v = 'y';
} else if (v === 'cx') {
v = 'center-x';
} else if (v === 'cy') {
v = 'center-y';
}
// normalize window var names
if (sel.selector === '::window') {
if (v === 'right') {
v = 'width'
} else if (v === 'bottom') {
v = 'height'
}
}
}
if (sel.selector || sel.isVirtual) {
return ['get$',v,sel.ast];
} else {
return ['get',"["+v+"]"];
}
})(pos0, result0[0], result0[2]);
}
if (result0 === null) {
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("variable");
}
return result0;
}
function parse_VarNames() {
var result0;
result0 = "";
return result0;
}
function parse_NameChars() {
var result0;
if (/^[a-zA-Z0-9#.\-_$]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z0-9#.\\-_$]");
}
}
return result0;
}
function parse_NameCharsWithSpace() {
var result0;
result0 = parse_NameChars();
if (result0 === null) {
if (input.charCodeAt(pos) === 32) {
result0 = " ";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\" \"");
}
}
}
return result0;
}
function parse_Literal() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_Real();
if (result0 === null) {
result0 = parse_Integer();
}
if (result0 !== null) {
result0 = (function(offset, val) {
return [ "number",
val
]
})(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Integer() {
var result0, result1;
var pos0;
pos0 = pos;
if (/^[0-9]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (/^[0-9]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, digits) {
return parseInt(digits.join(""));
})(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Real() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_Integer();
if (result0 !== null) {
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 !== null) {
result2 = parse_Integer();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, digits) {
return parseFloat(digits.join(""));
})(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_SignedInteger() {
var result0, result1, result2;
var pos0;
pos0 = pos;
if (/^[\-+]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\-+]");
}
}
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
if (/^[0-9]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
if (/^[0-9]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
}
} else {
result1 = null;
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_SourceCharacter() {
var result0;
if (input.length > pos) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("any character");
}
}
return result0;
}
function parse_WhiteSpace() {
var result0;
reportFailures++;
if (/^[\t\x0B\f \xA0\uFEFF]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\t\\x0B\\f \\xA0\\uFEFF]");
}
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("whitespace");
}
return result0;
}
function parse_LineTerminator() {
var result0;
if (/^[\n\r\u2028\u2029]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\n\\r\\u2028\\u2029]");
}
}
return result0;
}
function parse_LineTerminatorSequence() {
var result0;
reportFailures++;
if (input.charCodeAt(pos) === 10) {
result0 = "\n";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\n\"");
}
}
if (result0 === null) {
if (input.substr(pos, 2) === "\r\n") {
result0 = "\r\n";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\r\\n\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 13) {
result0 = "\r";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\r\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 8232) {
result0 = "\u2028";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\u2028\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 8233) {
result0 = "\u2029";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\u2029\"");
}
}
}
}
}
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("end of line");
}
return result0;
}
function parse_EOS() {
var result0, result1;
var pos0;
pos0 = pos;
result0 = parse___();
if (result0 !== null) {
if (input.charCodeAt(pos) === 59) {
result1 = ";";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
result0 = parse__();
if (result0 !== null) {
result1 = parse_LineTerminatorSequence();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
result0 = parse___();
if (result0 !== null) {
result1 = parse_EOF();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
}
}
return result0;
}
function parse_EOF() {
var result0;
var pos0;
pos0 = pos;
reportFailures++;
if (input.length > pos) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("any character");
}
}
reportFailures--;
if (result0 === null) {
result0 = "";
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Comment() {
var result0;
reportFailures++;
result0 = parse_MultiLineComment();
if (result0 === null) {
result0 = parse_SingleLineComment();
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("comment");
}
return result0;
}
function parse_MultiLineComment() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
if (input.substr(pos, 2) === "/*") {
result0 = "/*";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/*\"");
}
}
if (result0 !== null) {
result1 = [];
pos1 = pos;
pos2 = pos;
reportFailures++;
if (input.substr(pos, 2) === "*/") {
result2 = "*/";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"*/\"");
}
}
reportFailures--;
if (result2 === null) {
result2 = "";
} else {
result2 = null;
pos = pos2;
}
if (result2 !== null) {
result3 = parse_SourceCharacter();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
pos2 = pos;
reportFailures++;
if (input.substr(pos, 2) === "*/") {
result2 = "*/";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"*/\"");
}
}
reportFailures--;
if (result2 === null) {
result2 = "";
} else {
result2 = null;
pos = pos2;
}
if (result2 !== null) {
result3 = parse_SourceCharacter();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
if (input.substr(pos, 2) === "*/") {
result2 = "*/";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"*/\"");
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_MultiLineCommentNoLineTerminator() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
if (input.substr(pos, 2) === "/*") {
result0 = "/*";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/*\"");
}
}
if (result0 !== null) {
result1 = [];
pos1 = pos;
pos2 = pos;
reportFailures++;
if (input.substr(pos, 2) === "*/") {
result2 = "*/";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"*/\"");
}
}
if (result2 === null) {
result2 = parse_LineTerminator();
}
reportFailures--;
if (result2 === null) {
result2 = "";
} else {
result2 = null;
pos = pos2;
}
if (result2 !== null) {
result3 = parse_SourceCharacter();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
pos2 = pos;
reportFailures++;
if (input.substr(pos, 2) === "*/") {
result2 = "*/";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"*/\"");
}
}
if (result2 === null) {
result2 = parse_LineTerminator();
}
reportFailures--;
if (result2 === null) {
result2 = "";
} else {
result2 = null;
pos = pos2;
}
if (result2 !== null) {
result3 = parse_SourceCharacter();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
if (input.substr(pos, 2) === "*/") {
result2 = "*/";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"*/\"");
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_SingleLineComment() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
if (input.substr(pos, 2) === "//") {
result0 = "//";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"//\"");
}
}
if (result0 !== null) {
result1 = [];
pos1 = pos;
pos2 = pos;
reportFailures++;
result2 = parse_LineTerminator();
reportFailures--;
if (result2 === null) {
result2 = "";
} else {
result2 = null;
pos = pos2;
}
if (result2 !== null) {
result3 = parse_SourceCharacter();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
pos2 = pos;
reportFailures++;
result2 = parse_LineTerminator();
reportFailures--;
if (result2 === null) {
result2 = "";
} else {
result2 = null;
pos = pos2;
}
if (result2 !== null) {
result3 = parse_SourceCharacter();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result2 = parse_LineTerminator();
if (result2 === null) {
result2 = parse_EOF();
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse__() {
var result0, result1;
result0 = [];
result1 = parse_WhiteSpace();
if (result1 === null) {
result1 = parse_MultiLineCommentNoLineTerminator();
if (result1 === null) {
result1 = parse_SingleLineComment();
}
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_WhiteSpace();
if (result1 === null) {
result1 = parse_MultiLineCommentNoLineTerminator();
if (result1 === null) {
result1 = parse_SingleLineComment();
}
}
}
return result0;
}
function parse___() {
var result0, result1;
result0 = [];
result1 = parse_WhiteSpace();
if (result1 === null) {
result1 = parse_LineTerminatorSequence();
if (result1 === null) {
result1 = parse_Comment();
}
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_WhiteSpace();
if (result1 === null) {
result1 = parse_LineTerminatorSequence();
if (result1 === null) {
result1 = parse_Comment();
}
}
}
return result0;
}
function parse_Selector() {
var result0, result1, result2, result3;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 35) {
result0 = "#";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"#\"");
}
}
if (result0 !== null) {
result2 = parse_NameChars();
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
result2 = parse_NameChars();
}
} else {
result1 = null;
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, sel) {
sel=p.toString(sel); return {selector:"#"+sel,ast:["$id",sel]}
})(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_ReservedPseudos();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, sel) {
return {selector:"::"+sel,ast:["$reserved", sel]}
})(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 34) {
result0 = "\"";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\\"\"");
}
}
if (result0 !== null) {
if (/^[a-zA-Z0-9.\-_$=:+><~ ]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z0-9.\\-_$=:+><~ ]");
}
}
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
if (/^[a-zA-Z0-9.\-_$=:+><~ ]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z0-9.\\-_$=:+><~ ]");
}
}
}
} else {
result1 = null;
}
if (result1 !== null) {
if (input.charCodeAt(pos) === 34) {
result2 = "\"";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"\\\"\"");
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, name) {
name=p.toString(name);
return {isVirtual:true, ast:["$virtual", name]}
})(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 46) {
result0 = ".";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result0 !== null) {
result2 = parse_NameChars();
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
result2 = parse_NameChars();
}
} else {
result1 = null;
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, sel) {
sel=p.toString(sel);
return {selector:"."+sel,ast:["$class",sel]};
})(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
result1 = parse_NameChars();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_NameChars();
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, sel) {
sel=p.toString(sel);
return {selector:sel,ast:["$tag",sel]}
})(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 36) {
result0 = "$";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
if (input.charCodeAt(pos) === 40) {
result1 = "(";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result1 !== null) {
result3 = parse_QuerySelectorChars();
if (result3 !== null) {
result2 = [];
while (result3 !== null) {
result2.push(result3);
result3 = parse_QuerySelectorChars();
}
} else {
result2 = null;
}
if (result2 !== null) {
if (input.charCodeAt(pos) === 41) {
result3 = ")";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, sel) {
sel=p.toString(sel); return {selector:sel,ast:["$all",sel]}
})(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
}
}
}
}
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("selector");
}
return result0;
}
function parse_QuerySelectorChars() {
var result0;
if (/^[a-zA-Z0-9#.\-_$=:+>'" \][]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z0-9#.\\-_$=:+>'\" \\][]");
}
}
return result0;
}
function parse_ReservedPseudos() {
var result0;
var pos0;
if (input.substr(pos, 8) === "document") {
result0 = "document";
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"document\"");
}
}
if (result0 === null) {
if (input.substr(pos, 4) === "host") {
result0 = "host";
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"host\"");
}
}
if (result0 === null) {
if (input.substr(pos, 5) === "scope") {
result0 = "scope";
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"scope\"");
}
}
if (result0 === null) {
if (input.substr(pos, 6) === "parent") {
result0 = "parent";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"parent\"");
}
}
}
}
}
if (result0 === null) {
pos0 = pos;
if (input.substr(pos, 6) === "window") {
result0 = "window";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"window\"");
}
}
if (result0 === null) {
if (input.substr(pos, 8) === "viewport") {
result0 = "viewport";
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"viewport\"");
}
}
}
if (result0 !== null) {
result0 = (function(offset) {return "window"})(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.substr(pos, 4) === "this") {
result0 = "this";
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"this\"");
}
}
if (result0 === null) {
result0 = "";
}
if (result0 !== null) {
result0 = (function(offset) {return "this"})(pos0);
}
if (result0 === null) {
pos = pos0;
}
}
}
return result0;
}
function parse_StrengthAndWeight() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 33) {
result0 = "!";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result0 !== null) {
result1 = parse_Strength();
if (result1 !== null) {
result2 = parse_Weight();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, s, w) {
if (w.length === 0) {return [s];}
return [s,w];
})(pos0, result0[1], result0[2]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 33) {
result0 = "!";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result0 !== null) {
if (input.length > pos) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("any character");
}
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return parser.error("Invalid Strength or Weight",line,column)})(pos0);
}
if (result0 === null) {
pos = pos0;
}
}
return result0;
}
function parse_Weight() {
var result0, result1;
var pos0;
pos0 = pos;
if (/^[0-9]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (/^[0-9]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, w) {return Number(w.join(""))})(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Strength() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 7) === "require") {
result0 = "require";
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"require\"");
}
}
if (result0 === null) {
if (input.substr(pos, 7) === "REQUIRE") {
result0 = "REQUIRE";
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"REQUIRE\"");
}
}
if (result0 === null) {
if (input.substr(pos, 7) === "Require") {
result0 = "Require";
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"Require\"");
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {return "require"})(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.substr(pos, 6) === "strong") {
result0 = "strong";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"strong\"");
}
}
if (result0 === null) {
if (input.substr(pos, 6) === "STRONG") {
result0 = "STRONG";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"STRONG\"");
}
}
if (result0 === null) {
if (input.substr(pos, 6) === "Strong") {
result0 = "Strong";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"Strong\"");
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {return "strong"})(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.substr(pos, 6) === "medium") {
result0 = "medium";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"medium\"");
}
}
if (result0 === null) {
if (input.substr(pos, 6) === "MEDIUM") {
result0 = "MEDIUM";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"MEDIUM\"");
}
}
if (result0 === null) {
if (input.substr(pos, 6) === "Medium") {
result0 = "Medium";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"Medium\"");
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {return "medium"})(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.substr(pos, 4) === "weak") {
result0 = "weak";
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"weak\"");
}
}
if (result0 === null) {
if (input.substr(pos, 4) === "WEAK") {
result0 = "WEAK";
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"WEAK\"");
}
}
if (result0 === null) {
if (input.substr(pos, 4) === "Weak") {
result0 = "Weak";
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"Weak\"");
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {return "weak"})(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.substr(pos, 8) === "required") {
result0 = "required";
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"required\"");
}
}
if (result0 === null) {
if (input.substr(pos, 8) === "REQUIRED") {
result0 = "REQUIRED";
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"REQUIRED\"");
}
}
if (result0 === null) {
if (input.substr(pos, 8) === "Required") {
result0 = "Required";
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"Required\"");
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {return "require"})(pos0);
}
if (result0 === null) {
pos = pos0;
}
}
}
}
}
return result0;
}
function parse_Virtual() {
var result0, result1, result2, result3, result4;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 64) {
result0 = "@";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result0 !== null) {
if (input.substr(pos, 12) === "-gss-virtual") {
result1 = "-gss-virtual";
pos += 12;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-gss-virtual\"");
}
}
if (result1 === null) {
if (input.substr(pos, 7) === "virtual") {
result1 = "virtual";
pos += 7;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"virtual\"");
}
}
}
if (result1 !== null) {
result2 = parse___();
if (result2 !== null) {
result4 = parse_VirtualName();
if (result4 !== null) {
result3 = [];
while (result4 !== null) {
result3.push(result4);
result4 = parse_VirtualName();
}
} else {
result3 = null;
}
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, names) {
var command = ["virtual"].concat(names);
parser.addC(command);
return command;
})(pos0, result0[3]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_VirtualName() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 34) {
result0 = "\"";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\\"\"");
}
}
if (result0 !== null) {
if (/^[^"]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[^\"]");
}
}
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
if (/^[^"]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[^\"]");
}
}
}
} else {
result1 = null;
}
if (result1 !== null) {
if (input.charCodeAt(pos) === 34) {
result2 = "\"";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"\\\"\"");
}
}
if (result2 !== null) {
result3 = parse___();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, name) { return name.join("") })(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Stay() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_StayStart();
if (result0 !== null) {
result2 = parse_StayVars();
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
result2 = parse_StayVars();
}
} else {
result1 = null;
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, vars) {
var stay = ["stay"].concat(vars)
parser.addC(stay)
return stay;
})(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_StayVars() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse___();
if (result0 !== null) {
result1 = parse_Var();
if (result1 !== null) {
result2 = parse___();
if (result2 !== null) {
if (input.charCodeAt(pos) === 44) {
result3 = ",";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, v) {return v})(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_StayStart() {
var result0;
if (input.substr(pos, 10) === "@-gss-stay") {
result0 = "@-gss-stay";
pos += 10;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@-gss-stay\"");
}
}
if (result0 === null) {
if (input.substr(pos, 5) === "@stay") {
result0 = "@stay";
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@stay\"");
}
}
}
return result0;
}
function parse_Conditional() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 5) === "@cond") {
result0 = "@cond";
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@cond\"");
}
}
if (result0 !== null) {
result1 = parse___();
if (result1 !== null) {
result2 = parse_AndOrExpression();
if (result2 !== null) {
result3 = parse___();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, result) {parser.addC(result); return result;})(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_ForEach() {
var result0, result1, result2, result3, result4;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_ForLooperType();
if (result0 !== null) {
result1 = parse___();
if (result1 !== null) {
result2 = parse_Selector();
if (result2 !== null) {
result3 = parse___();
if (result3 !== null) {
result4 = parse_JavaScript();
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, type, sel, js) {
parser.add$(sel.selector);
parser.addC([type,sel.ast,js]);
})(pos0, result0[0], result0[2], result0[4]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_JavaScript() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 3) === "```") {
result0 = "```";
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"```\"");
}
}
if (result0 !== null) {
result1 = [];
if (/^[^`]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[^`]");
}
}
while (result2 !== null) {
result1.push(result2);
if (/^[^`]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[^`]");
}
}
}
if (result1 !== null) {
if (input.substr(pos, 3) === "```") {
result2 = "```";
pos += 3;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"```\"");
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, js) {return ['js',js.join("").trim()]})(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_ForLooperType() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 14) === "@-gss-for-each") {
result0 = "@-gss-for-each";
pos += 14;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@-gss-for-each\"");
}
}
if (result0 === null) {
if (input.substr(pos, 9) === "@for-each") {
result0 = "@for-each";
pos += 9;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@for-each\"");
}
}
}
if (result0 !== null) {
result0 = (function(offset) {return "for-each"})(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.substr(pos, 13) === "@-gss-for-all") {
result0 = "@-gss-for-all";
pos += 13;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@-gss-for-all\"");
}
}
if (result0 === null) {
if (input.substr(pos, 8) === "@for-all") {
result0 = "@for-all";
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@for-all\"");
}
}
}
if (result0 !== null) {
result0 = (function(offset) {return "for-all"})(pos0);
}
if (result0 === null) {
pos = pos0;
}
}
return result0;
}
function parse_Chain() {
var result0, result1, result2, result3, result4, result5, result6, result7;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 64) {
result0 = "@";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result0 !== null) {
if (input.substr(pos, 5) === "-gss-") {
result1 = "-gss-";
pos += 5;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-gss-\"");
}
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
if (input.substr(pos, 5) === "chain") {
result2 = "chain";
pos += 5;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"chain\"");
}
}
if (result2 !== null) {
result3 = parse___();
if (result3 !== null) {
result4 = parse_Selector();
if (result4 !== null) {
result5 = parse___();
if (result5 !== null) {
result7 = parse_Chainer();
if (result7 !== null) {
result6 = [];
while (result7 !== null) {
result6.push(result7);
result7 = parse_Chainer();
}
} else {
result6 = null;
}
if (result6 !== null) {
result7 = parse___();
if (result7 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, sel, chainers) { //sw:StrengthAndWeight?
parser.add$(sel.selector);
var ast = ['chain',sel.ast];
chainers.forEach(function(chainer){
//if (sw && !chainer.__has_sw ) {
// chainer = chainer.concat(sw);
//}
ast = ast.concat(chainer);
});
p.addC(ast);
})(pos0, result0[4], result0[6]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Chainer() {
var result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11, result12, result13, result14, result15;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (/^[a-zA-Z\-_0-9]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z\\-_0-9]");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (/^[a-zA-Z\-_0-9]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z\\-_0-9]");
}
}
}
} else {
result0 = null;
}
if (result0 !== null) {
if (input.charCodeAt(pos) === 40) {
result1 = "(";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result1 !== null) {
result2 = parse__();
if (result2 !== null) {
result3 = parse_HeadExp();
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
result4 = parse__();
if (result4 !== null) {
result5 = parse_ChainEq();
if (result5 !== null) {
result6 = parse__();
if (result6 !== null) {
result7 = parse_AdditiveExpression();
result7 = result7 !== null ? result7 : "";
if (result7 !== null) {
result8 = parse__();
if (result8 !== null) {
result9 = parse_ChainEq();
result9 = result9 !== null ? result9 : "";
if (result9 !== null) {
result10 = parse__();
if (result10 !== null) {
result11 = parse_StrengthAndWeight();
result11 = result11 !== null ? result11 : "";
if (result11 !== null) {
result12 = parse__();
if (result12 !== null) {
if (input.charCodeAt(pos) === 41) {
result13 = ")";
pos++;
} else {
result13 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
if (result13 !== null) {
result14 = [];
if (/^[a-zA-Z\-_0-9]/.test(input.charAt(pos))) {
result15 = input.charAt(pos);
pos++;
} else {
result15 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z\\-_0-9]");
}
}
while (result15 !== null) {
result14.push(result15);
if (/^[a-zA-Z\-_0-9]/.test(input.charAt(pos))) {
result15 = input.charAt(pos);
pos++;
} else {
result15 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z\\-_0-9]");
}
}
}
if (result14 !== null) {
result15 = parse___();
if (result15 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11, result12, result13, result14, result15];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, head, headExp, headEq, bridgeVal, tailEq, sw, tail) {
var asts = []
head = p.toString(head);
tail = p.toString(tail);
var getAST = function (op, e1, e2) {
var ast = [op, e1, e2];
if (sw) {
ast = ast.concat(sw);
//ast.__has_sw = true;
}
return ast
}
if (tail.length === 0) {tail = head;}
if (headExp) {
headExp.splice(1,1,head);
head = headExp;
}
/*
if (tailExp) {
tailExp.splice(2,1,tail);
tail = tailExp;
}
*/
if (bridgeVal) {
asts.push( getAST(headEq,head,bridgeVal) );
if (tailEq) {
asts.push( getAST(tailEq,bridgeVal,tail) );
}
else {
p.error("Invalid Chain Statement",line,column);
}
} else {
asts.push( getAST(headEq,head,tail) );
}
return asts;
})(pos0, result0[0], result0[3], result0[5], result0[7], result0[9], result0[11], result0[14]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_HeadExp() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_ChainMath();
if (result0 !== null) {
result1 = parse_AdditiveExpression();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, math, val) {
return [math, "_REPLACE_ME_", val]
})(pos0, result0[0], result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_TailExp() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_AdditiveExpression();
if (result0 !== null) {
result1 = parse_ChainMath();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, val, math) {
return [math, val, "_REPLACE_ME_"]
})(pos0, result0[0], result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_ChainMath() {
var result0;
var pos0;
pos0 = pos;
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 !== null) {
result0 = (function(offset) {return "plus-chain"})(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.charCodeAt(pos) === 45) {
result0 = "-";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result0 !== null) {
result0 = (function(offset) {return "minus-chain"})(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.charCodeAt(pos) === 42) {
result0 = "*";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result0 !== null) {
result0 = (function(offset) {return "multiply-chain"})(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.charCodeAt(pos) === 47) {
result0 = "/";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result0 !== null) {
result0 = (function(offset) {return "divide-chain"})(pos0);
}
if (result0 === null) {
pos = pos0;
}
}
}
}
return result0;
}
function parse_ChainEq() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_LinearConstraintOperator();
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
result0 = (function(offset, chainEq) {
if (!chainEq) {chainEq = "eq";}
chainEq += "-chain";
return chainEq;
})(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function cleanupExpected(expected) {
expected.sort();
var lastExpected = null;
var cleanExpected = [];
for (var i = 0; i < expected.length; i++) {
if (expected[i] !== lastExpected) {
cleanExpected.push(expected[i]);
lastExpected = expected[i];
}
}
return cleanExpected;
}
function computeErrorPosition() {
/*
* The first idea was to use |String.split| to break the input up to the
* error position along newlines and derive the line and column from
* there. However IE's |split| implementation is so broken that it was
* enough to prevent it.
*/
var line = 1;
var column = 1;
var seenCR = false;
for (var i = 0; i < Math.max(pos, rightmostFailuresPos); i++) {
var ch = input.charAt(i);
if (ch === "\n") {
if (!seenCR) { line++; }
column = 1;
seenCR = false;
} else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") {
line++;
column = 1;
seenCR = true;
} else {
column++;
seenCR = false;
}
}
return { line: line, column: column };
}
var p, parser, flatten, _varsCache, _measuresCache;
p = parser = this;
p.commands = [];
p.cs = [];
p.addC = function (c) {
p.commands.push(c);
};
p.$s = [];
p.add$ = function ($) {
if (!$) {return undefined};
if (p.$s.indexOf($) === -1) {p.$s.push($);}
return $;
}
_measuresCache = [];
p.measures = [];
p.processMeasure = function (ast) {
var _id;
_id = ast.toString(); // assuming stringified ast arrays CAN be used for cache lookup
if (_measuresCache.indexOf(_id) === -1) {
_measuresCache.push(_id);
p.measures.push(ast);
}
return ast;
}
p.getResults = function () {
return {
"selectors": p.$s,
// potential shared state from chaining
"commands": JSON.parse(JSON.stringify(p.commands))
//"measures": p.measures,
//"constraints": p.cs
}
}
p.toString = function (x) {
if (typeof x === "string") {return x}
if (x instanceof Array) {return x.join("")}
return ""
}
p.error = function (m,l,c) {
if (!!l && !!c) {m = m+ " {line:" + l + ", col:" + c + "}"}
console.error(m);
return m;
}
var result = parseFunctions[startRule]();
/*
* The parser is now in one of the following three states:
*
* 1. The parser successfully parsed the whole input.
*
* - |result !== null|
* - |pos === input.length|
* - |rightmostFailuresExpected| may or may not contain something
*
* 2. The parser successfully parsed only a part of the input.
*
* - |result !== null|
* - |pos < input.length|
* - |rightmostFailuresExpected| may or may not contain something
*
* 3. The parser did not successfully parse any part of the input.
*
* - |result === null|
* - |pos === 0|
* - |rightmostFailuresExpected| contains at least one failure
*
* All code following this comment (including called functions) must
* handle these states.
*/
if (result === null || pos !== input.length) {
var offset = Math.max(pos, rightmostFailuresPos);
var found = offset < input.length ? input.charAt(offset) : null;
var errorPosition = computeErrorPosition();
throw new this.SyntaxError(
cleanupExpected(rightmostFailuresExpected),
found,
offset,
errorPosition.line,
errorPosition.column
);
}
return result;
},
/* Returns the parser source code. */
toSource: function() { return this._source; }
};
/* Thrown when a parser encounters a syntax error. */
result.SyntaxError = function(expected, found, offset, line, column) {
function buildMessage(expected, found) {
var expectedHumanized, foundHumanized;
switch (expected.length) {
case 0:
expectedHumanized = "end of input";
break;
case 1:
expectedHumanized = expected[0];
break;
default:
expectedHumanized = expected.slice(0, expected.length - 1).join(", ")
+ " or "
+ expected[expected.length - 1];
}
foundHumanized = found ? quote(found) : "end of input";
return "Expected " + expectedHumanized + " but " + foundHumanized + " found.";
}
this.name = "SyntaxError";
this.expected = expected;
this.found = found;
this.message = buildMessage(expected, found);
this.offset = offset;
this.line = line;
this.column = column;
};
result.SyntaxError.prototype = Error.prototype;
return result;
})();
});
require.register("the-gss-vfl-compiler/lib/vfl-compiler.js", function(exports, require, module){
module.exports = (function(){
/*
* Generated by PEG.js 0.7.0.
*
* http://pegjs.majda.cz/
*/
function quote(s) {
/*
* ECMA-262, 5th ed., 7.8.4: All characters may appear literally in a
* string literal except for the closing quote character, backslash,
* carriage return, line separator, paragraph separator, and line feed.
* Any character may appear in the form of an escape sequence.
*
* For portability, we also escape escape all control and non-ASCII
* characters. Note that "\0" and "\v" escape sequences are not used
* because JSHint does not like the first and IE the second.
*/
return '"' + s
.replace(/\\/g, '\\\\') // backslash
.replace(/"/g, '\\"') // closing quote character
.replace(/\x08/g, '\\b') // backspace
.replace(/\t/g, '\\t') // horizontal tab
.replace(/\n/g, '\\n') // line feed
.replace(/\f/g, '\\f') // form feed
.replace(/\r/g, '\\r') // carriage return
.replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g, escape)
+ '"';
}
var result = {
/*
* Parses the input with a generated parser. If the parsing is successfull,
* returns a value explicitly or implicitly specified by the grammar from
* which the parser was generated (see |PEG.buildParser|). If the parsing is
* unsuccessful, throws |PEG.parser.SyntaxError| describing the error.
*/
parse: function(input, startRule) {
var parseFunctions = {
"start": parse_start,
"debug": parse_debug,
"Statement": parse_Statement,
"VFLStatement": parse_VFLStatement,
"VFLPluralStatement": parse_VFLPluralStatement,
"Dimension": parse_Dimension,
"Options": parse_Options,
"Option": parse_Option,
"OpionValueChars": parse_OpionValueChars,
"Chain": parse_Chain,
"ChainPredicate": parse_ChainPredicate,
"ChainPredicateItems": parse_ChainPredicateItems,
"ChainPredicateItem": parse_ChainPredicateItem,
"ChainPredVal": parse_ChainPredVal,
"View": parse_View,
"Point": parse_Point,
"Predicate": parse_Predicate,
"PredExpression": parse_PredExpression,
"PredEq": parse_PredEq,
"PredOp": parse_PredOp,
"PredView": parse_PredView,
"PredLiteral": parse_PredLiteral,
"PredVariable": parse_PredVariable,
"PredViewVariable": parse_PredViewVariable,
"PredSeperator": parse_PredSeperator,
"Connection": parse_Connection,
"GapChars": parse_GapChars,
"StrengthAndWeight": parse_StrengthAndWeight,
"Strength": parse_Strength,
"NameChars": parse_NameChars,
"NameCharsWithSpace": parse_NameCharsWithSpace,
"Literal": parse_Literal,
"Number": parse_Number,
"Integer": parse_Integer,
"Real": parse_Real,
"SignedInteger": parse_SignedInteger,
"SourceCharacter": parse_SourceCharacter,
"WhiteSpace": parse_WhiteSpace,
"LineTerminator": parse_LineTerminator,
"LineTerminatorSequence": parse_LineTerminatorSequence,
"EOS": parse_EOS,
"EOF": parse_EOF,
"Comment": parse_Comment,
"MultiLineComment": parse_MultiLineComment,
"MultiLineCommentNoLineTerminator": parse_MultiLineCommentNoLineTerminator,
"SingleLineComment": parse_SingleLineComment,
"_": parse__,
"__": parse___
};
if (startRule !== undefined) {
if (parseFunctions[startRule] === undefined) {
throw new Error("Invalid rule name: " + quote(startRule) + ".");
}
} else {
startRule = "start";
}
var pos = 0;
var reportFailures = 0;
var rightmostFailuresPos = 0;
var rightmostFailuresExpected = [];
function padLeft(input, padding, length) {
var result = input;
var padLength = length - input.length;
for (var i = 0; i < padLength; i++) {
result = padding + result;
}
return result;
}
function escape(ch) {
var charCode = ch.charCodeAt(0);
var escapeChar;
var length;
if (charCode <= 0xFF) {
escapeChar = 'x';
length = 2;
} else {
escapeChar = 'u';
length = 4;
}
return '\\' + escapeChar + padLeft(charCode.toString(16).toUpperCase(), '0', length);
}
function matchFailed(failure) {
if (pos < rightmostFailuresPos) {
return;
}
if (pos > rightmostFailuresPos) {
rightmostFailuresPos = pos;
rightmostFailuresExpected = [];
}
rightmostFailuresExpected.push(failure);
}
function parse_start() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse___();
if (result0 !== null) {
result1 = [];
result2 = parse_Statement();
while (result2 !== null) {
result1.push(result2);
result2 = parse_Statement();
}
if (result1 !== null) {
result2 = parse___();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) { return parser.getResults(); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_debug() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse___();
if (result0 !== null) {
result1 = [];
result2 = parse_Statement();
while (result2 !== null) {
result1.push(result2);
result2 = parse_Statement();
}
if (result1 !== null) {
result2 = parse___();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, vfl) { return parser.getResults().concat(vfl); })(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Statement() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_VFLStatement();
if (result0 !== null) {
result1 = parse_EOS();
if (result1 !== null) {
result2 = parse___();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, exp) { return exp; })(pos0, result0[0]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_VFLStatement() {
var result0, result1, result2, result3, result4, result5, result6, result7;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_Dimension();
if (result0 !== null) {
result1 = parse___();
if (result1 !== null) {
result2 = parse_View();
if (result2 !== null) {
result3 = [];
pos2 = pos;
result4 = parse___();
if (result4 !== null) {
result5 = parse_Connection();
result5 = result5 !== null ? result5 : "";
if (result5 !== null) {
result6 = parse___();
if (result6 !== null) {
result7 = parse_View();
if (result7 !== null) {
result4 = [result4, result5, result6, result7];
} else {
result4 = null;
pos = pos2;
}
} else {
result4 = null;
pos = pos2;
}
} else {
result4 = null;
pos = pos2;
}
} else {
result4 = null;
pos = pos2;
}
while (result4 !== null) {
result3.push(result4);
pos2 = pos;
result4 = parse___();
if (result4 !== null) {
result5 = parse_Connection();
result5 = result5 !== null ? result5 : "";
if (result5 !== null) {
result6 = parse___();
if (result6 !== null) {
result7 = parse_View();
if (result7 !== null) {
result4 = [result4, result5, result6, result7];
} else {
result4 = null;
pos = pos2;
}
} else {
result4 = null;
pos = pos2;
}
} else {
result4 = null;
pos = pos2;
}
} else {
result4 = null;
pos = pos2;
}
}
if (result3 !== null) {
result4 = parse___();
if (result4 !== null) {
result5 = parse_Options();
result5 = result5 !== null ? result5 : "";
if (result5 !== null) {
result0 = [result0, result1, result2, result3, result4, result5];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, d, head, tail, o) {
var connection, result, ccss, chainedViews, withContainer,
tailView, tailViewObj, headView, headViewObj;
result = head;
headViewObj = head;
headView = headViewObj.view;
chainedViews = [];
if (headView !== "|") {chainedViews.push(headView);}
parser.addPreds(headView,head.preds,d);
for (var i = 0; i < tail.length; i++) {
connection = tail[i][1];
tailViewObj = tail[i][3]
tailView = tailViewObj.view;
if (tailView !== "|") {chainedViews.push(tailView);}
parser.addPreds(tailView,tail[i][3].preds,d);
result = [
//"c",
connection,
result,
tailView
];
if (!(headViewObj.isPoint && tailViewObj.isPoint)) {
withContainer = ( headView =="|" || tailView === "|");
ccss = p.getLeftVar(headView, d, o, headViewObj) + " "
+ p.getConnectionString(connection, d, o, withContainer) + " "
+ p.getRightVar(tailView, d, o, tailViewObj)
+ p.getTrailingOptions(o)
+ p.getSW(o);
parser.addC(
ccss.trim()
);}
headViewObj = tailViewObj;
headView = tailView;
}
parser.addChains(chainedViews,o);
return {'vfl':d, o:o};
})(pos0, result0[0], result0[2], result0[3], result0[5]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
result0 = parse_VFLPluralStatement();
}
return result0;
}
function parse_VFLPluralStatement() {
var result0, result1, result2, result3, result4, result5, result6;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_Dimension();
if (result0 !== null) {
result1 = parse___();
if (result1 !== null) {
result3 = parse_NameChars();
if (result3 !== null) {
result2 = [];
while (result3 !== null) {
result2.push(result3);
result3 = parse_NameChars();
}
} else {
result2 = null;
}
if (result2 !== null) {
result3 = parse___();
if (result3 !== null) {
result4 = parse_Options();
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
result5 = parse___();
if (result5 !== null) {
result6 = parse_StrengthAndWeight();
result6 = result6 !== null ? result6 : "";
if (result6 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, d, selector, o, s) {
var ccss = "@chain ";
selector = selector.join("").trim();
ccss += selector + " ";
ccss += p.leftVarNames[d] + "(";
if (!o) {o = {};}
if (o.gap) {
ccss += "+" + o.gap;
}
ccss += ")" + p.rightVarNames[d];
if (o.chains) {
o.chains.forEach( function (chain) {
ccss += " " + chain[0] + "(";
if (chain[1].raw) {
ccss += chain[1].raw;
}
ccss += ")";
});
}
ccss += p.getTrailingOptions(o);
ccss += p.getSW(o);
parser.addC(ccss.trim());
return {vfl:d,o:o}
})(pos0, result0[0], result0[2], result0[4], result0[6]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Dimension() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 11) === "@horizontal") {
result0 = "@horizontal";
pos += 11;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@horizontal\"");
}
}
if (result0 === null) {
if (input.substr(pos, 16) === "@-gss-horizontal") {
result0 = "@-gss-horizontal";
pos += 16;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@-gss-horizontal\"");
}
}
if (result0 === null) {
if (input.substr(pos, 7) === "@-gss-h") {
result0 = "@-gss-h";
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@-gss-h\"");
}
}
if (result0 === null) {
if (input.substr(pos, 2) === "@h") {
result0 = "@h";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@h\"");
}
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {return 0;})(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.substr(pos, 9) === "@vertical") {
result0 = "@vertical";
pos += 9;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@vertical\"");
}
}
if (result0 === null) {
if (input.substr(pos, 14) === "@-gss-vertical") {
result0 = "@-gss-vertical";
pos += 14;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@-gss-vertical\"");
}
}
if (result0 === null) {
if (input.substr(pos, 7) === "@-gss-v") {
result0 = "@-gss-v";
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@-gss-v\"");
}
}
if (result0 === null) {
if (input.substr(pos, 2) === "@v") {
result0 = "@v";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@v\"");
}
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {return 1;})(pos0);
}
if (result0 === null) {
pos = pos0;
}
}
return result0;
}
function parse_Options() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_Option();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_Option();
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, os) {
var obj = {};
obj.chains = [];
for (var i = 0; i < os.length; i++) {
// proccess chains
if (!!os[i].chain) {
obj.chains.push(os[i].chain);
}
// or just add option
else {
obj[os[i].key] = os[i].value;
}
}
return obj;
})(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Option() {
var result0, result1, result2, result3, result4;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
result0 = parse___();
if (result0 !== null) {
result1 = parse_Chain();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, chain) { return chain; })(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
result0 = parse___();
if (result0 !== null) {
result2 = parse_NameChars();
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
result2 = parse_NameChars();
}
} else {
result1 = null;
}
if (result1 !== null) {
if (input.charCodeAt(pos) === 40) {
result2 = "(";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result2 !== null) {
result4 = parse_OpionValueChars();
if (result4 !== null) {
result3 = [];
while (result4 !== null) {
result3.push(result4);
result4 = parse_OpionValueChars();
}
} else {
result3 = null;
}
if (result3 !== null) {
if (input.charCodeAt(pos) === 41) {
result4 = ")";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, key, value) {return {key:key.join(''), value:value.join('')};})(pos0, result0[1], result0[3]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
result0 = parse___();
if (result0 !== null) {
result1 = parse_StrengthAndWeight();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, sw) {return {key:"sw",value:sw}; })(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
}
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("Option");
}
return result0;
}
function parse_OpionValueChars() {
var result0;
if (/^[^>=<!)]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[^>=<!)]");
}
}
return result0;
}
function parse_Chain() {
var result0, result1, result2;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 6) === "chain-") {
result0 = "chain-";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"chain-\"");
}
}
if (result0 !== null) {
result2 = parse_NameChars();
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
result2 = parse_NameChars();
}
} else {
result1 = null;
}
if (result1 !== null) {
result2 = parse_ChainPredicate();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, prop, preds) { return {'chain':[prop.join(""),preds]};})(pos0, result0[1], result0[2]);
}
if (result0 === null) {
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("Chain");
}
return result0;
}
function parse_ChainPredicate() {
var result0, result1, result2;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 40) {
result0 = "(";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result0 !== null) {
result2 = parse_ChainPredicateItems();
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
result2 = parse_ChainPredicateItems();
}
} else {
result1 = null;
}
if (result1 !== null) {
if (input.charCodeAt(pos) === 41) {
result2 = ")";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, items) {
items.raw = "";
items.forEach( function (item){
items.raw += item.raw;
});
return items;
})(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.substr(pos, 2) === "()") {
result0 = "()";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"()\"");
}
}
if (result0 !== null) {
result0 = (function(offset) {return {raw:""};})(pos0);
}
if (result0 === null) {
pos = pos0;
}
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("ChainPredicate");
}
return result0;
}
function parse_ChainPredicateItems() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_ChainPredicateItem();
if (result0 !== null) {
result1 = parse__();
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
if (input.charCodeAt(pos) === 44) {
result2 = ",";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, item) {
item.raw = item.headEq + item.value + item.tailEq + item.s;
return item;
})(pos0, result0[0]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_ChainPredicateItem() {
var result0, result1, result2, result3, result4, result5, result6;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_PredEq();
if (result0 !== null) {
result1 = parse__();
if (result1 !== null) {
result2 = parse_ChainPredVal();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result3 = parse__();
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
result4 = parse_PredEq();
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
result5 = parse__();
result5 = result5 !== null ? result5 : "";
if (result5 !== null) {
result6 = parse_StrengthAndWeight();
result6 = result6 !== null ? result6 : "";
if (result6 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, headEq, value, tailEq, s) {
return {headEq:p.join(headEq),value:p.join(value),tailEq:p.join(tailEq),s:s};})(pos0, result0[0], result0[2], result0[4], result0[6]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
result0 = parse_PredEq();
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
result1 = parse__();
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result2 = parse_ChainPredVal();
if (result2 !== null) {
result3 = parse__();
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
result4 = parse_PredEq();
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
result5 = parse__();
result5 = result5 !== null ? result5 : "";
if (result5 !== null) {
result6 = parse_StrengthAndWeight();
result6 = result6 !== null ? result6 : "";
if (result6 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, headEq, value, tailEq, s) {
return {headEq:p.join(headEq),value:p.join(value),tailEq:p.join(tailEq),s:s};})(pos0, result0[0], result0[2], result0[4], result0[6]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
result0 = parse_PredEq();
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
result1 = parse__();
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result2 = parse_ChainPredVal();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result3 = parse__();
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
result4 = parse_PredEq();
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
result5 = parse__();
result5 = result5 !== null ? result5 : "";
if (result5 !== null) {
result6 = parse_StrengthAndWeight();
if (result6 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, headEq, value, tailEq, s) {
return {headEq:p.join(headEq),value:p.join(value),tailEq:p.join(tailEq),s:s};})(pos0, result0[0], result0[2], result0[4], result0[6]);
}
if (result0 === null) {
pos = pos0;
}
}
}
return result0;
}
function parse_ChainPredVal() {
var result0, result1;
if (/^[^>=<!) ]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[^>=<!) ]");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (/^[^>=<!) ]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[^>=<!) ]");
}
}
}
} else {
result0 = null;
}
return result0;
}
function parse_View() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
reportFailures++;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 91) {
result0 = "[";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result0 !== null) {
result2 = parse_NameChars();
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
result2 = parse_NameChars();
}
} else {
result1 = null;
}
if (result1 !== null) {
result2 = parse_Predicate();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
if (input.charCodeAt(pos) === 93) {
result3 = "]";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, name, pred) {return {view:p.stringify(name),preds:pred};})(pos0, result0[1], result0[2]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 124) {
result0 = "|";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"|\"");
}
}
if (result0 !== null) {
pos2 = pos;
if (/^[^~\-]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[^~\\-]");
}
}
if (result1 !== null) {
result3 = parse_NameChars();
if (result3 !== null) {
result2 = [];
while (result3 !== null) {
result2.push(result3);
result3 = parse_NameChars();
}
} else {
result2 = null;
}
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
if (result1 !== null) {
result2 = parse_Predicate();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
if (input.charCodeAt(pos) === 124) {
result3 = "|";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"|\"");
}
}
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, name, pred) {return {view:p.stringify(name),preds:pred};})(pos0, result0[1], result0[2]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
result0 = parse_Point();
if (result0 !== null) {
result0 = (function(offset, point) {return {view:"|", isPoint:true, pos:point};})(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.charCodeAt(pos) === 124) {
result0 = "|";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"|\"");
}
}
if (result0 !== null) {
result0 = (function(offset) {return {view:"|"};})(pos0);
}
if (result0 === null) {
pos = pos0;
}
}
}
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("VFL Element");
}
return result0;
}
function parse_Point() {
var result0, result1, result2, result3, result4;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 60) {
result0 = "<";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"<\"");
}
}
if (result0 !== null) {
result1 = parse__();
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
if (/^[^>]/.test(input.charAt(pos))) {
result3 = input.charAt(pos);
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("[^>]");
}
}
if (result3 !== null) {
result2 = [];
while (result3 !== null) {
result2.push(result3);
if (/^[^>]/.test(input.charAt(pos))) {
result3 = input.charAt(pos);
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("[^>]");
}
}
}
} else {
result2 = null;
}
if (result2 !== null) {
result3 = parse__();
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
if (input.charCodeAt(pos) === 62) {
result4 = ">";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\">\"");
}
}
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, position) {
return p.stringify(position);
})(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("Point");
}
return result0;
}
function parse_Predicate() {
var result0, result1, result2, result3, result4, result5, result6, result7;
var pos0, pos1, pos2;
reportFailures++;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 40) {
result0 = "(";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result0 !== null) {
pos2 = pos;
result2 = parse_PredEq();
if (result2 !== null) {
result3 = parse_PredExpression();
if (result3 !== null) {
result4 = parse_StrengthAndWeight();
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
result5 = parse__();
result5 = result5 !== null ? result5 : "";
if (result5 !== null) {
result6 = parse_PredSeperator();
if (result6 !== null) {
result7 = parse__();
result7 = result7 !== null ? result7 : "";
if (result7 !== null) {
result2 = [result2, result3, result4, result5, result6, result7];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_PredEq();
if (result2 !== null) {
result3 = parse_PredExpression();
if (result3 !== null) {
result4 = parse_StrengthAndWeight();
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
result5 = parse__();
result5 = result5 !== null ? result5 : "";
if (result5 !== null) {
result6 = parse_PredSeperator();
if (result6 !== null) {
result7 = parse__();
result7 = result7 !== null ? result7 : "";
if (result7 !== null) {
result2 = [result2, result3, result4, result5, result6, result7];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
} else {
result1 = null;
}
if (result1 !== null) {
if (input.charCodeAt(pos) === 41) {
result2 = ")";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, preds) {return preds;})(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("Predicate");
}
return result0;
}
function parse_PredExpression() {
var result0, result1;
reportFailures++;
result1 = parse_PredOp();
if (result1 === null) {
result1 = parse_PredLiteral();
if (result1 === null) {
result1 = parse_PredVariable();
if (result1 === null) {
result1 = parse_PredViewVariable();
if (result1 === null) {
result1 = parse_PredView();
}
}
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_PredOp();
if (result1 === null) {
result1 = parse_PredLiteral();
if (result1 === null) {
result1 = parse_PredVariable();
if (result1 === null) {
result1 = parse_PredViewVariable();
if (result1 === null) {
result1 = parse_PredView();
}
}
}
}
}
} else {
result0 = null;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("Predicate Expression");
}
return result0;
}
function parse_PredEq() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse__();
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
if (input.substr(pos, 2) === "==") {
result1 = "==";
pos += 2;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"==\"");
}
}
if (result1 === null) {
if (input.substr(pos, 2) === "<=") {
result1 = "<=";
pos += 2;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"<=\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 60) {
result1 = "<";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"<\"");
}
}
if (result1 === null) {
if (input.substr(pos, 2) === ">=") {
result1 = ">=";
pos += 2;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\">=\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 62) {
result1 = ">";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\">\"");
}
}
if (result1 === null) {
pos2 = pos;
if (input.substr(pos, 2) === "=<") {
result1 = "=<";
pos += 2;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=<\"");
}
}
if (result1 !== null) {
result1 = (function(offset) {return "<=";})(pos2);
}
if (result1 === null) {
pos = pos2;
}
if (result1 === null) {
pos2 = pos;
if (input.substr(pos, 2) === "=>") {
result1 = "=>";
pos += 2;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=>\"");
}
}
if (result1 !== null) {
result1 = (function(offset) {return ">=";})(pos2);
}
if (result1 === null) {
pos = pos2;
}
}
}
}
}
}
}
if (result1 !== null) {
result2 = parse__();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, eq) {return eq;})(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_PredOp() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (/^[+\-\/*]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[+\\-\\/*]");
}
}
if (result0 !== null) {
result1 = parse__();
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, op) {return op;})(pos0, result0[0]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_PredView() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result1 = parse_NameChars();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_NameChars();
}
} else {
result0 = null;
}
if (result0 !== null) {
result1 = parse__();
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, name) {return ["view",name.join("")];})(pos0, result0[0]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_PredLiteral() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result1 = parse_Number();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_Number();
}
} else {
result0 = null;
}
if (result0 !== null) {
result1 = parse__();
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, n) {return n.join("");})(pos0, result0[0]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_PredVariable() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 91) {
result0 = "[";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result0 !== null) {
result2 = parse_NameChars();
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
result2 = parse_NameChars();
}
} else {
result1 = null;
}
if (result1 !== null) {
if (input.charCodeAt(pos) === 93) {
result2 = "]";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result2 !== null) {
result3 = parse__();
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, name) {return "[" + name.join("") + "]";})(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_PredViewVariable() {
var result0, result1, result2, result3, result4;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result1 = parse_NameChars();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_NameChars();
}
} else {
result0 = null;
}
if (result0 !== null) {
if (input.charCodeAt(pos) === 91) {
result1 = "[";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result1 !== null) {
result3 = parse_NameChars();
if (result3 !== null) {
result2 = [];
while (result3 !== null) {
result2.push(result3);
result3 = parse_NameChars();
}
} else {
result2 = null;
}
if (result2 !== null) {
if (input.charCodeAt(pos) === 93) {
result3 = "]";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result3 !== null) {
result4 = parse__();
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, view, prop) {return view.join("") + "[" + prop.join("") + "]";})(pos0, result0[0], result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_PredSeperator() {
var result0;
var pos0;
pos0 = pos;
if (input.charCodeAt(pos) === 44) {
result0 = ",";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
result0 = (function(offset) {return "";})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Connection() {
var result0, result1, result2;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 45) {
result0 = "-";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result0 !== null) {
result2 = parse_GapChars();
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
result2 = parse_GapChars();
}
} else {
result1 = null;
}
if (result1 !== null) {
if (input.charCodeAt(pos) === 45) {
result2 = "-";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, gap) {return {op:"==",gap:gap.join("")};})(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.charCodeAt(pos) === 45) {
result0 = "-";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result0 !== null) {
result0 = (function(offset) {return {op:"==",gap:"__STANDARD__"};})(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 126) {
result0 = "~";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
if (result0 !== null) {
result2 = parse_GapChars();
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
result2 = parse_GapChars();
}
} else {
result1 = null;
}
if (result1 !== null) {
if (input.charCodeAt(pos) === 126) {
result2 = "~";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, gap) {return {op:"<=",gap:gap.join("")};})(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 126) {
result0 = "~";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
if (result0 !== null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 !== null) {
if (input.charCodeAt(pos) === 126) {
result2 = "~";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return {op:"<=",gap:"__STANDARD__"};})(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.charCodeAt(pos) === 126) {
result0 = "~";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
if (result0 !== null) {
result0 = (function(offset) {return {op:"<="};})(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
result0 = "";
if (result0 !== null) {
result0 = (function(offset) {return {op:"=="};})(pos0);
}
if (result0 === null) {
pos = pos0;
}
}
}
}
}
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("VFL Connection");
}
return result0;
}
function parse_GapChars() {
var result0;
reportFailures++;
if (/^[a-zA-Z0-9#._$]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z0-9#._$]");
}
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("VFL Connection Gap");
}
return result0;
}
function parse_StrengthAndWeight() {
var result0, result1, result2, result3;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 33) {
result0 = "!";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result0 !== null) {
if (/^[a-zA-Z]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z]");
}
}
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
if (/^[a-zA-Z]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z]");
}
}
}
} else {
result1 = null;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
if (/^[0-9]/.test(input.charAt(pos))) {
result3 = input.charAt(pos);
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
if (result3 !== null) {
result2 = [];
while (result3 !== null) {
result2.push(result3);
if (/^[0-9]/.test(input.charAt(pos))) {
result3 = input.charAt(pos);
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
}
} else {
result2 = null;
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, s, w) {
var val;
val = "!" + p.join(s) + p.join(w);
return val.trim();
})(pos0, result0[1], result0[2]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 33) {
result0 = "!";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result0 !== null) {
if (input.length > pos) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("any character");
}
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return parser.error("Invalid Strength or Weight",line,column);})(pos0);
}
if (result0 === null) {
pos = pos0;
}
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("Strength / Weight");
}
return result0;
}
function parse_Strength() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 7) === "require") {
result0 = "require";
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"require\"");
}
}
if (result0 === null) {
if (input.substr(pos, 7) === "REQUIRE") {
result0 = "REQUIRE";
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"REQUIRE\"");
}
}
if (result0 === null) {
if (input.substr(pos, 7) === "Require") {
result0 = "Require";
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"Require\"");
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {return "require";})(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.substr(pos, 6) === "strong") {
result0 = "strong";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"strong\"");
}
}
if (result0 === null) {
if (input.substr(pos, 6) === "STRONG") {
result0 = "STRONG";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"STRONG\"");
}
}
if (result0 === null) {
if (input.substr(pos, 6) === "Strong") {
result0 = "Strong";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"Strong\"");
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {return "strong";})(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.substr(pos, 6) === "medium") {
result0 = "medium";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"medium\"");
}
}
if (result0 === null) {
if (input.substr(pos, 6) === "MEDIUM") {
result0 = "MEDIUM";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"MEDIUM\"");
}
}
if (result0 === null) {
if (input.substr(pos, 6) === "Medium") {
result0 = "Medium";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"Medium\"");
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {return "medium";})(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.substr(pos, 4) === "weak") {
result0 = "weak";
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"weak\"");
}
}
if (result0 === null) {
if (input.substr(pos, 4) === "WEAK") {
result0 = "WEAK";
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"WEAK\"");
}
}
if (result0 === null) {
if (input.substr(pos, 4) === "Weak") {
result0 = "Weak";
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"Weak\"");
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {return "weak";})(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.substr(pos, 8) === "required") {
result0 = "required";
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"required\"");
}
}
if (result0 === null) {
if (input.substr(pos, 8) === "REQUIRED") {
result0 = "REQUIRED";
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"REQUIRED\"");
}
}
if (result0 === null) {
if (input.substr(pos, 8) === "Required") {
result0 = "Required";
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"Required\"");
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {return "require";})(pos0);
}
if (result0 === null) {
pos = pos0;
}
}
}
}
}
return result0;
}
function parse_NameChars() {
var result0;
if (/^[a-zA-Z0-9#.\-_$:""]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z0-9#.\\-_$:\"\"]");
}
}
return result0;
}
function parse_NameCharsWithSpace() {
var result0;
result0 = parse_NameChars();
if (result0 === null) {
if (input.charCodeAt(pos) === 32) {
result0 = " ";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\" \"");
}
}
}
return result0;
}
function parse_Literal() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_Number();
if (result0 !== null) {
result0 = (function(offset, val) {
return [ "number",
val
];
})(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Number() {
var result0;
result0 = parse_Real();
if (result0 === null) {
result0 = parse_Integer();
}
return result0;
}
function parse_Integer() {
var result0, result1;
var pos0;
pos0 = pos;
if (/^[0-9]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (/^[0-9]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, digits) {
return parseInt(digits.join(""), 10);
})(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Real() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_Integer();
if (result0 !== null) {
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 !== null) {
result2 = parse_Integer();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, digits) {
return parseFloat(digits.join(""));
})(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_SignedInteger() {
var result0, result1, result2;
var pos0;
pos0 = pos;
if (/^[\-+]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\-+]");
}
}
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
if (/^[0-9]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
if (/^[0-9]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
}
} else {
result1 = null;
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_SourceCharacter() {
var result0;
if (input.length > pos) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("any character");
}
}
return result0;
}
function parse_WhiteSpace() {
var result0;
reportFailures++;
if (/^[\t\x0B\f \xA0\uFEFF]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\t\\x0B\\f \\xA0\\uFEFF]");
}
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("whitespace");
}
return result0;
}
function parse_LineTerminator() {
var result0;
if (/^[\n\r\u2028\u2029]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\n\\r\\u2028\\u2029]");
}
}
return result0;
}
function parse_LineTerminatorSequence() {
var result0;
reportFailures++;
if (input.charCodeAt(pos) === 10) {
result0 = "\n";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\n\"");
}
}
if (result0 === null) {
if (input.substr(pos, 2) === "\r\n") {
result0 = "\r\n";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\r\\n\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 13) {
result0 = "\r";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\r\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 8232) {
result0 = "\u2028";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\u2028\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 8233) {
result0 = "\u2029";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\u2029\"");
}
}
}
}
}
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("end of line");
}
return result0;
}
function parse_EOS() {
var result0, result1;
var pos0;
pos0 = pos;
result0 = parse___();
if (result0 !== null) {
if (input.charCodeAt(pos) === 59) {
result1 = ";";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
result0 = parse__();
if (result0 !== null) {
result1 = parse_LineTerminatorSequence();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
result0 = parse___();
if (result0 !== null) {
result1 = parse_EOF();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
}
}
return result0;
}
function parse_EOF() {
var result0;
var pos0;
pos0 = pos;
reportFailures++;
if (input.length > pos) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("any character");
}
}
reportFailures--;
if (result0 === null) {
result0 = "";
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Comment() {
var result0;
reportFailures++;
result0 = parse_MultiLineComment();
if (result0 === null) {
result0 = parse_SingleLineComment();
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("comment");
}
return result0;
}
function parse_MultiLineComment() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
if (input.substr(pos, 2) === "/*") {
result0 = "/*";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/*\"");
}
}
if (result0 !== null) {
result1 = [];
pos1 = pos;
pos2 = pos;
reportFailures++;
if (input.substr(pos, 2) === "*/") {
result2 = "*/";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"*/\"");
}
}
reportFailures--;
if (result2 === null) {
result2 = "";
} else {
result2 = null;
pos = pos2;
}
if (result2 !== null) {
result3 = parse_SourceCharacter();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
pos2 = pos;
reportFailures++;
if (input.substr(pos, 2) === "*/") {
result2 = "*/";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"*/\"");
}
}
reportFailures--;
if (result2 === null) {
result2 = "";
} else {
result2 = null;
pos = pos2;
}
if (result2 !== null) {
result3 = parse_SourceCharacter();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
if (input.substr(pos, 2) === "*/") {
result2 = "*/";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"*/\"");
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_MultiLineCommentNoLineTerminator() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
if (input.substr(pos, 2) === "/*") {
result0 = "/*";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/*\"");
}
}
if (result0 !== null) {
result1 = [];
pos1 = pos;
pos2 = pos;
reportFailures++;
if (input.substr(pos, 2) === "*/") {
result2 = "*/";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"*/\"");
}
}
if (result2 === null) {
result2 = parse_LineTerminator();
}
reportFailures--;
if (result2 === null) {
result2 = "";
} else {
result2 = null;
pos = pos2;
}
if (result2 !== null) {
result3 = parse_SourceCharacter();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
pos2 = pos;
reportFailures++;
if (input.substr(pos, 2) === "*/") {
result2 = "*/";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"*/\"");
}
}
if (result2 === null) {
result2 = parse_LineTerminator();
}
reportFailures--;
if (result2 === null) {
result2 = "";
} else {
result2 = null;
pos = pos2;
}
if (result2 !== null) {
result3 = parse_SourceCharacter();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
if (input.substr(pos, 2) === "*/") {
result2 = "*/";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"*/\"");
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_SingleLineComment() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
if (input.substr(pos, 2) === "//") {
result0 = "//";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"//\"");
}
}
if (result0 !== null) {
result1 = [];
pos1 = pos;
pos2 = pos;
reportFailures++;
result2 = parse_LineTerminator();
reportFailures--;
if (result2 === null) {
result2 = "";
} else {
result2 = null;
pos = pos2;
}
if (result2 !== null) {
result3 = parse_SourceCharacter();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
pos2 = pos;
reportFailures++;
result2 = parse_LineTerminator();
reportFailures--;
if (result2 === null) {
result2 = "";
} else {
result2 = null;
pos = pos2;
}
if (result2 !== null) {
result3 = parse_SourceCharacter();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result2 = parse_LineTerminator();
if (result2 === null) {
result2 = parse_EOF();
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse__() {
var result0, result1;
result0 = [];
result1 = parse_WhiteSpace();
if (result1 === null) {
result1 = parse_MultiLineCommentNoLineTerminator();
if (result1 === null) {
result1 = parse_SingleLineComment();
}
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_WhiteSpace();
if (result1 === null) {
result1 = parse_MultiLineCommentNoLineTerminator();
if (result1 === null) {
result1 = parse_SingleLineComment();
}
}
}
return result0;
}
function parse___() {
var result0, result1;
result0 = [];
result1 = parse_WhiteSpace();
if (result1 === null) {
result1 = parse_LineTerminatorSequence();
if (result1 === null) {
result1 = parse_Comment();
}
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_WhiteSpace();
if (result1 === null) {
result1 = parse_LineTerminatorSequence();
if (result1 === null) {
result1 = parse_Comment();
}
}
}
return result0;
}
function cleanupExpected(expected) {
expected.sort();
var lastExpected = null;
var cleanExpected = [];
for (var i = 0; i < expected.length; i++) {
if (expected[i] !== lastExpected) {
cleanExpected.push(expected[i]);
lastExpected = expected[i];
}
}
return cleanExpected;
}
function computeErrorPosition() {
/*
* The first idea was to use |String.split| to break the input up to the
* error position along newlines and derive the line and column from
* there. However IE's |split| implementation is so broken that it was
* enough to prevent it.
*/
var line = 1;
var column = 1;
var seenCR = false;
for (var i = 0; i < Math.max(pos, rightmostFailuresPos); i++) {
var ch = input.charAt(i);
if (ch === "\n") {
if (!seenCR) { line++; }
column = 1;
seenCR = false;
} else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") {
line++;
column = 1;
seenCR = true;
} else {
column++;
seenCR = false;
}
}
return { line: line, column: column };
}
var p, parser, cs, leftVarNames, superLeftVarNames, rightVarNames, superRightVarNames, standardGapNames, getSuperViewName, getGapString, sizeVarNames;
p = parser = this;
p.trickleDownOptions = ["name"];
sizeVarNames = p.sizeVarNames = ["width", "height"];
leftVarNames = p.leftVarNames = ["right", "bottom"];
superLeftVarNames = p.superLeftVarNames = ["left", "top"];
rightVarNames = p.rightVarNames = ["left", "top"];
superRightVarNames = p.superRightVarNames = ["right", "bottom"];
cs = parser.cs = [];
parser.addC = function (c) {
cs.push(c);
};
parser.addPreds = function (view,preds,d) {
var pred, ccss, eq, exps, exp;
if (preds) {
for (var i = 0; i < preds.length; i++) {
pred = preds[i];
eq = pred[0];
ccss = view + "[" + sizeVarNames[d] + "] " + eq + " ";
exps = pred[1];
for (var j = 0; j < exps.length; j++) {
exp = exps[j];
if (exp[0] === "view") {
exp = exp[1] + "[" + sizeVarNames[d] + "]";
}
ccss += exp + " ";
}
ccss += pred[2]; // strength & weight
cs.push(ccss.trim());
}
}
};
parser.defaultChainObject = {
headEq: "==",
value: "",
tailEq: "",
s: ""
};
parser.chainTailEqMap = {
"<=": ">=",
">=": "<=",
"==": "==",
"<" : ">",
">" : "<"
};
parser.addChains = function (views,o) {
var chains, chain, prop, preds, connector, ccss, view, pred;
chains = o.chains;
if (chains) {
for (var i = 0; i < chains.length; i++) {
chain = chains[i];
prop = chain[0];
preds = chain[1];
if (preds === "") {
preds = [parser.defaultChainObject];
} // load default chain predicate
for (var j = 0; j < preds.length; j++) {
pred = preds[j];
ccss = "";
for (var k = 0; k < views.length - 1; k++) {
view = views[k];
if (pred.headEq === "") {
pred.headEq = parser.defaultChainObject.headEq;
}
ccss += " " + view + "[" + prop + "] " + pred.headEq;
if (pred.value !== "") {
ccss += " " + pred.value;
if (views.length > 1) {
if (pred.tailEq === "") {
pred.tailEq = parser.chainTailEqMap[pred.headEq];
}
ccss += " " + pred.tailEq;
}
else {
ccss += " " + pred.s;
cs.push(ccss.trim());
}
}
}
if (views.length > 1) {
ccss += " " + views[views.length-1] + "[" + prop + "]";
ccss += p.getTrailingOptions(o);
ccss += " " + pred.s;
cs.push(ccss.trim());
}
}
}
}
};
getSuperViewName = function (o) {
if (o.in === undefined) {
return "::this";
}
return o.in;
};
parser.getLeftVar = function (view, dimension, o, viewObj) {
var varName, viewName;
if (viewObj.isPoint) {
return viewObj.pos;
}
else if (view === "|") {
viewName = getSuperViewName(o);
varName = superLeftVarNames[dimension];
}
else {
viewName = view;
varName = leftVarNames[dimension];
}
return viewName + "[" + varName + "]";
};
parser.getRightVar = function (view, dimension, o, viewObj) {
var varName;
if (viewObj.isPoint) {
return viewObj.pos;
}
else if (view === "|") {
view = getSuperViewName(o);
varName = superRightVarNames[dimension];
}
else {
varName = rightVarNames[dimension];
}
return view + "[" + varName + "]";
};
standardGapNames = ["[hgap]", "[vgap]"];
getGapString = function (g,d,o,withContainer) {
if (g === undefined) {return "";}
if (g === "__STANDARD__") {
// use gap if given with `gap()` or `outer-gap`
if (withContainer && o['outer-gap']) {
g = o['outer-gap'];
} else if (o.gap) {
g = o.gap;
// else use standard var
} else {
g = standardGapNames[d];
}
}
return "+ " + g;
};
parser.getConnectionString = function (c, d, o, withContainer) {
return (getGapString(c.gap,d,o,withContainer) + " " + c.op).trim();
};
p.getTrailingOptions = function (o) {
var string = "";
p.trickleDownOptions.forEach(function(key){
if (o[key] != null) {
string = string + " " + key + "(" + o[key] + ")";
}
});
return string;
};
p.getSW = function (o) {
if (o.sw) {
return " " + o.sw.trim();
}
return "";
};
parser.getResults = function () {
return this.cs;
};
parser.error = function (m,l,c) {
if (!!l && !!c) {
m = m + " {line:" + l + ", col:" + c + "}";
}
console.error(m);
return m;
};
p.flatten = function (array, isShallow) {
if (typeof array === "string") {return array;}
var index = -1,
length = array ? array.length : 0,
result = [];
while (++index < length) {
var value = array[index];
if (value instanceof Array) {
Array.prototype.push.apply(result, isShallow ? value : p.flatten(value));
}
else {
result.push(value);
}
}
return result;
}
p.trim = function (x) {
if (typeof x === "string") {return x.trim();}
if (x instanceof Array) {return x.join("").trim();}
return ""
};
p.join = function (a) {
if (a.join){return a.join("");}
return a;
};
p.stringify = function (array) {
return p.trim(p.join(p.flatten(array)));
};
var result = parseFunctions[startRule]();
/*
* The parser is now in one of the following three states:
*
* 1. The parser successfully parsed the whole input.
*
* - |result !== null|
* - |pos === input.length|
* - |rightmostFailuresExpected| may or may not contain something
*
* 2. The parser successfully parsed only a part of the input.
*
* - |result !== null|
* - |pos < input.length|
* - |rightmostFailuresExpected| may or may not contain something
*
* 3. The parser did not successfully parse any part of the input.
*
* - |result === null|
* - |pos === 0|
* - |rightmostFailuresExpected| contains at least one failure
*
* All code following this comment (including called functions) must
* handle these states.
*/
if (result === null || pos !== input.length) {
var offset = Math.max(pos, rightmostFailuresPos);
var found = offset < input.length ? input.charAt(offset) : null;
var errorPosition = computeErrorPosition();
throw new this.SyntaxError(
cleanupExpected(rightmostFailuresExpected),
found,
offset,
errorPosition.line,
errorPosition.column
);
}
return result;
},
/* Returns the parser source code. */
toSource: function() { return this._source; }
};
/* Thrown when a parser encounters a syntax error. */
result.SyntaxError = function(expected, found, offset, line, column) {
function buildMessage(expected, found) {
var expectedHumanized, foundHumanized;
switch (expected.length) {
case 0:
expectedHumanized = "end of input";
break;
case 1:
expectedHumanized = expected[0];
break;
default:
expectedHumanized = expected.slice(0, expected.length - 1).join(", ")
+ " or "
+ expected[expected.length - 1];
}
foundHumanized = found ? quote(found) : "end of input";
return "Expected " + expectedHumanized + " but " + foundHumanized + " found.";
}
this.name = "SyntaxError";
this.expected = expected;
this.found = found;
this.message = buildMessage(expected, found);
this.offset = offset;
this.line = line;
this.column = column;
};
result.SyntaxError.prototype = Error.prototype;
return result;
})();
});
require.register("the-gss-vfl-compiler/lib/compiler.js", function(exports, require, module){
var vfl = require('./vfl-compiler');
exports.parse = function (rules) {
return vfl.parse(rules);
};
});
require.register("the-gss-vgl-compiler/lib/vgl-compiler.js", function(exports, require, module){
module.exports = (function(){
/*
* Generated by PEG.js 0.7.0.
*
* http://pegjs.majda.cz/
*/
function quote(s) {
/*
* ECMA-262, 5th ed., 7.8.4: All characters may appear literally in a
* string literal except for the closing quote character, backslash,
* carriage return, line separator, paragraph separator, and line feed.
* Any character may appear in the form of an escape sequence.
*
* For portability, we also escape escape all control and non-ASCII
* characters. Note that "\0" and "\v" escape sequences are not used
* because JSHint does not like the first and IE the second.
*/
return '"' + s
.replace(/\\/g, '\\\\') // backslash
.replace(/"/g, '\\"') // closing quote character
.replace(/\x08/g, '\\b') // backspace
.replace(/\t/g, '\\t') // horizontal tab
.replace(/\n/g, '\\n') // line feed
.replace(/\f/g, '\\f') // form feed
.replace(/\r/g, '\\r') // carriage return
.replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g, escape)
+ '"';
}
var result = {
/*
* Parses the input with a generated parser. If the parsing is successfull,
* returns a value explicitly or implicitly specified by the grammar from
* which the parser was generated (see |PEG.buildParser|). If the parsing is
* unsuccessful, throws |PEG.parser.SyntaxError| describing the error.
*/
parse: function(input, startRule) {
var parseFunctions = {
"start": parse_start,
"Statement": parse_Statement,
"VGLStatement": parse_VGLStatement,
"RowsCols": parse_RowsCols,
"Template": parse_Template,
"TemplateLine": parse_TemplateLine,
"TemplateOptions": parse_TemplateOptions,
"TemplateOption": parse_TemplateOption,
"OpionValueChars": parse_OpionValueChars,
"TemplateZone": parse_TemplateZone,
"RowColDimension": parse_RowColDimension,
"Line": parse_Line,
"LineChunk": parse_LineChunk,
"Connection": parse_Connection,
"ConnectionTypes": parse_ConnectionTypes,
"VirtualNameChars": parse_VirtualNameChars,
"NameChars": parse_NameChars,
"NameCharsWithSpace": parse_NameCharsWithSpace,
"Literal": parse_Literal,
"Number": parse_Number,
"Integer": parse_Integer,
"Real": parse_Real,
"SignedInteger": parse_SignedInteger,
"SourceCharacter": parse_SourceCharacter,
"WhiteSpace": parse_WhiteSpace,
"LineTerminator": parse_LineTerminator,
"LineTerminatorSequence": parse_LineTerminatorSequence,
"AnyChar": parse_AnyChar,
"EOS": parse_EOS,
"EOF": parse_EOF,
"Comment": parse_Comment,
"MultiLineComment": parse_MultiLineComment,
"MultiLineCommentNoLineTerminator": parse_MultiLineCommentNoLineTerminator,
"SingleLineComment": parse_SingleLineComment,
"_": parse__,
"__": parse___
};
if (startRule !== undefined) {
if (parseFunctions[startRule] === undefined) {
throw new Error("Invalid rule name: " + quote(startRule) + ".");
}
} else {
startRule = "start";
}
var pos = 0;
var reportFailures = 0;
var rightmostFailuresPos = 0;
var rightmostFailuresExpected = [];
function padLeft(input, padding, length) {
var result = input;
var padLength = length - input.length;
for (var i = 0; i < padLength; i++) {
result = padding + result;
}
return result;
}
function escape(ch) {
var charCode = ch.charCodeAt(0);
var escapeChar;
var length;
if (charCode <= 0xFF) {
escapeChar = 'x';
length = 2;
} else {
escapeChar = 'u';
length = 4;
}
return '\\' + escapeChar + padLeft(charCode.toString(16).toUpperCase(), '0', length);
}
function matchFailed(failure) {
if (pos < rightmostFailuresPos) {
return;
}
if (pos > rightmostFailuresPos) {
rightmostFailuresPos = pos;
rightmostFailuresExpected = [];
}
rightmostFailuresExpected.push(failure);
}
function parse_start() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse___();
if (result0 !== null) {
result1 = [];
result2 = parse_Statement();
while (result2 !== null) {
result1.push(result2);
result2 = parse_Statement();
}
if (result1 !== null) {
result2 = parse___();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return p.getResults()})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Statement() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 64) {
result0 = "@";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result0 !== null) {
result1 = parse_VGLStatement();
if (result1 !== null) {
result2 = parse_EOS();
if (result2 !== null) {
result3 = parse___();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, vfls) { return vfls; })(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_VGLStatement() {
var result0;
result0 = parse_RowsCols();
if (result0 === null) {
result0 = parse_Template();
}
return result0;
}
function parse_RowsCols() {
var result0, result1, result2, result3, result4, result5, result6, result7, result8;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 5) === "grid-") {
result0 = "grid-";
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"grid-\"");
}
}
if (result0 === null) {
if (input.substr(pos, 10) === "-gss-grid-") {
result0 = "-gss-grid-";
pos += 10;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"-gss-grid-\"");
}
}
}
if (result0 !== null) {
result1 = parse_RowColDimension();
if (result1 !== null) {
result2 = parse___();
if (result2 !== null) {
if (input.charCodeAt(pos) === 34) {
result3 = "\"";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"\\\"\"");
}
}
if (result3 !== null) {
result4 = parse_Line();
if (result4 !== null) {
if (input.charCodeAt(pos) === 34) {
result5 = "\"";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\"\\\"\"");
}
}
if (result5 !== null) {
result6 = parse___();
if (result6 !== null) {
result7 = [];
result8 = parse_AnyChar();
while (result8 !== null) {
result7.push(result8);
result8 = parse_AnyChar();
}
if (result7 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, d, line, stuff) {
var vfl, props;
vfl = "@"+ ['v','h'][d] +" "+
line +" "+
"in"+"(::)" +" "+
"chain-"+p.size[d]+"(::["+p.size[d] +"]) "+
"chain-"+p.size[1-d] +" "+
"chain-"+p.pos[d]+"(::["+p.pos[d] +"]) "+
p.trim(stuff);
p.addVFL(vfl.trim());
})(pos0, result0[1], result0[4], result0[7]);
}
if (result0 === null) {
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("grid-rows / grid-cols");
}
return result0;
}
function parse_Template() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 5) === "grid-") {
result0 = "grid-";
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"grid-\"");
}
}
if (result0 === null) {
if (input.substr(pos, 10) === "-gss-grid-") {
result0 = "-gss-grid-";
pos += 10;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"-gss-grid-\"");
}
}
}
if (result0 !== null) {
if (input.substr(pos, 8) === "template") {
result1 = "template";
pos += 8;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"template\"");
}
}
if (result1 !== null) {
result2 = parse___();
if (result2 !== null) {
if (/^[0-9a-zA-Z\-_]/.test(input.charAt(pos))) {
result4 = input.charAt(pos);
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("[0-9a-zA-Z\\-_]");
}
}
if (result4 !== null) {
result3 = [];
while (result4 !== null) {
result3.push(result4);
if (/^[0-9a-zA-Z\-_]/.test(input.charAt(pos))) {
result4 = input.charAt(pos);
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("[0-9a-zA-Z\\-_]");
}
}
}
} else {
result3 = null;
}
if (result3 !== null) {
result5 = parse_TemplateLine();
if (result5 !== null) {
result4 = [];
while (result5 !== null) {
result4.push(result5);
result5 = parse_TemplateLine();
}
} else {
result4 = null;
}
if (result4 !== null) {
result5 = parse_TemplateOptions();
if (result5 !== null) {
result0 = [result0, result1, result2, result3, result4, result5];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, name, lines, options) {
p.addTemplate(lines,p.stringify(name),options);
})(pos0, result0[3], result0[4], result0[5]);
}
if (result0 === null) {
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("grid-template");
}
return result0;
}
function parse_TemplateLine() {
var result0, result1, result2, result3, result4;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
result0 = parse___();
if (result0 !== null) {
if (input.charCodeAt(pos) === 34) {
result1 = "\"";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"\\\"\"");
}
}
if (result1 !== null) {
result3 = parse_TemplateZone();
if (result3 !== null) {
result2 = [];
while (result3 !== null) {
result2.push(result3);
result3 = parse_TemplateZone();
}
} else {
result2 = null;
}
if (result2 !== null) {
if (input.charCodeAt(pos) === 34) {
result3 = "\"";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"\\\"\"");
}
}
if (result3 !== null) {
result4 = parse___();
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, zones) {
return p.processHZones(zones);
})(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("template line");
}
return result0;
}
function parse_TemplateOptions() {
var result0, result1;
var pos0;
reportFailures++;
pos0 = pos;
result0 = [];
result1 = parse_TemplateOption();
while (result1 !== null) {
result0.push(result1);
result1 = parse_TemplateOption();
}
if (result0 !== null) {
result0 = (function(offset, o) {
var result = {};
if (o) {
result = {}
o.forEach(function(obj){
result[obj.key] = obj.value;
})
}
return result;
})(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("Template Options");
}
return result0;
}
function parse_TemplateOption() {
var result0, result1, result2, result3, result4;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
result0 = parse___();
if (result0 !== null) {
result2 = parse_NameChars();
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
result2 = parse_NameChars();
}
} else {
result1 = null;
}
if (result1 !== null) {
if (input.charCodeAt(pos) === 40) {
result2 = "(";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result2 !== null) {
result4 = parse_OpionValueChars();
if (result4 !== null) {
result3 = [];
while (result4 !== null) {
result3.push(result4);
result4 = parse_OpionValueChars();
}
} else {
result3 = null;
}
if (result3 !== null) {
if (input.charCodeAt(pos) === 41) {
result4 = ")";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, key, value) {return {key:key.join(''), value:value.join('')};})(pos0, result0[1], result0[3]);
}
if (result0 === null) {
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("TemplateOption");
}
return result0;
}
function parse_OpionValueChars() {
var result0;
if (/^[^>=<!)]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[^>=<!)]");
}
}
return result0;
}
function parse_TemplateZone() {
var result0, result1, result2;
var pos0, pos1;
reportFailures++;
pos0 = pos;
if (input.charCodeAt(pos) === 48) {
result1 = "0";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"0\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 48) {
result1 = "0";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"0\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 49) {
result1 = "1";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"1\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 49) {
result1 = "1";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"1\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 50) {
result1 = "2";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"2\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 50) {
result1 = "2";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"2\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 51) {
result1 = "3";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"3\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 51) {
result1 = "3";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"3\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 52) {
result1 = "4";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"4\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 52) {
result1 = "4";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"4\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 53) {
result1 = "5";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"5\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 53) {
result1 = "5";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"5\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 54) {
result1 = "6";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"6\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 54) {
result1 = "6";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"6\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 55) {
result1 = "7";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"7\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 55) {
result1 = "7";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"7\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 56) {
result1 = "8";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"8\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 56) {
result1 = "8";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"8\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 57) {
result1 = "9";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"9\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 57) {
result1 = "9";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"9\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 97) {
result1 = "a";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"a\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 97) {
result1 = "a";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"a\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 98) {
result1 = "b";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"b\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 98) {
result1 = "b";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"b\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 99) {
result1 = "c";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"c\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 99) {
result1 = "c";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"c\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 100) {
result1 = "d";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"d\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 100) {
result1 = "d";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"d\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 101) {
result1 = "e";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"e\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 101) {
result1 = "e";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"e\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
pos1 = pos;
if (input.charCodeAt(pos) === 102) {
result1 = "f";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"f\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 102) {
result1 = "f";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"f\"");
}
}
}
} else {
result0 = null;
}
if (result0 !== null) {
if (input.charCodeAt(pos) === 103) {
result2 = "g";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"g\"");
}
}
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
if (input.charCodeAt(pos) === 103) {
result2 = "g";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"g\"");
}
}
}
} else {
result1 = null;
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 104) {
result1 = "h";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"h\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 104) {
result1 = "h";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"h\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 105) {
result1 = "i";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"i\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 105) {
result1 = "i";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"i\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 106) {
result1 = "j";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"j\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 106) {
result1 = "j";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"j\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 107) {
result1 = "k";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"k\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 107) {
result1 = "k";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"k\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 108) {
result1 = "l";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"l\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 108) {
result1 = "l";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"l\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 109) {
result1 = "m";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"m\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 109) {
result1 = "m";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"m\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 110) {
result1 = "n";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"n\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 110) {
result1 = "n";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"n\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 111) {
result1 = "o";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"o\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 111) {
result1 = "o";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"o\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 112) {
result1 = "p";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"p\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 112) {
result1 = "p";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"p\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 113) {
result1 = "q";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"q\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 113) {
result1 = "q";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"q\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 114) {
result1 = "r";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"r\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 114) {
result1 = "r";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"r\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 115) {
result1 = "s";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"s\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 115) {
result1 = "s";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"s\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 116) {
result1 = "t";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"t\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 116) {
result1 = "t";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"t\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 117) {
result1 = "u";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"u\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 117) {
result1 = "u";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"u\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 118) {
result1 = "v";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"v\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 118) {
result1 = "v";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"v\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 119) {
result1 = "w";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"w\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 119) {
result1 = "w";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"w\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 120) {
result1 = "x";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"x\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 120) {
result1 = "x";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"x\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 121) {
result1 = "y";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"y\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 121) {
result1 = "y";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"y\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 122) {
result1 = "z";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"z\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 122) {
result1 = "z";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"z\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 65) {
result1 = "A";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"A\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 65) {
result1 = "A";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"A\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 66) {
result1 = "B";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"B\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 66) {
result1 = "B";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"B\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 67) {
result1 = "C";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"C\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 67) {
result1 = "C";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"C\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 68) {
result1 = "D";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"D\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 68) {
result1 = "D";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"D\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 69) {
result1 = "E";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"E\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 69) {
result1 = "E";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"E\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 70) {
result1 = "F";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"F\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 70) {
result1 = "F";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"F\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 71) {
result1 = "G";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"G\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 71) {
result1 = "G";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"G\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 72) {
result1 = "H";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"H\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 72) {
result1 = "H";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"H\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 73) {
result1 = "I";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"I\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 73) {
result1 = "I";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"I\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 74) {
result1 = "J";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"J\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 74) {
result1 = "J";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"J\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 75) {
result1 = "K";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"K\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 75) {
result1 = "K";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"K\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 76) {
result1 = "L";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"L\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 76) {
result1 = "L";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"L\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 77) {
result1 = "M";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"M\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 77) {
result1 = "M";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"M\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 78) {
result1 = "N";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"N\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 78) {
result1 = "N";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"N\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 79) {
result1 = "O";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"O\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 79) {
result1 = "O";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"O\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 80) {
result1 = "P";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"P\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 80) {
result1 = "P";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"P\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 81) {
result1 = "Q";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"Q\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 81) {
result1 = "Q";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"Q\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 82) {
result1 = "R";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"R\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 82) {
result1 = "R";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"R\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 83) {
result1 = "S";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"S\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 83) {
result1 = "S";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"S\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 84) {
result1 = "T";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"T\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 84) {
result1 = "T";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"T\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 85) {
result1 = "U";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"U\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 85) {
result1 = "U";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"U\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 86) {
result1 = "V";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"V\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 86) {
result1 = "V";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"V\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 87) {
result1 = "W";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"W\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 87) {
result1 = "W";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"W\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 88) {
result1 = "X";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"X\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 88) {
result1 = "X";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"X\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 89) {
result1 = "Y";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"Y\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 89) {
result1 = "Y";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"Y\"");
}
}
}
} else {
result0 = null;
}
if (result0 === null) {
if (input.charCodeAt(pos) === 90) {
result1 = "Z";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"Z\"");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (input.charCodeAt(pos) === 90) {
result1 = "Z";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"Z\"");
}
}
}
} else {
result0 = null;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
if (result0 !== null) {
result0 = (function(offset, zone) {
return {xspan:zone.length,name:zone[0],x:zone};
})(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.charCodeAt(pos) === 46) {
result0 = ".";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result0 !== null) {
result0 = (function(offset) {
var name = p.getBlankName();
return {xspan:1,name:name,x:[name]};
})(pos0);
}
if (result0 === null) {
pos = pos0;
}
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("Template Zone");
}
return result0;
}
function parse_RowColDimension() {
var result0;
var pos0;
reportFailures++;
pos0 = pos;
if (input.substr(pos, 4) === "rows") {
result0 = "rows";
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"rows\"");
}
}
if (result0 !== null) {
result0 = (function(offset) {return 0;})(pos0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.substr(pos, 4) === "cols") {
result0 = "cols";
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"cols\"");
}
}
if (result0 !== null) {
result0 = (function(offset) {return 1;})(pos0);
}
if (result0 === null) {
pos = pos0;
}
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("Row or Col Dimension");
}
return result0;
}
function parse_Line() {
var result0, result1, result2, result3;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
result0 = parse_Connection();
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
result1 = parse_LineChunk();
if (result1 !== null) {
result2 = [];
result3 = parse_LineChunk();
while (result3 !== null) {
result2.push(result3);
result3 = parse_LineChunk();
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, headcon, head, tails) {
var result;
result = "|";
if (headcon) {result += headcon;}
result += head;
tails.forEach(function (tail){
result += tail;
});
result += "|";
return result;
})(pos0, result0[0], result0[1], result0[2]);
}
if (result0 === null) {
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("1D Line");
}
return result0;
}
function parse_LineChunk() {
var result0, result1, result2, result3, result4;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
result0 = parse___();
if (result0 !== null) {
result2 = parse_VirtualNameChars();
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
result2 = parse_VirtualNameChars();
}
} else {
result1 = null;
}
if (result1 !== null) {
result2 = parse___();
if (result2 !== null) {
result3 = parse_Connection();
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
result4 = parse___();
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, name, connect) {
var result;
name = p.trim(name);
result = '["'+name+'"]';
p.addVirtual(name);
if (connect) {
result = result + connect;
}
return result;
})(pos0, result0[1], result0[3]);
}
if (result0 === null) {
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("!D LineChunk");
}
return result0;
}
function parse_Connection() {
var result0, result1, result2;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 45) {
result0 = "-";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 126) {
result0 = "~";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
}
if (result0 !== null) {
if (/^[0-9]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
if (/^[0-9]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
}
} else {
result1 = null;
}
if (result1 === null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
if (input.charCodeAt(pos) === 45) {
result2 = "-";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 126) {
result2 = "~";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, connect) {return p.stringify(connect);})(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("1D Connection");
}
return result0;
}
function parse_ConnectionTypes() {
var result0, result1, result2;
var pos0;
reportFailures++;
if (input.charCodeAt(pos) === 45) {
result0 = "-";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 126) {
result0 = "~";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
if (result0 === null) {
pos0 = pos;
if (input.charCodeAt(pos) === 45) {
result0 = "-";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result0 !== null) {
if (/^[0-9]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
if (/^[0-9]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
}
} else {
result1 = null;
}
if (result1 !== null) {
if (input.charCodeAt(pos) === 45) {
result2 = "-";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.charCodeAt(pos) === 126) {
result0 = "~";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
if (result0 !== null) {
if (/^[0-9]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
if (/^[0-9]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
}
} else {
result1 = null;
}
if (result1 === null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
}
if (result1 !== null) {
if (input.charCodeAt(pos) === 126) {
result2 = "~";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
}
}
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("!D Connection Type");
}
return result0;
}
function parse_VirtualNameChars() {
var result0;
if (/^[a-zA-Z0-9#_$:]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z0-9#_$:]");
}
}
return result0;
}
function parse_NameChars() {
var result0;
if (/^[a-zA-Z0-9#.\-_$:]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z0-9#.\\-_$:]");
}
}
return result0;
}
function parse_NameCharsWithSpace() {
var result0;
result0 = parse_NameChars();
if (result0 === null) {
if (input.charCodeAt(pos) === 32) {
result0 = " ";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\" \"");
}
}
}
return result0;
}
function parse_Literal() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_Number();
if (result0 !== null) {
result0 = (function(offset, val) {
return [ "number",
val
];
})(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Number() {
var result0;
result0 = parse_Real();
if (result0 === null) {
result0 = parse_Integer();
}
return result0;
}
function parse_Integer() {
var result0, result1;
var pos0;
pos0 = pos;
if (/^[0-9]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (/^[0-9]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, digits) {
return parseInt(digits.join(""), 10);
})(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Real() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_Integer();
if (result0 !== null) {
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 !== null) {
result2 = parse_Integer();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, digits) {
return parseFloat(digits.join(""));
})(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_SignedInteger() {
var result0, result1, result2;
var pos0;
pos0 = pos;
if (/^[\-+]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\-+]");
}
}
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
if (/^[0-9]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
if (/^[0-9]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
}
} else {
result1 = null;
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_SourceCharacter() {
var result0;
if (input.length > pos) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("any character");
}
}
return result0;
}
function parse_WhiteSpace() {
var result0;
reportFailures++;
if (/^[\t\x0B\f \xA0\uFEFF]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\t\\x0B\\f \\xA0\\uFEFF]");
}
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("whitespace");
}
return result0;
}
function parse_LineTerminator() {
var result0;
if (/^[\n\r\u2028\u2029]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\n\\r\\u2028\\u2029]");
}
}
return result0;
}
function parse_LineTerminatorSequence() {
var result0;
reportFailures++;
if (input.charCodeAt(pos) === 10) {
result0 = "\n";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\n\"");
}
}
if (result0 === null) {
if (input.substr(pos, 2) === "\r\n") {
result0 = "\r\n";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\r\\n\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 13) {
result0 = "\r";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\r\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 8232) {
result0 = "\u2028";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\u2028\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 8233) {
result0 = "\u2029";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\u2029\"");
}
}
}
}
}
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("end of line");
}
return result0;
}
function parse_AnyChar() {
var result0;
if (/^[a-zA-Z0-9 .,#:+?!^=()_\-$*\/\\""'[\]]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z0-9 .,#:+?!^=()_\\-$*\\/\\\\\"\"'[\\]]");
}
}
return result0;
}
function parse_EOS() {
var result0, result1;
var pos0;
reportFailures++;
pos0 = pos;
result0 = parse___();
if (result0 !== null) {
if (input.charCodeAt(pos) === 59) {
result1 = ";";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
result0 = parse__();
if (result0 !== null) {
result1 = parse_LineTerminatorSequence();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
result0 = parse___();
if (result0 !== null) {
result1 = parse_EOF();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
}
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("End of Statement");
}
return result0;
}
function parse_EOF() {
var result0;
var pos0;
pos0 = pos;
reportFailures++;
if (input.length > pos) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("any character");
}
}
reportFailures--;
if (result0 === null) {
result0 = "";
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Comment() {
var result0;
reportFailures++;
result0 = parse_MultiLineComment();
if (result0 === null) {
result0 = parse_SingleLineComment();
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("Comment");
}
return result0;
}
function parse_MultiLineComment() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
reportFailures++;
pos0 = pos;
if (input.substr(pos, 2) === "/*") {
result0 = "/*";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/*\"");
}
}
if (result0 !== null) {
result1 = [];
pos1 = pos;
pos2 = pos;
reportFailures++;
if (input.substr(pos, 2) === "*/") {
result2 = "*/";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"*/\"");
}
}
reportFailures--;
if (result2 === null) {
result2 = "";
} else {
result2 = null;
pos = pos2;
}
if (result2 !== null) {
result3 = parse_SourceCharacter();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
pos2 = pos;
reportFailures++;
if (input.substr(pos, 2) === "*/") {
result2 = "*/";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"*/\"");
}
}
reportFailures--;
if (result2 === null) {
result2 = "";
} else {
result2 = null;
pos = pos2;
}
if (result2 !== null) {
result3 = parse_SourceCharacter();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
if (input.substr(pos, 2) === "*/") {
result2 = "*/";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"*/\"");
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("MultiLineComment");
}
return result0;
}
function parse_MultiLineCommentNoLineTerminator() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
reportFailures++;
pos0 = pos;
if (input.substr(pos, 2) === "/*") {
result0 = "/*";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/*\"");
}
}
if (result0 !== null) {
result1 = [];
pos1 = pos;
pos2 = pos;
reportFailures++;
if (input.substr(pos, 2) === "*/") {
result2 = "*/";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"*/\"");
}
}
if (result2 === null) {
result2 = parse_LineTerminator();
}
reportFailures--;
if (result2 === null) {
result2 = "";
} else {
result2 = null;
pos = pos2;
}
if (result2 !== null) {
result3 = parse_SourceCharacter();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
pos2 = pos;
reportFailures++;
if (input.substr(pos, 2) === "*/") {
result2 = "*/";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"*/\"");
}
}
if (result2 === null) {
result2 = parse_LineTerminator();
}
reportFailures--;
if (result2 === null) {
result2 = "";
} else {
result2 = null;
pos = pos2;
}
if (result2 !== null) {
result3 = parse_SourceCharacter();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
if (input.substr(pos, 2) === "*/") {
result2 = "*/";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"*/\"");
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("MultiLineCommentNoLineTerminator");
}
return result0;
}
function parse_SingleLineComment() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
reportFailures++;
pos0 = pos;
if (input.substr(pos, 2) === "//") {
result0 = "//";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"//\"");
}
}
if (result0 !== null) {
result1 = [];
pos1 = pos;
pos2 = pos;
reportFailures++;
result2 = parse_LineTerminator();
reportFailures--;
if (result2 === null) {
result2 = "";
} else {
result2 = null;
pos = pos2;
}
if (result2 !== null) {
result3 = parse_SourceCharacter();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
pos2 = pos;
reportFailures++;
result2 = parse_LineTerminator();
reportFailures--;
if (result2 === null) {
result2 = "";
} else {
result2 = null;
pos = pos2;
}
if (result2 !== null) {
result3 = parse_SourceCharacter();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result2 = parse_LineTerminator();
if (result2 === null) {
result2 = parse_EOF();
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("Single Line Comment");
}
return result0;
}
function parse__() {
var result0, result1;
reportFailures++;
result0 = [];
result1 = parse_WhiteSpace();
if (result1 === null) {
result1 = parse_MultiLineCommentNoLineTerminator();
if (result1 === null) {
result1 = parse_SingleLineComment();
}
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_WhiteSpace();
if (result1 === null) {
result1 = parse_MultiLineCommentNoLineTerminator();
if (result1 === null) {
result1 = parse_SingleLineComment();
}
}
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("Whitespace / Comment");
}
return result0;
}
function parse___() {
var result0, result1;
reportFailures++;
result0 = [];
result1 = parse_WhiteSpace();
if (result1 === null) {
result1 = parse_LineTerminatorSequence();
if (result1 === null) {
result1 = parse_Comment();
}
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_WhiteSpace();
if (result1 === null) {
result1 = parse_LineTerminatorSequence();
if (result1 === null) {
result1 = parse_Comment();
}
}
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("Whitespace / Comment / Newline");
}
return result0;
}
function cleanupExpected(expected) {
expected.sort();
var lastExpected = null;
var cleanExpected = [];
for (var i = 0; i < expected.length; i++) {
if (expected[i] !== lastExpected) {
cleanExpected.push(expected[i]);
lastExpected = expected[i];
}
}
return cleanExpected;
}
function computeErrorPosition() {
/*
* The first idea was to use |String.split| to break the input up to the
* error position along newlines and derive the line and column from
* there. However IE's |split| implementation is so broken that it was
* enough to prevent it.
*/
var line = 1;
var column = 1;
var seenCR = false;
for (var i = 0; i < Math.max(pos, rightmostFailuresPos); i++) {
var ch = input.charAt(i);
if (ch === "\n") {
if (!seenCR) { line++; }
column = 1;
seenCR = false;
} else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") {
line++;
column = 1;
seenCR = true;
} else {
column++;
seenCR = false;
}
}
return { line: line, column: column };
}
var p, parser, vfls, virtuals, ccss, asts, blankCount;
p = parser = this;
blankCount = 0;
p.getBlankName = function () {
blankCount++;
return "blank-" + blankCount;
};
p.size = ['width','height'];
p.pos = ['x','y'];
p.getResults = function () {
var _ccss = virtuals.sort().join(" ");
if (_ccss.length == 0) {
_ccss = ccss;
}
else {
_ccss = ["@virtual "+_ccss].concat(ccss);
}
return {
//asts: asts, // DEBUG
ccss: _ccss,
vfl: vfls
}
}
asts = [];
p.addAST = function (stuff) {
asts.push(stuff);
}
ccss = [];
p.addCCSS = function (statement) {
ccss.push(statement)
}
virtuals = [];
p.addVirtual = function (virtual) {
if (virtuals.indexOf(virtual) === -1) {
virtuals.push('"'+virtual+'"');
}
}
vfls = [];
p.addVFL = function (vfl) {
vfls.push(vfl);
}
p.addTemplate = function (lines,name,options) {
var ast, prefix, container;
prefix = name+'-';
ast = p.processHLines(lines);
ast.name = name;
if (options.in) {
container = options.in;
}
else {
container = "::";
}
var md, mdOp, outergap, gaps, g, hasGap;
gaps = {};
hasGap = false;
g = options.gap;
if (g) {
hasGap = true;
gaps.top = g;
gaps.right = g;
gaps.bottom = g;
gaps.left = g;
gaps.h = g;
gaps.v = g;
}
g = options['h-gap'];
if (g) {
hasGap = true;
gaps.right = g;
gaps.left = g;
gaps.h = g;
}
g = options['v-gap'];
if (g) {
hasGap = true;
gaps.top = g;
gaps.bottom = g;
gaps.v = g;
}
g = options['outer-gap'];
if (g) {
hasGap = true;
gaps.top = g;
gaps.right = g;
gaps.bottom = g;
gaps.left = g;
}
g = options['top-gap'];
if (g) {
hasGap = true;
gaps.top = g;
}
g = options['right-gap'];
if (g) {
hasGap = true;
gaps.right = g;
}
g = options['bottom-gap'];
if (g) {
hasGap = true;
gaps.bottom = g;
}
g = options['left-gap'];
if (g) {
hasGap = true;
gaps.left = g;
}
if (hasGap) {
mdOp = "<=";
} else {
mdOp = "==";
}
// md-width
// -------------------------------------------------
// == (this[width] - gap.left - gap.right - gap * (span - 1)) / span
md = '::['+name+'-md-width] ' + mdOp + ' ';
if (gaps.right || gaps.left || gaps.h) {
md += '(' + container + '[width]';
if (gaps.right) {md += ' - ' + gaps.right;}
if (gaps.left ) {md += ' - ' + gaps.left;}
if (gaps.h && ast.yspan > 1){
md += ' - ' + gaps.h;
if (ast.yspan > 2) {md += ' * ' + (ast.yspan - 1);}
}
md += ')';
} else {
md += container + '[width]';
}
if (ast.yspan > 1){md += ' / ' + ast.yspan;}
md += " !require";
p.addCCSS(md);
// md-height
// -------------------------------------------------
md = '::['+name+'-md-height] ' + mdOp + ' ';
if (gaps.top || gaps.bottom || gaps.v) {
md += '(' + container + '[height]';
if (gaps.top) {md += ' - ' + gaps.top;}
if (gaps.bottom ) {md += ' - ' + gaps.bottom;}
if (gaps.v && ast.xspan > 1){
md += ' - ' + gaps.v;
if (ast.xspan > 2) {md += ' * ' + (ast.xspan - 1);}
}
md += ')';
} else {
md += container + '[height]';
}
if (ast.xspan > 1){md += ' / ' + ast.xspan;}
md += " !require";
p.addCCSS(md);
// virtual widths
// -------------------------------------------------
// == md-width * span - gap * (span - 1)
var xspan, wccss;
for (var el in ast.widths) {
p.addVirtual(prefix+el);
xspan = ast.widths[el];
wccss = '"'+prefix+el+'"[width] == ';
wccss +='::['+ast.name+'-md-width]';
if (xspan > 1) {
wccss += ' * ' + xspan;
if (gaps.h) {
wccss += ' + ' + gaps.h;
if (xspan > 2) {
wccss += ' * ' + (xspan - 1);
}
}
}
p.addCCSS(wccss)
}
// virtual heights
// -------------------------------------------------
var yspan, hccss;
for (var el in ast.heights) {
yspan = ast.heights[el];
hccss = '"'+prefix+el+'"[height] == ';
hccss +='::['+ast.name+'-md-height]';
if (yspan > 1) {
hccss += ' * ' + yspan;
if (gaps.v) {
hccss += ' + ' + gaps.v;
if (yspan > 2) {
hccss += ' * ' + (yspan - 1);
}
}
}
p.addCCSS(hccss);
}
var vfl, vflFooter;
ast.v.forEach(function(brij){
brij = brij.split("%-v-%");
vfl = '@v ["'+prefix+brij[0]+'"]';
if (gaps.v) {vfl += '-';}
vfl += '["'+prefix+brij[1]+'"]';
if (gaps.v) {vfl += ' gap('+gaps.v+')';}
p.addVFL(vfl);
});
ast.h.forEach(function(brij){
brij = brij.split("%-h-%");
vfl = '@h ["'+prefix+brij[0]+'"]';
if (gaps.h) {vfl += '-';}
vfl += '["'+prefix+brij[1]+'"]';
if (gaps.h) {vfl += ' gap('+gaps.h+')';}
p.addVFL(vfl);
});
var edgeEls;
edgeEls = [];
ast.cols[0].y.forEach(function(el){
if (edgeEls.indexOf(el) > -1) {return null;}
edgeEls.push(el);
vfl = '@h |';
if (gaps.left) {vfl += '-';}
vfl += '["'+prefix+el+'"]'+' in('+container+')';
if (gaps.left) {vfl += ' gap('+gaps.left+')';}
p.addVFL(vfl);
});
edgeEls = [];
ast.rows[0].x.forEach(function(el){
if (edgeEls.indexOf(el) > -1) {return null;}
edgeEls.push(el);
vfl = '@v |';
if (gaps.top) {vfl += '-';}
vfl += '["'+prefix+el+'"]'+' in('+container+')';
if (gaps.top) {vfl += ' gap('+gaps.top+')';}
p.addVFL(vfl);
});
edgeEls = [];
ast.cols[ast.cols.length-1].y.forEach(function(el){
if (edgeEls.indexOf(el) > -1) {return null;}
edgeEls.push(el);
vfl = '@h ["'+prefix+el+'"]';
if (gaps.right) {vfl += '-';}
vfl +='|'+' in('+container+')';
if (gaps.right) {vfl += ' gap('+gaps.right+')';}
p.addVFL(vfl);
});
edgeEls = [];
ast.rows[ast.rows.length-1].x.forEach(function(el){
if (edgeEls.indexOf(el) > -1) {return null;}
edgeEls.push(el);
vfl = '@v ["'+prefix+el+'"]';
if (gaps.bottom) {vfl += '-';}
vfl += '|'+' in('+container+')';
if (gaps.bottom) {vfl += ' gap('+gaps.bottom+')';}
p.addVFL(vfl);
});
//p.addVFL(ast);
p.addAST(ast);
return ast;
}
p.processHZones = function (zones) {
var xspan, curr, prev, h, x, widths,
dotCounter, isDot;
xspan = 0;
h = [];
widths = {};
x = [];
dotCounter = 0;
zones.forEach(function(zone){
isDot = false;
curr = zone.name;
// "." are each treated as an empty zone
if (curr === "-DOT-") {
isDot = false;
dotCounter++;
curr += dotCounter;
}
x = x.concat(zone.x);
delete zone.x;
if (prev && prev !== curr) {
h.push([prev,curr].join("%-h-%"));
}
widths[zone.name] = zone.xspan;
xspan += zone.xspan;
prev = curr;
});
return {xspan:xspan,x:x,h:h,widths:widths};
}
p.processHLines = function (lines) {
var cols,i,j,col,results;
results = {heights:{},widths:{},v:[],h:[]};
cols = [];
i = 0;
lines.forEach(function(row){
j = 0;
for (var nam in row.widths) {
results.widths[nam] = row.widths[nam];
}
row.h.forEach(function(hh){
if (results.h.indexOf(hh) === -1) {results.h.push(hh);}
})
row.x.forEach(function(xx){
var col;
if (!cols[j]) {cols[j] = {y:[]};}
col = cols[j];
col.y.push(xx);
j++;
})
i++;
});
cols.forEach(function(col){
var curr, currspan, prev, vStr, heights, i, v;
v = [];
currspan = 0;
prev = null;
i = 0;
col.y.forEach(function(name){
curr = name;
currspan++;
if (col.y[i+1]!==curr) {
results.heights[name] = currspan;
currspan = 0;
}
if (prev && prev !== curr) {
vStr = [prev,curr].join("%-v-%")
if (results.v.indexOf(vStr) === -1) {results.v.push(vStr);}
}
prev = curr;
i++;
})
})
results.yspan = cols.length;
results.xspan = lines.length;
results.cols = cols;
results.rows = lines;
return results;
}
p.error = function (m,l,c) {
if (!!l && !!c) {
m = m + " {line:" + l + ", col:" + c + "}";
}
console.error(m);
return m;
};
p.trim = function (x) {
if (typeof x === "string") {return x.trim();}
if (x instanceof Array) {return x.join("").trim();}
return ""
};
p.flatten = function (array, isShallow) {
var index = -1,
length = array ? array.length : 0,
result = [];
while (++index < length) {
var value = array[index];
if (value instanceof Array) {
Array.prototype.push.apply(result, isShallow ? value : p.flatten(value));
}
else {
result.push(value);
}
}
return result;
}
p.stringify = function (array) {
return p.trim(p.flatten(array));
};
var result = parseFunctions[startRule]();
/*
* The parser is now in one of the following three states:
*
* 1. The parser successfully parsed the whole input.
*
* - |result !== null|
* - |pos === input.length|
* - |rightmostFailuresExpected| may or may not contain something
*
* 2. The parser successfully parsed only a part of the input.
*
* - |result !== null|
* - |pos < input.length|
* - |rightmostFailuresExpected| may or may not contain something
*
* 3. The parser did not successfully parse any part of the input.
*
* - |result === null|
* - |pos === 0|
* - |rightmostFailuresExpected| contains at least one failure
*
* All code following this comment (including called functions) must
* handle these states.
*/
if (result === null || pos !== input.length) {
var offset = Math.max(pos, rightmostFailuresPos);
var found = offset < input.length ? input.charAt(offset) : null;
var errorPosition = computeErrorPosition();
throw new this.SyntaxError(
cleanupExpected(rightmostFailuresExpected),
found,
offset,
errorPosition.line,
errorPosition.column
);
}
return result;
},
/* Returns the parser source code. */
toSource: function() { return this._source; }
};
/* Thrown when a parser encounters a syntax error. */
result.SyntaxError = function(expected, found, offset, line, column) {
function buildMessage(expected, found) {
var expectedHumanized, foundHumanized;
switch (expected.length) {
case 0:
expectedHumanized = "end of input";
break;
case 1:
expectedHumanized = expected[0];
break;
default:
expectedHumanized = expected.slice(0, expected.length - 1).join(", ")
+ " or "
+ expected[expected.length - 1];
}
foundHumanized = found ? quote(found) : "end of input";
return "Expected " + expectedHumanized + " but " + foundHumanized + " found.";
}
this.name = "SyntaxError";
this.expected = expected;
this.found = found;
this.message = buildMessage(expected, found);
this.offset = offset;
this.line = line;
this.column = column;
};
result.SyntaxError.prototype = Error.prototype;
return result;
})();
});
require.register("the-gss-vgl-compiler/lib/compiler.js", function(exports, require, module){
var vgl = require('./vgl-compiler');
exports.parse = function (rules) {
return vgl.parse(rules);
};
});
require.register("the-gss-compiler/lib/gss-compiler.js", function(exports, require, module){
var ccss, compile, inject, parseRules, preparser, uuid, vfl, vgl;
preparser = require('gss-preparser');
ccss = require('ccss-compiler');
vfl = require('vfl-compiler');
vgl = require('vgl-compiler');
uuid = function() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
var r, v;
r = Math.random() * 16 | 0;
v = (c === "x" ? r : r & 0x3 | 0x8);
return v.toString(16);
});
};
compile = function(gss) {
var e, rules;
try {
rules = preparser.parse(gss.trim());
} catch (_error) {
e = _error;
console.log("Preparse Error", e);
}
rules = parseRules(rules);
return rules;
};
parseRules = function(rules) {
var ccssRule, ccssRules, chunk, css, e, key, parsed, subParsed, subrules, val, vflRule, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref, _ref1;
css = "";
for (_i = 0, _len = rules.length; _i < _len; _i++) {
chunk = rules[_i];
parsed = {};
switch (chunk.type) {
case 'directive':
switch (chunk.name) {
case 'grid-template':
case '-gss-grid-template':
case 'grid-rows':
case '-gss-rows':
case 'grid-cols':
case '-gss-grid-cols':
try {
subrules = vgl.parse("@" + chunk.name + " " + chunk.terms);
} catch (_error) {
e = _error;
console.log("VGL Parse Error: @" + chunk.name + " " + chunk.terms, e);
}
parsed = {
selectors: [],
commands: []
};
_ref = subrules.ccss;
for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
ccssRule = _ref[_j];
try {
subParsed = ccss.parse(ccssRule);
} catch (_error) {
e = _error;
console.log("VGL generated CCSS parse Error", e);
}
parsed.selectors = parsed.selectors.concat(subParsed.selectors);
parsed.commands = parsed.commands.concat(subParsed.commands);
}
_ref1 = subrules.vfl;
for (_k = 0, _len2 = _ref1.length; _k < _len2; _k++) {
vflRule = _ref1[_k];
try {
subParsed = ccss.parse(vfl.parse(vflRule).join("; "));
} catch (_error) {
e = _error;
console.log("VGL generated VFL parse Error", e);
}
parsed.selectors = parsed.selectors.concat(subParsed.selectors);
parsed.commands = parsed.commands.concat(subParsed.commands);
}
break;
case 'horizontal':
case 'vertical':
case '-gss-horizontal':
case '-gss-vertical':
case 'h':
case 'v':
case '-gss-h':
case '-gss-v':
try {
ccssRules = vfl.parse("@" + chunk.name + " " + chunk.terms);
} catch (_error) {
e = _error;
console.log("VFL Parse Error: @" + chunk.name + " " + chunk.terms, e);
}
parsed = {
selectors: [],
commands: []
};
for (_l = 0, _len3 = ccssRules.length; _l < _len3; _l++) {
ccssRule = ccssRules[_l];
try {
subParsed = ccss.parse(ccssRule);
} catch (_error) {
e = _error;
console.log("VFL generated CCSS parse Error", e);
}
parsed.selectors = parsed.selectors.concat(subParsed.selectors);
parsed.commands = parsed.commands.concat(subParsed.commands);
}
break;
case 'if':
case 'elseif':
case 'else':
if (chunk.terms.length > 0) {
try {
parsed = ccss.parse("@cond" + chunk.terms + ";");
} catch (_error) {
e = _error;
console.log("CCSS conditional parse Error", e);
}
parsed.clause = parsed.commands[0];
delete parsed.commands;
} else {
parsed.clause = null;
}
}
break;
case 'constraint':
try {
parsed = ccss.parse(chunk.cssText);
} catch (_error) {
e = _error;
console.log("Constraint Parse Error", e);
}
}
for (key in parsed) {
val = parsed[key];
chunk[key] = val;
}
if (chunk.rules) {
parseRules(chunk.rules);
}
}
return rules;
};
inject = function(chunks) {
var _inject;
_inject = function(_rules, parent) {
var rule, _i, _len, _ref, _results;
_results = [];
for (_i = 0, _len = _rules.length; _i < _len; _i++) {
rule = _rules[_i];
rule._uuid = uuid();
if (parent) {
rule._parent_uuid = parent._uuid;
}
if (((_ref = rule.rules) != null ? _ref.length : void 0) > 0) {
_results.push(_inject(rule.rules, rule));
} else {
_results.push(void 0);
}
}
return _results;
};
_inject(chunks);
return chunks;
};
exports.compile = compile;
});
require.register("d4tocchini-customevent-polyfill/CustomEvent.js", function(exports, require, module){
var CustomEvent;
CustomEvent = function(event, params) {
var evt;
params = params || {
bubbles: false,
cancelable: false,
detail: undefined
};
evt = document.createEvent("CustomEvent");
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
return evt;
};
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
});
require.register("slightlyoff-cassowary.js/index.js", function(exports, require, module){
module.exports = require("./src/c.js");
require("./src/HashTable.js");
require("./src/HashSet.js");
require("./src/Error.js");
require("./src/SymbolicWeight.js");
require("./src/Strength.js");
require("./src/Variable.js");
require("./src/Point.js");
require("./src/Expression.js");
require("./src/Constraint.js");
require("./src/Constraint.js");
require("./src/EditInfo.js");
require("./src/Tableau.js");
require("./src/SimplexSolver.js");
require("./src/Timer.js");
require("./src/parser/parser.js");
require("./src/parser/api.js");
});
require.register("slightlyoff-cassowary.js/src/c.js", function(exports, require, module){
// Copyright (C) 1998-2000 Greg J. Badros
// Use of this source code is governed by
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Parts Copyright (C) 2011-2012, Alex Russell (slightlyoff@chromium.org)
(function(scope){
"use strict";
// For Safari 5.x. Go-go-gadget ridiculously long release cycle!
try {
(function(){}).bind(scope);
} catch (e) {
Object.defineProperty(Function.prototype, "bind", {
value: function(scope) {
var f = this;
return function() { return f.apply(scope, arguments); }
},
enumerable: false,
configurable: true,
writable: true,
});
}
var inBrowser = (typeof scope["HTMLElement"] != "undefined");
var getTagName = function(proto) {
var tn = null;
while (proto && proto != Object.prototype) {
if (proto.tagName) {
tn = proto.tagName;
break;
}
proto = proto.prototype;
}
return tn || "div";
};
var epsilon = 1e-8;
var _t_map = {};
var walkForMethod = function(ctor, name) {
if (!ctor || !name) return;
// Check the class-side first, the look at the prototype, then walk up
if (typeof ctor[name] == "function") {
return ctor[name];
}
var p = ctor.prototype;
if (p && typeof p[name] == "function") {
return p[name];
}
if (p === Object.prototype ||
p === Function.prototype) {
return;
}
if (typeof ctor.__super__ == "function") {
return walkForMethod(ctor.__super__, name);
}
};
// Global
var c = scope.c = function() {
if(c._api) {
return c._api.apply(this, arguments);
}
};
//
// Configuration
//
c.debug = false;
c.trace = false;
c.verbose = false;
c.traceAdded = false;
c.GC = false;
//
// Constants
//
c.GEQ = 1;
c.LEQ = 2;
//
// Utility methods
//
c.inherit = function(props) {
var ctor = null;
var parent = null;
if (props["extends"]) {
parent = props["extends"];
delete props["extends"];
}
if (props["initialize"]) {
ctor = props["initialize"];
delete props["initialize"];
}
var realCtor = ctor || function() { };
Object.defineProperty(realCtor, "__super__", {
value: (parent) ? parent : Object,
enumerable: false,
configurable: true,
writable: false,
});
if (props["_t"]) {
_t_map[props["_t"]] = realCtor;
}
// FIXME(slightlyoff): would like to have class-side inheritance!
// It's easy enough to do when we have __proto__, but we don't in IE 9/10.
// = (
/*
// NOTE: would happily do this except it's 2x slower. Boo!
props.__proto__ = parent ? parent.prototype : Object.prototype;
realCtor.prototype = props;
*/
var rp = realCtor.prototype = Object.create(
((parent) ? parent.prototype : Object.prototype)
);
c.extend(rp, props);
// If we're in a browser, we want to support "subclassing" HTML elements.
// This needs some magic and we rely on a wrapped constructor hack to make
// it happen.
if (inBrowser) {
if (parent && parent.prototype instanceof scope.HTMLElement) {
var intermediateCtor = realCtor;
var tn = getTagName(rp);
var upgrade = function(el) {
el.__proto__ = rp;
intermediateCtor.apply(el, arguments);
if (rp["created"]) { el.created(); }
if (rp["decorate"]) { el.decorate(); }
return el;
};
this.extend(rp, { upgrade: upgrade, });
realCtor = function() {
// We hack the constructor to always return an element with it's
// prototype wired to ours. Boo.
return upgrade(
scope.document.createElement(tn)
);
}
realCtor.prototype = rp;
this.extend(realCtor, { ctor: intermediateCtor, }); // HACK!!!
}
}
return realCtor;
};
c.own = function(obj, cb, context) {
Object.getOwnPropertyNames(obj).forEach(cb, context||scope);
return obj;
};
c.extend = function(obj, props) {
c.own(props, function(x) {
var pd = Object.getOwnPropertyDescriptor(props, x);
try {
if ( (typeof pd["get"] == "function") ||
(typeof pd["set"] == "function") ) {
Object.defineProperty(obj, x, pd);
} else if (typeof pd["value"] == "function" ||x.charAt(0) === "_") {
pd.writable = true;
pd.configurable = true;
pd.enumerable = false;
Object.defineProperty(obj, x, pd);
} else {
obj[x] = props[x];
}
} catch(e) {
// console.warn("c.extend assignment failed on property", x);
}
});
return obj;
};
// FIXME: legacy API to be removed
c.traceprint = function(s /*String*/) { if (c.verbose) { console.log(s); } };
c.fnenterprint = function(s /*String*/) { console.log("* " + s); };
c.fnexitprint = function(s /*String*/) { console.log("- " + s); };
c.assert = function(f /*boolean*/, description /*String*/) {
if (!f) {
throw new c.InternalError("Assertion failed: " + description);
}
};
var exprFromVarOrValue = function(v) {
if (typeof v == "number" ) {
return c.Expression.fromConstant(v);
} else if(v instanceof c.Variable) {
return c.Expression.fromVariable(v);
}
return v;
};
c.plus = function(e1, e2) {
e1 = exprFromVarOrValue(e1);
e2 = exprFromVarOrValue(e2);
return e1.plus(e2);
};
c.minus = function(e1, e2) {
e1 = exprFromVarOrValue(e1);
e2 = exprFromVarOrValue(e2);
return e1.minus(e2);
};
c.times = function(e1, e2) {
e1 = exprFromVarOrValue(e1);
e2 = exprFromVarOrValue(e2);
return e1.times(e2);
};
c.divide = function(e1, e2) {
e1 = exprFromVarOrValue(e1);
e2 = exprFromVarOrValue(e2);
return e1.divide(e2);
};
c.approx = function(a, b) {
if (a === b) { return true; }
a = +(a);
b = +(b);
if (a == 0) {
return (Math.abs(b) < epsilon);
}
if (b == 0) {
return (Math.abs(a) < epsilon);
}
return (Math.abs(a - b) < Math.abs(a) * epsilon);
};
var count = 1;
c._inc = function() { return count++; };
c.parseJSON = function(str) {
return JSON.parse(str, function(k, v) {
if (typeof v != "object" || typeof v["_t"] != "string") {
return v;
}
var type = v["_t"];
var ctor = _t_map[type];
if (type && ctor) {
var fromJSON = walkForMethod(ctor, "fromJSON");
if (fromJSON) {
return fromJSON(v, ctor);
}
}
return v;
});
};
// For Node...not that I'm bitter. No no, not at all. Not me. Never...
if (typeof require == "function" &&
typeof module != "undefined" &&
typeof load == "undefined") {
scope.exports = c;
}
// ...well, hardly ever.
})(this);
});
require.register("slightlyoff-cassowary.js/src/HashTable.js", function(exports, require, module){
/**
* Copyright 2012 Alex Russell <slightlyoff@google.com>.
*
* Use of this source code is governed by http://www.apache.org/licenses/LICENSE-2.0
*
* This is an API compatible re-implementation of the subset of jshashtable
* which Cassowary actually uses.
*
* Features removed:
*
* - multiple values per key
* - error tollerent hashing of any variety
* - overly careful (or lazy) size counting, etc.
* - Crockford's "class" pattern. We use the system from c.js.
* - any attempt at back-compat with broken runtimes.
*
* APIs removed, mostly for lack of use in Cassowary:
*
* - support for custom hashing and equality functions as keys to ctor
* - isEmpty() -> check for !ht.size()
* - putAll()
* - entries()
* - containsKey()
* - containsValue()
* - keys()
* - values()
*
* Additions:
*
* - new "scope" parameter to each() and escapingEach()
*/
(function(c) {
"use strict";
var keyCode = function(key) {
return key.hashCode;
};
var copyOwn = function(src, dest) {
Object.keys(src).forEach(function(x) {
dest[x] = src[x];
});
};
if (false && typeof Map != "undefined") {
c.HashTable = c.inherit({
initialize: function() {
this.size = 0;
this._store = new Map();
this._keys = [];
// this.get = this._store.get.bind(this._store);
},
set: function(key, value) {
this._store.set(key, value);
if (this._keys.indexOf(key) == -1) {
this.size++;
// delete this._keys[this._keys.indexOf(key)];
this._keys.push(key);
} /* else {
delete this._keys[this._keys.indexOf(key)];
this._keys.push(key);
}
*/
},
get: function(key) {
return this._store.get(key);
},
clear: function() {
this.size = 0;
this._store = new Map();
this._keys = [];
},
delete: function(key) {
if (this._store.delete(key) && this.size > 0) {
delete this._keys[this._keys.indexOf(key)];
this.size--;
}
},
each: function(callback, scope) {
if (!this.size) { return; }
this._keys.forEach(function(k){
if (typeof k == "undefined") { return; }
var v = this._store.get(k);
if (typeof v != "undefined") {
callback.call(scope||null, k, v);
}
}, this);
},
escapingEach: function(callback, scope) {
if (!this.size) { return; }
var that = this;
var kl = this._keys.length;
var context;
for (var x = 0; x < kl; x++) {
if (typeof this._keys[x] != "undefined") {
(function(k) {
var v = that._store.get(k);
if (typeof v != "undefined") {
context = callback.call(scope||null, k, v);
}
})(this._keys[x]);
if (context) {
if (context.retval !== undefined) {
return context;
}
if (context.brk) {
break;
}
}
}
}
},
clone: function() {
var n = new c.HashTable();
if (this.size) {
this.each(function(k, v) {
n.set(k, v);
});
}
return n;
}
});
} else {
// For escapingEach
var defaultContext = {};
c.HashTable = c.inherit({
initialize: function() {
this.size = 0;
this._store = {};
this._keyStrMap = {};
this._deleted = 0;
},
set: function(key, value) {
var hash = key.hashCode;
if (typeof this._store[hash] == "undefined") {
// FIXME(slightlyoff): if size gooes above the V8 property limit,
// compact or go to a tree.
this.size++;
}
this._store[hash] = value;
this._keyStrMap[hash] = key;
},
get: function(key) {
if(!this.size) { return null; }
key = key.hashCode;
var v = this._store[key];
if (typeof v != "undefined") {
return this._store[key];
}
return null;
},
clear: function() {
this.size = 0;
this._store = {};
this._keyStrMap = {};
},
_compact: function() {
// console.time("HashTable::_compact()");
var ns = {};
copyOwn(this._store, ns);
this._store = ns;
// console.timeEnd("HashTable::_compact()");
},
_compactThreshold: 100,
_perhapsCompact: function() {
// If we have more properties than V8's fast property lookup limit, don't
// bother
if (this._size > 30) return;
if (this._deleted > this._compactThreshold) {
this._compact();
this._deleted = 0;
}
},
delete: function(key) {
key = key.hashCode;
if (!this._store.hasOwnProperty(key)) {
return;
}
this._deleted++;
// FIXME(slightlyoff):
// I hate this because it causes these objects to go megamorphic = (
// Sadly, Cassowary is hugely sensitive to iteration order changes, and
// "delete" preserves order when Object.keys() is called later.
delete this._store[key];
// Note: we don't delete from _keyStrMap because we only get the
// Object.keys() from _store, so it's the only one we need to keep up-to-
// date.
if (this.size > 0) {
this.size--;
}
},
each: function(callback, scope) {
if (!this.size) { return; }
this._perhapsCompact();
var store = this._store;
var keyMap = this._keyStrMap;
for (var x in this._store) {
if (this._store.hasOwnProperty(x)) {
callback.call(scope||null, keyMap[x], store[x]);
}
}
},
escapingEach: function(callback, scope) {
if (!this.size) { return; }
this._perhapsCompact();
var that = this;
var store = this._store;
var keyMap = this._keyStrMap;
var context = defaultContext;
var kl = Object.keys(store);
for (var x = 0; x < kl.length; x++) {
(function(v) {
if (that._store.hasOwnProperty(v)) {
context = callback.call(scope||null, keyMap[v], store[v]);
}
})(kl[x]);
if (context) {
if (context.retval !== undefined) {
return context;
}
if (context.brk) {
break;
}
}
}
},
clone: function() {
var n = new c.HashTable();
if (this.size) {
n.size = this.size;
copyOwn(this._store, n._store);
copyOwn(this._keyStrMap, n._keyStrMap);
}
return n;
},
equals: function(other) {
if (other === this) {
return true;
}
if (!(other instanceof c.HashTable) || other._size !== this._size) {
return false;
}
var codes = Object.keys(this._store);
for (var i = 0; i < codes.length; i++) {
var code = codes[i];
if (this._keyStrMap[code] !== other._keyStrMap[code] ||
this._store[code] !== other._store[code]) {
return false;
}
}
return true;
},
toString: function(h) {
var answer = "";
this.each(function(k, v) { answer += k + " => " + v + "\n"; });
return answer;
},
});
}
})(this["c"]||module.parent.exports||{});
});
require.register("slightlyoff-cassowary.js/src/HashSet.js", function(exports, require, module){
/**
* Copyright 2011, Alex Russell <slightlyoff@google.com>
*
* Use of this source code is governed by http://www.apache.org/licenses/LICENSE-2.0
*
* API compatible re-implementation of jshashset.js, including only what
* Cassowary needs. Built for speed, not comfort.
*/
(function(c) {
"use strict";
c.HashSet = c.inherit({
_t: "c.HashSet",
initialize: function() {
this.storage = [];
this.size = 0;
this.hashCode = c._inc();
},
add: function(item) {
var s = this.storage, io = s.indexOf(item);
if (s.indexOf(item) == -1) { s[s.length] = item; }
this.size = this.storage.length;
},
values: function() {
// FIXME(slightlyoff): is it safe to assume we won't be mutated by our caller?
// if not, return this.storage.slice(0);
return this.storage;
},
has: function(item) {
var s = this.storage;
return (s.indexOf(item) != -1);
},
delete: function(item) {
var io = this.storage.indexOf(item);
if (io == -1) { return null; }
this.storage.splice(io, 1)[0];
this.size = this.storage.length;
},
clear: function() {
this.storage.length = 0;
},
each: function(func, scope) {
if(this.size)
this.storage.forEach(func, scope);
},
escapingEach: function(func, scope) {
// FIXME(slightlyoff): actually escape!
if (this.size)
this.storage.forEach(func, scope);
},
toString: function() {
var answer = this.size + " {";
var first = true;
this.each(function(e) {
if (!first) {
answer += ", ";
} else {
first = false;
}
answer += e;
});
answer += "}\n";
return answer;
},
toJSON: function() {
var d = [];
this.each(function(e) {
d[d.length] = e.toJSON();
});
return {
_t: "c.HashSet",
data: d
};
},
fromJSON: function(o) {
var r = new c.HashSet();
if (o.data) {
r.size = o.data.length;
r.storage = o.data;
}
return r;
},
});
})(this["c"]||module.parent.exports||{});
});
require.register("slightlyoff-cassowary.js/src/Error.js", function(exports, require, module){
// Copyright (C) 1998-2000 Greg J. Badros
// Use of this source code is governed by http://www.apache.org/licenses/LICENSE-2.0
//
// Parts Copyright (C) 2011-2012, Alex Russell (slightlyoff@chromium.org)
(function(c){
"use strict";
c.Error = c.inherit({
// extends: Error,
initialize: function(s /*String*/) { if (s) { this._description = s; } },
_name: "c.Error",
_description: "An error has occured in Cassowary",
set description(v) { this._description = v; },
get description() { return "(" + this._name + ") " + this._description; },
get message() { return this.description; },
toString: function() { return this.description; },
});
var errorType = function(name, error) {
return c.inherit({
extends: c.Error,
initialize: function() { c.Error.apply(this, arguments); },
_name: name||"", _description: error||""
});
};
c.ConstraintNotFound =
errorType("c.ConstraintNotFound",
"Tried to remove a constraint never added to the tableu");
c.InternalError =
errorType("c.InternalError");
c.NonExpression =
errorType("c.NonExpression",
"The resulting expression would be non");
c.NotEnoughStays =
errorType("c.NotEnoughStays",
"There are not enough stays to give specific values to every variable");
c.RequiredFailure =
errorType("c.RequiredFailure", "A required constraint cannot be satisfied");
c.TooDifficult =
errorType("c.TooDifficult", "The constraints are too difficult to solve");
})(this["c"]||module.parent.exports||{});
});
require.register("slightlyoff-cassowary.js/src/SymbolicWeight.js", function(exports, require, module){
// Copyright (C) 1998-2000 Greg J. Badros
// Use of this source code is governed by http://www.apache.org/licenses/LICENSE-2.0
//
// Parts Copyright (C) 2011-2012, Alex Russell (slightlyoff@chromium.org)
(function(c) {
"use strict";
var multiplier = 1000;
c.SymbolicWeight = c.inherit({
_t: "c.SymbolicWeight",
initialize: function(/*w1, w2, w3*/) {
this.value = 0;
var factor = 1;
for (var i = arguments.length - 1; i >= 0; --i) {
this.value += arguments[i] * factor;
factor *= multiplier;
}
},
toJSON: function() {
return {
_t: this._t,
value: this.value
};
},
});
})(this["c"]||module.parent.exports||{});
});
require.register("slightlyoff-cassowary.js/src/Strength.js", function(exports, require, module){
// Copyright (C) 1998-2000 Greg J. Badros
// Use of this source code is governed by http://www.apache.org/licenses/LICENSE-2.0
//
// Parts Copyright (C) 2011, Alex Russell (slightlyoff@chromium.org)
// FILE: EDU.Washington.grad.gjb.cassowary
// package EDU.Washington.grad.gjb.cassowary;
(function(c) {
c.Strength = c.inherit({
initialize: function(name /*String*/, symbolicWeight, w2, w3) {
this.name = name;
if (symbolicWeight instanceof c.SymbolicWeight) {
this.symbolicWeight = symbolicWeight;
} else {
this.symbolicWeight = new c.SymbolicWeight(symbolicWeight, w2, w3);
}
},
get required() {
return (this === c.Strength.required);
},
toString: function() {
return this.name + (!this.isRequired ? (":" + this.symbolicWeight) : "");
},
});
/* public static final */
c.Strength.required = new c.Strength("<Required>", 1000, 1000, 1000);
/* public static final */
c.Strength.strong = new c.Strength("strong", 1, 0, 0);
/* public static final */
c.Strength.medium = new c.Strength("medium", 0, 1, 0);
/* public static final */
c.Strength.weak = new c.Strength("weak", 0, 0, 1);
})(this["c"]||((typeof module != "undefined") ? module.parent.exports.c : {}));
});
require.register("slightlyoff-cassowary.js/src/Variable.js", function(exports, require, module){
// Copyright (C) 1998-2000 Greg J. Badros
// Use of this source code is governed by http://www.apache.org/licenses/LICENSE-2.0
//
// Parts Copyright (C) 2011-2012, Alex Russell (slightlyoff@chromium.org)
(function(c) {
"use strict";
c.AbstractVariable = c.inherit({
isDummy: false,
isExternal: false,
isPivotable: false,
isRestricted: false,
_init: function(args, varNamePrefix) {
// Common mixin initialization.
this.hashCode = c._inc();
this.name = (varNamePrefix||"") + this.hashCode;
if (args) {
if (typeof args.name != "undefined") {
this.name = args.name;
}
if (typeof args.value != "undefined") {
this.value = args.value;
}
if (typeof args.prefix != "undefined") {
this._prefix = args.prefix;
}
}
},
_prefix: "",
name: "",
value: 0,
valueOf: function() { return this.value; },
toJSON: function() {
var o = {};
if (this._t) {
o._t = this._t;
}
if (this.name) {
o.name = this.name;
}
if (typeof this.value != "undefined") {
o.value = this.value;
}
if (this._prefix) {
o._prefix = this._prefix;
}
if (this._t) {
o._t = this._t;
}
return o;
},
fromJSON: function(o, Ctor) {
var r = new Ctor();
c.extend(r, o);
return r;
},
toString: function() {
return this._prefix + "[" + this.name + ":" + this.value + "]";
},
});
c.Variable = c.inherit({
_t: "c.Variable",
extends: c.AbstractVariable,
initialize: function(args) {
this._init(args, "v");
var vm = c.Variable._map;
if (vm) { vm[this.name] = this; }
},
isExternal: true,
});
/* static */
// c.Variable._map = [];
c.DummyVariable = c.inherit({
_t: "c.DummyVariable",
extends: c.AbstractVariable,
initialize: function(args) {
this._init(args, "d");
},
isDummy: true,
isRestricted: true,
value: "dummy",
});
c.ObjectiveVariable = c.inherit({
_t: "c.ObjectiveVariable",
extends: c.AbstractVariable,
initialize: function(args) {
this._init(args, "o");
},
value: "obj",
});
c.SlackVariable = c.inherit({
_t: "c.SlackVariable",
extends: c.AbstractVariable,
initialize: function(args) {
this._init(args, "s");
},
isPivotable: true,
isRestricted: true,
value: "slack",
});
})(this["c"]||module.parent.exports||{});
});
require.register("slightlyoff-cassowary.js/src/Point.js", function(exports, require, module){
// Copyright (C) 1998-2000 Greg J. Badros
// Use of this source code is governed by http://www.apache.org/licenses/LICENSE-2.0
//
// Parts Copyright (C) 2011, Alex Russell (slightlyoff@chromium.org)
(function(c) {
"use strict";
c.Point = c.inherit({
initialize: function(x, y, suffix) {
if (x instanceof c.Variable) {
this._x = x;
} else {
var xArgs = { value: x };
if (suffix) {
xArgs.name = "x" + suffix;
}
this._x = new c.Variable(xArgs);
}
if (y instanceof c.Variable) {
this._y = y;
} else {
var yArgs = { value: y };
if (suffix) {
yArgs.name = "y" + suffix;
}
this._y = new c.Variable(yArgs);
}
},
get x() { return this._x; },
set x(x) {
if (x instanceof c.Variable) {
this._x = x;
} else {
this._x.value = x;
}
},
get y() { return this._y; },
set y(y) {
if (y instanceof c.Variable) {
this._y = y;
} else {
this._y.value = y;
}
},
toString: function() {
return "(" + this.x + ", " + this.y + ")";
},
});
})(this["c"]||module.parent.exports||{});
});
require.register("slightlyoff-cassowary.js/src/Expression.js", function(exports, require, module){
// Copyright (C) 1998-2000 Greg J. Badros
// Use of this source code is governed by http://www.apache.org/licenses/LICENSE-2.0
//
// Parts Copyright (C) 2011, Alex Russell (slightlyoff@chromium.org)
// FILE: EDU.Washington.grad.gjb.cassowary
// package EDU.Washington.grad.gjb.cassowary;
(function(c) {
"use strict";
var checkNumber = function(value, otherwise){
// if(isNaN(value)) { debugger; }
return (typeof value === "number") ? value : otherwise;
};
c.Expression = c.inherit({
initialize: function(cvar /*c.AbstractVariable*/,
value /*double*/,
constant /*double*/) {
this.constant = checkNumber(constant, 0);
this.terms = new c.HashTable();
if (cvar instanceof c.AbstractVariable) {
value = checkNumber(value, 1);
this.setVariable(cvar, value);
} else if (typeof cvar == "number") {
if (!isNaN(cvar)) {
this.constant = cvar;
} else {
console.trace();
}
}
},
initializeFromHash: function(constant /*ClDouble*/, terms /*c.Hashtable*/) {
if (c.verbose) {
console.log("*******************************");
console.log("clone c.initializeFromHash");
console.log("*******************************");
}
if (c.GC) console.log("clone c.Expression");
this.constant = constant;
this.terms = terms.clone();
return this;
},
multiplyMe: function(x /*double*/) {
this.constant *= x;
var t = this.terms;
t.each(function(clv, coeff) { t.set(clv, coeff * x); });
return this;
},
clone: function() {
if (c.verbose) {
console.log("*******************************");
console.log("clone c.Expression");
console.log("*******************************");
}
var e = c.Expression.empty();
e.initializeFromHash(this.constant, this.terms);
return e;
},
times: function(x) {
if (typeof x == 'number') {
return (this.clone()).multiplyMe(x);
} else {
if (this.isConstant) {
return x.times(this.constant);
} else if (x.isConstant) {
return this.times(x.constant);
} else {
throw new c.NonExpression();
}
}
},
plus: function(expr /*c.Expression*/) {
if (expr instanceof c.Expression) {
return this.clone().addExpression(expr, 1);
} else if (expr instanceof c.Variable) {
return this.clone().addVariable(expr, 1);
}
},
minus: function(expr /*c.Expression*/) {
if (expr instanceof c.Expression) {
return this.clone().addExpression(expr, -1);
} else if (expr instanceof c.Variable) {
return this.clone().addVariable(expr, -1);
}
},
divide: function(x) {
if (typeof x == 'number') {
if (c.approx(x, 0)) {
throw new c.NonExpression();
}
return this.times(1 / x);
} else if (x instanceof c.Expression) {
if (!x.isConstant) {
throw new c.NonExpression();
}
return this.times(1 / x.constant);
}
},
addExpression: function(expr /*c.Expression*/,
n /*double*/,
subject /*c.AbstractVariable*/,
solver /*c.Tableau*/) {
// console.log("c.Expression::addExpression()", expr, n);
// console.trace();
if (expr instanceof c.AbstractVariable) {
expr = c.Expression.fromVariable(expr);
// if(c.trace) console.log("addExpression: Had to cast a var to an expression");
}
n = checkNumber(n, 1);
this.constant += (n * expr.constant);
expr.terms.each(function(clv, coeff) {
// console.log("clv:", clv, "coeff:", coeff, "subject:", subject);
this.addVariable(clv, coeff * n, subject, solver);
}, this);
return this;
},
addVariable: function(v /*c.AbstractVariable*/, cd /*double*/, subject, solver) {
if (cd == null) {
cd = 1;
}
/*
if (c.trace) console.log("c.Expression::addVariable():", v , cd);
*/
var coeff = this.terms.get(v);
if (coeff) {
var newCoefficient = coeff + cd;
if (newCoefficient == 0 || c.approx(newCoefficient, 0)) {
if (solver) {
solver.noteRemovedVariable(v, subject);
}
this.terms.delete(v);
} else {
this.setVariable(v, newCoefficient);
}
} else {
if (!c.approx(cd, 0)) {
this.setVariable(v, cd);
if (solver) {
solver.noteAddedVariable(v, subject);
}
}
}
return this;
},
setVariable: function(v /*c.AbstractVariable*/, c /*double*/) {
// console.log("terms.set(", v, c, ")");
this.terms.set(v, c);
return this;
},
anyPivotableVariable: function() {
if (this.isConstant) {
throw new c.InternalError("anyPivotableVariable called on a constant");
}
var rv = this.terms.escapingEach(function(clv, c) {
if (clv.isPivotable) return { retval: clv };
});
if (rv && rv.retval !== undefined) {
return rv.retval;
}
return null;
},
substituteOut: function(outvar /*c.AbstractVariable*/,
expr /*c.Expression*/,
subject /*c.AbstractVariable*/,
solver /*ClTableau*/) {
/*
if (c.trace) {
c.fnenterprint("CLE:substituteOut: " + outvar + ", " + expr + ", " + subject + ", ...");
c.traceprint("this = " + this);
}
*/
var setVariable = this.setVariable.bind(this);
var terms = this.terms;
var multiplier = terms.get(outvar);
terms.delete(outvar);
this.constant += (multiplier * expr.constant);
/*
console.log("substituteOut:",
"\n\toutvar:", outvar,
"\n\texpr:", expr.toString(),
"\n\tmultiplier:", multiplier,
"\n\tterms:", terms);
*/
expr.terms.each(function(clv, coeff) {
var oldCoefficient = terms.get(clv);
if (oldCoefficient) {
var newCoefficient = oldCoefficient + multiplier * coeff;
if (c.approx(newCoefficient, 0)) {
solver.noteRemovedVariable(clv, subject);
terms.delete(clv);
} else {
terms.set(clv, newCoefficient);
}
} else {
terms.set(clv, multiplier * coeff);
if (solver) {
solver.noteAddedVariable(clv, subject);
}
}
});
// if (c.trace) c.traceprint("Now this is " + this);
},
changeSubject: function(old_subject /*c.AbstractVariable*/,
new_subject /*c.AbstractVariable*/) {
this.setVariable(old_subject, this.newSubject(new_subject));
},
newSubject: function(subject /*c.AbstractVariable*/) {
// if (c.trace) c.fnenterprint("newSubject:" + subject);
var reciprocal = 1 / this.terms.get(subject);
this.terms.delete(subject);
this.multiplyMe(-reciprocal);
return reciprocal;
},
// Return the coefficient corresponding to variable var, i.e.,
// the 'ci' corresponding to the 'vi' that var is:
// v1*c1 + v2*c2 + .. + vn*cn + c
coefficientFor: function(clv /*c.AbstractVariable*/) {
return this.terms.get(clv) || 0;
},
get isConstant() {
return this.terms.size == 0;
},
toString: function() {
var bstr = ''; // answer
var needsplus = false;
if (!c.approx(this.constant, 0) || this.isConstant) {
bstr += this.constant;
if (this.isConstant) {
return bstr;
} else {
needsplus = true;
}
}
this.terms.each( function(clv, coeff) {
if (needsplus) {
bstr += " + ";
}
bstr += coeff + "*" + clv;
needsplus = true;
});
return bstr;
},
equals: function(other) {
if (other === this) {
return true;
}
return other instanceof c.Expression &&
other.constant === this.constant &&
other.terms.equals(this.terms);
},
Plus: function(e1 /*c.Expression*/, e2 /*c.Expression*/) {
return e1.plus(e2);
},
Minus: function(e1 /*c.Expression*/, e2 /*c.Expression*/) {
return e1.minus(e2);
},
Times: function(e1 /*c.Expression*/, e2 /*c.Expression*/) {
return e1.times(e2);
},
Divide: function(e1 /*c.Expression*/, e2 /*c.Expression*/) {
return e1.divide(e2);
},
});
c.Expression.empty = function() {
return new c.Expression(undefined, 1, 0);
};
c.Expression.fromConstant = function(cons) {
return new c.Expression(cons);
};
c.Expression.fromValue = function(v) {
v = +(v);
return new c.Expression(undefined, v, 0);
};
c.Expression.fromVariable = function(v) {
return new c.Expression(v, 1, 0);
}
})(this["c"]||module.parent.exports||{});
});
require.register("slightlyoff-cassowary.js/src/Constraint.js", function(exports, require, module){
// Copyright (C) 1998-2000 Greg J. Badros
// Use of this source code is governed by http://www.apache.org/licenses/LICENSE-2.0
//
// Parts Copyright (C) 2011-2012, Alex Russell (slightlyoff@chromium.org)
(function(c) {
"use strict";
c.AbstractConstraint = c.inherit({
initialize: function(strength /*c.Strength*/, weight /*double*/) {
this.hashCode = c._inc();
this.strength = strength || c.Strength.required;
this.weight = weight || 1;
},
isEditConstraint: false,
isInequality: false,
isStayConstraint: false,
get required() { return (this.strength === c.Strength.required); },
toString: function() {
// this is abstract -- it intentionally leaves the parens unbalanced for
// the subclasses to complete (e.g., with ' = 0', etc.
return this.strength + " {" + this.weight + "} (" + this.expression +")";
},
});
var ts = c.AbstractConstraint.prototype.toString;
var EditOrStayCtor = function(cv /*c.Variable*/, strength /*c.Strength*/, weight /*double*/) {
c.AbstractConstraint.call(this, strength || c.Strength.strong, weight);
this.variable = cv;
this.expression = new c.Expression(cv, -1, cv.value);
};
c.EditConstraint = c.inherit({
extends: c.AbstractConstraint,
initialize: function() { EditOrStayCtor.apply(this, arguments); },
isEditConstraint: true,
toString: function() { return "edit:" + ts.call(this); },
});
c.StayConstraint = c.inherit({
extends: c.AbstractConstraint,
initialize: function() { EditOrStayCtor.apply(this, arguments); },
isStayConstraint: true,
toString: function() { return "stay:" + ts.call(this); },
});
var lc =
c.Constraint = c.inherit({
extends: c.AbstractConstraint,
initialize: function(cle /*c.Expression*/,
strength /*c.Strength*/,
weight /*double*/) {
c.AbstractConstraint.call(this, strength, weight);
this.expression = cle;
},
});
c.Inequality = c.inherit({
extends: c.Constraint,
_cloneOrNewCle: function(cle) {
// FIXME(D4): move somewhere else?
if (cle.clone) {
return cle.clone();
} else {
return new c.Expression(cle);
}
},
initialize: function(a1, a2, a3, a4, a5) {
// FIXME(slightlyoff): what a disgusting mess. Should at least add docs.
// console.log("c.Inequality.initialize(", a1, a2, a3, a4, a5, ")");
var a1IsExp = a1 instanceof c.Expression,
a3IsExp = a3 instanceof c.Expression,
a1IsVar = a1 instanceof c.AbstractVariable,
a3IsVar = a3 instanceof c.AbstractVariable,
a1IsNum = typeof(a1) == 'number',
a3IsNum = typeof(a3) == 'number';
// (cle || number), op, cv
if ((a1IsExp || a1IsNum) && a3IsVar) {
var cle = a1, op = a2, cv = a3, strength = a4, weight = a5;
lc.call(this, this._cloneOrNewCle(cle), strength, weight);
if (op == c.LEQ) {
this.expression.multiplyMe(-1);
this.expression.addVariable(cv);
} else if (op == c.GEQ) {
this.expression.addVariable(cv, -1);
} else {
throw new c.InternalError("Invalid operator in c.Inequality constructor");
}
// cv, op, (cle || number)
} else if (a1IsVar && (a3IsExp || a3IsNum)) {
var cle = a3, op = a2, cv = a1, strength = a4, weight = a5;
lc.call(this, this._cloneOrNewCle(cle), strength, weight);
if (op == c.GEQ) {
this.expression.multiplyMe(-1);
this.expression.addVariable(cv);
} else if (op == c.LEQ) {
this.expression.addVariable(cv, -1);
} else {
throw new c.InternalError("Invalid operator in c.Inequality constructor");
}
// cle, op, num
} else if (a1IsExp && a3IsNum) {
var cle1 = a1, op = a2, cle2 = a3, strength = a4, weight = a5;
lc.call(this, this._cloneOrNewCle(cle1), strength, weight);
if (op == c.LEQ) {
this.expression.multiplyMe(-1);
this.expression.addExpression(this._cloneOrNewCle(cle2));
} else if (op == c.GEQ) {
this.expression.addExpression(this._cloneOrNewCle(cle2), -1);
} else {
throw new c.InternalError("Invalid operator in c.Inequality constructor");
}
return this
// num, op, cle
} else if (a1IsNum && a3IsExp) {
var cle1 = a3, op = a2, cle2 = a1, strength = a4, weight = a5;
lc.call(this, this._cloneOrNewCle(cle1), strength, weight);
if (op == c.GEQ) {
this.expression.multiplyMe(-1);
this.expression.addExpression(this._cloneOrNewCle(cle2));
} else if (op == c.LEQ) {
this.expression.addExpression(this._cloneOrNewCle(cle2), -1);
} else {
throw new c.InternalError("Invalid operator in c.Inequality constructor");
}
return this
// cle op cle
} else if (a1IsExp && a3IsExp) {
var cle1 = a1, op = a2, cle2 = a3, strength = a4, weight = a5;
lc.call(this, this._cloneOrNewCle(cle2), strength, weight);
if (op == c.GEQ) {
this.expression.multiplyMe(-1);
this.expression.addExpression(this._cloneOrNewCle(cle1));
} else if (op == c.LEQ) {
this.expression.addExpression(this._cloneOrNewCle(cle1), -1);
} else {
throw new c.InternalError("Invalid operator in c.Inequality constructor");
}
// cle
} else if (a1IsExp) {
return lc.call(this, a1, a2, a3);
// >=
} else if (a2 == c.GEQ) {
lc.call(this, new c.Expression(a3), a4, a5);
this.expression.multiplyMe(-1);
this.expression.addVariable(a1);
// <=
} else if (a2 == c.LEQ) {
lc.call(this, new c.Expression(a3), a4, a5);
this.expression.addVariable(a1,-1);
// error
} else {
throw new c.InternalError("Invalid operator in c.Inequality constructor");
}
},
isInequality: true,
toString: function() {
// return "c.Inequality: " + this.hashCode;
return lc.prototype.toString.call(this) + " >= 0) id: " + this.hashCode;
},
});
c.Equation = c.inherit({
extends: c.Constraint,
initialize: function(a1, a2, a3, a4) {
// FIXME(slightlyoff): this is just a huge mess.
if (a1 instanceof c.Expression && !a2 || a2 instanceof c.Strength) {
lc.call(this, a1, a2, a3);
} else if ((a1 instanceof c.AbstractVariable) &&
(a2 instanceof c.Expression)) {
var cv = a1, cle = a2, strength = a3, weight = a4;
lc.call(this, cle.clone(), strength, weight);
this.expression.addVariable(cv, -1);
} else if ((a1 instanceof c.AbstractVariable) &&
(typeof(a2) == 'number')) {
var cv = a1, val = a2, strength = a3, weight = a4;
lc.call(this, new c.Expression(val), strength, weight);
this.expression.addVariable(cv, -1);
} else if ((a1 instanceof c.Expression) &&
(a2 instanceof c.AbstractVariable)) {
var cle = a1, cv = a2, strength = a3, weight = a4;
lc.call(this, cle.clone(), strength, weight);
this.expression.addVariable(cv, -1);
} else if (((a1 instanceof c.Expression) || (a1 instanceof c.AbstractVariable) ||
(typeof(a1) == 'number')) &&
((a2 instanceof c.Expression) || (a2 instanceof c.AbstractVariable) ||
(typeof(a2) == 'number'))) {
if (a1 instanceof c.Expression) {
a1 = a1.clone();
} else {
a1 = new c.Expression(a1);
}
if (a2 instanceof c.Expression) {
a2 = a2.clone();
} else {
a2 = new c.Expression(a2);
}
lc.call(this, a1, a3, a4);
this.expression.addExpression(a2, -1);
} else {
throw "Bad initializer to c.Equation";
}
c.assert(this.strength instanceof c.Strength, "_strength not set");
},
toString: function() {
return lc.prototype.toString.call(this) + " = 0)";
},
});
})(this["c"]||module.parent.exports||{});
});
require.register("slightlyoff-cassowary.js/src/EditInfo.js", function(exports, require, module){
// Copyright (C) 1998-2000 Greg J. Badros
// Use of this source code is governed by http://www.apache.org/licenses/LICENSE-2.0
//
// Parts Copyright (C) 2011, Alex Russell (slightlyoff@chromium.org)
(function(c) {
"use strict";
c.EditInfo = c.inherit({
initialize: function(cn /*c.Constraint*/,
eplus /*c.SlackVariable*/,
eminus /*c.SlackVariable*/,
prevEditConstant /*double*/,
i /*int*/) {
this.constraint = cn;
this.editPlus = eplus;
this.editMinus = eminus;
this.prevEditConstant = prevEditConstant;
this.index = i;
},
toString: function() {
return "<cn=" + this.constraint +
", ep=" + this.editPlus +
", em=" + this.editMinus +
", pec=" + this.prevEditConstant +
", index=" + this.index + ">";
}
});
})(this["c"]||module.parent.exports||{});
});
require.register("slightlyoff-cassowary.js/src/Tableau.js", function(exports, require, module){
// Copyright (C) 1998-2000 Greg J. Badros
// Use of this source code is governed by http://www.apache.org/licenses/LICENSE-2.0
//
// Parts Copyright (C) 2011, Alex Russell (slightlyoff@chromium.org)
(function(c) {
"use strict";
c.Tableau = c.inherit({
initialize: function() {
// columns is a mapping from variables which occur in expressions to the
// set of basic variables whose expressions contain them
// i.e., it's a mapping from variables in expressions (a column) to the
// set of rows that contain them
this.columns = new c.HashTable(); // values are sets
// _rows maps basic variables to the expressions for that row in the tableau
this.rows = new c.HashTable(); // values are c.Expressions
// the collection of basic variables that have infeasible rows
// (used when reoptimizing)
this._infeasibleRows = new c.HashSet();
// the set of rows where the basic variable is external this was added to
// the C++ version to reduce time in setExternalVariables()
this._externalRows = new c.HashSet();
// the set of external variables which are parametric this was added to the
// C++ version to reduce time in setExternalVariables()
this._externalParametricVars = new c.HashSet();
},
// Variable v has been removed from an Expression. If the Expression is in a
// tableau the corresponding basic variable is subject (or if subject is nil
// then it's in the objective function). Update the column cross-indices.
noteRemovedVariable: function(v /*c.AbstractVariable*/,
subject /*c.AbstractVariable*/) {
c.trace && console.log("c.Tableau::noteRemovedVariable: ", v, subject);
var column = this.columns.get(v);
if (subject && column) {
column.delete(subject);
}
},
noteAddedVariable: function(v /*c.AbstractVariable*/, subject /*c.AbstractVariable*/) {
// if (c.trace) console.log("c.Tableau::noteAddedVariable:", v, subject);
if (subject) {
this.insertColVar(v, subject);
}
},
getInternalInfo: function() {
var retstr = "Tableau Information:\n";
retstr += "Rows: " + this.rows.size;
retstr += " (= " + (this.rows.size - 1) + " constraints)";
retstr += "\nColumns: " + this.columns.size;
retstr += "\nInfeasible Rows: " + this._infeasibleRows.size;
retstr += "\nExternal basic variables: " + this._externalRows.size;
retstr += "\nExternal parametric variables: ";
retstr += this._externalParametricVars.size;
retstr += "\n";
return retstr;
},
toString: function() {
var bstr = "Tableau:\n";
this.rows.each(function(clv, expr) {
bstr += clv;
bstr += " <==> ";
bstr += expr;
bstr += "\n";
});
bstr += "\nColumns:\n";
bstr += this.columns;
bstr += "\nInfeasible rows: ";
bstr += this._infeasibleRows;
bstr += "External basic variables: ";
bstr += this._externalRows;
bstr += "External parametric variables: ";
bstr += this._externalParametricVars;
return bstr;
},
/*
toJSON: function() {
// Creates an object representation of the Tableau.
},
*/
// Convenience function to insert a variable into
// the set of rows stored at columns[param_var],
// creating a new set if needed
insertColVar: function(param_var /*c.Variable*/,
rowvar /*c.Variable*/) {
var rowset = /* Set */ this.columns.get(param_var);
if (!rowset) {
rowset = new c.HashSet();
this.columns.set(param_var, rowset);
}
rowset.add(rowvar);
},
addRow: function(aVar /*c.AbstractVariable*/,
expr /*c.Expression*/) {
if (c.trace) c.fnenterprint("addRow: " + aVar + ", " + expr);
this.rows.set(aVar, expr);
expr.terms.each(function(clv, coeff) {
this.insertColVar(clv, aVar);
if (clv.isExternal) {
this._externalParametricVars.add(clv);
}
}, this);
if (aVar.isExternal) {
this._externalRows.add(aVar);
}
if (c.trace) c.traceprint(this.toString());
},
removeColumn: function(aVar /*c.AbstractVariable*/) {
if (c.trace) c.fnenterprint("removeColumn:" + aVar);
var rows = /* Set */ this.columns.get(aVar);
if (rows) {
this.columns.delete(aVar);
rows.each(function(clv) {
var expr = /* c.Expression */this.rows.get(clv);
expr.terms.delete(aVar);
}, this);
} else {
if (c.trace) console.log("Could not find var", aVar, "in columns");
}
if (aVar.isExternal) {
this._externalRows.delete(aVar);
this._externalParametricVars.delete(aVar);
}
},
removeRow: function(aVar /*c.AbstractVariable*/) {
if (c.trace) c.fnenterprint("removeRow:" + aVar);
var expr = /* c.Expression */this.rows.get(aVar);
c.assert(expr != null);
expr.terms.each(function(clv, coeff) {
var varset = this.columns.get(clv);
if (varset != null) {
if (c.trace) console.log("removing from varset:", aVar);
varset.delete(aVar);
}
}, this);
this._infeasibleRows.delete(aVar);
if (aVar.isExternal) {
this._externalRows.delete(aVar);
}
this.rows.delete(aVar);
if (c.trace) c.fnexitprint("returning " + expr);
return expr;
},
substituteOut: function(oldVar /*c.AbstractVariable*/,
expr /*c.Expression*/) {
if (c.trace) c.fnenterprint("substituteOut:" + oldVar + ", " + expr);
if (c.trace) c.traceprint(this.toString());
var varset = this.columns.get(oldVar);
varset.each(function(v) {
var row = this.rows.get(v);
row.substituteOut(oldVar, expr, v, this);
if (v.isRestricted && row.constant < 0) {
this._infeasibleRows.add(v);
}
}, this);
if (oldVar.isExternal) {
this._externalRows.add(oldVar);
this._externalParametricVars.delete(oldVar);
}
this.columns.delete(oldVar);
},
columnsHasKey: function(subject /*c.AbstractVariable*/) {
return !!this.columns.get(subject);
},
});
})(this["c"]||module.parent.exports||{});
});
require.register("slightlyoff-cassowary.js/src/SimplexSolver.js", function(exports, require, module){
// Copyright (C) 1998-2000 Greg J. Badros
// Use of this source code is governed by http://www.apache.org/licenses/LICENSE-2.0
//
// Parts Copyright (C) 2011, Alex Russell (slightlyoff@chromium.org)
(function(c) {
var t = c.Tableau;
var tp = t.prototype;
var epsilon = 1e-8;
var weak = c.Strength.weak;
c.SimplexSolver = c.inherit({
extends: c.Tableau,
initialize: function(){
c.Tableau.call(this);
this._stayMinusErrorVars = [];
this._stayPlusErrorVars = [];
this._errorVars = new c.HashTable(); // cn -> Set of cv
this._markerVars = new c.HashTable(); // cn -> Set of cv
// this._resolve_pair = [0, 0];
this._objective = new c.ObjectiveVariable({ name: "Z" });
this._editVarMap = new c.HashTable(); // cv -> c.EditInfo
this._editVarList = [];
this._slackCounter = 0;
this._artificialCounter = 0;
this._dummyCounter = 0;
this.autoSolve = true;
this._needsSolving = false;
this._optimizeCount = 0;
this.rows.set(this._objective, c.Expression.empty());
this._editVariableStack = [0]; // Stack
if (c.trace)
c.traceprint("objective expr == " + this.rows.get(this._objective));
},
add: function(/*c.Constraint, ...*/) {
for (var x = 0; x < arguments.length; x++) {
this.addConstraint(arguments[x]);
}
return this;
},
_addEditConstraint: function(cn, eplus_eminus, prevEConstant) {
var i = this._editVarMap.size;
var cvEplus = /* c.SlackVariable */eplus_eminus[0];
var cvEminus = /* c.SlackVariable */eplus_eminus[1];
/*
if (!cvEplus instanceof c.SlackVariable) {
console.warn("cvEplus not a slack variable =", cvEplus);
}
if (!cvEminus instanceof c.SlackVariable) {
console.warn("cvEminus not a slack variable =", cvEminus);
}
c.debug && console.log("new c.EditInfo(" + cn + ", " + cvEplus + ", " +
cvEminus + ", " + prevEConstant + ", " +
i +")");
*/
var ei = new c.EditInfo(cn, cvEplus, cvEminus, prevEConstant, i)
this._editVarMap.set(cn.variable, ei);
this._editVarList[i] = { v: cn.variable, info: ei };
},
addConstraint: function(cn /*c.Constraint*/) {
c.trace && c.fnenterprint("addConstraint: " + cn);
var eplus_eminus = new Array(2);
var prevEConstant = new Array(1); // so it can be output to
var expr = this.newExpression(cn, /*output to*/ eplus_eminus, prevEConstant);
prevEConstant = prevEConstant[0];
if (!this.tryAddingDirectly(expr)) {
this.addWithArtificialVariable(expr);
}
this._needsSolving = true;
if (cn.isEditConstraint) {
this._addEditConstraint(cn, eplus_eminus, prevEConstant);
}
if (this.autoSolve) {
this.optimize(this._objective);
this._setExternalVariables();
}
return this;
},
addConstraintNoException: function(cn /*c.Constraint*/) {
c.trace && c.fnenterprint("addConstraintNoException: " + cn);
// FIXME(slightlyoff): change this to enable chaining
try {
this.addConstraint(cn);
return true;
} catch (e /*c.RequiredFailure*/){
return false;
}
},
addEditVar: function(v /*c.Variable*/, strength /*c.Strength*/, weight /*double*/) {
c.trace && c.fnenterprint("addEditVar: " + v + " @ " + strength + " {" + weight + "}");
return this.addConstraint(
new c.EditConstraint(v, strength || c.Strength.strong, weight));
},
beginEdit: function() {
// FIXME(slightlyoff): we shouldn't throw here. Log instead
c.assert(this._editVarMap.size > 0, "_editVarMap.size > 0");
this._infeasibleRows.clear();
this._resetStayConstants();
this._editVariableStack[this._editVariableStack.length] = this._editVarMap.size;
return this;
},
endEdit: function() {
// FIXME(slightlyoff): we shouldn't throw here. Log instead
c.assert(this._editVarMap.size > 0, "_editVarMap.size > 0");
this.resolve();
this._editVariableStack.pop();
this.removeEditVarsTo(
this._editVariableStack[this._editVariableStack.length - 1]
);
return this;
},
removeAllEditVars: function() {
return this.removeEditVarsTo(0);
},
removeEditVarsTo: function(n /*int*/) {
try {
var evll = this._editVarList.length;
// only remove the variable if it's not in the set of variable
// from a previous nested outer edit
// e.g., if I do:
// Edit x,y
// Edit w,h,x,y
// EndEdit
// The end edit needs to only get rid of the edits on w,h
// not the ones on x,y
for(var x = n; x < evll; x++) {
if (this._editVarList[x]) {
this.removeConstraint(
this._editVarMap.get(this._editVarList[x].v).constraint
);
}
}
this._editVarList.length = n;
c.assert(this._editVarMap.size == n, "_editVarMap.size == n");
return this;
} catch (e /*ConstraintNotFound*/){
throw new c.InternalError("Constraint not found in removeEditVarsTo");
}
},
// Add weak stays to the x and y parts of each point. These have
// increasing weights so that the solver will try to satisfy the x
// and y stays on the same point, rather than the x stay on one and
// the y stay on another.
addPointStays: function(points /*[{ x: .., y: ..}, ...]*/) {
c.trace && console.log("addPointStays", points);
points.forEach(function(p, idx) {
this.addStay(p.x, weak, Math.pow(2, idx));
this.addStay(p.y, weak, Math.pow(2, idx));
}, this);
return this;
},
addStay: function(v /*c.Variable*/, strength /*c.Strength*/, weight /*double*/) {
var cn = new c.StayConstraint(v,
strength || weak,
weight || 1);
return this.addConstraint(cn);
},
// FIXME(slightlyoff): add a removeStay
removeConstraint: function(cn /*c.Constraint*/) {
// console.log("removeConstraint('", cn, "')");
c.trace && c.fnenterprint("removeConstraintInternal: " + cn);
c.trace && c.traceprint(this.toString());
this._needsSolving = true;
this._resetStayConstants();
var zRow = this.rows.get(this._objective);
var eVars = /* Set */this._errorVars.get(cn);
c.trace && c.traceprint("eVars == " + eVars);
if (eVars != null) {
eVars.each(function(cv) {
var expr = this.rows.get(cv);
if (expr == null) {
zRow.addVariable(cv,
-cn.weight * cn.strength.symbolicWeight.value,
this._objective,
this);
} else {
zRow.addExpression(expr,
-cn.weight * cn.strength.symbolicWeight.value,
this._objective,
this);
}
c.trace && c.traceprint("now eVars == " + eVars);
}, this);
}
var marker = this._markerVars.get(cn);
this._markerVars.delete(cn);
if (marker == null) {
throw new c.InternalError("Constraint not found in removeConstraintInternal");
}
c.trace && c.traceprint("Looking to remove var " + marker);
if (this.rows.get(marker) == null) {
var col = this.columns.get(marker);
// console.log("col is:", col, "from marker:", marker);
c.trace && c.traceprint("Must pivot -- columns are " + col);
var exitVar = null;
var minRatio = 0;
col.each(function(v) {
if (v.isRestricted) {
var expr = this.rows.get(v);
var coeff = expr.coefficientFor(marker);
c.trace && c.traceprint("Marker " + marker + "'s coefficient in " + expr + " is " + coeff);
if (coeff < 0) {
var r = -expr.constant / coeff;
if (
exitVar == null ||
r < minRatio ||
(c.approx(r, minRatio) && v.hashCode < exitVar.hashCode)
) {
minRatio = r;
exitVar = v;
}
}
}
}, this);
if (exitVar == null) {
c.trace && c.traceprint("exitVar is still null");
col.each(function(v) {
if (v.isRestricted) {
var expr = this.rows.get(v);
var coeff = expr.coefficientFor(marker);
var r = expr.constant / coeff;
if (exitVar == null || r < minRatio) {
minRatio = r;
exitVar = v;
}
}
}, this);
}
if (exitVar == null) {
if (col.size == 0) {
this.removeColumn(marker);
} else {
col.escapingEach(function(v) {
if (v != this._objective) {
exitVar = v;
return { brk: true };
}
}, this);
}
}
if (exitVar != null) {
this.pivot(marker, exitVar);
}
}
if (this.rows.get(marker) != null) {
var expr = this.removeRow(marker);
}
if (eVars != null) {
eVars.each(function(v) {
if (v != marker) { this.removeColumn(v); }
}, this);
}
if (cn.isStayConstraint) {
if (eVars != null) {
for (var i = 0; i < this._stayPlusErrorVars.length; i++) {
eVars.delete(this._stayPlusErrorVars[i]);
eVars.delete(this._stayMinusErrorVars[i]);
}
}
} else if (cn.isEditConstraint) {
c.assert(eVars != null, "eVars != null");
var cei = this._editVarMap.get(cn.variable);
this.removeColumn(cei.editMinus);
this._editVarMap.delete(cn.variable);
}
if (eVars != null) {
this._errorVars.delete(eVars);
}
if (this.autoSolve) {
this.optimize(this._objective);
this._setExternalVariables();
}
return this;
},
reset: function() {
c.trace && c.fnenterprint("reset");
throw new c.InternalError("reset not implemented");
},
resolveArray: function(newEditConstants) {
c.trace && c.fnenterprint("resolveArray" + newEditConstants);
var l = newEditConstants.length
this._editVarMap.each(function(v, cei) {
var i = cei.index;
if (i < l)
this.suggestValue(v, newEditConstants[i]);
}, this);
this.resolve();
},
resolvePair: function(x /*double*/, y /*double*/) {
this.suggestValue(this._editVarList[0].v, x);
this.suggestValue(this._editVarList[1].v, y);
this.resolve();
},
resolve: function() {
c.trace && c.fnenterprint("resolve()");
this.dualOptimize();
this._setExternalVariables();
this._infeasibleRows.clear();
this._resetStayConstants();
},
suggestValue: function(v /*c.Variable*/, x /*double*/) {
c.trace && console.log("suggestValue(" + v + ", " + x + ")");
var cei = this._editVarMap.get(v);
if (!cei) {
throw new c.Error("suggestValue for variable " + v + ", but var is not an edit variable");
}
var delta = x - cei.prevEditConstant;
cei.prevEditConstant = x;
this.deltaEditConstant(delta, cei.editPlus, cei.editMinus);
return this;
},
solve: function() {
if (this._needsSolving) {
this.optimize(this._objective);
this._setExternalVariables();
}
return this;
},
setEditedValue: function(v /*c.Variable*/, n /*double*/) {
if (!(this.columnsHasKey(v) || (this.rows.get(v) != null))) {
v.value = n;
return this;
}
if (!c.approx(n, v.value)) {
this.addEditVar(v);
this.beginEdit();
try {
this.suggestValue(v, n);
} catch (e) {
throw new c.InternalError("Error in setEditedValue");
}
this.endEdit();
}
return this;
},
addVar: function(v /*c.Variable*/) {
if (!(this.columnsHasKey(v) || (this.rows.get(v) != null))) {
try {
this.addStay(v);
} catch (e /*c.RequiredFailure*/){
throw new c.InternalError("Error in addVar -- required failure is impossible");
}
c.trace && c.traceprint("added initial stay on " + v);
}
return this;
},
getInternalInfo: function() {
var retstr = tp.getInternalInfo.call(this);
retstr += "\nSolver info:\n";
retstr += "Stay Error Variables: ";
retstr += this._stayPlusErrorVars.length + this._stayMinusErrorVars.length;
retstr += " (" + this._stayPlusErrorVars.length + " +, ";
retstr += this._stayMinusErrorVars.length + " -)\n";
retstr += "Edit Variables: " + this._editVarMap.size;
retstr += "\n";
return retstr;
},
getDebugInfo: function() {
return this.toString() + this.getInternalInfo() + "\n";
},
toString: function() {
var bstr = tp.getInternalInfo.call(this);
bstr += "\n_stayPlusErrorVars: ";
bstr += '[' + this._stayPlusErrorVars + ']';
bstr += "\n_stayMinusErrorVars: ";
bstr += '[' + this._stayMinusErrorVars + ']';
bstr += "\n";
bstr += "_editVarMap:\n" + this._editVarMap;
bstr += "\n";
return bstr;
},
addWithArtificialVariable: function(expr /*c.Expression*/) {
c.trace && c.fnenterprint("addWithArtificialVariable: " + expr);
var av = new c.SlackVariable({
value: ++this._artificialCounter,
prefix: "a"
});
var az = new c.ObjectiveVariable({ name: "az" });
var azRow = /* c.Expression */expr.clone();
c.trace && c.traceprint("before addRows:\n" + this);
this.addRow(az, azRow);
this.addRow(av, expr);
c.trace && c.traceprint("after addRows:\n" + this);
this.optimize(az);
var azTableauRow = this.rows.get(az);
c.trace && c.traceprint("azTableauRow.constant == " + azTableauRow.constant);
if (!c.approx(azTableauRow.constant, 0)) {
this.removeRow(az);
this.removeColumn(av);
throw new c.RequiredFailure();
}
var e = this.rows.get(av);
if (e != null) {
if (e.isConstant) {
this.removeRow(av);
this.removeRow(az);
return;
}
var entryVar = e.anyPivotableVariable();
this.pivot(entryVar, av);
}
c.assert(this.rows.get(av) == null, "rowExpression(av) == null");
this.removeColumn(av);
this.removeRow(az);
},
tryAddingDirectly: function(expr /*c.Expression*/) {
c.trace && c.fnenterprint("tryAddingDirectly: " + expr);
var subject = this.chooseSubject(expr);
if (subject == null) {
c.trace && c.fnexitprint("returning false");
return false;
}
expr.newSubject(subject);
if (this.columnsHasKey(subject)) {
this.substituteOut(subject, expr);
}
this.addRow(subject, expr);
c.trace && c.fnexitprint("returning true");
return true;
},
chooseSubject: function(expr /*c.Expression*/) {
c.trace && c.fnenterprint("chooseSubject: " + expr);
var subject = null;
var foundUnrestricted = false;
var foundNewRestricted = false;
var terms = expr.terms;
var rv = terms.escapingEach(function(v, c) {
if (foundUnrestricted) {
if (!v.isRestricted) {
if (!this.columnsHasKey(v)) {
return { retval: v };
}
}
} else {
if (v.isRestricted) {
if (!foundNewRestricted && !v.isDummy && c < 0) {
var col = this.columns.get(v);
if (col == null ||
(col.size == 1 && this.columnsHasKey(this._objective))
) {
subject = v;
foundNewRestricted = true;
}
}
} else {
subject = v;
foundUnrestricted = true;
}
}
}, this);
if (rv && rv.retval !== undefined) {
return rv.retval;
}
if (subject != null) {
return subject;
}
var coeff = 0;
// subject is nil.
// Make one last check -- if all of the variables in expr are dummy
// variables, then we can pick a dummy variable as the subject
var rv = terms.escapingEach(function(v,c) {
if (!v.isDummy) {
return {retval:null};
}
if (!this.columnsHasKey(v)) {
subject = v;
coeff = c;
}
}, this);
if (rv && rv.retval !== undefined) return rv.retval;
if (!c.approx(expr.constant, 0)) {
throw new c.RequiredFailure();
}
if (coeff > 0) {
expr.multiplyMe(-1);
}
return subject;
},
deltaEditConstant: function(delta /*double*/,
plusErrorVar /*c.AbstractVariable*/,
minusErrorVar /*c.AbstractVariable*/) {
if (c.trace)
c.fnenterprint("deltaEditConstant :" + delta + ", " + plusErrorVar + ", " + minusErrorVar);
var exprPlus = this.rows.get(plusErrorVar);
if (exprPlus != null) {
exprPlus.constant += delta;
if (exprPlus.constant < 0) {
this._infeasibleRows.add(plusErrorVar);
}
return;
}
var exprMinus = this.rows.get(minusErrorVar);
if (exprMinus != null) {
exprMinus.constant += -delta;
if (exprMinus.constant < 0) {
this._infeasibleRows.add(minusErrorVar);
}
return;
}
var columnVars = this.columns.get(minusErrorVar);
if (!columnVars) {
console.log("columnVars is null -- tableau is:\n" + this);
}
columnVars.each(function(basicVar) {
var expr = this.rows.get(basicVar);
var c = expr.coefficientFor(minusErrorVar);
expr.constant += (c * delta);
if (basicVar.isRestricted && expr.constant < 0) {
this._infeasibleRows.add(basicVar);
}
}, this);
},
// We have set new values for the constants in the edit constraints.
// Re-Optimize using the dual simplex algorithm.
dualOptimize: function() {
c.trace && c.fnenterprint("dualOptimize:");
var zRow = this.rows.get(this._objective);
// need to handle infeasible rows
while (this._infeasibleRows.size) {
var exitVar = this._infeasibleRows.values()[0];
this._infeasibleRows.delete(exitVar);
var entryVar = null;
var expr = this.rows.get(exitVar);
// exitVar might have become basic after some other pivoting
// so allow for the case of its not being there any longer
if (expr) {
if (expr.constant < 0) {
var ratio = Number.MAX_VALUE;
var r;
var terms = expr.terms;
terms.each(function(v, cd) {
if (cd > 0 && v.isPivotable) {
var zc = zRow.coefficientFor(v);
r = zc / cd;
if (r < ratio ||
(c.approx(r, ratio) && v.hashCode < entryVar.hashCode)
) {
entryVar = v;
ratio = r;
}
}
});
if (ratio == Number.MAX_VALUE) {
throw new c.InternalError("ratio == nil (MAX_VALUE) in dualOptimize");
}
this.pivot(entryVar, exitVar);
}
}
}
},
// Make a new linear Expression representing the constraint cn,
// replacing any basic variables with their defining expressions.
// Normalize if necessary so that the Constant is non-negative. If
// the constraint is non-required give its error variables an
// appropriate weight in the objective function.
newExpression: function(cn /*c.Constraint*/,
/** outputs to **/ eplus_eminus /*Array*/,
prevEConstant) {
if (c.trace) {
c.fnenterprint("newExpression: " + cn);
c.traceprint("cn.isInequality == " + cn.isInequality);
c.traceprint("cn.required == " + cn.required);
}
var cnExpr = cn.expression;
var expr = c.Expression.fromConstant(cnExpr.constant);
var slackVar = new c.SlackVariable();
var dummyVar = new c.DummyVariable();
var eminus = new c.SlackVariable();
var eplus = new c.SlackVariable();
var cnTerms = cnExpr.terms;
// console.log(cnTerms.size);
cnTerms.each(function(v, c) {
var e = this.rows.get(v);
if (!e) {
expr.addVariable(v, c);
} else {
expr.addExpression(e, c);
}
}, this);
if (cn.isInequality) {
// cn is an inequality, so Add a slack variable. The original constraint
// is expr>=0, so that the resulting equality is expr-slackVar=0. If cn is
// also non-required Add a negative error variable, giving:
//
// expr - slackVar = -errorVar
//
// in other words:
//
// expr - slackVar + errorVar = 0
//
// Since both of these variables are newly created we can just Add
// them to the Expression (they can't be basic).
c.trace && c.traceprint("Inequality, adding slack");
++this._slackCounter;
slackVar = new c.SlackVariable({
value: this._slackCounter,
prefix: "s"
});
expr.setVariable(slackVar, -1);
this._markerVars.set(cn, slackVar);
if (!cn.required) {
++this._slackCounter;
eminus = new c.SlackVariable({
value: this._slackCounter,
prefix: "em"
});
expr.setVariable(eminus, 1);
var zRow = this.rows.get(this._objective);
zRow.setVariable(eminus, cn.strength.symbolicWeight.value * cn.weight);
this.insertErrorVar(cn, eminus);
this.noteAddedVariable(eminus, this._objective);
}
} else {
if (cn.required) {
c.trace && c.traceprint("Equality, required");
// Add a dummy variable to the Expression to serve as a marker for this
// constraint. The dummy variable is never allowed to enter the basis
// when pivoting.
++this._dummyCounter;
dummyVar = new c.DummyVariable({
value: this._dummyCounter,
prefix: "d"
});
eplus_eminus[0] = dummyVar;
eplus_eminus[1] = dummyVar;
prevEConstant[0] = cnExpr.constant;
expr.setVariable(dummyVar, 1);
this._markerVars.set(cn, dummyVar);
c.trace && c.traceprint("Adding dummyVar == d" + this._dummyCounter);
} else {
// cn is a non-required equality. Add a positive and a negative error
// variable, making the resulting constraint
// expr = eplus - eminus
// in other words:
// expr - eplus + eminus = 0
c.trace && c.traceprint("Equality, not required");
++this._slackCounter;
eplus = new c.SlackVariable({
value: this._slackCounter,
prefix: "ep"
});
eminus = new c.SlackVariable({
value: this._slackCounter,
prefix: "em"
});
expr.setVariable(eplus, -1);
expr.setVariable(eminus, 1);
this._markerVars.set(cn, eplus);
var zRow = this.rows.get(this._objective);
c.trace && console.log(zRow);
var swCoeff = cn.strength.symbolicWeight.value * cn.weight;
if (swCoeff == 0) {
c.trace && c.traceprint("cn == " + cn);
c.trace && c.traceprint("adding " + eplus + " and " + eminus + " with swCoeff == " + swCoeff);
}
zRow.setVariable(eplus, swCoeff);
this.noteAddedVariable(eplus, this._objective);
zRow.setVariable(eminus, swCoeff);
this.noteAddedVariable(eminus, this._objective);
this.insertErrorVar(cn, eminus);
this.insertErrorVar(cn, eplus);
if (cn.isStayConstraint) {
this._stayPlusErrorVars[this._stayPlusErrorVars.length] = eplus;
this._stayMinusErrorVars[this._stayMinusErrorVars.length] = eminus;
} else if (cn.isEditConstraint) {
eplus_eminus[0] = eplus;
eplus_eminus[1] = eminus;
prevEConstant[0] = cnExpr.constant;
}
}
}
// the Constant in the Expression should be non-negative. If necessary
// normalize the Expression by multiplying by -1
if (expr.constant < 0) expr.multiplyMe(-1);
c.trace && c.fnexitprint("returning " + expr);
return expr;
},
// Minimize the value of the objective. (The tableau should already be
// feasible.)
optimize: function(zVar /*c.ObjectiveVariable*/) {
c.trace && c.fnenterprint("optimize: " + zVar);
c.trace && c.traceprint(this.toString());
this._optimizeCount++;
var zRow = this.rows.get(zVar);
c.assert(zRow != null, "zRow != null");
var entryVar = null;
var exitVar = null;
var objectiveCoeff, terms;
while (true) {
objectiveCoeff = 0;
terms = zRow.terms;
// Find the most negative coefficient in the objective function (ignoring
// the non-pivotable dummy variables). If all coefficients are positive
// we're done
terms.escapingEach(function(v, c) {
if (v.isPivotable && c < objectiveCoeff) {
objectiveCoeff = c;
entryVar = v;
// Break on success
return { brk: 1 };
}
}, this);
if (objectiveCoeff >= -epsilon)
return;
c.trace && console.log("entryVar:", entryVar,
"objectiveCoeff:", objectiveCoeff);
// choose which variable to move out of the basis
// Only consider pivotable basic variables
// (i.e. restricted, non-dummy variables)
var minRatio = Number.MAX_VALUE;
var columnVars = this.columns.get(entryVar);
var r = 0;
columnVars.each(function(v) {
c.trace && c.traceprint("Checking " + v);
if (v.isPivotable) {
var expr = this.rows.get(v);
var coeff = expr.coefficientFor(entryVar);
c.trace && c.traceprint("pivotable, coeff = " + coeff);
// only consider negative coefficients
if (coeff < 0) {
r = -expr.constant / coeff;
// Bland's anti-cycling rule:
// if multiple variables are about the same,
// always pick the lowest via some total
// ordering -- I use their addresses in memory
// if (r < minRatio ||
// (c.approx(r, minRatio) &&
// v.get_pclv() < exitVar.get_pclv()))
if (r < minRatio ||
(c.approx(r, minRatio) &&
v.hashCode < exitVar.hashCode)
) {
minRatio = r;
exitVar = v;
}
}
}
}, this);
// If minRatio is still nil at this point, it means that the
// objective function is unbounded, i.e. it can become
// arbitrarily negative. This should never happen in this
// application.
if (minRatio == Number.MAX_VALUE) {
throw new c.InternalError("Objective function is unbounded in optimize");
}
// console.time("SimplexSolver::optimize pivot()");
this.pivot(entryVar, exitVar);
// console.timeEnd("SimplexSolver::optimize pivot()");
c.trace && c.traceprint(this.toString());
}
},
// Do a Pivot. Move entryVar into the basis (i.e. make it a basic variable),
// and move exitVar out of the basis (i.e., make it a parametric variable)
pivot: function(entryVar /*c.AbstractVariable*/, exitVar /*c.AbstractVariable*/) {
c.trace && console.log("pivot: ", entryVar, exitVar);
var time = false;
time && console.time(" SimplexSolver::pivot");
// the entryVar might be non-pivotable if we're doing a RemoveConstraint --
// otherwise it should be a pivotable variable -- enforced at call sites,
// hopefully
if (entryVar == null) {
console.warn("pivot: entryVar == null");
}
if (exitVar == null) {
console.warn("pivot: exitVar == null");
}
// console.log("SimplexSolver::pivot(", entryVar, exitVar, ")")
// expr is the Expression for the exit variable (about to leave the basis) --
// so that the old tableau includes the equation:
// exitVar = expr
time && console.time(" removeRow");
var expr = this.removeRow(exitVar);
time && console.timeEnd(" removeRow");
// Compute an Expression for the entry variable. Since expr has
// been deleted from the tableau we can destructively modify it to
// build this Expression.
time && console.time(" changeSubject");
expr.changeSubject(exitVar, entryVar);
time && console.timeEnd(" changeSubject");
time && console.time(" substituteOut");
this.substituteOut(entryVar, expr);
time && console.timeEnd(" substituteOut");
/*
if (entryVar.isExternal) {
// entry var is no longer a parametric variable since we're moving
// it into the basis
console.log("entryVar is external!");
this._externalParametricVars.delete(entryVar);
}
*/
time && console.time(" addRow")
this.addRow(entryVar, expr);
time && console.timeEnd(" addRow")
time && console.timeEnd(" SimplexSolver::pivot");
},
// Each of the non-required stays will be represented by an equation
// of the form
// v = c + eplus - eminus
// where v is the variable with the stay, c is the previous value of
// v, and eplus and eminus are slack variables that hold the error
// in satisfying the stay constraint. We are about to change
// something, and we want to fix the constants in the equations
// representing the stays. If both eplus and eminus are nonbasic
// they have value 0 in the current solution, meaning the previous
// stay was exactly satisfied. In this case nothing needs to be
// changed. Otherwise one of them is basic, and the other must
// occur only in the Expression for that basic error variable.
// Reset the Constant in this Expression to 0.
_resetStayConstants: function() {
c.trace && console.log("_resetStayConstants");
var spev = this._stayPlusErrorVars;
var l = spev.length;
for (var i = 0; i < l; i++) {
var expr = this.rows.get(spev[i]);
if (expr === null) {
expr = this.rows.get(this._stayMinusErrorVars[i]);
}
if (expr != null) {
expr.constant = 0;
}
}
},
_setExternalVariables: function() {
c.trace && c.fnenterprint("_setExternalVariables:");
c.trace && c.traceprint(this.toString());
var changed = {};
// console.log("this._externalParametricVars:", this._externalParametricVars);
this._externalParametricVars.each(function(v) {
if (this.rows.get(v) != null) {
if (c.trace)
console.log("Error: variable" + v + " in _externalParametricVars is basic");
} else {
v.value = 0;
changed[v.name] = 0;
}
}, this);
// console.log("this._externalRows:", this._externalRows);
this._externalRows.each(function(v) {
var expr = this.rows.get(v);
if (v.value != expr.constant) {
// console.log(v.toString(), v.value, expr.constant);
v.value = expr.constant;
changed[v.name] = expr.constant;
}
// c.trace && console.log("v == " + v);
// c.trace && console.log("expr == " + expr);
}, this);
this._changed = changed;
this._needsSolving = false;
this._informCallbacks();
this.onsolved();
},
onsolved: function() {
// Lifecycle stub. Here for dirty, dirty monkey patching.
},
_informCallbacks: function() {
if(!this._callbacks) return;
var changed = this._changed;
this._callbacks.forEach(function(fn) {
fn(changed);
});
},
_addCallback: function(fn) {
var a = (this._callbacks || (this._callbacks = []));
a[a.length] = fn;
},
insertErrorVar: function(cn /*c.Constraint*/, aVar /*c.AbstractVariable*/) {
c.trace && c.fnenterprint("insertErrorVar:" + cn + ", " + aVar);
var constraintSet = /* Set */this._errorVars.get(aVar);
if (!constraintSet) {
constraintSet = new c.HashSet();
this._errorVars.set(cn, constraintSet);
}
constraintSet.add(aVar);
},
});
})(this["c"]||module.parent.exports||{});
});
require.register("slightlyoff-cassowary.js/src/Timer.js", function(exports, require, module){
// Copyright (C) 1998-2000 Greg J. Badros
// Use of this source code is governed by http://www.apache.org/licenses/LICENSE-2.0
//
// Parts Copyright (C) 2011, Alex Russell (slightlyoff@chromium.org)
(function(c) {
"use strict";
c.Timer = c.inherit({
initialize: function() {
this.isRunning = false;
this._elapsedMs = 0;
},
start: function() {
this.isRunning = true;
this._startReading = new Date();
return this;
},
stop: function() {
this.isRunning = false;
this._elapsedMs += (new Date()) - this._startReading;
return this;
},
reset: function() {
this.isRunning = false;
this._elapsedMs = 0;
return this;
},
elapsedTime : function() {
if (!this.isRunning) {
return this._elapsedMs / 1000;
} else {
return (this._elapsedMs + (new Date() - this._startReading)) / 1000;
}
},
});
})(this["c"]||module.parent.exports||{});
});
require.register("slightlyoff-cassowary.js/src/parser/parser.js", function(exports, require, module){
this.c.parser = (function(){
/*
* Generated by PEG.js 0.7.0.
*
* http://pegjs.majda.cz/
*/
function quote(s) {
/*
* ECMA-262, 5th ed., 7.8.4: All characters may appear literally in a
* string literal except for the closing quote character, backslash,
* carriage return, line separator, paragraph separator, and line feed.
* Any character may appear in the form of an escape sequence.
*
* For portability, we also escape escape all control and non-ASCII
* characters. Note that "\0" and "\v" escape sequences are not used
* because JSHint does not like the first and IE the second.
*/
return '"' + s
.replace(/\\/g, '\\\\') // backslash
.replace(/"/g, '\\"') // closing quote character
.replace(/\x08/g, '\\b') // backspace
.replace(/\t/g, '\\t') // horizontal tab
.replace(/\n/g, '\\n') // line feed
.replace(/\f/g, '\\f') // form feed
.replace(/\r/g, '\\r') // carriage return
.replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g, escape)
+ '"';
}
var result = {
/*
* Parses the input with a generated parser. If the parsing is successfull,
* returns a value explicitly or implicitly specified by the grammar from
* which the parser was generated (see |PEG.buildParser|). If the parsing is
* unsuccessful, throws |PEG.parser.SyntaxError| describing the error.
*/
parse: function(input, startRule) {
var parseFunctions = {
"start": parse_start,
"Statement": parse_Statement,
"SourceCharacter": parse_SourceCharacter,
"IdentifierStart": parse_IdentifierStart,
"WhiteSpace": parse_WhiteSpace,
"LineTerminator": parse_LineTerminator,
"LineTerminatorSequence": parse_LineTerminatorSequence,
"EOS": parse_EOS,
"EOF": parse_EOF,
"Comment": parse_Comment,
"MultiLineComment": parse_MultiLineComment,
"MultiLineCommentNoLineTerminator": parse_MultiLineCommentNoLineTerminator,
"SingleLineComment": parse_SingleLineComment,
"_": parse__,
"__": parse___,
"Literal": parse_Literal,
"Integer": parse_Integer,
"Real": parse_Real,
"SignedInteger": parse_SignedInteger,
"Identifier": parse_Identifier,
"IdentifierName": parse_IdentifierName,
"PrimaryExpression": parse_PrimaryExpression,
"UnaryExpression": parse_UnaryExpression,
"UnaryOperator": parse_UnaryOperator,
"MultiplicativeExpression": parse_MultiplicativeExpression,
"MultiplicativeOperator": parse_MultiplicativeOperator,
"AdditiveExpression": parse_AdditiveExpression,
"AdditiveOperator": parse_AdditiveOperator,
"InequalityExpression": parse_InequalityExpression,
"InequalityOperator": parse_InequalityOperator,
"LinearExpression": parse_LinearExpression
};
if (startRule !== undefined) {
if (parseFunctions[startRule] === undefined) {
throw new Error("Invalid rule name: " + quote(startRule) + ".");
}
} else {
startRule = "start";
}
var pos = 0;
var reportFailures = 0;
var rightmostFailuresPos = 0;
var rightmostFailuresExpected = [];
function padLeft(input, padding, length) {
var result = input;
var padLength = length - input.length;
for (var i = 0; i < padLength; i++) {
result = padding + result;
}
return result;
}
function escape(ch) {
var charCode = ch.charCodeAt(0);
var escapeChar;
var length;
if (charCode <= 0xFF) {
escapeChar = 'x';
length = 2;
} else {
escapeChar = 'u';
length = 4;
}
return '\\' + escapeChar + padLeft(charCode.toString(16).toUpperCase(), '0', length);
}
function matchFailed(failure) {
if (pos < rightmostFailuresPos) {
return;
}
if (pos > rightmostFailuresPos) {
rightmostFailuresPos = pos;
rightmostFailuresExpected = [];
}
rightmostFailuresExpected.push(failure);
}
function parse_start() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse___();
if (result0 !== null) {
result1 = [];
result2 = parse_Statement();
while (result2 !== null) {
result1.push(result2);
result2 = parse_Statement();
}
if (result1 !== null) {
result2 = parse___();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, statements) { return statements; })(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Statement() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_LinearExpression();
if (result0 !== null) {
result1 = parse_EOS();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, expression) { return expression; })(pos0, result0[0]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_SourceCharacter() {
var result0;
if (input.length > pos) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("any character");
}
}
return result0;
}
function parse_IdentifierStart() {
var result0;
if (/^[a-zA-Z]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z]");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 36) {
result0 = "$";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 95) {
result0 = "_";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
}
}
return result0;
}
function parse_WhiteSpace() {
var result0;
reportFailures++;
if (/^[\t\x0B\f \xA0\uFEFF]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\t\\x0B\\f \\xA0\\uFEFF]");
}
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("whitespace");
}
return result0;
}
function parse_LineTerminator() {
var result0;
if (/^[\n\r\u2028\u2029]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\n\\r\\u2028\\u2029]");
}
}
return result0;
}
function parse_LineTerminatorSequence() {
var result0;
reportFailures++;
if (input.charCodeAt(pos) === 10) {
result0 = "\n";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\n\"");
}
}
if (result0 === null) {
if (input.substr(pos, 2) === "\r\n") {
result0 = "\r\n";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\r\\n\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 13) {
result0 = "\r";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\r\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 8232) {
result0 = "\u2028";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\u2028\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 8233) {
result0 = "\u2029";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\u2029\"");
}
}
}
}
}
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("end of line");
}
return result0;
}
function parse_EOS() {
var result0, result1;
var pos0;
pos0 = pos;
result0 = parse___();
if (result0 !== null) {
if (input.charCodeAt(pos) === 59) {
result1 = ";";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
result0 = parse__();
if (result0 !== null) {
result1 = parse_LineTerminatorSequence();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
result0 = parse___();
if (result0 !== null) {
result1 = parse_EOF();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
}
}
return result0;
}
function parse_EOF() {
var result0;
var pos0;
pos0 = pos;
reportFailures++;
if (input.length > pos) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("any character");
}
}
reportFailures--;
if (result0 === null) {
result0 = "";
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Comment() {
var result0;
reportFailures++;
result0 = parse_MultiLineComment();
if (result0 === null) {
result0 = parse_SingleLineComment();
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("comment");
}
return result0;
}
function parse_MultiLineComment() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
if (input.substr(pos, 2) === "/*") {
result0 = "/*";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/*\"");
}
}
if (result0 !== null) {
result1 = [];
pos1 = pos;
pos2 = pos;
reportFailures++;
if (input.substr(pos, 2) === "*/") {
result2 = "*/";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"*/\"");
}
}
reportFailures--;
if (result2 === null) {
result2 = "";
} else {
result2 = null;
pos = pos2;
}
if (result2 !== null) {
result3 = parse_SourceCharacter();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
pos2 = pos;
reportFailures++;
if (input.substr(pos, 2) === "*/") {
result2 = "*/";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"*/\"");
}
}
reportFailures--;
if (result2 === null) {
result2 = "";
} else {
result2 = null;
pos = pos2;
}
if (result2 !== null) {
result3 = parse_SourceCharacter();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
if (input.substr(pos, 2) === "*/") {
result2 = "*/";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"*/\"");
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_MultiLineCommentNoLineTerminator() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
if (input.substr(pos, 2) === "/*") {
result0 = "/*";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/*\"");
}
}
if (result0 !== null) {
result1 = [];
pos1 = pos;
pos2 = pos;
reportFailures++;
if (input.substr(pos, 2) === "*/") {
result2 = "*/";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"*/\"");
}
}
if (result2 === null) {
result2 = parse_LineTerminator();
}
reportFailures--;
if (result2 === null) {
result2 = "";
} else {
result2 = null;
pos = pos2;
}
if (result2 !== null) {
result3 = parse_SourceCharacter();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
pos2 = pos;
reportFailures++;
if (input.substr(pos, 2) === "*/") {
result2 = "*/";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"*/\"");
}
}
if (result2 === null) {
result2 = parse_LineTerminator();
}
reportFailures--;
if (result2 === null) {
result2 = "";
} else {
result2 = null;
pos = pos2;
}
if (result2 !== null) {
result3 = parse_SourceCharacter();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
if (input.substr(pos, 2) === "*/") {
result2 = "*/";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"*/\"");
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_SingleLineComment() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
if (input.substr(pos, 2) === "//") {
result0 = "//";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"//\"");
}
}
if (result0 !== null) {
result1 = [];
pos1 = pos;
pos2 = pos;
reportFailures++;
result2 = parse_LineTerminator();
reportFailures--;
if (result2 === null) {
result2 = "";
} else {
result2 = null;
pos = pos2;
}
if (result2 !== null) {
result3 = parse_SourceCharacter();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
pos2 = pos;
reportFailures++;
result2 = parse_LineTerminator();
reportFailures--;
if (result2 === null) {
result2 = "";
} else {
result2 = null;
pos = pos2;
}
if (result2 !== null) {
result3 = parse_SourceCharacter();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result2 = parse_LineTerminator();
if (result2 === null) {
result2 = parse_EOF();
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse__() {
var result0, result1;
result0 = [];
result1 = parse_WhiteSpace();
if (result1 === null) {
result1 = parse_MultiLineCommentNoLineTerminator();
if (result1 === null) {
result1 = parse_SingleLineComment();
}
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_WhiteSpace();
if (result1 === null) {
result1 = parse_MultiLineCommentNoLineTerminator();
if (result1 === null) {
result1 = parse_SingleLineComment();
}
}
}
return result0;
}
function parse___() {
var result0, result1;
result0 = [];
result1 = parse_WhiteSpace();
if (result1 === null) {
result1 = parse_LineTerminatorSequence();
if (result1 === null) {
result1 = parse_Comment();
}
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_WhiteSpace();
if (result1 === null) {
result1 = parse_LineTerminatorSequence();
if (result1 === null) {
result1 = parse_Comment();
}
}
}
return result0;
}
function parse_Literal() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_Real();
if (result0 === null) {
result0 = parse_Integer();
}
if (result0 !== null) {
result0 = (function(offset, val) {
return {
type: "NumericLiteral",
value: val
}
})(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Integer() {
var result0, result1;
var pos0;
pos0 = pos;
if (/^[0-9]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (/^[0-9]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, digits) {
return parseInt(digits.join(""));
})(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Real() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_Integer();
if (result0 !== null) {
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 !== null) {
result2 = parse_Integer();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, digits) {
return parseFloat(digits.join(""));
})(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_SignedInteger() {
var result0, result1, result2;
var pos0;
pos0 = pos;
if (/^[\-+]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\-+]");
}
}
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
if (/^[0-9]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
if (/^[0-9]/.test(input.charAt(pos))) {
result2 = input.charAt(pos);
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
}
} else {
result1 = null;
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Identifier() {
var result0;
var pos0;
reportFailures++;
pos0 = pos;
result0 = parse_IdentifierName();
if (result0 !== null) {
result0 = (function(offset, name) { return name; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("identifier");
}
return result0;
}
function parse_IdentifierName() {
var result0, result1, result2;
var pos0, pos1;
reportFailures++;
pos0 = pos;
pos1 = pos;
result0 = parse_IdentifierStart();
if (result0 !== null) {
result1 = [];
result2 = parse_IdentifierStart();
while (result2 !== null) {
result1.push(result2);
result2 = parse_IdentifierStart();
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, start, parts) {
return start + parts.join("");
})(pos0, result0[0], result0[1]);
}
if (result0 === null) {
pos = pos0;
}
reportFailures--;
if (reportFailures === 0 && result0 === null) {
matchFailed("identifier");
}
return result0;
}
function parse_PrimaryExpression() {
var result0, result1, result2, result3, result4;
var pos0, pos1;
pos0 = pos;
result0 = parse_Identifier();
if (result0 !== null) {
result0 = (function(offset, name) { return { type: "Variable", name: name }; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
result0 = parse_Literal();
if (result0 === null) {
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 40) {
result0 = "(";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result0 !== null) {
result1 = parse___();
if (result1 !== null) {
result2 = parse_LinearExpression();
if (result2 !== null) {
result3 = parse___();
if (result3 !== null) {
if (input.charCodeAt(pos) === 41) {
result4 = ")";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, expression) { return expression; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
}
}
return result0;
}
function parse_UnaryExpression() {
var result0, result1, result2;
var pos0, pos1;
result0 = parse_PrimaryExpression();
if (result0 === null) {
pos0 = pos;
pos1 = pos;
result0 = parse_UnaryOperator();
if (result0 !== null) {
result1 = parse___();
if (result1 !== null) {
result2 = parse_UnaryExpression();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, operator, expression) {
return {
type: "UnaryExpression",
operator: operator,
expression: expression
};
})(pos0, result0[0], result0[2]);
}
if (result0 === null) {
pos = pos0;
}
}
return result0;
}
function parse_UnaryOperator() {
var result0;
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 45) {
result0 = "-";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 33) {
result0 = "!";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
}
}
return result0;
}
function parse_MultiplicativeExpression() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_UnaryExpression();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse___();
if (result2 !== null) {
result3 = parse_MultiplicativeOperator();
if (result3 !== null) {
result4 = parse___();
if (result4 !== null) {
result5 = parse_UnaryExpression();
if (result5 !== null) {
result2 = [result2, result3, result4, result5];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse___();
if (result2 !== null) {
result3 = parse_MultiplicativeOperator();
if (result3 !== null) {
result4 = parse___();
if (result4 !== null) {
result5 = parse_UnaryExpression();
if (result5 !== null) {
result2 = [result2, result3, result4, result5];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, head, tail) {
var result = head;
for (var i = 0; i < tail.length; i++) {
result = {
type: "MultiplicativeExpression",
operator: tail[i][1],
left: result,
right: tail[i][3]
};
}
return result;
})(pos0, result0[0], result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_MultiplicativeOperator() {
var result0;
if (input.charCodeAt(pos) === 42) {
result0 = "*";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 47) {
result0 = "/";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
}
return result0;
}
function parse_AdditiveExpression() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_MultiplicativeExpression();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse___();
if (result2 !== null) {
result3 = parse_AdditiveOperator();
if (result3 !== null) {
result4 = parse___();
if (result4 !== null) {
result5 = parse_MultiplicativeExpression();
if (result5 !== null) {
result2 = [result2, result3, result4, result5];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse___();
if (result2 !== null) {
result3 = parse_AdditiveOperator();
if (result3 !== null) {
result4 = parse___();
if (result4 !== null) {
result5 = parse_MultiplicativeExpression();
if (result5 !== null) {
result2 = [result2, result3, result4, result5];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, head, tail) {
var result = head;
for (var i = 0; i < tail.length; i++) {
result = {
type: "AdditiveExpression",
operator: tail[i][1],
left: result,
right: tail[i][3]
};
}
return result;
})(pos0, result0[0], result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_AdditiveOperator() {
var result0;
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 45) {
result0 = "-";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
}
return result0;
}
function parse_InequalityExpression() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_AdditiveExpression();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse___();
if (result2 !== null) {
result3 = parse_InequalityOperator();
if (result3 !== null) {
result4 = parse___();
if (result4 !== null) {
result5 = parse_AdditiveExpression();
if (result5 !== null) {
result2 = [result2, result3, result4, result5];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse___();
if (result2 !== null) {
result3 = parse_InequalityOperator();
if (result3 !== null) {
result4 = parse___();
if (result4 !== null) {
result5 = parse_AdditiveExpression();
if (result5 !== null) {
result2 = [result2, result3, result4, result5];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, head, tail) {
var result = head;
for (var i = 0; i < tail.length; i++) {
result = {
type: "Inequality",
operator: tail[i][1],
left: result,
right: tail[i][3]
};
}
return result;
})(pos0, result0[0], result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_InequalityOperator() {
var result0;
if (input.substr(pos, 2) === "<=") {
result0 = "<=";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"<=\"");
}
}
if (result0 === null) {
if (input.substr(pos, 2) === ">=") {
result0 = ">=";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\">=\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 60) {
result0 = "<";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"<\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 62) {
result0 = ">";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\">\"");
}
}
}
}
}
return result0;
}
function parse_LinearExpression() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_InequalityExpression();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse___();
if (result2 !== null) {
if (input.substr(pos, 2) === "==") {
result3 = "==";
pos += 2;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"==\"");
}
}
if (result3 !== null) {
result4 = parse___();
if (result4 !== null) {
result5 = parse_InequalityExpression();
if (result5 !== null) {
result2 = [result2, result3, result4, result5];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse___();
if (result2 !== null) {
if (input.substr(pos, 2) === "==") {
result3 = "==";
pos += 2;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"==\"");
}
}
if (result3 !== null) {
result4 = parse___();
if (result4 !== null) {
result5 = parse_InequalityExpression();
if (result5 !== null) {
result2 = [result2, result3, result4, result5];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, head, tail) {
var result = head;
for (var i = 0; i < tail.length; i++) {
result = {
type: "Equality",
operator: tail[i][1],
left: result,
right: tail[i][3]
};
}
return result;
})(pos0, result0[0], result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function cleanupExpected(expected) {
expected.sort();
var lastExpected = null;
var cleanExpected = [];
for (var i = 0; i < expected.length; i++) {
if (expected[i] !== lastExpected) {
cleanExpected.push(expected[i]);
lastExpected = expected[i];
}
}
return cleanExpected;
}
function computeErrorPosition() {
/*
* The first idea was to use |String.split| to break the input up to the
* error position along newlines and derive the line and column from
* there. However IE's |split| implementation is so broken that it was
* enough to prevent it.
*/
var line = 1;
var column = 1;
var seenCR = false;
for (var i = 0; i < Math.max(pos, rightmostFailuresPos); i++) {
var ch = input.charAt(i);
if (ch === "\n") {
if (!seenCR) { line++; }
column = 1;
seenCR = false;
} else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") {
line++;
column = 1;
seenCR = true;
} else {
column++;
seenCR = false;
}
}
return { line: line, column: column };
}
var result = parseFunctions[startRule]();
/*
* The parser is now in one of the following three states:
*
* 1. The parser successfully parsed the whole input.
*
* - |result !== null|
* - |pos === input.length|
* - |rightmostFailuresExpected| may or may not contain something
*
* 2. The parser successfully parsed only a part of the input.
*
* - |result !== null|
* - |pos < input.length|
* - |rightmostFailuresExpected| may or may not contain something
*
* 3. The parser did not successfully parse any part of the input.
*
* - |result === null|
* - |pos === 0|
* - |rightmostFailuresExpected| contains at least one failure
*
* All code following this comment (including called functions) must
* handle these states.
*/
if (result === null || pos !== input.length) {
var offset = Math.max(pos, rightmostFailuresPos);
var found = offset < input.length ? input.charAt(offset) : null;
var errorPosition = computeErrorPosition();
throw new this.SyntaxError(
cleanupExpected(rightmostFailuresExpected),
found,
offset,
errorPosition.line,
errorPosition.column
);
}
return result;
},
/* Returns the parser source code. */
toSource: function() { return this._source; }
};
/* Thrown when a parser encounters a syntax error. */
result.SyntaxError = function(expected, found, offset, line, column) {
function buildMessage(expected, found) {
var expectedHumanized, foundHumanized;
switch (expected.length) {
case 0:
expectedHumanized = "end of input";
break;
case 1:
expectedHumanized = expected[0];
break;
default:
expectedHumanized = expected.slice(0, expected.length - 1).join(", ")
+ " or "
+ expected[expected.length - 1];
}
foundHumanized = found ? quote(found) : "end of input";
return "Expected " + expectedHumanized + " but " + foundHumanized + " found.";
}
this.name = "SyntaxError";
this.expected = expected;
this.found = found;
this.message = buildMessage(expected, found);
this.offset = offset;
this.line = line;
this.column = column;
};
result.SyntaxError.prototype = Error.prototype;
return result;
})();
});
require.register("slightlyoff-cassowary.js/src/parser/api.js", function(exports, require, module){
// Copyright (C) 2013, Alex Russell <slightlyoff@chromium.org>
// Use of this source code is governed by
// http://www.apache.org/licenses/LICENSE-2.0
(function(c){
"use strict";
var solver = new c.SimplexSolver();
var vars = {};
var exprs = {};
var weak = c.Strength.weak;
var medium = c.Strength.medium;
var strong = c.Strength.strong;
var required = c.Strength.required;
var _c = function(expr) {
if (exprs[expr]) {
return exprs[expr];
}
switch(expr.type) {
case "Inequality":
var op = (expr.operator == "<=") ? c.LEQ : c.GEQ;
var i = new c.Inequality(_c(expr.left), op, _c(expr.right), weak);
solver.addConstraint(i);
return i;
case "Equality":
var i = new c.Equation(_c(expr.left), _c(expr.right), weak);
solver.addConstraint(i);
return i;
case "MultiplicativeExpression":
var i = c.times(_c(expr.left), _c(expr.right));
solver.addConstraint(i);
return i;
case "AdditiveExpression":
if (expr.operator == "+") {
return c.plus(_c(expr.left), _c(expr.right));
} else {
return c.minus(_c(expr.left), _c(expr.right));
}
case "NumericLiteral":
return new c.Expression(expr.value);
case "Variable":
// console.log(expr);
if(!vars[expr.name]) {
vars[expr.name] = new c.Variable({ name: expr.name });
}
return vars[expr.name];
case "UnaryExpression":
console.log("UnaryExpression...WTF?");
break;
}
};
var compile = function(expressions) {
return expressions.map(_c);
};
// Global API entrypoint
c._api = function() {
var args = Array.prototype.slice.call(arguments);
if (args.length == 1) {
if(typeof args[0] == "string") {
// Parse and execute it
var r = c.parser.parse(args[0]);
return compile(r);
} else if(typeof args[0] == "function") {
solver._addCallback(args[0]);
}
}
};
})(this["c"]||module.parent.exports||{});
});
require.register("gss/lib/GSS-with-compiler.js", function(exports, require, module){
var Compiler;
require("./GSS.js");
Compiler = GSS.Compiler = require("gss-compiler");
GSS.compile = function(rules) {
var ast, e;
ast = {};
if (typeof rules === "string") {
try {
ast = Compiler.compile(rules);
} catch (_error) {
e = _error;
console.warn("compiler error", e);
ast = {};
}
} else if (typeof rules === "object") {
ast = rules;
} else {
throw new Error("Unrecognized GSS rule format. Should be string or AST");
}
return ast;
};
GSS.Engine.prototype['compile'] = function(source) {
return this.run(GSS.compile(source));
};
GSS.Getter.prototype['readAST:text/gss'] = function(node) {
var ast, source;
source = node.textContent.trim();
if (source.length === 0) {
return {};
}
ast = GSS.compile(source);
return ast;
};
});
require.register("gss/lib/GSS.js", function(exports, require, module){
var GSS, LOG_PASS, TIME, TIME_END, key, val, _ref;
require("customevent-polyfill");
require("cassowary");
if (window.GSS) {
throw new Error("Only one GSS object per window");
}
GSS = window.GSS = function(o) {
var engine;
if (o === document || o === window) {
return GSS.engines.root;
}
if (o.tagName) {
engine = GSS.get.engine(o);
if (engine) {
return engine;
}
return new GSS.Engine({
scope: o
});
} else if (o !== null && typeof o === 'object') {
if (o.scope) {
engine = GSS.get.engine(o.scope);
if (engine) {
return engine;
}
}
return new GSS.Engine(o);
} else {
throw new Error("");
}
};
GSS.config = {
defaultStrength: 'weak',
defaultWeight: 0,
verticalScroll: true,
horizontalScroll: false,
resizeDebounce: 32,
defaultMatrixType: 'mat4',
observe: true,
observerOptions: {
subtree: true,
childList: true,
attributes: true,
characterData: true
},
debug: false,
warn: false,
perf: false,
fractionalPixels: true,
readyClass: true,
processBeforeSet: null,
maxDisplayRecursionDepth: 30,
useWorker: !!window.Worker,
worker: '../dist/worker.js',
useOffsetParent: true
};
if (typeof GSS_CONFIG !== "undefined" && GSS_CONFIG !== null) {
for (key in GSS_CONFIG) {
val = GSS_CONFIG[key];
GSS.config[key] = val;
}
}
GSS.deblog = function() {
if (GSS.config.debug) {
return console.log.apply(console, arguments);
}
};
GSS.warn = function() {
if (GSS.config.warn) {
return console.warn.apply(console, arguments);
}
};
LOG_PASS = function(pass, bg) {
if (bg == null) {
bg = "green";
}
return GSS.deblog("%c" + pass, "color:white; padding:2px; font-size:14px; background:" + bg + ";");
};
TIME = function() {
if (GSS.config.perf) {
return console.time.apply(console, arguments);
}
};
TIME_END = function() {
if (GSS.config.perf) {
return console.timeEnd.apply(console, arguments);
}
};
GSS._ = require("./_.js");
GSS.glMatrix = require('../vendor/gl-matrix');
GSS.EventTrigger = require("./EventTrigger.js");
GSS.Getter = require("./dom/Getter.js");
GSS.Commander = require("./Commander.js");
GSS.Query = require("./dom/Query.js");
GSS.Thread = require("./Thread.js");
GSS.Engine = require("./Engine.js");
GSS.View = require("./dom/View.js");
GSS.Rule = require("./gssom/Rule.js");
require("./gssom/StyleSheet.js");
_ref = require("./dom/IdMixin.js");
for (key in _ref) {
val = _ref[key];
if (GSS[key]) {
throw new Error("IdMixin key clash: " + key);
}
GSS[key] = val;
}
GSS.EventTrigger.make(GSS);
GSS.get = new GSS.Getter();
GSS.observer = require("./dom/Observer.js");
GSS.boot = function() {
var html;
GSS.body = document.body || GSS.getElementsByTagName('body')[0];
GSS.html = html = GSS.body.parentNode;
GSS({
scope: GSS.Getter.getRootScope(),
is_root: true
});
document.dispatchEvent(new CustomEvent('GSS', {
detail: GSS,
bubbles: false,
cancelable: false
}));
GSS.setupObserver();
GSS.update();
GSS.observe();
return GSS.trigger("afterLoaded");
};
GSS.update = function() {
GSS.styleSheets.find();
GSS.updateIfNeeded();
return GSS.layoutIfNeeded();
};
GSS.needsUpdate = false;
GSS.setNeedsUpdate = function(bool) {
if (bool) {
if (!GSS.needsUpdate) {
GSS._.defer(GSS.updateIfNeeded);
}
return GSS.needsUpdate = true;
} else {
return GSS.needsUpdate = false;
}
};
GSS.updateIfNeeded = function() {
if (GSS.needsUpdate) {
LOG_PASS("Update Pass", "orange");
TIME("update pass");
GSS.engines.root.updateIfNeeded();
GSS.setNeedsUpdate(false);
return TIME_END("update pass");
}
};
GSS.needsLayout = false;
GSS.setNeedsLayout = function(bool) {
if (bool) {
if (!GSS.needsLayout) {
GSS._.defer(GSS.layoutIfNeeded);
}
return GSS.needsLayout = true;
} else {
return GSS.needsLayout = false;
}
};
GSS.layoutIfNeeded = function() {
if (GSS.needsLayout) {
LOG_PASS("Layout Pass", "green");
TIME("layout pass");
GSS.engines.root.layoutIfNeeded();
GSS.setNeedsLayout(false);
return TIME_END("layout pass");
}
};
/*
GSS.needsDisplay = false
GSS.setNeedsDisplay = (bool) ->
if bool
if !GSS.needsDisplay
GSS._.defer GSS.displayIfNeeded
GSS.needsDisplay = true
else
GSS.needsDisplay = false
GSS.displayIfNeeded = () ->
if GSS.needsDisplay
LOG_PASS "Display Pass", "violet"
TIME "display pass"
GSS.engines.root.displayIfNeeded()
GSS.setNeedsDisplay false
TIME_END "display pass"
TIME_END "RENDER"
*/
});
require.register("gss/lib/_.js", function(exports, require, module){
var firstSupportedStylePrefix, getTime, tempDiv, _,
__slice = [].slice;
getTime = Date.now || function() {
return new Date().getTime();
};
tempDiv = document.createElement("div");
firstSupportedStylePrefix = function(prefixedPropertyNames) {
var name, _i, _len;
for (_i = 0, _len = prefixedPropertyNames.length; _i < _len; _i++) {
name = prefixedPropertyNames[_i];
if (typeof tempDiv.style[name] !== 'undefined') {
return name;
}
}
return null;
};
_ = {
transformPrefix: firstSupportedStylePrefix(["transform", "WebkitTransform", "MozTransform", "OTransform", "msTransform"]),
boxSizingPrefix: firstSupportedStylePrefix(["boxSizing", "WebkitBoxSizing", "MozBoxSizing", "OBoxSizing", "msBoxSizing"]),
defer: function(func) {
return setTimeout(func, 1);
},
debounce: function(func, wait, immediate) {
var args, context, result, timeout, timestamp;
timeout = void 0;
args = void 0;
context = void 0;
timestamp = void 0;
result = void 0;
return function() {
var callNow, later;
context = this;
args = __slice.call(arguments);
timestamp = getTime();
later = function() {
var last;
last = getTime() - timestamp;
if (last < wait) {
return timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
return result = func.apply(context, args);
}
}
};
callNow = immediate && !timeout;
if (!timeout) {
timeout = setTimeout(later, wait);
}
if (callNow) {
result = func.apply(context, args);
}
return result;
};
},
cloneDeep: function(obj) {
return JSON.parse(JSON.stringify(obj));
},
cloneObject: function(obj) {
var i, target;
target = {};
for (i in obj) {
if (obj.hasOwnProperty(i)) {
target[i] = obj[i];
}
}
return target;
},
filterVarsForDisplay: function(vars) {
var idx, k, key, keysToKill, obj, val, _i, _len;
obj = {};
keysToKill = [];
for (key in vars) {
val = vars[key];
idx = key.indexOf("intrinsic-");
if (idx !== -1) {
keysToKill.push(key.replace("intrinsic-", ""));
} else {
obj[key] = val;
}
}
for (_i = 0, _len = keysToKill.length; _i < _len; _i++) {
k = keysToKill[_i];
delete obj[k];
}
return obj;
},
varsByViewId: function(vars) {
var gid, key, prop, val, varsById;
varsById = {};
for (key in vars) {
val = vars[key];
if (key[0] === "$") {
gid = key.substring(1, key.indexOf("["));
if (!varsById[gid]) {
varsById[gid] = {};
}
prop = key.substring(key.indexOf("[") + 1, key.indexOf("]"));
varsById[gid][prop] = val;
}
}
return varsById;
},
mat4ToCSS: function(a) {
return 'matrix3d(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ', ' + a[4] + ', ' + a[5] + ', ' + a[6] + ', ' + a[7] + ', ' + a[8] + ', ' + a[9] + ', ' + a[10] + ', ' + a[11] + ', ' + a[12] + ', ' + a[13] + ', ' + a[14] + ', ' + a[15] + ')';
},
mat2dToCSS: function(a) {
return 'matrix(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ', ' + a[4] + ', ' + a[5] + ')';
},
camelize: function(s) {
var result;
result = s.replace(/[-_\s]+(.)?/g, function(match, c) {
if (c) {
return c.toUpperCase();
} else {
return "";
}
});
return result;
}
};
module.exports = _;
});
require.register("gss/lib/EventTrigger.js", function(exports, require, module){
var EventTrigger;
EventTrigger = (function() {
function EventTrigger() {
this._listenersByType = {};
this;
}
EventTrigger.prototype._getListeners = function(type) {
var byType;
if (this._listenersByType[type]) {
byType = this._listenersByType[type];
} else {
byType = [];
this._listenersByType[type] = byType;
}
return byType;
};
EventTrigger.prototype.on = function(type, listener) {
var listeners;
listeners = this._getListeners(type);
if (listeners.indexOf(listener) === -1) {
listeners.push(listener);
}
return this;
};
EventTrigger.prototype.once = function(type, listener) {
var that, wrap;
wrap = null;
that = this;
wrap = function(o) {
that.off(type, wrap);
return listener.call(that, o);
};
this.on(type, wrap);
return this;
};
EventTrigger.prototype.off = function(type, listener) {
var i, listeners;
listeners = this._getListeners(type);
i = listeners.indexOf(listener);
if (i !== -1) {
listeners.splice(i, 1);
}
return this;
};
EventTrigger.prototype.offAll = function(target) {
var i, listeners, type, _ref;
if (typeof target === "string") {
if (target) {
this._listenersByType[target] = [];
}
} else if (typeof target === "function") {
_ref = this._listenersByType;
for (type in _ref) {
listeners = _ref[type];
i = listeners.indexOf(target);
if (i !== -1) {
listeners.splice(i, 1);
}
}
} else {
this._listenersByType = {};
}
return this;
};
EventTrigger.prototype.trigger = function(type, o) {
var listener, _i, _len, _ref;
_ref = this._getListeners(type);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
listener = _ref[_i];
if (listener != null) {
listener.call(this, o);
}
}
return this;
};
return EventTrigger;
})();
EventTrigger.make = function(obj) {
var key, val, _ref;
if (obj == null) {
obj = {};
}
EventTrigger.prototype.constructor.call(obj);
_ref = EventTrigger.prototype;
for (key in _ref) {
val = _ref[key];
if (key === "constructor") {
val.call(obj);
} else {
obj[key] = val;
}
}
return obj;
};
module.exports = EventTrigger;
});
require.register("gss/lib/dom/Query.js", function(exports, require, module){
/*
Encapsulates Dom Queries used in GSS rules
JSPerf debunking *big* perf gain from liveNodeLists:
- http://jsperf.com/getelementsbyclassname-vs-queryselectorall/70
- http://jsperf.com/queryselectorall-vs-getelementsbytagname/77
*/
var LOG, Query, arrayAddsRemoves,
__slice = [].slice,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
arrayAddsRemoves = function(old, neu) {
var adds, n, o, removes, _i, _j, _len, _len1;
adds = [];
removes = [];
for (_i = 0, _len = neu.length; _i < _len; _i++) {
n = neu[_i];
if (old.indexOf(n) === -1) {
adds.push(n);
}
}
for (_j = 0, _len1 = old.length; _j < _len1; _j++) {
o = old[_j];
if (neu.indexOf(o) === -1) {
removes.push(o);
}
}
return {
adds: adds,
removes: removes
};
};
LOG = function() {
return GSS.deblog.apply(GSS, ["Query"].concat(__slice.call(arguments)));
};
Query = (function(_super) {
__extends(Query, _super);
Query.prototype.isQuery = true;
function Query(o) {
if (o == null) {
o = {};
}
Query.__super__.constructor.apply(this, arguments);
this.selector = o.selector || (function() {
throw new Error("GssQuery must have a selector");
})();
this.createNodeList = o.createNodeList || (function() {
throw new Error("GssQuery must implement createNodeList()");
})();
this.isMulti = o.isMulti || false;
this.isLive = o.isLive || false;
this.ids = o.ids || [];
this.lastAddedIds = [];
this.lastRemovedIds = [];
LOG("constructor() @", this);
this;
}
Query.prototype._updated_once = false;
Query.prototype.changedLastUpdate = false;
Query.prototype.update = function() {
var adds, el, id, newIds, oldIds, removes, _i, _len, _ref, _ref1;
LOG("update() @", this);
if (this.is_destroyed) {
throw new Error("Can't update destroyed query: " + selector);
}
this.changedLastUpdate = false;
if (!this.isLive || !this._updated_once) {
this.nodeList = this.createNodeList();
this._updated_once = true;
}
oldIds = this.ids;
newIds = [];
_ref = this.nodeList;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
el = _ref[_i];
id = GSS.setupId(el);
if (id) {
newIds.push(id);
}
}
_ref1 = arrayAddsRemoves(oldIds, newIds), adds = _ref1.adds, removes = _ref1.removes;
if (adds.length > 0) {
this.changedLastUpdate = true;
}
this.lastAddedIds = adds;
if (removes.length > 0) {
this.changedLastUpdate = true;
}
this.lastRemovedIds = removes;
this.ids = newIds;
if (this.changedLastUpdate) {
this.trigger('afterChange');
}
return this;
};
Query.prototype.forEach = function(callback) {
var el, _i, _len, _ref, _results;
_ref = this.nodeList;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
el = _ref[_i];
_results.push(callback.call(this, el));
}
return _results;
};
Query.prototype.first = function() {
return this.nodeList[0];
};
Query.prototype.last = function() {
return this.nodeList[this.nodeList.length - 1];
};
Query.prototype.next = function(el) {
return this.nodeList[this.indexOf(el) + 1];
};
Query.prototype.prev = function(el) {
return this.nodeList[this.indexOf(el) - 1];
};
Query.prototype.indexOf = function(el) {
return Array.prototype.indexOf.call(this.nodeList, el);
};
Query.prototype.is_destroyed = false;
Query.prototype.destroy = function() {
this.offAll();
this.is_destroyed = true;
this.ids = null;
this.lastAddedIds = null;
this.lastRemovedIds = null;
this.createNodeList = null;
this.nodeList = null;
return this.changedLastUpdate = null;
};
return Query;
})(GSS.EventTrigger);
Query.Set = (function(_super) {
__extends(Set, _super);
function Set() {
Set.__super__.constructor.apply(this, arguments);
this.bySelector = {};
return this;
}
Set.prototype.clean = function() {
var query, selector, _ref;
_ref = this.bySelector;
for (selector in _ref) {
query = _ref[selector];
query.destroy();
this.bySelector[selector] = null;
}
return this.bySelector = {};
};
Set.prototype.destroy = function() {
var query, selector, _ref;
_ref = this.bySelector;
for (selector in _ref) {
query = _ref[selector];
query.destroy();
this.bySelector[selector] = null;
}
this.offAll();
return this.bySelector = null;
};
Set.prototype.add = function(o) {
var query, selector;
selector = o.selector;
query = this.bySelector[selector];
if (!query) {
query = new GSS.Query(o);
query.update();
this.bySelector[selector] = query;
}
return query;
};
Set.prototype.update = function() {
var el, globalRemoves, o, query, removedIds, removes, rid, selector, selectorsWithAdds, trigger, _i, _len, _ref;
selectorsWithAdds = [];
removes = [];
globalRemoves = [];
trigger = false;
_ref = this.bySelector;
for (selector in _ref) {
query = _ref[selector];
query.update();
if (query.changedLastUpdate) {
if (query.lastAddedIds.length > 0) {
trigger = true;
selectorsWithAdds.push(selector);
}
if (query.lastRemovedIds.length > 0) {
trigger = true;
removedIds = query.lastRemovedIds;
for (_i = 0, _len = removedIds.length; _i < _len; _i++) {
rid = removedIds[_i];
if (globalRemoves.indexOf(rid) === -1) {
el = GSS.getById(rid);
if (document.documentElement.contains(el)) {
globalRemoves.push(rid);
removes.push(selector + "$" + rid);
} else {
removes.push("$" + rid);
}
}
}
}
}
}
GSS._ids_killed(globalRemoves);
if (!trigger) {
return trigger;
}
if (trigger) {
o = {
removes: removes,
selectorsWithAdds: selectorsWithAdds
};
this.trigger('update', o);
return o;
}
};
return Set;
})(GSS.EventTrigger);
module.exports = Query;
});
require.register("gss/lib/dom/View.js", function(exports, require, module){
var View, transformPrefix,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
transformPrefix = GSS._.transformPrefix;
View = (function() {
function View() {
this.recycle = __bind(this.recycle, this);
this.attach = __bind(this.attach, this);
this.values = {};
this.is_positioned = false;
this.el = null;
this.id = null;
this.parentOffsets = null;
this.style = null;
this.Matrix = null;
this.matrixType = null;
this.virtuals = null;
this;
}
View.prototype.attach = function(el, id) {
this.el = el;
this.id = id;
if (!this.el) {
throw new Error("View needs el");
}
if (!this.id) {
throw new Error("View needs id");
}
View.byId[this.id] = this;
this.is_positioned = false;
GSS.trigger('view:attach', this);
if (!this.matrixType) {
this.matrixType = GSS.config.defaultMatrixType;
}
this.Matrix = GSS.glMatrix[this.matrixType] || (function() {
throw new Error("View matrixType not found: " + this.matrixType);
}).call(this);
if (!this.matrix) {
this.matrix = this.Matrix.create();
}
return this;
};
View.prototype.recycle = function() {
GSS.trigger('view:detach', this);
this.is_positioned = false;
this.el = null;
delete View.byId[this.id];
this.id = null;
this.parentOffsets = null;
this.style = null;
this.Matrix.identity(this.matrix);
this.matrixType = null;
this.virtuals = null;
this.values = {};
return View.recycled.push(this);
};
View.prototype.positionIfNeeded = function() {
if (!this.is_positioned) {
this.style.position = 'absolute';
this.style.margin = '0px';
this.style.top = '0px';
this.style.left = '0px';
}
return this.is_positioned = true;
};
View.prototype.updateParentOffsets = function() {
return this.parentOffsets = this.getParentOffsets();
};
View.prototype.getParentOffsets = function() {
var box;
box = this.el.getBoundingClientRect();
return {
y: box.top + (window.pageYOffset || document.documentElement.scrollTop) - (document.documentElement.clientTop || 0),
x: box.left + (window.pageXOffset || document.documentElement.scrollLeft) - (document.documentElement.clientLeft || 0)
};
};
View.prototype.getParentOffsets__ = function() {
var el, offsets;
el = this.el;
/*
if !GSS.config.useOffsetParent
return {
x:0
y:0
}
*/
offsets = {
x: 0,
y: 0
};
if (!el.offsetParent) {
return offsets;
}
el = el.offsetParent;
while (true) {
offsets.x += el.offsetLeft;
offsets.y += el.offsetTop;
if (!el.offsetParent) {
break;
}
el = el.offsetParent;
}
return offsets;
};
View.prototype.needsDisplay = false;
View.prototype.display = function(offsets) {
var key, o, val, xLocal, yLocal, _ref, _ref1;
if (!this.values) {
return;
}
o = {};
_ref = this.values;
for (key in _ref) {
val = _ref[key];
o[key] = val;
}
if ((o.x != null) || (o.y != null)) {
if (this.parentOffsets) {
offsets.x += this.parentOffsets.x;
offsets.y += this.parentOffsets.y;
}
if (o.x != null) {
xLocal = o.x - offsets.x;
delete o.x;
} else {
xLocal = 0;
}
if (o.y != null) {
yLocal = o.y - offsets.y;
delete o.y;
} else {
yLocal = 0;
}
if (!GSS.config.fractionalPixels) {
xLocal = Math.round(xLocal);
yLocal = Math.round(yLocal);
}
this.values.xLocal = xLocal;
this.values.yLocal = yLocal;
this._positionMatrix(xLocal, yLocal);
}
if (o['z-index'] != null) {
this.style['zIndex'] = o['z-index'];
delete o['z-index'];
}
/*
if o['line-height']?
@style['line-height'] = o['line-height']
delete o['line-height']
*/
if (!GSS.config.fractionalPixels) {
if (o.width != null) {
o.width = Math.round(o.width);
}
if (o.height != null) {
o.height = Math.round(o.height);
}
}
for (key in o) {
val = o[key];
key = GSS._.camelize(key);
this.style[key] = val + "px";
}
_ref1 = this.style;
for (key in _ref1) {
val = _ref1[key];
this.el.style[key] = val;
}
return this;
};
/*
_positionTranslate: (xLocal, yLocal) ->
@style[transformPrefix] += " translateX(#{@xLocal}px)"
@style[transformPrefix] += " translateY(#{@yLocal}px)"
*/
View.prototype._positionMatrix = function(xLocal, yLocal) {
this.Matrix.translate(this.matrix, this.matrix, [xLocal, yLocal, 0]);
return this.style[transformPrefix] = GSS._[this.matrixType + "ToCSS"](this.matrix);
};
View.prototype.displayIfNeeded = function(offsets, pass_to_children) {
if (offsets == null) {
offsets = {
x: 0,
y: 0
};
}
if (pass_to_children == null) {
pass_to_children = true;
}
if (this.needsDisplay) {
this.display(offsets);
this.setNeedsDisplay(false);
}
offsets = {
x: 0,
y: 0
};
if (this.values.x) {
offsets.x += this.values.x;
}
if (this.values.y) {
offsets.y += this.values.y;
}
if (pass_to_children) {
return this.displayChildrenIfNeeded(offsets);
}
};
View.prototype.setNeedsDisplay = function(bool) {
if (bool) {
return this.needsDisplay = true;
} else {
return this.needsDisplay = false;
}
};
View.prototype.displayChildrenIfNeeded = function(offsets) {
return this._displayChildrenIfNeeded(this.el, offsets, 0);
};
View.prototype._displayChildrenIfNeeded = function(el, offsets, recurseLevel) {
var child, children, view, _i, _len, _results;
if (recurseLevel <= GSS.config.maxDisplayRecursionDepth) {
children = el.children;
if (!children) {
return null;
}
_results = [];
for (_i = 0, _len = children.length; _i < _len; _i++) {
child = children[_i];
view = GSS.get.view(child);
if (view) {
_results.push(view.displayIfNeeded(offsets));
} else {
_results.push(this._displayChildrenIfNeeded(child, offsets, recurseLevel + 1));
}
}
return _results;
}
};
View.prototype.updateValues = function(o) {
this.values = o;
this.style = {};
this.Matrix.identity(this.matrix);
if (this.el.getAttribute('gss-parent-offsets') != null) {
this.updateParentOffsets();
}
if ((o.x != null) || (o.y != null)) {
this.positionIfNeeded();
}
this.setNeedsDisplay(true);
return this;
};
View.prototype.getParentView = function() {
var el, gid;
el = this.el.parentElement;
while (true) {
gid = el._gss_id;
if (gid) {
return View.byId[gid];
}
if (!el.parentElement) {
break;
}
el = el.parentElement;
}
};
View.prototype.addVirtuals = function(names) {
var name, _i, _len;
if (!this.virtuals) {
return this.virtuals = [].concat(names);
}
for (_i = 0, _len = names.length; _i < _len; _i++) {
name = names[_i];
this.addVirtual(name);
}
return null;
};
View.prototype.addVirtual = function(name) {
if (!this.virtuals) {
return this.virtuals = [name];
}
if (this.virtuals.indexOf(name) === -1) {
this.virtuals.push(name);
}
return null;
};
View.prototype.hasVirtual = function(name) {
if (!this.virtuals) {
return false;
} else if (this.virtuals.indexOf(name) === -1) {
return false;
}
return true;
};
View.prototype.nearestViewWithVirtual = function(name) {
var ancestor;
ancestor = this;
while (ancestor) {
if (ancestor.hasVirtual(name)) {
return ancestor;
}
ancestor = ancestor.parentElement;
}
return null;
};
return View;
})();
View.byId = {};
View.recycled = [];
View.count = 0;
View["new"] = function(_arg) {
var el, id, view;
el = _arg.el, id = _arg.id;
View.count++;
if (View.recycled.length > 0) {
view = View.recycled.pop();
} else {
view = new View();
}
return view.attach(el, id);
};
module.exports = View;
});
require.register("gss/lib/dom/Observer.js", function(exports, require, module){
var LOG, observer, _unobservedElements,
__slice = [].slice;
LOG = function() {
return GSS.deblog.apply(GSS, ["Observer"].concat(__slice.call(arguments)));
};
observer = null;
GSS.is_observing = false;
GSS.observe = function() {
if (!observer) {
return;
}
if (!GSS.is_observing && GSS.config.observe) {
observer.observe(document.body, GSS.config.observerOptions);
return GSS.is_observing = true;
}
};
GSS.unobserve = function() {
if (!observer) {
return;
}
observer.disconnect();
return GSS.is_observing = false;
};
GSS._unobservedElements = _unobservedElements = [];
GSS.observeElement = function(el) {
if (_unobservedElements.indexOf(el) === -1) {
return _unobservedElements.push(el);
}
};
GSS.unobserveElement = function(el) {
var i;
i = _unobservedElements.indexOf(el);
if (i > -1) {
return _unobservedElements.splice(i, 1);
}
};
GSS.setupObserver = function() {
if (!window.MutationObserver) {
if (window.WebKitMutationObserver) {
window.MutationObserver = window.WebKitMutationObserver;
} else {
window.MutationObserver = window.JsMutationObserver;
}
}
if (!window.MutationObserver) {
return;
}
return observer = new MutationObserver(function(mutations) {
var e, engine, enginesToReset, gid, i, invalidMeasureIds, m, needsUpdateQueries, nodesToIgnore, observableMutation, removed, scope, sheet, target, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _m, _ref;
LOG("MutationObserver", mutations);
enginesToReset = [];
nodesToIgnore = [];
needsUpdateQueries = [];
invalidMeasureIds = [];
observableMutation = false;
for (_i = 0, _len = mutations.length; _i < _len; _i++) {
m = mutations[_i];
if (_unobservedElements.indexOf(m.target) !== -1) {
continue;
} else {
observableMutation = true;
}
if (m.type === "characterData") {
if (!m.target.parentElement) {
continue;
}
sheet = m.target.parentElement.gssStyleSheet;
if (sheet) {
sheet.reload();
e = sheet.engine;
if (enginesToReset.indexOf(e) === -1) {
enginesToReset.push(e);
}
}
}
if (m.type === "attributes" || m.type === "childList") {
if (m.type === "attributes" && m.attributename === "data-gss-id") {
nodesToIgnore.push(m.target);
} else if (nodesToIgnore.indexOf(m.target) === -1) {
scope = GSS.get.nearestScope(m.target);
if (scope) {
if (needsUpdateQueries.indexOf(scope) === -1) {
needsUpdateQueries.push(scope);
}
}
}
}
gid = null;
if (m.type === "characterData" || m.type === "attributes" || m.type === "childList") {
if (m.type === "characterData") {
target = m.target.parentElement;
gid = GSS.getId(m.target.parentElement);
} else if (nodesToIgnore.indexOf(m.target) === -1) {
gid = GSS.getId(m.target);
}
if (gid != null) {
gid = "$" + gid;
if (invalidMeasureIds.indexOf(gid) === -1) {
invalidMeasureIds.push(gid);
}
}
}
}
if (!observableMutation) {
return null;
}
removed = GSS.styleSheets.findAllRemoved();
for (_j = 0, _len1 = removed.length; _j < _len1; _j++) {
sheet = removed[_j];
sheet.destroy();
e = sheet.engine;
if (enginesToReset.indexOf(e) === -1) {
enginesToReset.push(e);
}
}
i = 0;
engine = GSS.engines[i];
while (!!engine) {
if (i > 0) {
if (engine.scope) {
if (!document.documentElement.contains(engine.scope)) {
engine.destroyChildren();
engine.destroy();
}
}
}
i++;
engine = GSS.engines[i];
}
for (_k = 0, _len2 = enginesToReset.length; _k < _len2; _k++) {
e = enginesToReset[_k];
if (!e.is_destroyed) {
e.reset();
}
}
for (_l = 0, _len3 = needsUpdateQueries.length; _l < _len3; _l++) {
scope = needsUpdateQueries[_l];
e = GSS.get.engine(scope);
if (e) {
if (!e.is_destroyed) {
if (enginesToReset.indexOf(e) === -1) {
e.updateQueries();
}
}
}
}
if (invalidMeasureIds.length > 0) {
_ref = GSS.engines;
for (_m = 0, _len4 = _ref.length; _m < _len4; _m++) {
e = _ref[_m];
if (!e.is_destroyed) {
e.commander.handleInvalidMeasures(invalidMeasureIds);
}
}
}
enginesToReset = null;
nodesToIgnore = null;
needsUpdateQueries = null;
invalidMeasureIds = null;
return GSS.update();
/*
for m in mutations
if m.removedNodes.length > 0 # nodelist are weird?
for node in m.removedNodes
if m.addedNodes.length > 0 # nodelist are weird?
for node in m.addedNodes
*/
});
};
GSS.isDisplayed = false;
GSS.onDisplay = function() {
GSS.trigger("display");
if (GSS.isDisplayed) {
return;
}
GSS.isDisplayed = true;
if (GSS.config.readyClass) {
return GSS._.defer(function() {
GSS.html.classList.add("gss-ready");
return GSS.html.classList.remove("gss-not-ready");
});
}
};
document.addEventListener("DOMContentLoaded", function(e) {
return GSS.boot();
});
module.exports = observer;
});
require.register("gss/lib/gssom/Node.js", function(exports, require, module){
});
require.register("gss/lib/gssom/StyleSheet.js", function(exports, require, module){
var Rule, StyleSheet,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Rule = GSS.Rule;
StyleSheet = (function(_super) {
__extends(StyleSheet, _super);
StyleSheet.prototype.isScoped = false;
/*
el: Node
engine: Engine
rules: []
isScoped: Boolean
*/
function StyleSheet(o) {
var key, tagName, val;
if (o == null) {
o = {};
}
StyleSheet.__super__.constructor.apply(this, arguments);
for (key in o) {
val = o[key];
this[key] = val;
}
if (!this.engine) {
throw new Error("StyleSheet needs engine");
}
this.engine.addStyleSheet(this);
GSS.styleSheets.push(this);
this.isRemote = false;
this.remoteSourceText = null;
if (this.el) {
tagName = this.el.tagName;
if (tagName === "LINK") {
this.isRemote = true;
}
}
this.rules = [];
if (o.rules) {
this.addRules(o.rules);
}
this.loadIfNeeded();
return this;
}
StyleSheet.prototype.addRules = function(rules) {
var r, rule, _i, _len, _results;
this.setNeedsInstall(true);
_results = [];
for (_i = 0, _len = rules.length; _i < _len; _i++) {
r = rules[_i];
r.parent = this;
r.styleSheet = this;
r.engine = this.engine;
rule = new GSS.Rule(r);
_results.push(this.rules.push(rule));
}
return _results;
};
StyleSheet.prototype.isLoading = false;
StyleSheet.prototype.needsLoad = true;
StyleSheet.prototype.reload = function() {
this.destroyRules();
return this._load();
};
StyleSheet.prototype.loadIfNeeded = function() {
if (this.needsLoad) {
this.needsLoad = false;
this._load();
}
return this;
};
StyleSheet.prototype._load = function() {
if (this.isRemote) {
return this._loadRemote();
} else if (this.el) {
return this._loadInline();
}
};
StyleSheet.prototype._loadInline = function() {
return this.addRules(GSS.get.readAST(this.el));
};
StyleSheet.prototype._loadRemote = function() {
var req, url,
_this = this;
if (this.remoteSourceText) {
return this.addRules(GSS.compile(this.remoteSourceText));
}
url = this.el.getAttribute('href');
if (!url) {
return null;
}
req = new XMLHttpRequest;
req.onreadystatechange = function() {
if (req.readyState !== 4) {
return;
}
if (req.status !== 200) {
return;
}
_this.remoteSourceText = req.responseText.trim();
_this.addRules(GSS.compile(_this.remoteSourceText));
_this.isLoading = false;
return _this.trigger('loaded');
};
this.isLoading = true;
req.open('GET', url, true);
return req.send(null);
};
StyleSheet.prototype.needsInstall = false;
StyleSheet.prototype.setNeedsInstall = function(bool) {
if (bool) {
this.engine.setNeedsUpdate(true);
return this.needsInstall = true;
} else {
return this.needsInstall = false;
}
};
StyleSheet.prototype.install = function() {
if (this.needsInstall) {
this.setNeedsInstall(false);
return this._install();
}
};
StyleSheet.prototype.reinstall = function() {
return this._install();
};
StyleSheet.prototype._install = function() {
var rule, _i, _len, _ref, _results;
_ref = this.rules;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
rule = _ref[_i];
_results.push(rule.install());
}
return _results;
};
StyleSheet.prototype.reset = function() {
var rule, _i, _len, _ref, _results;
this.setNeedsInstall(true);
_ref = this.rules;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
rule = _ref[_i];
_results.push(rule.reset());
}
return _results;
};
StyleSheet.prototype.destroyRules = function() {
var rule, _i, _len, _ref;
_ref = this.rules;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
rule = _ref[_i];
rule.destroy();
}
return this.rules = [];
};
StyleSheet.prototype.destroy = function() {
var i;
i = this.engine.styleSheets.indexOf(this);
this.engine.styleSheets.splice(i, 1);
i = GSS.styleSheets.indexOf(this);
return GSS.styleSheets.splice(i, 1);
};
StyleSheet.prototype.isRemoved = function() {
if (this.el && !document.body.contains(this.el) && !document.head.contains(this.el)) {
return true;
}
return false;
};
StyleSheet.prototype.needsDumpCSS = false;
StyleSheet.prototype.setNeedsDumpCSS = function(bool) {
if (bool) {
this.engine.setNeedsDumpCSS(true);
return this.needsDumpCSS = true;
} else {
return this.needsDumpCSS = false;
}
};
StyleSheet.prototype.dumpCSSIfNeeded = function() {
if (this.needsDumpCSS) {
return this.dumpCSS();
}
};
StyleSheet.prototype.dumpCSS = function() {
var css, rule, ruleCSS, _i, _len, _ref;
css = "";
_ref = this.rules;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
rule = _ref[_i];
ruleCSS = rule.dumpCSS();
if (ruleCSS) {
css = css + ruleCSS;
}
}
return css;
};
return StyleSheet;
})(GSS.EventTrigger);
StyleSheet.fromNode = function(node) {
var engine, sheet;
if (node.gssStyleSheet) {
return node.gssStyleSheet;
}
engine = GSS({
scope: GSS.get.scopeForStyleNode(node)
});
sheet = new GSS.StyleSheet({
el: node,
engine: engine,
engineId: engine.id
});
node.gssStyleSheet = sheet;
return sheet;
};
StyleSheet.Collection = (function() {
function Collection() {
var collection, key, val;
collection = [];
for (key in this) {
val = this[key];
collection[key] = val;
}
return collection;
}
Collection.prototype.install = function() {
var sheet, _i, _len;
for (_i = 0, _len = this.length; _i < _len; _i++) {
sheet = this[_i];
sheet.install();
}
return this;
};
Collection.prototype.find = function() {
var node, nodes, sheet, _i, _len;
nodes = document.querySelectorAll('[type="text/gss"], [type="text/gss-ast"]');
for (_i = 0, _len = nodes.length; _i < _len; _i++) {
node = nodes[_i];
sheet = GSS.StyleSheet.fromNode(node);
}
return this;
};
Collection.prototype.findAllRemoved = function() {
var removed, sheet, _i, _len;
removed = [];
for (_i = 0, _len = this.length; _i < _len; _i++) {
sheet = this[_i];
if (sheet.isRemoved()) {
removed.push(sheet);
}
}
return removed;
};
return Collection;
})();
GSS.StyleSheet = StyleSheet;
GSS.styleSheets = new GSS.StyleSheet.Collection();
module.exports = StyleSheet;
});
require.register("gss/lib/gssom/Rule.js", function(exports, require, module){
var Rule, _rule_cid;
_rule_cid = 0;
Rule = (function() {
Rule.prototype.isRule = true;
function Rule(o) {
var key, val;
_rule_cid++;
this.cid = _rule_cid;
for (key in o) {
val = o[key];
this[key] = val;
}
this.boundConditionals = [];
if (this.name === 'else' || this.name === 'elseif' || this.name === "if") {
this.isConditional = true;
}
/*
@rules
@commands
@selectors
@type
@parent
@styleSheet
@isApplied
*/
this.rules = [];
if (o.rules) {
this.addRules(o.rules);
}
this.Type = Rule.types[this.type] || (function() {
throw new Error("Rule type, " + type + ", not found");
})();
this;
}
Rule.prototype.addRules = function(rules) {
var r, rule, _i, _len, _results;
_results = [];
for (_i = 0, _len = rules.length; _i < _len; _i++) {
r = rules[_i];
r.parent = this;
r.styleSheet = this.styleSheet;
r.engine = this.engine;
rule = new GSS.Rule(r);
_results.push(this.rules.push(rule));
}
return _results;
};
Rule.prototype._selectorContext = null;
Rule.prototype.needsInstall = true;
Rule.prototype.install = function() {
var rule, _i, _len, _ref;
if (this.needsInstall) {
this.needsInstall = false;
this.Type.install.call(this);
}
_ref = this.rules;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
rule = _ref[_i];
rule.install();
}
return this;
};
Rule.prototype.uninstall = function() {};
Rule.prototype.reset = function() {
var rule, _i, _len, _ref, _results;
this.needsInstall = true;
this.boundConditionals = [];
_ref = this.rules;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
rule = _ref[_i];
_results.push(rule.reset());
}
return _results;
};
Rule.prototype.destroy = function() {
this.rules = null;
this.commands = null;
this.engine = null;
this.parent = null;
this.styleSheet = null;
return this.boundConditionals = null;
};
Rule.prototype.executeCommands = function() {
if (this.commands) {
return this.engine.run(this);
}
};
Rule.prototype.nextSibling = function() {
var i;
i = this.parent.rules.indexOf(this);
return this.parent.rules[i + 1];
};
Rule.prototype.prevSibling = function() {
var i;
i = this.parent.rules.indexOf(this);
return this.parent.rules[i - 1];
};
Rule.prototype.getSelectorContext = function() {
if (!this._selectorContext) {
this._selectorContext = this._computeSelectorContext();
}
return this._selectorContext;
};
Rule.prototype._computeSelectorContext = function() {
var $, $$, parent, rule, selectorContext, _context, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2;
selectorContext = [];
rule = this;
while (rule.parent) {
parent = rule.parent;
if (!parent.isConditional) {
if ((parent != null ? (_ref = parent.selectors) != null ? _ref.length : void 0 : void 0) > 0) {
if (selectorContext.length === 0) {
_ref1 = parent.selectors;
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
$ = _ref1[_i];
selectorContext.push($);
}
} else {
_context = [];
_ref2 = parent.selectors;
for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
$ = _ref2[_j];
for (_k = 0, _len2 = selectorContext.length; _k < _len2; _k++) {
$$ = selectorContext[_k];
_context.push($ + " " + $$);
}
}
selectorContext = _context;
}
}
}
rule = parent;
}
this.selectorContext = selectorContext;
return selectorContext;
};
Rule.prototype.getContextQuery = function() {
if (!this.query) {
return this.setupContextQuery();
}
return this.query;
};
Rule.prototype.setupContextQuery = function() {
var effectiveSelector, engine;
effectiveSelector = this.getSelectorContext().join(", ");
engine = this.engine;
return this.query = engine.registerDomQuery({
selector: effectiveSelector,
isMulti: true,
isLive: false,
createNodeList: function() {
return engine.queryScope.querySelectorAll(effectiveSelector);
}
});
};
Rule.prototype.gatherCondCommand = function() {
var command, next, nextIsConditional;
command = ["cond"];
next = this;
nextIsConditional = true;
while (nextIsConditional) {
command.push(next.getClauseCommand());
next = next.nextSibling();
nextIsConditional = next != null ? next.isConditional : void 0;
}
return command;
};
Rule.prototype.getClauseCommand = function() {
return ["clause", this.clause, this.getClauseTracker()];
};
Rule.prototype.getClauseTracker = function() {
return "gss-cond-" + this.cid;
};
Rule.prototype.injectChildrenCondtionals = function(conditional) {
var command, rule, _i, _j, _len, _len1, _ref, _ref1, _results;
_ref = this.rules;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
rule = _ref[_i];
rule.boundConditionals.push(conditional);
if (rule.commands) {
_ref1 = rule.commands;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
command = _ref1[_j];
command.push(["where", conditional.getClauseTracker()]);
}
}
rule.isCondtionalBound = true;
_results.push(rule.injectChildrenCondtionals(conditional));
}
return _results;
};
Rule.prototype.setNeedsDumpCSS = function(bool) {
if (bool) {
return this.styleSheet.setNeedsDumpCSS(true);
}
};
Rule.prototype.dumpCSS = function() {
var css, rule, ruleCSS, _i, _len, _ref, _ref1;
css = (_ref = this.Type.dumpCSS) != null ? _ref.call(this) : void 0;
_ref1 = this.rules;
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
rule = _ref1[_i];
ruleCSS = rule.dumpCSS();
if (ruleCSS) {
css = css + ruleCSS;
}
}
return css;
};
return Rule;
})();
Rule.types = {
directive: {
install: function() {
if (this.name === 'else' || this.name === 'elseif') {
this.injectChildrenCondtionals(this);
return this;
} else if (this.name === 'if') {
this.commands = [this.gatherCondCommand()];
this.injectChildrenCondtionals(this);
return this.executeCommands();
} else {
return this.executeCommands();
}
}
},
constraint: {
install: function() {
return this.executeCommands();
}
},
style: {
install: function() {
return this.setNeedsDumpCSS(true);
},
dumpCSS: function() {}
},
ruleset: {
install: function() {},
dumpCSS: function() {
var css, effectiveSelector, foundStyle, rule, _i, _len, _ref;
foundStyle = false;
css = "";
effectiveSelector = null;
_ref = this.rules;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
rule = _ref[_i];
if (rule.type === "style") {
if (!foundStyle) {
effectiveSelector = rule.getSelectorContext().join(", ");
foundStyle = true;
}
css = css + rule.key + ":" + rule.val + ";";
}
}
if (foundStyle) {
css = effectiveSelector + "{" + css + "}";
}
return css;
}
}
};
module.exports = Rule;
});
require.register("gss/lib/Engine.js", function(exports, require, module){
var Engine, LOG, TIME, TIME_END, engines, _,
__slice = [].slice,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
if (typeof GSS === "undefined" || GSS === null) {
throw new Error("GSS object needed for Engine");
}
_ = GSS._;
TIME = function() {
if (GSS.config.perf) {
return console.time.apply(console, arguments);
}
};
TIME_END = function() {
if (GSS.config.perf) {
return console.timeEnd.apply(console, arguments);
}
};
LOG = function() {
return GSS.deblog.apply(GSS, ["Engine"].concat(__slice.call(arguments)));
};
GSS.engines = engines = [];
engines.byId = {};
engines.root = null;
Engine = (function(_super) {
__extends(Engine, _super);
function Engine(o) {
if (o == null) {
o = {};
}
this.dispatch = __bind(this.dispatch, this);
this.updateQueries = __bind(this.updateQueries, this);
this.handleWorkerMessage = __bind(this.handleWorkerMessage, this);
this.reset = __bind(this.reset, this);
Engine.__super__.constructor.apply(this, arguments);
this.scope = o.scope, this.workerURL = o.workerURL, this.vars = o.vars, this.getter = o.getter, this.is_root = o.is_root, this.useWorker = o.useWorker;
if (!this.vars) {
this.vars = {};
}
this.clauses = null;
if (!GSS.config.useWorker) {
this.useWorker = false;
} else {
if (this.useWorker == null) {
this.useWorker = true;
}
}
this.worker = null;
this.workerCommands = [];
this.workerMessageHistory = [];
if (!this.workerURL) {
this.workerURL = GSS.config.worker;
}
if (this.scope) {
if (this.scope.tagName === "HEAD") {
this.scope = document;
}
this.id = GSS.setupScopeId(this.scope);
if (this.scope === GSS.Getter.getRootScope()) {
this.queryScope = document;
} else {
this.queryScope = this.scope;
}
} else {
this.id = GSS.uid();
this.queryScope = document;
}
if (!this.getter) {
this.getter = new GSS.Getter(this.scope);
}
this.commander = new GSS.Commander(this);
this.lastWorkerCommands = null;
this.cssDump = null;
GSS.engines.push(this);
engines.byId[this.id] = this;
this._Hierarchy_setup();
this._Queries_setup();
this._StyleSheets_setup();
LOG("constructor() @", this);
this;
}
Engine.prototype.getVarsById = function(vars) {
var varsById;
if (GSS.config.processBeforeSet) {
vars = GSS.config.processBeforeSet(vars);
}
return varsById = _.varsByViewId(_.filterVarsForDisplay(vars));
};
Engine.prototype.isDescendantOf = function(engine) {
var parentEngine;
parentEngine = this.parentEngine;
while (parentEngine) {
if (parentEngine === engine) {
return true;
}
parentEngine = parentEngine.parentEngine;
}
return false;
};
Engine.prototype._Hierarchy_setup = function() {
var _ref;
this.childEngines = [];
this.parentEngine = null;
if (this.is_root) {
engines.root = this;
} else if (this.scope) {
this.parentEngine = GSS.get.nearestEngine(this.scope, true);
} else {
this.parentEngine = engines.root;
}
if (!this.parentEngine && !this.is_root) {
throw new Error("ParentEngine missing, WTF");
}
return (_ref = this.parentEngine) != null ? _ref.childEngines.push(this) : void 0;
};
Engine.prototype._Hierarchy_destroy = function() {
this.parentEngine.childEngines.splice(this.parentEngine.childEngines.indexOf(this), 1);
return this.parentEngine = null;
};
Engine.prototype.is_running = false;
Engine.prototype.run = function(asts) {
var ast, _i, _len, _results;
LOG(this.id, ".run(asts)", asts);
if (asts instanceof Array) {
_results = [];
for (_i = 0, _len = asts.length; _i < _len; _i++) {
ast = asts[_i];
_results.push(this._run(ast));
}
return _results;
} else {
return this._run(asts);
}
};
Engine.prototype._run = function(ast) {
return this.commander.execute(ast);
};
Engine.prototype.load = function() {
var sheet, _i, _len, _ref, _results;
if (!this.scope) {
throw new Error("can't load scopeless engine");
}
if (this.is_running) {
this.clean();
}
_ref = this.styleSheets;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
sheet = _ref[_i];
_results.push(sheet.execute());
}
return _results;
};
Engine.prototype.reset = function() {
var sheet, styleSheets, _i, _len;
LOG(this.id, ".reset()");
if (!this.scope) {
throw new Error("can't reset scopeless engine");
}
styleSheets = this.styleSheets;
if (this.is_running) {
this.clean();
}
this.styleSheets = styleSheets;
for (_i = 0, _len = styleSheets.length; _i < _len; _i++) {
sheet = styleSheets[_i];
sheet.reset();
}
this.setNeedsUpdate(true);
return this;
};
Engine.prototype.registerCommands = function(commands) {
var command, _i, _len, _results;
_results = [];
for (_i = 0, _len = commands.length; _i < _len; _i++) {
command = commands[_i];
_results.push(this.registerCommand(command));
}
return _results;
};
Engine.prototype.registerCommand = function(command) {
this.workerCommands.push(command);
this.setNeedsLayout(true);
return this;
};
Engine.prototype._StyleSheets_setup = function() {
return this.styleSheets = [];
};
Engine.prototype.addStyleSheet = function(sheet) {
this.setNeedsUpdate(true);
return this.styleSheets.push(sheet);
};
Engine.prototype.needsUpdate = false;
Engine.prototype.setNeedsUpdate = function(bool) {
if (bool) {
GSS.setNeedsUpdate(true);
return this.needsUpdate = true;
} else {
return this.needsUpdate = false;
}
};
Engine.prototype.updateIfNeeded = function() {
var _this = this;
if (this.needsUpdate) {
this._whenReadyForUpdate(function() {
var sheet, _i, _len, _ref;
_ref = _this.styleSheets;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
sheet = _ref[_i];
sheet.install();
}
return _this.updateChildrenIfNeeded();
});
return this.setNeedsUpdate(false);
} else {
return this.updateChildrenIfNeeded();
}
};
Engine.prototype._whenReadyForUpdate = function(cb) {
var loadingCount, sheet, _i, _len, _ref,
_this = this;
loadingCount = 0;
_ref = this.styleSheets;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
sheet = _ref[_i];
if (sheet.isLoading) {
loadingCount++;
sheet.once("loaded", function() {
loadingCount--;
if (loadingCount === 0) {
return cb.call(_this);
}
});
}
}
if (loadingCount === 0) {
cb.call(this);
}
return this;
};
Engine.prototype.updateChildrenIfNeeded = function() {
var child, _i, _len, _ref, _results;
_ref = this.childEngines;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
child = _ref[_i];
_results.push(child.updateIfNeeded());
}
return _results;
};
Engine.prototype.needsLayout = false;
Engine.prototype.setNeedsLayout = function(bool) {
if (bool) {
if (!this.needsLayout) {
GSS.setNeedsLayout(true);
return this.needsLayout = true;
}
} else {
return this.needsLayout = false;
}
};
Engine.prototype._beforeLayoutCalls = null;
Engine.prototype.layout = function() {
this.hoistedTrigger("beforeLayout", this);
this.is_running = true;
TIME("" + this.id + " LAYOUT & DISPLAY");
this.dumpCSSIfNeeded();
this.solve();
return this.setNeedsLayout(false);
};
Engine.prototype.layoutIfNeeded = function() {
if (this.needsLayout) {
this.layout();
}
return this.layoutSubTreeIfNeeded();
};
Engine.prototype.waitingToLayoutSubtree = false;
Engine.prototype.layoutSubTreeIfNeeded = function() {
var child, _i, _len, _ref, _results;
this.waitingToLayoutSubtree = false;
_ref = this.childEngines;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
child = _ref[_i];
_results.push(child.layoutIfNeeded());
}
return _results;
};
Engine.prototype.needsDisplay = false;
Engine.prototype.setNeedsDisplay = function(bool) {
if (bool) {
GSS.setNeedsDisplay(true);
return this.needsDisplay = true;
} else {
return this.needsDisplay = false;
}
};
/*
displayIfNeeded: () ->
LOG @, "displayIfNeeded"
if @needsDisplay #@workerCommands.length > 0
@display(@vars)
@setNeedsDisplay false
for child in @childEngines
child.displayIfNeeded()
*/
Engine.prototype.display = function(data, forceViewCacheById) {
var el, id, needsToDisplayViews, obj, vars, varsById, _ref;
if (forceViewCacheById == null) {
forceViewCacheById = false;
}
vars = data.values;
LOG(this.id, ".display()");
this.hoistedTrigger("beforeDisplay", this);
GSS.unobserve();
varsById = this.getVarsById(vars);
needsToDisplayViews = false;
for (id in varsById) {
obj = varsById[id];
needsToDisplayViews = true;
if (forceViewCacheById) {
el = document.getElementById(id);
if (el) {
GSS.setupId(el);
}
}
if ((_ref = GSS.View.byId[id]) != null) {
if (typeof _ref.updateValues === "function") {
_ref.updateValues(obj);
}
}
}
if (needsToDisplayViews) {
if (this.scope) {
GSS.get.view(this.scope).displayIfNeeded();
}
}
if (!this.isMeasuring && this.needsMeasure) {
this.measureIfNeeded();
if (!this.needsLayout) {
this._didDisplay();
}
} else {
this._didDisplay();
}
GSS.observe();
this.dispatchedTrigger("solved", {
values: vars
});
TIME_END("" + this.id + " LAYOUT & DISPLAY");
return this;
};
Engine.prototype._didDisplay = function() {
this.trigger("display");
GSS.onDisplay();
return this.isMeasuring = false;
};
Engine.prototype.forceDisplay = function(vars) {};
Engine.prototype.updateClauses = function(clauses) {
var clause, html, nue, old, _i, _j, _k, _len, _len1, _len2;
html = GSS.html;
old = this.clauses;
nue = clauses;
if (old) {
for (_i = 0, _len = old.length; _i < _len; _i++) {
clause = old[_i];
if (nue.indexOf(clause) === -1) {
html.classList.remove(clause);
}
}
for (_j = 0, _len1 = nue.length; _j < _len1; _j++) {
clause = nue[_j];
if (old.indexOf(clause) === -1) {
html.classList.add(clause);
}
}
} else {
for (_k = 0, _len2 = nue.length; _k < _len2; _k++) {
clause = nue[_k];
html.classList.add(clause);
}
}
return this.clauses = nue;
};
Engine.prototype.isMeasuring = false;
Engine.prototype.needsMeasure = false;
Engine.prototype.setNeedsMeasure = function(bool) {
if (bool) {
return this.needsMeasure = true;
} else {
return this.needsMeasure = false;
}
};
Engine.prototype.measureIfNeeded = function() {
if (this.needsMeasure) {
this.isMeasuring = true;
this.needsMeasure = false;
return this.measure();
}
};
Engine.prototype.measure = function() {
return this.commander.validateMeasures();
};
Engine.prototype.measureByGssId = function(id, prop) {
var el, val;
el = GSS.getById(id);
val = this.getter.measure(el, prop);
LOG(this.id, ".measureByGssId()", id, prop, val);
return val;
};
Engine.prototype.solve = function() {
if (this.useWorker) {
return this.solveWithWorker();
} else {
return this.solveWithoutWorker();
}
};
Engine.prototype.solveWithWorker = function() {
var workerMessage;
LOG(this.id, ".solveWithWorker()", this.workerCommands);
workerMessage = {
commands: this.workerCommands
};
this.workerMessageHistory.push(workerMessage);
if (!this.worker) {
this.worker = new Worker(this.workerURL);
this.worker.addEventListener("message", this.handleWorkerMessage, false);
this.worker.addEventListener("error", this.handleError, false);
workerMessage.config = {
defaultStrength: GSS.config.defaultStrength,
defaultWeight: GSS.config.defaultWeight
};
}
this.worker.postMessage(workerMessage);
this.lastWorkerCommands = this.workerCommands;
return this.workerCommands = [];
};
Engine.prototype.solveWithoutWorker = function() {
var workerMessage,
_this = this;
LOG(this.id, ".solveWithoutWorker()", this.workerCommands);
workerMessage = {
commands: this.workerCommands
};
this.workerMessageHistory.push(workerMessage);
if (!this.worker) {
this.worker = new GSS.Thread({
defaultStrength: GSS.config.defaultStrength,
defaultWeight: GSS.config.defaultWeight
});
}
this.worker.postMessage(_.cloneDeep(workerMessage));
_.defer(function() {
if (_this.worker) {
return _this.handleWorkerMessage({
data: _this.worker.output()
});
}
});
this.lastWorkerCommands = this.workerCommands;
return this.workerCommands = [];
};
Engine.prototype.handleWorkerMessage = function(message) {
LOG(this.id, ".handleWorkerMessage()", this.workerCommands);
this.vars = message.data.values;
return this.display(message.data);
};
Engine.prototype.handleError = function(event) {
if (this.onError) {
return this.onError(event);
}
throw new Error("" + event.message + " (" + event.filename + ":" + event.lineno + ")");
};
Engine.prototype._Worker_destroy = function() {
if (this.worker) {
this.worker.terminate();
this.worker = null;
}
this.workerCommands = null;
this.workerMessageHistory = null;
return this.lastWorkerCommands = null;
};
Engine.prototype._Worker_clean = function() {
this.workerCommands = [];
this.lastWorkerCommands = null;
if (this.worker) {
this.worker.terminate();
return this.worker = null;
}
};
Engine.prototype._Queries_setup = function() {
var _this = this;
this.querySet = new GSS.Query.Set();
return this.querySet.on("update", function(o) {
_this.commander.handleRemoves(o.removes);
return _this.commander.handleSelectorsWithAdds(o.selectorsWithAdds);
});
};
Engine.prototype.getDomQuery = function(selector) {
return this.querySet.bySelector[selector];
};
Engine.prototype.registerDomQuery = function(o) {
return this.querySet.add(o);
};
Engine.prototype.updateQueries = function() {
return this.querySet.update();
};
Engine.prototype._Queries_destroy = function() {
return this.querySet.destroy();
};
Engine.prototype._Queries_clean = function() {
return this.querySet.clean();
};
Engine.prototype.hoistedTrigger = function(ev, obj) {
this.trigger(ev, obj);
return GSS.trigger("engine:" + ev, obj);
};
Engine.prototype.dispatchedTrigger = function(e, o, b, c) {
this.trigger(e, o);
return this.dispatch(e, o, b, c);
};
Engine.prototype.dispatch = function(eName, oDetail, bubbles, cancelable) {
var e, o;
if (oDetail == null) {
oDetail = {};
}
if (bubbles == null) {
bubbles = true;
}
if (cancelable == null) {
cancelable = true;
}
if (!this.scope) {
return;
}
oDetail.engine = this;
o = {
detail: oDetail,
bubbles: bubbles,
cancelable: cancelable
};
e = new CustomEvent(eName, o);
return this.scope.dispatchEvent(e);
};
Engine.prototype.cssToDump = null;
Engine.prototype.cssDump = null;
Engine.prototype.setupCSSDumpIfNeeded = function() {
var dumpNode;
dumpNode = this.scope || document.body;
if (!this.cssDump) {
this.cssDump = document.createElement("style");
this.cssDump.id = "gss-css-dump-" + this.id;
return dumpNode.appendChild(this.cssDump);
}
};
Engine.prototype.needsDumpCSS = false;
Engine.prototype.setNeedsDumpCSS = function(bool) {
if (bool) {
this.setNeedsLayout(true);
return this.needsDumpCSS = true;
} else {
return this.needsDumpCSS = false;
}
};
Engine.prototype.dumpCSSIfNeeded = function() {
var css, sheet, sheetCSS, _i, _len, _ref;
if (this.needsDumpCSS) {
this.needsDumpCSS = false;
this.setupCSSDumpIfNeeded();
css = "";
_ref = this.styleSheets;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
sheet = _ref[_i];
sheetCSS = sheet.dumpCSSIfNeeded();
if (sheetCSS) {
css = css + sheetCSS;
}
}
if (css.length > 0) {
return this.cssDump.innerHTML = css;
}
}
};
Engine.prototype._CSSDumper_clean = function() {
var _ref;
return (_ref = this.cssDump) != null ? _ref.innerHTML = "" : void 0;
};
Engine.prototype._CSSDumper_destroy = function() {
this.needsDumpCSS = false;
return this.cssDump = null;
};
Engine.prototype.clean = function() {
var key, val, _base, _ref;
LOG(this.id, ".clean()");
_ref = this.vars;
for (key in _ref) {
val = _ref[key];
delete this.vars[key];
}
this.setNeedsLayout(false);
this.setNeedsDisplay(false);
this.setNeedsLayout(false);
this.setNeedsMeasure(false);
this.isMeasuring = false;
this.waitingToLayoutSubtree = false;
this.commander.clean();
if (typeof (_base = this.getter).clean === "function") {
_base.clean();
}
this._CSSDumper_clean();
this._Worker_clean();
this._Queries_clean();
return this;
};
Engine.prototype.is_destroyed = false;
Engine.prototype.destroyChildren = function() {
var e, _i, _len, _ref, _results;
_ref = this.childEngines;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
e = _ref[_i];
if (!e.is_destroyed) {
_results.push(e.destroy());
} else {
_results.push(void 0);
}
}
return _results;
};
Engine.prototype.destroy = function() {
var d, descdendants, i, kill, _base, _i, _len;
LOG(this.id, ".destroy()");
this.hoistedTrigger("beforeDestroy", this);
GSS._ids_killed([this.id]);
if (this.scope) {
descdendants = GSS.get.descdendantNodes(this.scope);
for (_i = 0, _len = descdendants.length; _i < _len; _i++) {
d = descdendants[_i];
kill = d._gss_id;
if (kill) {
GSS._id_killed(kill);
}
}
}
i = engines.indexOf(this);
if (i > -1) {
engines.splice(i, 1);
}
delete engines.byId[this.id];
this.offAll();
this.setNeedsLayout(false);
this.setNeedsDisplay(false);
this.setNeedsLayout(false);
this.waitingToLayoutSubtree = false;
this.commander.destroy();
if (typeof (_base = this.getter).destroy === "function") {
_base.destroy();
}
this.vars = null;
this.clauses = null;
this.ast = null;
this.getter = null;
this.scope = null;
this.commander = null;
this._Hierarchy_destroy();
this._CSSDumper_destroy();
this._Worker_destroy();
this._Queries_destroy();
this.is_running = null;
this.is_destroyed = true;
return this;
};
Engine.prototype.elVar = function(el, key, selector, tracker2) {
var ast, gid, varid;
gid = "$" + GSS.getId(el);
if (key === 'left') {
key = 'x';
} else if (key === 'top') {
key = 'y';
}
varid = gid + ("[" + key + "]");
ast = ['get$', key, gid, selector];
if (tracker2) {
ast.push(tracker2);
}
return ast;
};
Engine.prototype["var"] = function(key) {
return ['get', key];
};
Engine.prototype.varexp = function(key, exp, tracker) {
return ['get', key];
};
Engine.prototype.__e = function(key) {
if (key instanceof Array) {
return key;
}
if (!!Number(key) || (Number(key) === 0)) {
return ['number', key];
}
return this["var"](key);
};
Engine.prototype._addconstraint = function(op, e1, e2, s, w, more) {
var command, m, _i, _len;
e1 = this.__e(e1);
e2 = this.__e(e2);
command = ['eq', e1, e2];
if (s) {
command.push(s);
}
if (w) {
command.push(w);
}
if (more) {
for (_i = 0, _len = more.length; _i < _len; _i++) {
m = more[_i];
command.push(m);
}
}
return this.registerCommand(command);
};
Engine.prototype.eq = function(e1, e2, s, w, more) {
return this._addconstraint('eq', e1, e2, s, w, more);
};
Engine.prototype.lte = function(e1, e2, s, w, more) {
return this._addconstraint('lte', e1, e2, s, w, more);
};
Engine.prototype.gte = function(e1, e2, s, w, more) {
return this._addconstraint('gte', e1, e2, s, w, more);
};
Engine.prototype.suggest = function(v, val, strength) {
if (strength == null) {
strength = 'required';
}
v = this.__e(v);
return this.registerCommand(['suggest', v, ['number', val], strength]);
};
Engine.prototype.stay = function(v) {
v = this.__e(v);
return this.registerCommand(['stay', v]);
};
Engine.prototype.remove = function(tracker) {
return this.registerCommand(['remove', tracker]);
};
Engine.prototype['number'] = function(num) {
return ['number', num];
};
Engine.prototype['plus'] = function(e1, e2) {
e1 = this.__e(e1);
e2 = this.__e(e2);
return ['plus', e1, e2];
};
Engine.prototype['minus'] = function(e1, e2) {
e1 = this.__e(e1);
e2 = this.__e(e2);
return ['minus', e1, e2];
};
Engine.prototype['multiply'] = function(e1, e2) {
e1 = this.__e(e1);
e2 = this.__e(e2);
return ['multiply', e1, e2];
};
Engine.prototype['divide'] = function(e1, e2, s, w) {
e1 = this.__e(e1);
e2 = this.__e(e2);
return ['divide', e1, e2];
};
return Engine;
})(GSS.EventTrigger);
module.exports = Engine;
});
require.register("gss/lib/Commander.js", function(exports, require, module){
/*
Root commands, if bound to a dom query, will spawn commands
to match live results of query.
*/
var Commander, bindRoot, bindRootAsContext, bindRootAsMulti,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__slice = [].slice;
bindRoot = function(root, query) {
root.isQueryBound = true;
if (!root.queries) {
root.queries = [query];
} else if (root.queries.indexOf(query) === -1) {
root.queries.push(query);
}
return root;
};
bindRootAsMulti = function(root, query) {
bindRoot(root, query);
if (root.queries.multi && root.queries.multi !== query) {
throw new Error("bindRoot:: only one multiquery per statement");
}
return root.queries.multi = query;
};
bindRootAsContext = function(root, query) {
bindRoot(root, query);
return root.isContextBound = true;
};
Commander = (function() {
function Commander(engine) {
this.engine = engine;
this['js'] = __bind(this['js'], this);
this['for-all'] = __bind(this['for-all'], this);
this['for-each'] = __bind(this['for-each'], this);
this._e_for_chain = __bind(this._e_for_chain, this);
this._chainer_math = __bind(this._chainer_math, this);
this['divide-chain'] = __bind(this['divide-chain'], this);
this['multiply-chain'] = __bind(this['multiply-chain'], this);
this['minus-chain'] = __bind(this['minus-chain'], this);
this['plus-chain'] = __bind(this['plus-chain'], this);
this._chainer = __bind(this._chainer, this);
this['gt-chain'] = __bind(this['gt-chain'], this);
this['lt-chain'] = __bind(this['lt-chain'], this);
this['gte-chain'] = __bind(this['gte-chain'], this);
this['lte-chain'] = __bind(this['lte-chain'], this);
this['eq-chain'] = __bind(this['eq-chain'], this);
this['chain'] = __bind(this['chain'], this);
this['$reserved'] = __bind(this['$reserved'], this);
this['$id'] = __bind(this['$id'], this);
this['$tag'] = __bind(this['$tag'], this);
this['$class'] = __bind(this['$class'], this);
this['$virtual'] = __bind(this['$virtual'], this);
this['virtual'] = __bind(this['virtual'], this);
this['stay'] = __bind(this['stay'], this);
this['gt'] = __bind(this['gt'], this);
this['lt'] = __bind(this['lt'], this);
this['gte'] = __bind(this['gte'], this);
this['lte'] = __bind(this['lte'], this);
this['eq'] = __bind(this['eq'], this);
this['suggest'] = __bind(this['suggest'], this);
this['strength'] = __bind(this['strength'], this);
this["||"] = __bind(this["||"], this);
this["&&"] = __bind(this["&&"], this);
this["?<"] = __bind(this["?<"], this);
this["?>"] = __bind(this["?>"], this);
this["?!="] = __bind(this["?!="], this);
this["?=="] = __bind(this["?=="], this);
this["?<="] = __bind(this["?<="], this);
this["?>="] = __bind(this["?>="], this);
this["clause"] = __bind(this["clause"], this);
this["where"] = __bind(this["where"], this);
this["cond"] = __bind(this["cond"], this);
this['divide'] = __bind(this['divide'], this);
this['multiply'] = __bind(this['multiply'], this);
this['minus'] = __bind(this['minus'], this);
this['plus'] = __bind(this['plus'], this);
this['_get$'] = __bind(this['_get$'], this);
this['get$'] = __bind(this['get$'], this);
this['get'] = __bind(this['get'], this);
this.spawnForWindowSize = __bind(this.spawnForWindowSize, this);
this._execute = __bind(this._execute, this);
this.lazySpawnForWindowSize = GSS._.debounce(this.spawnForWindowSize, GSS.config.resizeDebounce, false);
this.cleanVars();
}
Commander.prototype.clean = function() {
this.cleanVars();
return this.unlisten();
};
Commander.prototype.cleanVars = function() {
this.spawnableRoots = [];
this.intrinsicRegistersById = {};
this.boundWindowProps = [];
this.get$cache = {};
return this.queryCommandCache = {};
};
Commander.prototype.destroy = function() {
this.spawnableRoots = null;
this.intrinsicRegistersById = null;
this.boundWindowProps = null;
this.get$cache = null;
this.queryCommandCache = null;
return this.unlisten();
};
Commander.prototype.execute = function(ast) {
var command, _i, _len, _ref, _results;
if (ast.commands != null) {
_ref = ast.commands;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
command = _ref[_i];
if (ast.isRule) {
command.parentRule = ast;
}
_results.push(this._execute(command, command));
}
return _results;
}
};
Commander.prototype._execute = function(command, root) {
var func, i, node, sub, _i, _len, _ref;
node = command;
func = this[node[0]];
if (func == null) {
throw new Error("Engine Commands broke, couldn't find method: " + node[0]);
}
_ref = node.slice(1, +node.length + 1 || 9e9);
for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
sub = _ref[i];
if (sub instanceof Array) {
node.splice(i + 1, 1, this._execute(sub, root));
}
}
return func.call.apply(func, [this.engine, root].concat(__slice.call(node.slice(1, node.length))));
};
Commander.prototype.unlisten = function() {
if (!this._bound_to_window_resize) {
window.removeEventListener("resize", this.lazySpawnForWindowSize, false);
}
return this._bound_to_window_resize = false;
};
Commander.prototype._bound_to_window_resize = false;
Commander.prototype.spawnForWindowWidth = function() {
var w;
w = window.innerWidth;
if (GSS.config.verticalScroll) {
w = w - GSS.get.scrollbarWidth();
}
if (this.engine.vars["::window[width]"] !== w) {
return this.engine.registerCommand(['suggest', ['get', "::window[width]"], ['number', w], 'required']);
}
};
Commander.prototype.spawnForWindowHeight = function() {
var h;
h = window.innerHeight;
if (GSS.config.horizontalScroll) {
h = h - GSS.get.scrollbarWidth();
}
if (this.engine.vars["::window[height]"] !== h) {
return this.engine.registerCommand(['suggest', ['get', "::window[height]"], ['number', h], 'required']);
}
};
Commander.prototype.spawnForWindowSize = function() {
if (this._bound_to_window_resize) {
if (this.boundWindowProps.indexOf('width') !== -1) {
this.spawnForWindowWidth();
}
if (this.boundWindowProps.indexOf('height') !== -1) {
this.spawnForWindowHeight();
}
return this.engine.solve();
}
};
Commander.prototype.bindToWindow = function(prop) {
if (prop === "center-x") {
this.bindToWindow("width");
this.engine.registerCommand(['eq', ['get', '::window[center-x]'], ['divide', ['get', '::window[width]'], 2], 'required']);
return null;
} else if (prop === "right") {
this.bindToWindow("width");
this.engine.registerCommand(['eq', ['get', '::window[right]'], ['get', '::window[width]'], 'required']);
return null;
} else if (prop === "center-y") {
this.bindToWindow("height");
this.engine.registerCommand(['eq', ['get', '::window[center-y]'], ['divide', ['get', '::window[height]'], 2], 'required']);
return null;
} else if (prop === "bottom") {
this.bindToWindow("width");
this.engine.registerCommand(['eq', ['get', '::window[bottom]'], ['get', '::window[height]'], 'required']);
return null;
}
if (this.boundWindowProps.indexOf(prop) === -1) {
this.boundWindowProps.push(prop);
}
if (prop === 'width' || prop === 'height') {
if (prop === 'width') {
this.spawnForWindowWidth();
} else {
this.spawnForWindowHeight();
}
if (!this._bound_to_window_resize) {
window.addEventListener("resize", this.lazySpawnForWindowSize, false);
return this._bound_to_window_resize = true;
}
} else if (prop === 'x') {
return this.engine.registerCommand(['eq', ['get', '::window[x]'], ['number', 0], 'required']);
} else if (prop === 'y') {
return this.engine.registerCommand(['eq', ['get', '::window[y]'], ['number', 0], 'required']);
}
};
Commander.prototype.spawnForScope = function(prop) {
var key, thisEngine;
key = "$" + this.engine.id + ("[" + prop + "]");
thisEngine = this.engine;
return GSS.on("engine:beforeDisplay", function(engine) {
var val;
val = engine.vars[key];
if (val != null) {
if (thisEngine.isDescendantOf(engine)) {
return thisEngine.registerCommand(['suggest', ['get', key], ['number', val], 'required']);
}
}
});
};
Commander.prototype.bindToScope = function(prop) {
return this.spawnForScope(prop);
/*
if prop is 'width' or prop is 'height'
if prop is 'width' then @spawnForScopeWidth() else @spawnForScopeHeight()
else if prop is 'x'
@engine.registerCommand ['eq', ['get', '::scope[x]'], ['number', 0], 'required']
else if prop is 'y'
@engine.registerCommand ['eq', ['get', '::scope[y]'], ['number', 0], 'required']
#else
# throw new Error "Not sure how to bind to window prop: #{prop}"
*/
};
Commander.prototype.handleRemoves = function(removes) {
var varid, _i, _len;
if (removes.length < 1) {
return this;
}
this.engine.registerCommand(['remove'].concat(__slice.call(removes)));
for (_i = 0, _len = removes.length; _i < _len; _i++) {
varid = removes[_i];
delete this.intrinsicRegistersById[varid];
}
return this;
};
Commander.prototype.handleSelectorsWithAdds = function(selectorsWithAdds) {
var query, root, _i, _j, _len, _len1, _ref, _ref1;
if (selectorsWithAdds.length < 1) {
return this;
}
_ref = this.spawnableRoots;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
root = _ref[_i];
_ref1 = root.queries;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
query = _ref1[_j];
if (selectorsWithAdds.indexOf(query.selector) !== -1) {
this.spawn(root);
break;
}
}
}
return this;
};
Commander.prototype.validateMeasures = function() {
var id, ids;
ids = [];
for (id in this.intrinsicRegistersById) {
ids.push(id);
}
return this.handleInvalidMeasures(ids);
};
Commander.prototype.handleInvalidMeasures = function(invalidMeasures) {
var id, prop, register, registersByProp, _i, _len;
if (invalidMeasures.length < 1) {
return this;
}
for (_i = 0, _len = invalidMeasures.length; _i < _len; _i++) {
id = invalidMeasures[_i];
registersByProp = this.intrinsicRegistersById[id];
if (registersByProp) {
for (prop in registersByProp) {
register = registersByProp[prop];
register.call(this);
}
}
}
return this;
};
/*
getWhereCommandIfNeeded: (rule) ->
# Condtional Bound`
if rule
if rule.isCondtionalBound & !rule.isConditional
whereCommand = ["where"]
for cond in rule.boundConditionals
whereCommand.push cond.getClauseTracker()
return whereCommand
else
return null
*/
Commander.prototype.registerSpawn = function(node) {
var newCommand, part, _i, _len;
if (!node.isQueryBound) {
newCommand = [];
for (_i = 0, _len = node.length; _i < _len; _i++) {
part = node[_i];
newCommand.push(part);
}
return this.engine.registerCommand(newCommand);
} else {
this.spawnableRoots.push(node);
return this.spawn(node);
}
};
Commander.prototype.spawn = function(node) {
var contextId, contextQuery, q, queries, ready, rule, _i, _j, _len, _len1, _ref, _results;
queries = node.queries;
ready = true;
for (_i = 0, _len = queries.length; _i < _len; _i++) {
q = queries[_i];
if (q.lastAddedIds.length <= 0) {
ready = false;
break;
}
}
if (ready) {
rule = node.parentRule;
if (node.isContextBound) {
contextQuery = rule.getContextQuery();
_ref = contextQuery.lastAddedIds;
_results = [];
for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
contextId = _ref[_j];
_results.push(this.engine.registerCommands(this.expandSpawnable(node, true, contextId)));
}
return _results;
} else {
return this.engine.registerCommands(this.expandSpawnable(node, true));
}
}
};
Commander.prototype.expandSpawnable = function(command, isRoot, contextId, tracker) {
var commands, hasPlural, i, j, newCommand, newPart, part, plural, pluralCommand, pluralLength, pluralPartLookup, _i, _j, _k, _len, _len1;
newCommand = [];
commands = [];
hasPlural = false;
pluralPartLookup = {};
plural = null;
pluralLength = 0;
for (i = _i = 0, _len = command.length; _i < _len; i = ++_i) {
part = command[i];
if (part) {
if (part.spawn != null) {
newPart = part.spawn(contextId);
newCommand.push(newPart);
if (part.isPlural) {
hasPlural = true;
pluralPartLookup[i] = newPart;
pluralLength = newPart.length;
}
} else {
newCommand.push(part);
}
}
}
if (isRoot) {
if (tracker) {
newCommand.push(tracker);
}
}
if (hasPlural) {
for (j = _j = 0; 0 <= pluralLength ? _j < pluralLength : _j > pluralLength; j = 0 <= pluralLength ? ++_j : --_j) {
pluralCommand = [];
for (i = _k = 0, _len1 = newCommand.length; _k < _len1; i = ++_k) {
part = newCommand[i];
if (pluralPartLookup[i]) {
pluralCommand.push(pluralPartLookup[i][j]);
} else {
pluralCommand.push(part);
}
}
commands.push(pluralCommand);
}
return commands;
} else {
if (isRoot) {
return [newCommand];
}
return newCommand;
}
};
Commander.prototype.makeNonRootSpawnableIfNeeded = function(command) {
var isPlural, isSpawnable, part, _i, _len,
_this = this;
isPlural = false;
for (_i = 0, _len = command.length; _i < _len; _i++) {
part = command[_i];
if (part) {
if (part.spawn != null) {
isSpawnable = true;
if (part.isPlural) {
isPlural = true;
}
}
}
}
if (!isSpawnable) {
return command;
}
return {
isPlural: isPlural,
spawn: function(contextId) {
return _this.expandSpawnable(command, false, contextId);
}
};
};
Commander.prototype['get'] = function(root, varId, tracker) {
var command;
command = ['get', varId];
if (tracker) {
command.push(tracker);
}
return command;
};
Commander.prototype['get$'] = function(root, prop, queryObject) {
var key, val;
key = queryObject.selectorKey;
if (!key) {
key = queryObject.selector;
}
key += prop;
val = this.get$cache[key];
if (!val) {
val = this._get$(root, prop, queryObject);
this.get$cache[key] = val;
}
return val;
};
Commander.prototype['_get$'] = function(root, prop, queryObject) {
var idProcessor, isContextBound, isMulti, isScopeBound, query, selector,
_this = this;
query = queryObject.query;
selector = queryObject.selector;
if (selector === 'window') {
this.bindToWindow(prop);
return ['get', "::window[" + prop + "]"];
}
isMulti = query.isMulti;
isContextBound = queryObject.isContextBound;
isScopeBound = queryObject.isScopeBound;
if (isScopeBound) {
this.bindToScope(prop);
}
if (prop.indexOf("intrinsic-") === 0) {
query.on('afterChange', function() {
return _this._processIntrinsics(query, selector, prop);
});
this._processIntrinsics(query, selector, prop);
}
if (isContextBound) {
idProcessor = queryObject.idProcessor;
return {
isQueryBound: true,
isPlural: false,
query: query,
spawn: function(id) {
if (idProcessor) {
id = idProcessor(id);
}
return ['get$', prop, "$" + id, selector];
}
};
}
return {
isQueryBound: true,
isPlural: isMulti,
query: query,
spawn: function() {
var id, nodes, _i, _len, _ref;
if (!isMulti) {
id = query.lastAddedIds[query.lastAddedIds.length - 1];
return ['get$', prop, "$" + id, selector];
}
nodes = [];
_ref = query.lastAddedIds;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
id = _ref[_i];
nodes.push(['get$', prop, "$" + id, selector]);
}
return nodes;
}
};
};
Commander.prototype._processIntrinsics = function(query, selector, prop) {
var _this = this;
return query.lastAddedIds.forEach(function(id) {
var elProp, engine, gid, k, register;
gid = "$" + id;
if (!_this.intrinsicRegistersById[gid]) {
_this.intrinsicRegistersById[gid] = {};
}
if (!_this.intrinsicRegistersById[gid][prop]) {
elProp = prop.split("intrinsic-")[1];
k = "" + gid + "[" + prop + "]";
engine = _this.engine;
register = function() {
var val;
val = engine.measureByGssId(id, elProp);
if (engine.vars[k] !== val) {
engine.registerCommand(['suggest', ['get$', prop, gid, selector], ['number', val], 'required']);
}
return engine.setNeedsMeasure(true);
};
_this.intrinsicRegistersById[gid][prop] = register;
return register.call(_this);
}
});
};
Commander.prototype['number'] = function(root, num) {
return ['number', num];
};
Commander.prototype['plus'] = function(root, e1, e2) {
return this.makeNonRootSpawnableIfNeeded(['plus', e1, e2]);
};
Commander.prototype['minus'] = function(root, e1, e2) {
return this.makeNonRootSpawnableIfNeeded(['minus', e1, e2]);
};
Commander.prototype['multiply'] = function(root, e1, e2) {
return this.makeNonRootSpawnableIfNeeded(['multiply', e1, e2]);
};
Commander.prototype['divide'] = function(root, e1, e2, s, w) {
return this.makeNonRootSpawnableIfNeeded(['divide', e1, e2]);
};
Commander.prototype["cond"] = function(self) {
return this.registerSpawn(self);
};
/*
"where": (root,name) =>
return ['where',name]
"clause": (root,cond,label) =>
return @makeNonRootSpawnableIfNeeded ["clause",cond,label]
*/
Commander.prototype["where"] = function(root, name) {
var command;
if (root.isContextBound) {
command = [
"where", name, {
spawn: function(contextId) {
return "-context-" + contextId;
}
}
];
} else {
command = ["where", name];
}
return this.makeNonRootSpawnableIfNeeded(command);
};
Commander.prototype["clause"] = function(root, cond, name) {
var command;
if (root.isContextBound) {
command = [
"clause", cond, {
spawn: function(contextId) {
if (contextId) {
return name + "-context-" + contextId;
}
return name;
}
}
];
} else {
command = ["clause", cond, name];
}
return this.makeNonRootSpawnableIfNeeded(command);
};
Commander.prototype["?>="] = function(root, e1, e2) {
return this.makeNonRootSpawnableIfNeeded(["?>=", e1, e2]);
};
Commander.prototype["?<="] = function(root, e1, e2) {
return this.makeNonRootSpawnableIfNeeded(["?<=", e1, e2]);
};
Commander.prototype["?=="] = function(root, e1, e2) {
return this.makeNonRootSpawnableIfNeeded(["?==", e1, e2]);
};
Commander.prototype["?!="] = function(root, e1, e2) {
return this.makeNonRootSpawnableIfNeeded(["?!=", e1, e2]);
};
Commander.prototype["?>"] = function(root, e1, e2) {
return this.makeNonRootSpawnableIfNeeded(["?>", e1, e2]);
};
Commander.prototype["?<"] = function(root, e1, e2) {
return this.makeNonRootSpawnableIfNeeded(["?<", e1, e2]);
};
Commander.prototype["&&"] = function(root, e1, e2) {
return this.makeNonRootSpawnableIfNeeded(["&&", e1, e2]);
};
Commander.prototype["||"] = function(root, e1, e2) {
return this.makeNonRootSpawnableIfNeeded(["||", e1, e2]);
};
Commander.prototype['strength'] = function(root, s) {
return ['strength', s];
};
Commander.prototype['suggest'] = function() {
var args;
args = __slice.call(arguments);
return this.engine.registerCommand(['suggest'].concat(__slice.call(args.slice(1, args.length))));
};
Commander.prototype['eq'] = function(self, e1, e2, s, w) {
return this.registerSpawn(self);
};
Commander.prototype['lte'] = function(self, e1, e2, s, w) {
return this.registerSpawn(self);
};
Commander.prototype['gte'] = function(self, e1, e2, s, w) {
return this.registerSpawn(self);
};
Commander.prototype['lt'] = function(self, e1, e2, s, w) {
return this.registerSpawn(self);
};
Commander.prototype['gt'] = function(self, e1, e2, s, w) {
return this.registerSpawn(self);
};
Commander.prototype['stay'] = function(self) {
return this.registerSpawn(self);
/*
if !self._is_bound then return @registerSpawn(self)
# break up stays to allow multiple plural queries
args = [arguments...]
gets = args[1...args.length]
for get in gets
stay = ['stay']
stay.push get
cloneBinds self, stay
@registerSpawn(stay)
*/
};
Commander.prototype['virtual'] = function(self, namesssss) {
/* TODO: register virtuals to DOM elements
parentRule = self.parentRule
if !parentRule then throw new 'Error virtual element "#{name}" requires parent rule for context'
query = parentRule.getContextQuery()
args = [arguments...]
names = [args[1...args.length]...]
query.on 'afterChange', ->
for id in query.lastAddedIds
view = GSS.get.view(id)
view.addVirtuals names
for id in query.lastAddedIds
view = GSS.get.view(id)
view.addVirtuals names
@registerSpawn(self)
*/
};
Commander.prototype['$virtual'] = function(root, name) {
var o, parentRule, query, selector, selectorKey;
parentRule = root.parentRule;
if (!parentRule) {
throw new 'Error virtual element "#{name}" requires parent rule for context';
}
query = parentRule.getContextQuery();
selector = query.selector;
selectorKey = query.selector + (" ::virtual(" + name + ")");
o = this.queryCommandCache[selectorKey];
if (!o) {
o = {
query: query,
selector: selector,
selectorKey: selectorKey,
isContextBound: true,
idProcessor: function(id) {
return id + '"' + name + '"';
/* TODO: allow virtual lookup from down DOM tree
#
console.log id
nearestWithV = GSS.get.view(id).nearestViewWithVirtual(name)
if nearestWithV
id = nearestWithV.id
return id + '"' + name + '"'
else
console.error "Virtual with name #{name} not found up tree"
*/
}
};
this.queryCommandCache[selectorKey] = o;
}
bindRootAsContext(root, query);
return o;
};
Commander.prototype['$class'] = function(root, sel) {
var o, query, selector,
_this = this;
selector = "." + sel;
o = this.queryCommandCache[selector];
if (!o) {
query = this.engine.registerDomQuery({
selector: selector,
isMulti: true,
isLive: false,
createNodeList: function() {
return _this.engine.queryScope.getElementsByClassName(sel);
}
});
o = {
query: query,
selector: selector
};
this.queryCommandCache[selector] = o;
}
bindRootAsMulti(root, o.query);
return o;
};
Commander.prototype['$tag'] = function(root, sel) {
var o, query, selector,
_this = this;
selector = sel;
o = this.queryCommandCache[selector];
if (!o) {
query = this.engine.registerDomQuery({
selector: selector,
isMulti: true,
isLive: false,
createNodeList: function() {
return _this.engine.queryScope.getElementsByTagName(sel);
}
});
o = {
query: query,
selector: selector
};
this.queryCommandCache[selector] = o;
}
bindRootAsMulti(root, o.query);
return o;
};
Commander.prototype['$id'] = function(root, sel) {
var o, query, selector,
_this = this;
selector = "#" + sel;
o = this.queryCommandCache[selector];
if (!o) {
query = this.engine.registerDomQuery({
selector: selector,
isMulti: false,
isLive: false,
createNodeList: function() {
var el;
el = document.getElementById(sel);
if (el) {
return [el];
} else {
return [];
}
}
});
o = {
query: query,
selector: selector
};
this.queryCommandCache[selector] = o;
}
bindRoot(root, o.query);
return o;
};
Commander.prototype['$reserved'] = function(root, sel) {
var engine, o, parentRule, query, selector, selectorKey;
if (sel === 'window') {
selector = 'window';
o = this.queryCommandCache[selector];
if (!o) {
o = {
selector: selector,
query: null
};
this.queryCommandCache[selector] = o;
}
return o;
}
engine = this.engine;
if (sel === '::this' || sel === 'this') {
parentRule = root.parentRule;
if (!parentRule) {
throw new Error("::this query requires parent rule for context");
}
query = parentRule.getContextQuery();
selector = query.selector;
selectorKey = selector + "::this";
o = this.queryCommandCache[selectorKey];
if (!o) {
o = {
query: query,
selector: selector,
selectorKey: selectorKey,
isContextBound: true
};
this.queryCommandCache[selectorKey] = o;
}
bindRootAsContext(root, query);
return o;
} else if (sel === '::parent' || sel === 'parent') {
parentRule = root.parentRule;
if (!parentRule) {
throw new Error("::this query requires parent rule for context");
}
query = parentRule.getContextQuery();
selector = query.selector + "::parent";
o = this.queryCommandCache[selector];
if (!o) {
o = {
query: query,
selector: selector,
isContextBound: true,
idProcessor: function(id) {
return GSS.setupId(GSS.getById(id).parentElement);
}
};
this.queryCommandCache[selector] = o;
}
bindRootAsContext(root, query);
return o;
} else if (sel === 'scope') {
selector = "::" + sel;
o = this.queryCommandCache[selector];
if (!o) {
query = engine.registerDomQuery({
selector: selector,
isMulti: false,
isLive: true,
createNodeList: function() {
return [engine.scope];
}
});
o = {
query: query,
selector: selector,
isScopeBound: true
};
this.queryCommandCache[selector] = o;
}
bindRoot(root, o.query);
return o;
}
throw new Error("$reserved selectors not yet handled: " + sel);
};
Commander.prototype['chain'] = function(root, queryObject, bridgessssss) {
var args, bridge, bridges, engine, more, query, _i, _j, _len, _len1;
query = queryObject.query;
args = __slice.call(arguments);
bridges = __slice.call(args.slice(2, args.length));
engine = this.engine;
more = null;
for (_i = 0, _len = bridges.length; _i < _len; _i++) {
bridge = bridges[_i];
if (typeof bridge !== "function") {
if (!more) {
more = [];
}
more.push(bridge);
bridges.splice(bridges.indexOf(bridge), 1);
}
}
for (_j = 0, _len1 = bridges.length; _j < _len1; _j++) {
bridge = bridges[_j];
bridge.call(engine, query, engine, more);
}
return query.on('afterChange', function() {
var _k, _len2, _results;
_results = [];
for (_k = 0, _len2 = bridges.length; _k < _len2; _k++) {
bridge = bridges[_k];
_results.push(bridge.call(engine, query, engine, more));
}
return _results;
});
};
Commander.prototype['eq-chain'] = function(root, head, tail, s, w) {
return this._chainer('eq', head, tail, s, w);
};
Commander.prototype['lte-chain'] = function(root, head, tail, s, w) {
return this._chainer('lte', head, tail, s, w);
};
Commander.prototype['gte-chain'] = function(root, head, tail, s, w) {
return this._chainer('gte', head, tail, s, w);
};
Commander.prototype['lt-chain'] = function(root, head, tail, s, w) {
return this._chainer('lt', head, tail, s, w);
};
Commander.prototype['gt-chain'] = function(root, head, tail, s, w) {
return this._chainer('gt', head, tail, s, w);
};
Commander.prototype._chainer = function(op, head, tail, s, w) {
var engine, tracker, _e_for_chain;
tracker = "eq-chain-" + GSS.uid();
engine = this.engine;
_e_for_chain = this._e_for_chain;
return function(query, e, more) {
e.remove(tracker);
return query.forEach(function(el) {
var e1, e2, nextEl;
nextEl = query.next(el);
if (!nextEl) {
return;
}
e1 = _e_for_chain(el, head, query, tracker, el, nextEl);
e2 = _e_for_chain(nextEl, tail, query, tracker, el, nextEl);
return e[op](e1, e2, s, w, more);
});
};
};
Commander.prototype['plus-chain'] = function(root, head, tail) {
return this._chainer_math(head, tail, 'plus');
};
Commander.prototype['minus-chain'] = function(root, head, tail) {
return this._chainer_math(head, tail, 'minus');
};
Commander.prototype['multiply-chain'] = function(root, head, tail) {
return this._chainer_math(head, tail, 'multiply');
};
Commander.prototype['divide-chain'] = function(root, head, tail) {
return this._chainer_math(head, tail, 'divide');
};
Commander.prototype._chainer_math = function(head, tail, op) {
var engine, _e_for_chain;
engine = this.engine;
_e_for_chain = this._e_for_chain;
return function(el, nextEl, query, tracker) {
var e1, e2;
e1 = _e_for_chain(el, head, query, tracker);
e2 = _e_for_chain(nextEl, tail, query, tracker);
return engine[op](e1, e2);
};
};
Commander.prototype._e_for_chain = function(el, exp, query, tracker, currentEl, nextEl) {
var e1;
if (typeof exp === "string") {
e1 = this.engine.elVar(el, exp, query.selector);
} else if (typeof exp === "function") {
e1 = exp.call(this, currentEl, nextEl, query, tracker);
} else {
e1 = exp;
}
return e1;
};
Commander.prototype['for-each'] = function(root, queryObject, callback) {
var el, query, _i, _len, _ref;
query = queryObject.query;
_ref = query.nodeList;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
el = _ref[_i];
callback.call(this.engine, el, query, this.engine);
}
return query.on('afterChange', function() {
var _j, _len1, _ref1, _results;
_ref1 = query.nodeList;
_results = [];
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
el = _ref1[_j];
_results.push(callback.call(this.engine, el, query));
}
return _results;
});
};
Commander.prototype['for-all'] = function(root, queryObject, callback) {
var query,
_this = this;
query = queryObject.query;
callback.call(this.engine, query, this.engine);
return query.on('afterChange', function() {
return callback.call(_this.engine, query, _this.engine);
});
};
Commander.prototype['js'] = function(root, js) {
eval("var callback =" + js);
return callback;
};
return Commander;
})();
module.exports = Commander;
});
require.register("gss/lib/Thread.js", function(exports, require, module){
var Thread, isConstraint, valueOf,
__slice = [].slice;
valueOf = function(e) {
var val;
val = e.value;
if (val != null) {
return val;
}
val = Number(e);
if (val != null) {
return val;
}
throw new Error("Thread.valueOf couldn't find value of: " + e);
};
isConstraint = function(root) {
if (root[0] === 'cond') {
return false;
}
return true;
};
Thread = (function() {
function Thread(o) {
var defaultStrength;
if (o == null) {
o = {};
}
defaultStrength = o.defaultStrength || 'required';
this.defaultStrength = c.Strength[defaultStrength];
if (!this.defaultStrength) {
this.defaultStrength = c.Strength['required'];
}
this.defaultWeight = o.defaultWeight || 0;
this.setupIfNeeded();
this;
}
Thread.prototype.needsSetup = true;
Thread.prototype.setupIfNeeded = function() {
if (!this.needsSetup) {
return this;
}
this.needsSetup = false;
this.solver = new c.SimplexSolver();
this.solver.autoSolve = false;
this.cachedVars = {};
this.elements = {};
this.constraintsByTracker = {};
this.varIdsByTracker = {};
this.conditionals = [];
this.activeClauses = [];
this.__editVarNames = [];
return this;
};
Thread.prototype.postMessage = function(message) {
this.execute(message);
return this;
};
Thread.prototype.terminate = function() {
this.needsSetup = true;
this.solver = null;
this.cachedVars = null;
this.constraintsByTracker = null;
this.varIdsByTracker = null;
this.conditionals = null;
this.activeClauses = null;
this.__editVarNames = null;
return this;
};
Thread.prototype.output = function() {
return {
values: this.getValues(),
clauses: this.activeClauses
};
};
Thread.prototype.execute = function(message) {
var command, uuid, _i, _len, _ref;
this.setupIfNeeded();
uuid = null;
if (message.uuid) {
uuid = message.uuid;
}
_ref = message.commands;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
command = _ref[_i];
this._trackRootIfNeeded(command, uuid);
this._execute(command, command);
}
return this;
};
Thread.prototype._execute = function(command, root) {
var func, i, node, sub, subResult;
node = command;
func = this[node[0]];
if (func == null) {
throw new Error("Thread.execute broke - couldn't find method: " + node[0]);
}
i = node.length - 1;
while (i > 0) {
sub = node[i];
if (sub instanceof Array) {
subResult = this._execute(sub, root);
if (subResult === "IGNORE") {
node.splice(i, 1);
} else {
node.splice(i, 1, subResult);
}
}
i--;
}
return func.call.apply(func, [this, root].concat(__slice.call(node.slice(1, node.length))));
};
Thread.prototype.getValues = function() {
var id, o;
this._solve();
o = {};
for (id in this.cachedVars) {
o[id] = this.cachedVars[id].value;
}
return o;
};
Thread.prototype._solve = function(recurses) {
var conditional, _i, _len, _ref;
if (recurses == null) {
recurses = 0;
}
this.solver.solve();
if (this.conditionals.length > 0 && recurses === 0) {
_ref = this.conditionals;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
conditional = _ref[_i];
conditional.update();
}
recurses++;
return this._solve(recurses);
}
};
Thread.prototype['virtual'] = function(self, id, names) {
return self;
};
Thread.prototype['track'] = function(root, tracker) {
this._trackRootIfNeeded(root, tracker);
return 'IGNORE';
};
Thread.prototype._trackRootIfNeeded = function(root, tracker) {
if (tracker) {
root._is_tracked = true;
if (!root._trackers) {
root._trackers = [];
}
if (root._trackers.indexOf(tracker) === -1) {
return root._trackers.push(tracker);
}
}
};
Thread.prototype['remove'] = function(self, trackersss) {
var args, tracker, trackers, _i, _len, _results;
args = __slice.call(arguments);
trackers = __slice.call(args.slice(1, args.length));
_results = [];
for (_i = 0, _len = trackers.length; _i < _len; _i++) {
tracker = trackers[_i];
_results.push(this._remove(tracker));
}
return _results;
};
Thread.prototype._remove = function(tracker) {
this._removeConstraintByTracker(tracker);
return this._removeVarByTracker(tracker);
};
Thread.prototype._removeVarByTracker = function(tracker) {
var id, _i, _len, _ref;
delete this.__editVarNames[tracker];
if (this.varIdsByTracker[tracker]) {
_ref = this.varIdsByTracker[tracker];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
id = _ref[_i];
delete this.cachedVars[id];
}
return delete this.varIdsByTracker[tracker];
}
};
Thread.prototype._removeConstraintByTracker = function(tracker, permenant) {
var constraint, error, movealong, _i, _len, _ref;
if (permenant == null) {
permenant = true;
}
if (this.constraintsByTracker[tracker]) {
_ref = this.constraintsByTracker[tracker];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
constraint = _ref[_i];
try {
this.solver.removeConstraint(constraint);
} catch (_error) {
error = _error;
movealong = 'please';
}
}
if (permenant) {
return this.constraintsByTracker[tracker] = null;
}
}
};
Thread.prototype._addConstraintByTracker = function(tracker) {
var constraint, _i, _len, _ref, _results;
if (this.constraintsByTracker[tracker]) {
_ref = this.constraintsByTracker[tracker];
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
constraint = _ref[_i];
_results.push(this.solver.addConstraint(constraint));
}
return _results;
}
};
Thread.prototype['where'] = function(root, label, labelSuffix) {
root._condition_bound = true;
this._trackRootIfNeeded(root, label);
this._trackRootIfNeeded(root, label + labelSuffix);
return "IGNORE";
};
Thread.prototype['cond'] = function(self, ifffff) {
var args, clause, clauses, that, _i, _len, _ref;
args = __slice.call(arguments);
clauses = [];
_ref = args.slice(1, args.length);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
clause = _ref[_i];
clauses.push(clause);
}
that = this;
return this.conditionals.push({
clauses: clauses,
activeLabel: null,
update: function() {
var found, newLabel, oldLabel, _j, _len1;
found = false;
oldLabel = this.activeLabel;
for (_j = 0, _len1 = clauses.length; _j < _len1; _j++) {
clause = clauses[_j];
newLabel = clause.test();
if (newLabel) {
found = true;
break;
}
}
if (found) {
if (oldLabel !== newLabel) {
if (oldLabel != null) {
that.activeClauses.splice(that.activeClauses.indexOf(oldLabel), 1);
that._removeConstraintByTracker(oldLabel, false);
}
that._addConstraintByTracker(newLabel);
that.activeClauses.push(newLabel);
return this.activeLabel = newLabel;
}
} else {
if (oldLabel != null) {
that.activeClauses.splice(that.activeClauses.indexOf(oldLabel), 1);
return that._removeConstraintByTracker(oldLabel, false);
}
}
}
});
};
Thread.prototype['clause'] = function(root, condition, label) {
return {
label: label,
test: function() {
if (!label) {
return condition;
}
if (!condition) {
return label;
}
if (condition.call(this)) {
return label;
} else {
return null;
}
}
};
};
Thread.prototype['?>='] = function(root, e1, e2) {
return function() {
return valueOf(e1) >= valueOf(e2);
};
};
Thread.prototype['?<='] = function(root, e1, e2) {
return function() {
return valueOf(e1) <= valueOf(e2);
};
};
Thread.prototype['?=='] = function(root, e1, e2) {
return function() {
return valueOf(e1) === valueOf(e2);
};
};
Thread.prototype['?>'] = function(root, e1, e2) {
return function() {
return valueOf(e1) > valueOf(e2);
};
};
Thread.prototype['?<'] = function(root, e1, e2) {
return function() {
return valueOf(e1) < valueOf(e2);
};
};
Thread.prototype['?!='] = function(root, e1, e2) {
return function() {
return valueOf(e1) !== valueOf(e2);
};
};
Thread.prototype['&&'] = function(root, c1, c2) {
return c1 && c2;
};
Thread.prototype['||'] = function(root, c1, c2) {
return c1 || c2;
};
Thread.prototype.number = function(root, num) {
return Number(num);
};
Thread.prototype._trackVarId = function(id, tracker) {
if (!this.varIdsByTracker[tracker]) {
this.varIdsByTracker[tracker] = [];
}
if (this.varIdsByTracker[tracker].indexOf(id) === -1) {
return this.varIdsByTracker[tracker].push(id);
}
};
Thread.prototype["var"] = function(self, id, tracker) {
var v;
if (this.cachedVars[id]) {
return this.cachedVars[id];
}
v = new c.Variable({
name: id
});
if (tracker) {
this._trackVarId(id, tracker);
v._tracker = tracker;
v._is_tracked = true;
}
this.cachedVars[id] = v;
return v;
};
Thread.prototype.varexp = function(self, id, expression, tracker) {
var cv, that;
cv = this.cachedVars;
if (cv[id]) {
return cv[id];
}
if (!(expression instanceof c.Expression)) {
throw new Error("Thread `varexp` requires an instance of c.Expression");
}
that = this;
Object.defineProperty(cv, id, {
get: function() {
var clone;
clone = expression.clone();
if (tracker) {
that._trackVarId(id, tracker);
clone._tracker = tracker;
clone._is_tracked = true;
}
return clone;
}
});
return expression;
};
Thread.prototype.get$ = function(root, prop, elId, selector) {
this._trackRootIfNeeded(root, elId);
if (selector) {
this._trackRootIfNeeded(root, selector + elId);
}
return this._get$(prop, elId);
};
Thread.prototype._get$ = function(prop, elId) {
var exp, varId;
varId = elId + ("[" + prop + "]");
switch (prop) {
case "right":
exp = c.plus(this._get$("x", elId), this._get$("width", elId));
return this.varexp(null, varId, exp, elId);
case "bottom":
exp = c.plus(this._get$("y", elId), this._get$("height", elId));
return this.varexp(null, varId, exp, elId);
case "center-x":
exp = c.plus(this._get$("x", elId), c.divide(this._get$("width", elId), 2));
return this.varexp(null, varId, exp, elId);
case "center-y":
exp = c.plus(this._get$("y", elId), c.divide(this._get$("height", elId), 2));
return this.varexp(null, varId, exp, elId);
default:
return this["var"](null, varId, elId);
}
};
Thread.prototype.get = function(root, id, tracker) {
var v;
if (tracker) {
this._trackRootIfNeeded(root, tracker);
}
v = this.cachedVars[id];
if (v) {
this._trackRootIfNeeded(root, v.tracker);
return v;
} else {
v = this["var"](null, id);
return v;
}
throw new Error("AST method 'get' couldn't find var with id: " + id);
};
Thread.prototype.plus = function(root, e1, e2) {
if (isConstraint(root)) {
return c.plus(e1, e2);
}
return Object.defineProperty({}, 'value', {
get: function() {
return valueOf(e1) + valueOf(e2);
}
});
};
Thread.prototype.minus = function(root, e1, e2) {
if (isConstraint(root)) {
return c.minus(e1, e2);
}
return Object.defineProperty({}, 'value', {
get: function() {
return valueOf(e1) - valueOf(e2);
}
});
};
Thread.prototype.multiply = function(root, e1, e2) {
if (isConstraint(root)) {
return c.times(e1, e2);
}
return Object.defineProperty({}, 'value', {
get: function() {
return valueOf(e1) * valueOf(e2);
}
});
};
Thread.prototype.divide = function(root, e1, e2) {
if (isConstraint(root)) {
return c.divide(e1, e2);
}
return Object.defineProperty({}, 'value', {
get: function() {
return valueOf(e1) / valueOf(e2);
}
});
};
/* Todo
remainder: (root,e1,e2) ->
'Math.abs': ->
'Math.acos': ->
'Math.asin': ->
'Math.atan': ->
'Math.atan2': ->
'Math.ceil': ->
'Math.cos': ->
'Math.exp': ->
'Math.floor': ->
'Math.imul': ->
'Math.log': ->
'Math.max': ->
'Math.min': ->
'Math.pow': ->
'Math.random': ->
'Math.round': ->
'Math.sin': ->
'Math.sqrt': ->
'Math.tan': ->
*/
Thread.prototype._strength = function(s) {
var strength;
if (typeof s === 'string') {
if (s === 'require') {
s = 'required';
}
strength = c.Strength[s];
if (strength) {
return strength;
}
}
return this.defaultStrength;
};
Thread.prototype._weight = function(w) {
if (typeof w === 'number') {
return w;
}
return this.defaultWeight;
};
Thread.prototype._addConstraint = function(root, constraint) {
var tracker, _i, _len, _ref;
if (!root._condition_bound) {
this.solver.addConstraint(constraint);
}
if (root._is_tracked) {
_ref = root._trackers;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
tracker = _ref[_i];
if (!this.constraintsByTracker[tracker]) {
this.constraintsByTracker[tracker] = [];
}
this.constraintsByTracker[tracker].push(constraint);
}
}
return constraint;
};
Thread.prototype.eq = function(self, e1, e2, s, w) {
return this._addConstraint(self, new c.Equation(e1, e2, this._strength(s), this._weight(w)));
};
Thread.prototype.lte = function(self, e1, e2, s, w) {
return this._addConstraint(self, new c.Inequality(e1, c.LEQ, e2, this._strength(s), this._weight(w)));
};
Thread.prototype.gte = function(self, e1, e2, s, w) {
return this._addConstraint(self, new c.Inequality(e1, c.GEQ, e2, this._strength(s), this._weight(w)));
};
Thread.prototype.lt = function(self, e1, e2, s, w) {
return this._addConstraint(self, new c.Inequality(e1, c.LEQ, e2, this._strength(s), this._weight(w)));
};
Thread.prototype.gt = function(self, e1, e2, s, w) {
return this._addConstraint(self, new c.Inequality(e1, c.GEQ, e2, this._strength(s), this._weight(w)));
};
Thread.prototype._editvar = function(varr, s, w) {
if (this.__editVarNames.indexOf(varr.name) === -1) {
this.__editVarNames.push(varr.name);
this.solver.addEditVar(varr, this._strength(s), this._weight(w));
}
return this;
};
Thread.prototype.suggest = function(self, varr, val, s, w) {
if (s == null) {
s = 'strong';
}
if (typeof varr === 'string') {
varr = this.get(self, varr);
}
this._editvar(varr, s, w);
this.solver.suggestValue(varr, val);
return this.solver.resolve();
};
Thread.prototype.stay = function(self) {
var args, v, _i, _len, _ref;
args = __slice.call(arguments);
_ref = args.slice(1, args.length);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
v = _ref[_i];
this.solver.addStay(v);
}
return this.solver;
};
return Thread;
})();
if (typeof module !== "undefined" && module !== null ? module.exports : void 0) {
module.exports = Thread;
}
});
require.register("gss/lib/dom/Getter.js", function(exports, require, module){
var Getter, getScrollbarWidth, scrollbarWidth;
getScrollbarWidth = function() {
var inner, outer, w1, w2;
inner = document.createElement("p");
inner.style.width = "100%";
inner.style.height = "200px";
outer = document.createElement("div");
outer.style.position = "absolute";
outer.style.top = "0px";
outer.style.left = "0px";
outer.style.visibility = "hidden";
outer.style.width = "200px";
outer.style.height = "150px";
outer.style.overflow = "hidden";
outer.style.zoom = "document";
outer.appendChild(inner);
document.body.appendChild(outer);
w1 = inner.offsetWidth;
outer.style.overflow = "scroll";
w2 = inner.offsetWidth;
if (w1 === w2) {
w2 = outer.clientWidth;
}
document.body.removeChild(outer);
return w1 - w2;
};
scrollbarWidth = null;
Getter = (function() {
function Getter(scope) {
this.scope = scope;
this.styleNodes = null;
if (!this.scope) {
this.scope = document;
}
}
Getter.prototype.clean = function() {};
Getter.prototype.destroy = function() {
this.scope = null;
return this.styleNodes = null;
};
Getter.prototype.scrollbarWidth = function() {
if (!scrollbarWidth) {
scrollbarWidth = getScrollbarWidth();
}
return scrollbarWidth;
};
Getter.prototype.get = function(selector) {
var identifier, method;
method = selector[0];
identifier = selector[1];
switch (method) {
case "$reserved":
if (identifier === 'this') {
return this.scope;
}
break;
case "$id":
if (identifier[0] === '#') {
identifier = identifier.substr(1);
}
return document.getElementById(identifier);
case "$class":
if (identifier[0] === '.') {
identifier = identifier.substr(1);
}
return this.scope.getElementsByClassName(identifier);
case "$tag":
return this.scope.getElementsByTagName(identifier);
}
return this.scope.querySelectorAll(identifier);
};
Getter.prototype.measure = function(node, dimension) {
var scroll;
switch (dimension) {
case 'width':
case 'w':
return node.getBoundingClientRect().width;
case 'height':
case 'h':
return node.getBoundingClientRect().height;
case 'left':
case 'x':
scroll = window.scrollX || window.scrollLeft || 0;
return node.getBoundingClientRect().left + scroll;
case 'top':
case 'y':
scroll = window.scrollY || window.scrollTop || 0;
return node.getBoundingClientRect().top + scroll;
case 'bottom':
return this.measure(node, 'top') + this.measure(node, 'height');
case 'right':
return this.measure(node, 'left') + this.measure(node, 'width');
case 'centerX':
return this.measure(node, 'left') + this.measure(node, 'width') / 2;
case 'centerY':
return this.measure(node, 'top') + this.measure(node, 'height') / 2;
}
};
Getter.prototype.offsets = function(element) {
var offsets;
offsets = {
x: 0,
y: 0
};
if (!element.offsetParent) {
return offsets;
}
element = element.offsetParent;
while (true) {
offsets.x += element.offsetLeft;
offsets.y += element.offsetTop;
if (!element.offsetParent) {
break;
}
element = element.offsetParent;
}
return offsets;
};
Getter.prototype.view = function(node) {
if (typeof node === "string") {
return GSS.View.byId[node];
}
return GSS.View.byId[GSS.getId(node)];
};
Getter.prototype.getAllStyleNodes = function() {
return this.scope.getElementsByTagName("style");
};
Getter.prototype.readAllASTs = function() {
var AST, ASTs, node, _i, _len, _ref;
ASTs = [];
_ref = this.getAllStyleNodes();
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
node = _ref[_i];
AST = this.readAST(node);
if (AST) {
ASTs.push(AST);
}
}
return ASTs;
};
Getter.prototype.scopeFor = function(node) {
if (this.isStyleNode(node)) {
return this.scopeForStyleNode(node);
} else {
return this.nearestScope(node);
}
};
Getter.prototype.isStyleNode = function(node) {
var mime, tagName;
tagName = node != null ? node.tagName : void 0;
if (tagName === "STYLE" || tagName === "LINK") {
mime = typeof node.getAttribute === "function" ? node.getAttribute("type") : void 0;
if (mime) {
return mime.indexOf("text/gss") === 0;
}
}
return false;
};
Getter.prototype.scopeForStyleNode = function(node) {
var scoped;
scoped = node.getAttribute('scoped');
if ((scoped != null) && scoped !== "false") {
return node.parentElement;
} else {
return Getter.getRootScope();
}
};
Getter.prototype.isScope = function(el) {
return !!(el != null ? el._gss_is_scope : void 0);
};
Getter.prototype.nearestScope = function(el, skipSelf) {
if (skipSelf == null) {
skipSelf = false;
}
if (skipSelf) {
el = el.parentElement;
}
while (el.parentElement) {
if (this.isScope(el)) {
return el;
}
el = el.parentElement;
}
return null;
};
Getter.prototype.nearestEngine = function(el, skipSelf) {
var scope;
if (skipSelf == null) {
skipSelf = false;
}
scope = this.nearestScope(el, skipSelf);
if (scope) {
return this.engine(scope);
}
return null;
};
Getter.prototype.descdendantNodes = function(el) {
return el.getElementsByTagName("*");
};
Getter.prototype.engine = function(el) {
return GSS.engines.byId[GSS.getId(el)];
};
Getter.prototype.readAST = function(node) {
var mime, reader;
mime = node.getAttribute("type");
reader = this["readAST:" + mime];
if (reader) {
return reader.call(this, node);
}
return null;
};
Getter.prototype['readAST:text/gss-ast'] = function(node) {
var ast, e, source;
source = node.textContent.trim();
if (source.length === 0) {
return {};
}
try {
ast = JSON.parse(source);
} catch (_error) {
e = _error;
console.error("Parsing compiled gss error", console.dir(e));
}
return ast;
};
Getter.prototype['readAST:text/gss'] = function(node) {
throw new Error("did not include GSS's compilers");
};
return Getter;
})();
Getter.getRootScope = function() {
if (typeof ShadowDOMPolyfill === "undefined" || ShadowDOMPolyfill === null) {
return document.body;
} else {
return ShadowDOMPolyfill.wrap(document.body);
}
};
module.exports = Getter;
});
require.register("gss/lib/dom/IdMixin.js", function(exports, require, module){
var IdMixin, boxSizingPrefix;
boxSizingPrefix = GSS._.boxSizingPrefix;
IdMixin = {
uid: function() {
return this._id_counter++;
},
_id_counter: 1,
_byIdCache: {},
_ids_killed: function(ids) {
var id, _i, _len, _results;
_results = [];
for (_i = 0, _len = ids.length; _i < _len; _i++) {
id = ids[_i];
_results.push(this._id_killed(id));
}
return _results;
},
_id_killed: function(id) {
var _ref;
this._byIdCache[id] = null;
delete this._byIdCache[id];
return (_ref = GSS.View.byId[id]) != null ? typeof _ref.recycle === "function" ? _ref.recycle() : void 0 : void 0;
},
getById: function(id) {
var el;
if (this._byIdCache[id]) {
return this._byIdCache[id];
}
el = document.querySelector('[data-gss-id="' + id + '"]');
if (el) {
this._byIdCache[id] = el;
}
return el;
},
setupScopeId: function(el) {
el._gss_is_scope = true;
return this.setupId(el);
},
setupId: function(el) {
var gid, _id;
if (!el) {
return null;
}
gid = this.getId(el);
if (gid == null) {
_id = this.uid();
gid = String(el.id || _id);
el.setAttribute('data-gss-id', gid);
el.style[boxSizingPrefix] = 'border-box';
el._gss_id = gid;
GSS.View["new"]({
el: el,
id: gid
});
if (this._byIdCache[gid] != null) {
GSS.warn("element by id cache replaced gss-id: " + gid);
}
}
this._byIdCache[gid] = el;
return gid;
},
getId: function(el) {
if (el != null ? el._gss_id : void 0) {
return el != null ? el._gss_id : void 0;
}
return null;
}
};
module.exports = IdMixin;
});
require.register("gss/vendor/gl-matrix.js", function(exports, require, module){
/**
* @fileoverview gl-matrix - High performance matrix and vector operations
* @author Brandon Jones
* @author Colin MacKenzie IV
* @version 2.2.0
*/
/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
(function(_global) {
"use strict";
var shim = {};
if (typeof(exports) === 'undefined') {
if(typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
shim.exports = {};
define(function() {
return shim.exports;
});
} else {
// gl-matrix lives in a browser, define its namespaces in global
shim.exports = typeof(window) !== 'undefined' ? window : _global;
}
}
else {
// gl-matrix lives in commonjs, define its namespaces in exports
shim.exports = exports;
}
(function(exports) {
/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
if(!GLMAT_EPSILON) {
var GLMAT_EPSILON = 0.000001;
}
if(!GLMAT_ARRAY_TYPE) {
var GLMAT_ARRAY_TYPE = (typeof Float32Array !== 'undefined') ? Float32Array : Array;
}
if(!GLMAT_RANDOM) {
var GLMAT_RANDOM = Math.random;
}
/**
* @class Common utilities
* @name glMatrix
*/
var glMatrix = {};
/**
* Sets the type of array used when creating new vectors and matricies
*
* @param {Type} type Array type, such as Float32Array or Array
*/
glMatrix.setMatrixArrayType = function(type) {
GLMAT_ARRAY_TYPE = type;
}
if(typeof(exports) !== 'undefined') {
exports.glMatrix = glMatrix;
}
var degree = Math.PI / 180;
/**
* Convert Degree To Radian
*
* @param {Number} Angle in Degrees
*/
glMatrix.toRadian = function(a){
return a * degree;
}
;
/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/**
* @class 2 Dimensional Vector
* @name vec2
*/
var vec2 = {};
/**
* Creates a new, empty vec2
*
* @returns {vec2} a new 2D vector
*/
vec2.create = function() {
var out = new GLMAT_ARRAY_TYPE(2);
out[0] = 0;
out[1] = 0;
return out;
};
/**
* Creates a new vec2 initialized with values from an existing vector
*
* @param {vec2} a vector to clone
* @returns {vec2} a new 2D vector
*/
vec2.clone = function(a) {
var out = new GLMAT_ARRAY_TYPE(2);
out[0] = a[0];
out[1] = a[1];
return out;
};
/**
* Creates a new vec2 initialized with the given values
*
* @param {Number} x X component
* @param {Number} y Y component
* @returns {vec2} a new 2D vector
*/
vec2.fromValues = function(x, y) {
var out = new GLMAT_ARRAY_TYPE(2);
out[0] = x;
out[1] = y;
return out;
};
/**
* Copy the values from one vec2 to another
*
* @param {vec2} out the receiving vector
* @param {vec2} a the source vector
* @returns {vec2} out
*/
vec2.copy = function(out, a) {
out[0] = a[0];
out[1] = a[1];
return out;
};
/**
* Set the components of a vec2 to the given values
*
* @param {vec2} out the receiving vector
* @param {Number} x X component
* @param {Number} y Y component
* @returns {vec2} out
*/
vec2.set = function(out, x, y) {
out[0] = x;
out[1] = y;
return out;
};
/**
* Adds two vec2's
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec2} out
*/
vec2.add = function(out, a, b) {
out[0] = a[0] + b[0];
out[1] = a[1] + b[1];
return out;
};
/**
* Subtracts vector b from vector a
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec2} out
*/
vec2.subtract = function(out, a, b) {
out[0] = a[0] - b[0];
out[1] = a[1] - b[1];
return out;
};
/**
* Alias for {@link vec2.subtract}
* @function
*/
vec2.sub = vec2.subtract;
/**
* Multiplies two vec2's
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec2} out
*/
vec2.multiply = function(out, a, b) {
out[0] = a[0] * b[0];
out[1] = a[1] * b[1];
return out;
};
/**
* Alias for {@link vec2.multiply}
* @function
*/
vec2.mul = vec2.multiply;
/**
* Divides two vec2's
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec2} out
*/
vec2.divide = function(out, a, b) {
out[0] = a[0] / b[0];
out[1] = a[1] / b[1];
return out;
};
/**
* Alias for {@link vec2.divide}
* @function
*/
vec2.div = vec2.divide;
/**
* Returns the minimum of two vec2's
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec2} out
*/
vec2.min = function(out, a, b) {
out[0] = Math.min(a[0], b[0]);
out[1] = Math.min(a[1], b[1]);
return out;
};
/**
* Returns the maximum of two vec2's
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec2} out
*/
vec2.max = function(out, a, b) {
out[0] = Math.max(a[0], b[0]);
out[1] = Math.max(a[1], b[1]);
return out;
};
/**
* Scales a vec2 by a scalar number
*
* @param {vec2} out the receiving vector
* @param {vec2} a the vector to scale
* @param {Number} b amount to scale the vector by
* @returns {vec2} out
*/
vec2.scale = function(out, a, b) {
out[0] = a[0] * b;
out[1] = a[1] * b;
return out;
};
/**
* Adds two vec2's after scaling the second operand by a scalar value
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @param {Number} scale the amount to scale b by before adding
* @returns {vec2} out
*/
vec2.scaleAndAdd = function(out, a, b, scale) {
out[0] = a[0] + (b[0] * scale);
out[1] = a[1] + (b[1] * scale);
return out;
};
/**
* Calculates the euclidian distance between two vec2's
*
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {Number} distance between a and b
*/
vec2.distance = function(a, b) {
var x = b[0] - a[0],
y = b[1] - a[1];
return Math.sqrt(x*x + y*y);
};
/**
* Alias for {@link vec2.distance}
* @function
*/
vec2.dist = vec2.distance;
/**
* Calculates the squared euclidian distance between two vec2's
*
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {Number} squared distance between a and b
*/
vec2.squaredDistance = function(a, b) {
var x = b[0] - a[0],
y = b[1] - a[1];
return x*x + y*y;
};
/**
* Alias for {@link vec2.squaredDistance}
* @function
*/
vec2.sqrDist = vec2.squaredDistance;
/**
* Calculates the length of a vec2
*
* @param {vec2} a vector to calculate length of
* @returns {Number} length of a
*/
vec2.length = function (a) {
var x = a[0],
y = a[1];
return Math.sqrt(x*x + y*y);
};
/**
* Alias for {@link vec2.length}
* @function
*/
vec2.len = vec2.length;
/**
* Calculates the squared length of a vec2
*
* @param {vec2} a vector to calculate squared length of
* @returns {Number} squared length of a
*/
vec2.squaredLength = function (a) {
var x = a[0],
y = a[1];
return x*x + y*y;
};
/**
* Alias for {@link vec2.squaredLength}
* @function
*/
vec2.sqrLen = vec2.squaredLength;
/**
* Negates the components of a vec2
*
* @param {vec2} out the receiving vector
* @param {vec2} a vector to negate
* @returns {vec2} out
*/
vec2.negate = function(out, a) {
out[0] = -a[0];
out[1] = -a[1];
return out;
};
/**
* Normalize a vec2
*
* @param {vec2} out the receiving vector
* @param {vec2} a vector to normalize
* @returns {vec2} out
*/
vec2.normalize = function(out, a) {
var x = a[0],
y = a[1];
var len = x*x + y*y;
if (len > 0) {
//TODO: evaluate use of glm_invsqrt here?
len = 1 / Math.sqrt(len);
out[0] = a[0] * len;
out[1] = a[1] * len;
}
return out;
};
/**
* Calculates the dot product of two vec2's
*
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {Number} dot product of a and b
*/
vec2.dot = function (a, b) {
return a[0] * b[0] + a[1] * b[1];
};
/**
* Computes the cross product of two vec2's
* Note that the cross product must by definition produce a 3D vector
*
* @param {vec3} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec3} out
*/
vec2.cross = function(out, a, b) {
var z = a[0] * b[1] - a[1] * b[0];
out[0] = out[1] = 0;
out[2] = z;
return out;
};
/**
* Performs a linear interpolation between two vec2's
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @param {Number} t interpolation amount between the two inputs
* @returns {vec2} out
*/
vec2.lerp = function (out, a, b, t) {
var ax = a[0],
ay = a[1];
out[0] = ax + t * (b[0] - ax);
out[1] = ay + t * (b[1] - ay);
return out;
};
/**
* Generates a random vector with the given scale
*
* @param {vec2} out the receiving vector
* @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned
* @returns {vec2} out
*/
vec2.random = function (out, scale) {
scale = scale || 1.0;
var r = GLMAT_RANDOM() * 2.0 * Math.PI;
out[0] = Math.cos(r) * scale;
out[1] = Math.sin(r) * scale;
return out;
};
/**
* Transforms the vec2 with a mat2
*
* @param {vec2} out the receiving vector
* @param {vec2} a the vector to transform
* @param {mat2} m matrix to transform with
* @returns {vec2} out
*/
vec2.transformMat2 = function(out, a, m) {
var x = a[0],
y = a[1];
out[0] = m[0] * x + m[2] * y;
out[1] = m[1] * x + m[3] * y;
return out;
};
/**
* Transforms the vec2 with a mat2d
*
* @param {vec2} out the receiving vector
* @param {vec2} a the vector to transform
* @param {mat2d} m matrix to transform with
* @returns {vec2} out
*/
vec2.transformMat2d = function(out, a, m) {
var x = a[0],
y = a[1];
out[0] = m[0] * x + m[2] * y + m[4];
out[1] = m[1] * x + m[3] * y + m[5];
return out;
};
/**
* Transforms the vec2 with a mat3
* 3rd vector component is implicitly '1'
*
* @param {vec2} out the receiving vector
* @param {vec2} a the vector to transform
* @param {mat3} m matrix to transform with
* @returns {vec2} out
*/
vec2.transformMat3 = function(out, a, m) {
var x = a[0],
y = a[1];
out[0] = m[0] * x + m[3] * y + m[6];
out[1] = m[1] * x + m[4] * y + m[7];
return out;
};
/**
* Transforms the vec2 with a mat4
* 3rd vector component is implicitly '0'
* 4th vector component is implicitly '1'
*
* @param {vec2} out the receiving vector
* @param {vec2} a the vector to transform
* @param {mat4} m matrix to transform with
* @returns {vec2} out
*/
vec2.transformMat4 = function(out, a, m) {
var x = a[0],
y = a[1];
out[0] = m[0] * x + m[4] * y + m[12];
out[1] = m[1] * x + m[5] * y + m[13];
return out;
};
/**
* Perform some operation over an array of vec2s.
*
* @param {Array} a the array of vectors to iterate over
* @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed
* @param {Number} offset Number of elements to skip at the beginning of the array
* @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array
* @param {Function} fn Function to call for each vector in the array
* @param {Object} [arg] additional argument to pass to fn
* @returns {Array} a
* @function
*/
vec2.forEach = (function() {
var vec = vec2.create();
return function(a, stride, offset, count, fn, arg) {
var i, l;
if(!stride) {
stride = 2;
}
if(!offset) {
offset = 0;
}
if(count) {
l = Math.min((count * stride) + offset, a.length);
} else {
l = a.length;
}
for(i = offset; i < l; i += stride) {
vec[0] = a[i]; vec[1] = a[i+1];
fn(vec, vec, arg);
a[i] = vec[0]; a[i+1] = vec[1];
}
return a;
};
})();
/**
* Returns a string representation of a vector
*
* @param {vec2} vec vector to represent as a string
* @returns {String} string representation of the vector
*/
vec2.str = function (a) {
return 'vec2(' + a[0] + ', ' + a[1] + ')';
};
if(typeof(exports) !== 'undefined') {
exports.vec2 = vec2;
}
;
/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/**
* @class 3 Dimensional Vector
* @name vec3
*/
var vec3 = {};
/**
* Creates a new, empty vec3
*
* @returns {vec3} a new 3D vector
*/
vec3.create = function() {
var out = new GLMAT_ARRAY_TYPE(3);
out[0] = 0;
out[1] = 0;
out[2] = 0;
return out;
};
/**
* Creates a new vec3 initialized with values from an existing vector
*
* @param {vec3} a vector to clone
* @returns {vec3} a new 3D vector
*/
vec3.clone = function(a) {
var out = new GLMAT_ARRAY_TYPE(3);
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
return out;
};
/**
* Creates a new vec3 initialized with the given values
*
* @param {Number} x X component
* @param {Number} y Y component
* @param {Number} z Z component
* @returns {vec3} a new 3D vector
*/
vec3.fromValues = function(x, y, z) {
var out = new GLMAT_ARRAY_TYPE(3);
out[0] = x;
out[1] = y;
out[2] = z;
return out;
};
/**
* Copy the values from one vec3 to another
*
* @param {vec3} out the receiving vector
* @param {vec3} a the source vector
* @returns {vec3} out
*/
vec3.copy = function(out, a) {
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
return out;
};
/**
* Set the components of a vec3 to the given values
*
* @param {vec3} out the receiving vector
* @param {Number} x X component
* @param {Number} y Y component
* @param {Number} z Z component
* @returns {vec3} out
*/
vec3.set = function(out, x, y, z) {
out[0] = x;
out[1] = y;
out[2] = z;
return out;
};
/**
* Adds two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
vec3.add = function(out, a, b) {
out[0] = a[0] + b[0];
out[1] = a[1] + b[1];
out[2] = a[2] + b[2];
return out;
};
/**
* Subtracts vector b from vector a
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
vec3.subtract = function(out, a, b) {
out[0] = a[0] - b[0];
out[1] = a[1] - b[1];
out[2] = a[2] - b[2];
return out;
};
/**
* Alias for {@link vec3.subtract}
* @function
*/
vec3.sub = vec3.subtract;
/**
* Multiplies two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
vec3.multiply = function(out, a, b) {
out[0] = a[0] * b[0];
out[1] = a[1] * b[1];
out[2] = a[2] * b[2];
return out;
};
/**
* Alias for {@link vec3.multiply}
* @function
*/
vec3.mul = vec3.multiply;
/**
* Divides two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
vec3.divide = function(out, a, b) {
out[0] = a[0] / b[0];
out[1] = a[1] / b[1];
out[2] = a[2] / b[2];
return out;
};
/**
* Alias for {@link vec3.divide}
* @function
*/
vec3.div = vec3.divide;
/**
* Returns the minimum of two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
vec3.min = function(out, a, b) {
out[0] = Math.min(a[0], b[0]);
out[1] = Math.min(a[1], b[1]);
out[2] = Math.min(a[2], b[2]);
return out;
};
/**
* Returns the maximum of two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
vec3.max = function(out, a, b) {
out[0] = Math.max(a[0], b[0]);
out[1] = Math.max(a[1], b[1]);
out[2] = Math.max(a[2], b[2]);
return out;
};
/**
* Scales a vec3 by a scalar number
*
* @param {vec3} out the receiving vector
* @param {vec3} a the vector to scale
* @param {Number} b amount to scale the vector by
* @returns {vec3} out
*/
vec3.scale = function(out, a, b) {
out[0] = a[0] * b;
out[1] = a[1] * b;
out[2] = a[2] * b;
return out;
};
/**
* Adds two vec3's after scaling the second operand by a scalar value
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @param {Number} scale the amount to scale b by before adding
* @returns {vec3} out
*/
vec3.scaleAndAdd = function(out, a, b, scale) {
out[0] = a[0] + (b[0] * scale);
out[1] = a[1] + (b[1] * scale);
out[2] = a[2] + (b[2] * scale);
return out;
};
/**
* Calculates the euclidian distance between two vec3's
*
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {Number} distance between a and b
*/
vec3.distance = function(a, b) {
var x = b[0] - a[0],
y = b[1] - a[1],
z = b[2] - a[2];
return Math.sqrt(x*x + y*y + z*z);
};
/**
* Alias for {@link vec3.distance}
* @function
*/
vec3.dist = vec3.distance;
/**
* Calculates the squared euclidian distance between two vec3's
*
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {Number} squared distance between a and b
*/
vec3.squaredDistance = function(a, b) {
var x = b[0] - a[0],
y = b[1] - a[1],
z = b[2] - a[2];
return x*x + y*y + z*z;
};
/**
* Alias for {@link vec3.squaredDistance}
* @function
*/
vec3.sqrDist = vec3.squaredDistance;
/**
* Calculates the length of a vec3
*
* @param {vec3} a vector to calculate length of
* @returns {Number} length of a
*/
vec3.length = function (a) {
var x = a[0],
y = a[1],
z = a[2];
return Math.sqrt(x*x + y*y + z*z);
};
/**
* Alias for {@link vec3.length}
* @function
*/
vec3.len = vec3.length;
/**
* Calculates the squared length of a vec3
*
* @param {vec3} a vector to calculate squared length of
* @returns {Number} squared length of a
*/
vec3.squaredLength = function (a) {
var x = a[0],
y = a[1],
z = a[2];
return x*x + y*y + z*z;
};
/**
* Alias for {@link vec3.squaredLength}
* @function
*/
vec3.sqrLen = vec3.squaredLength;
/**
* Negates the components of a vec3
*
* @param {vec3} out the receiving vector
* @param {vec3} a vector to negate
* @returns {vec3} out
*/
vec3.negate = function(out, a) {
out[0] = -a[0];
out[1] = -a[1];
out[2] = -a[2];
return out;
};
/**
* Normalize a vec3
*
* @param {vec3} out the receiving vector
* @param {vec3} a vector to normalize
* @returns {vec3} out
*/
vec3.normalize = function(out, a) {
var x = a[0],
y = a[1],
z = a[2];
var len = x*x + y*y + z*z;
if (len > 0) {
//TODO: evaluate use of glm_invsqrt here?
len = 1 / Math.sqrt(len);
out[0] = a[0] * len;
out[1] = a[1] * len;
out[2] = a[2] * len;
}
return out;
};
/**
* Calculates the dot product of two vec3's
*
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {Number} dot product of a and b
*/
vec3.dot = function (a, b) {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
};
/**
* Computes the cross product of two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
vec3.cross = function(out, a, b) {
var ax = a[0], ay = a[1], az = a[2],
bx = b[0], by = b[1], bz = b[2];
out[0] = ay * bz - az * by;
out[1] = az * bx - ax * bz;
out[2] = ax * by - ay * bx;
return out;
};
/**
* Performs a linear interpolation between two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @param {Number} t interpolation amount between the two inputs
* @returns {vec3} out
*/
vec3.lerp = function (out, a, b, t) {
var ax = a[0],
ay = a[1],
az = a[2];
out[0] = ax + t * (b[0] - ax);
out[1] = ay + t * (b[1] - ay);
out[2] = az + t * (b[2] - az);
return out;
};
/**
* Generates a random vector with the given scale
*
* @param {vec3} out the receiving vector
* @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned
* @returns {vec3} out
*/
vec3.random = function (out, scale) {
scale = scale || 1.0;
var r = GLMAT_RANDOM() * 2.0 * Math.PI;
var z = (GLMAT_RANDOM() * 2.0) - 1.0;
var zScale = Math.sqrt(1.0-z*z) * scale;
out[0] = Math.cos(r) * zScale;
out[1] = Math.sin(r) * zScale;
out[2] = z * scale;
return out;
};
/**
* Transforms the vec3 with a mat4.
* 4th vector component is implicitly '1'
*
* @param {vec3} out the receiving vector
* @param {vec3} a the vector to transform
* @param {mat4} m matrix to transform with
* @returns {vec3} out
*/
vec3.transformMat4 = function(out, a, m) {
var x = a[0], y = a[1], z = a[2];
out[0] = m[0] * x + m[4] * y + m[8] * z + m[12];
out[1] = m[1] * x + m[5] * y + m[9] * z + m[13];
out[2] = m[2] * x + m[6] * y + m[10] * z + m[14];
return out;
};
/**
* Transforms the vec3 with a mat3.
*
* @param {vec3} out the receiving vector
* @param {vec3} a the vector to transform
* @param {mat4} m the 3x3 matrix to transform with
* @returns {vec3} out
*/
vec3.transformMat3 = function(out, a, m) {
var x = a[0], y = a[1], z = a[2];
out[0] = x * m[0] + y * m[3] + z * m[6];
out[1] = x * m[1] + y * m[4] + z * m[7];
out[2] = x * m[2] + y * m[5] + z * m[8];
return out;
};
/**
* Transforms the vec3 with a quat
*
* @param {vec3} out the receiving vector
* @param {vec3} a the vector to transform
* @param {quat} q quaternion to transform with
* @returns {vec3} out
*/
vec3.transformQuat = function(out, a, q) {
// benchmarks: http://jsperf.com/quaternion-transform-vec3-implementations
var x = a[0], y = a[1], z = a[2],
qx = q[0], qy = q[1], qz = q[2], qw = q[3],
// calculate quat * vec
ix = qw * x + qy * z - qz * y,
iy = qw * y + qz * x - qx * z,
iz = qw * z + qx * y - qy * x,
iw = -qx * x - qy * y - qz * z;
// calculate result * inverse quat
out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
return out;
};
/**
* Perform some operation over an array of vec3s.
*
* @param {Array} a the array of vectors to iterate over
* @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed
* @param {Number} offset Number of elements to skip at the beginning of the array
* @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array
* @param {Function} fn Function to call for each vector in the array
* @param {Object} [arg] additional argument to pass to fn
* @returns {Array} a
* @function
*/
vec3.forEach = (function() {
var vec = vec3.create();
return function(a, stride, offset, count, fn, arg) {
var i, l;
if(!stride) {
stride = 3;
}
if(!offset) {
offset = 0;
}
if(count) {
l = Math.min((count * stride) + offset, a.length);
} else {
l = a.length;
}
for(i = offset; i < l; i += stride) {
vec[0] = a[i]; vec[1] = a[i+1]; vec[2] = a[i+2];
fn(vec, vec, arg);
a[i] = vec[0]; a[i+1] = vec[1]; a[i+2] = vec[2];
}
return a;
};
})();
/**
* Returns a string representation of a vector
*
* @param {vec3} vec vector to represent as a string
* @returns {String} string representation of the vector
*/
vec3.str = function (a) {
return 'vec3(' + a[0] + ', ' + a[1] + ', ' + a[2] + ')';
};
if(typeof(exports) !== 'undefined') {
exports.vec3 = vec3;
}
;
/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/**
* @class 4 Dimensional Vector
* @name vec4
*/
var vec4 = {};
/**
* Creates a new, empty vec4
*
* @returns {vec4} a new 4D vector
*/
vec4.create = function() {
var out = new GLMAT_ARRAY_TYPE(4);
out[0] = 0;
out[1] = 0;
out[2] = 0;
out[3] = 0;
return out;
};
/**
* Creates a new vec4 initialized with values from an existing vector
*
* @param {vec4} a vector to clone
* @returns {vec4} a new 4D vector
*/
vec4.clone = function(a) {
var out = new GLMAT_ARRAY_TYPE(4);
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
return out;
};
/**
* Creates a new vec4 initialized with the given values
*
* @param {Number} x X component
* @param {Number} y Y component
* @param {Number} z Z component
* @param {Number} w W component
* @returns {vec4} a new 4D vector
*/
vec4.fromValues = function(x, y, z, w) {
var out = new GLMAT_ARRAY_TYPE(4);
out[0] = x;
out[1] = y;
out[2] = z;
out[3] = w;
return out;
};
/**
* Copy the values from one vec4 to another
*
* @param {vec4} out the receiving vector
* @param {vec4} a the source vector
* @returns {vec4} out
*/
vec4.copy = function(out, a) {
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
return out;
};
/**
* Set the components of a vec4 to the given values
*
* @param {vec4} out the receiving vector
* @param {Number} x X component
* @param {Number} y Y component
* @param {Number} z Z component
* @param {Number} w W component
* @returns {vec4} out
*/
vec4.set = function(out, x, y, z, w) {
out[0] = x;
out[1] = y;
out[2] = z;
out[3] = w;
return out;
};
/**
* Adds two vec4's
*
* @param {vec4} out the receiving vector
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @returns {vec4} out
*/
vec4.add = function(out, a, b) {
out[0] = a[0] + b[0];
out[1] = a[1] + b[1];
out[2] = a[2] + b[2];
out[3] = a[3] + b[3];
return out;
};
/**
* Subtracts vector b from vector a
*
* @param {vec4} out the receiving vector
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @returns {vec4} out
*/
vec4.subtract = function(out, a, b) {
out[0] = a[0] - b[0];
out[1] = a[1] - b[1];
out[2] = a[2] - b[2];
out[3] = a[3] - b[3];
return out;
};
/**
* Alias for {@link vec4.subtract}
* @function
*/
vec4.sub = vec4.subtract;
/**
* Multiplies two vec4's
*
* @param {vec4} out the receiving vector
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @returns {vec4} out
*/
vec4.multiply = function(out, a, b) {
out[0] = a[0] * b[0];
out[1] = a[1] * b[1];
out[2] = a[2] * b[2];
out[3] = a[3] * b[3];
return out;
};
/**
* Alias for {@link vec4.multiply}
* @function
*/
vec4.mul = vec4.multiply;
/**
* Divides two vec4's
*
* @param {vec4} out the receiving vector
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @returns {vec4} out
*/
vec4.divide = function(out, a, b) {
out[0] = a[0] / b[0];
out[1] = a[1] / b[1];
out[2] = a[2] / b[2];
out[3] = a[3] / b[3];
return out;
};
/**
* Alias for {@link vec4.divide}
* @function
*/
vec4.div = vec4.divide;
/**
* Returns the minimum of two vec4's
*
* @param {vec4} out the receiving vector
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @returns {vec4} out
*/
vec4.min = function(out, a, b) {
out[0] = Math.min(a[0], b[0]);
out[1] = Math.min(a[1], b[1]);
out[2] = Math.min(a[2], b[2]);
out[3] = Math.min(a[3], b[3]);
return out;
};
/**
* Returns the maximum of two vec4's
*
* @param {vec4} out the receiving vector
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @returns {vec4} out
*/
vec4.max = function(out, a, b) {
out[0] = Math.max(a[0], b[0]);
out[1] = Math.max(a[1], b[1]);
out[2] = Math.max(a[2], b[2]);
out[3] = Math.max(a[3], b[3]);
return out;
};
/**
* Scales a vec4 by a scalar number
*
* @param {vec4} out the receiving vector
* @param {vec4} a the vector to scale
* @param {Number} b amount to scale the vector by
* @returns {vec4} out
*/
vec4.scale = function(out, a, b) {
out[0] = a[0] * b;
out[1] = a[1] * b;
out[2] = a[2] * b;
out[3] = a[3] * b;
return out;
};
/**
* Adds two vec4's after scaling the second operand by a scalar value
*
* @param {vec4} out the receiving vector
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @param {Number} scale the amount to scale b by before adding
* @returns {vec4} out
*/
vec4.scaleAndAdd = function(out, a, b, scale) {
out[0] = a[0] + (b[0] * scale);
out[1] = a[1] + (b[1] * scale);
out[2] = a[2] + (b[2] * scale);
out[3] = a[3] + (b[3] * scale);
return out;
};
/**
* Calculates the euclidian distance between two vec4's
*
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @returns {Number} distance between a and b
*/
vec4.distance = function(a, b) {
var x = b[0] - a[0],
y = b[1] - a[1],
z = b[2] - a[2],
w = b[3] - a[3];
return Math.sqrt(x*x + y*y + z*z + w*w);
};
/**
* Alias for {@link vec4.distance}
* @function
*/
vec4.dist = vec4.distance;
/**
* Calculates the squared euclidian distance between two vec4's
*
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @returns {Number} squared distance between a and b
*/
vec4.squaredDistance = function(a, b) {
var x = b[0] - a[0],
y = b[1] - a[1],
z = b[2] - a[2],
w = b[3] - a[3];
return x*x + y*y + z*z + w*w;
};
/**
* Alias for {@link vec4.squaredDistance}
* @function
*/
vec4.sqrDist = vec4.squaredDistance;
/**
* Calculates the length of a vec4
*
* @param {vec4} a vector to calculate length of
* @returns {Number} length of a
*/
vec4.length = function (a) {
var x = a[0],
y = a[1],
z = a[2],
w = a[3];
return Math.sqrt(x*x + y*y + z*z + w*w);
};
/**
* Alias for {@link vec4.length}
* @function
*/
vec4.len = vec4.length;
/**
* Calculates the squared length of a vec4
*
* @param {vec4} a vector to calculate squared length of
* @returns {Number} squared length of a
*/
vec4.squaredLength = function (a) {
var x = a[0],
y = a[1],
z = a[2],
w = a[3];
return x*x + y*y + z*z + w*w;
};
/**
* Alias for {@link vec4.squaredLength}
* @function
*/
vec4.sqrLen = vec4.squaredLength;
/**
* Negates the components of a vec4
*
* @param {vec4} out the receiving vector
* @param {vec4} a vector to negate
* @returns {vec4} out
*/
vec4.negate = function(out, a) {
out[0] = -a[0];
out[1] = -a[1];
out[2] = -a[2];
out[3] = -a[3];
return out;
};
/**
* Normalize a vec4
*
* @param {vec4} out the receiving vector
* @param {vec4} a vector to normalize
* @returns {vec4} out
*/
vec4.normalize = function(out, a) {
var x = a[0],
y = a[1],
z = a[2],
w = a[3];
var len = x*x + y*y + z*z + w*w;
if (len > 0) {
len = 1 / Math.sqrt(len);
out[0] = a[0] * len;
out[1] = a[1] * len;
out[2] = a[2] * len;
out[3] = a[3] * len;
}
return out;
};
/**
* Calculates the dot product of two vec4's
*
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @returns {Number} dot product of a and b
*/
vec4.dot = function (a, b) {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
};
/**
* Performs a linear interpolation between two vec4's
*
* @param {vec4} out the receiving vector
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @param {Number} t interpolation amount between the two inputs
* @returns {vec4} out
*/
vec4.lerp = function (out, a, b, t) {
var ax = a[0],
ay = a[1],
az = a[2],
aw = a[3];
out[0] = ax + t * (b[0] - ax);
out[1] = ay + t * (b[1] - ay);
out[2] = az + t * (b[2] - az);
out[3] = aw + t * (b[3] - aw);
return out;
};
/**
* Generates a random vector with the given scale
*
* @param {vec4} out the receiving vector
* @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned
* @returns {vec4} out
*/
vec4.random = function (out, scale) {
scale = scale || 1.0;
//TODO: This is a pretty awful way of doing this. Find something better.
out[0] = GLMAT_RANDOM();
out[1] = GLMAT_RANDOM();
out[2] = GLMAT_RANDOM();
out[3] = GLMAT_RANDOM();
vec4.normalize(out, out);
vec4.scale(out, out, scale);
return out;
};
/**
* Transforms the vec4 with a mat4.
*
* @param {vec4} out the receiving vector
* @param {vec4} a the vector to transform
* @param {mat4} m matrix to transform with
* @returns {vec4} out
*/
vec4.transformMat4 = function(out, a, m) {
var x = a[0], y = a[1], z = a[2], w = a[3];
out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;
out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;
out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;
out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;
return out;
};
/**
* Transforms the vec4 with a quat
*
* @param {vec4} out the receiving vector
* @param {vec4} a the vector to transform
* @param {quat} q quaternion to transform with
* @returns {vec4} out
*/
vec4.transformQuat = function(out, a, q) {
var x = a[0], y = a[1], z = a[2],
qx = q[0], qy = q[1], qz = q[2], qw = q[3],
// calculate quat * vec
ix = qw * x + qy * z - qz * y,
iy = qw * y + qz * x - qx * z,
iz = qw * z + qx * y - qy * x,
iw = -qx * x - qy * y - qz * z;
// calculate result * inverse quat
out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
return out;
};
/**
* Perform some operation over an array of vec4s.
*
* @param {Array} a the array of vectors to iterate over
* @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed
* @param {Number} offset Number of elements to skip at the beginning of the array
* @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array
* @param {Function} fn Function to call for each vector in the array
* @param {Object} [arg] additional argument to pass to fn
* @returns {Array} a
* @function
*/
vec4.forEach = (function() {
var vec = vec4.create();
return function(a, stride, offset, count, fn, arg) {
var i, l;
if(!stride) {
stride = 4;
}
if(!offset) {
offset = 0;
}
if(count) {
l = Math.min((count * stride) + offset, a.length);
} else {
l = a.length;
}
for(i = offset; i < l; i += stride) {
vec[0] = a[i]; vec[1] = a[i+1]; vec[2] = a[i+2]; vec[3] = a[i+3];
fn(vec, vec, arg);
a[i] = vec[0]; a[i+1] = vec[1]; a[i+2] = vec[2]; a[i+3] = vec[3];
}
return a;
};
})();
/**
* Returns a string representation of a vector
*
* @param {vec4} vec vector to represent as a string
* @returns {String} string representation of the vector
*/
vec4.str = function (a) {
return 'vec4(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ')';
};
if(typeof(exports) !== 'undefined') {
exports.vec4 = vec4;
}
;
/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/**
* @class 2x2 Matrix
* @name mat2
*/
var mat2 = {};
/**
* Creates a new identity mat2
*
* @returns {mat2} a new 2x2 matrix
*/
mat2.create = function() {
var out = new GLMAT_ARRAY_TYPE(4);
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 1;
return out;
};
/**
* Creates a new mat2 initialized with values from an existing matrix
*
* @param {mat2} a matrix to clone
* @returns {mat2} a new 2x2 matrix
*/
mat2.clone = function(a) {
var out = new GLMAT_ARRAY_TYPE(4);
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
return out;
};
/**
* Copy the values from one mat2 to another
*
* @param {mat2} out the receiving matrix
* @param {mat2} a the source matrix
* @returns {mat2} out
*/
mat2.copy = function(out, a) {
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
return out;
};
/**
* Set a mat2 to the identity matrix
*
* @param {mat2} out the receiving matrix
* @returns {mat2} out
*/
mat2.identity = function(out) {
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 1;
return out;
};
/**
* Transpose the values of a mat2
*
* @param {mat2} out the receiving matrix
* @param {mat2} a the source matrix
* @returns {mat2} out
*/
mat2.transpose = function(out, a) {
// If we are transposing ourselves we can skip a few steps but have to cache some values
if (out === a) {
var a1 = a[1];
out[1] = a[2];
out[2] = a1;
} else {
out[0] = a[0];
out[1] = a[2];
out[2] = a[1];
out[3] = a[3];
}
return out;
};
/**
* Inverts a mat2
*
* @param {mat2} out the receiving matrix
* @param {mat2} a the source matrix
* @returns {mat2} out
*/
mat2.invert = function(out, a) {
var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3],
// Calculate the determinant
det = a0 * a3 - a2 * a1;
if (!det) {
return null;
}
det = 1.0 / det;
out[0] = a3 * det;
out[1] = -a1 * det;
out[2] = -a2 * det;
out[3] = a0 * det;
return out;
};
/**
* Calculates the adjugate of a mat2
*
* @param {mat2} out the receiving matrix
* @param {mat2} a the source matrix
* @returns {mat2} out
*/
mat2.adjoint = function(out, a) {
// Caching this value is nessecary if out == a
var a0 = a[0];
out[0] = a[3];
out[1] = -a[1];
out[2] = -a[2];
out[3] = a0;
return out;
};
/**
* Calculates the determinant of a mat2
*
* @param {mat2} a the source matrix
* @returns {Number} determinant of a
*/
mat2.determinant = function (a) {
return a[0] * a[3] - a[2] * a[1];
};
/**
* Multiplies two mat2's
*
* @param {mat2} out the receiving matrix
* @param {mat2} a the first operand
* @param {mat2} b the second operand
* @returns {mat2} out
*/
mat2.multiply = function (out, a, b) {
var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3];
var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
out[0] = a0 * b0 + a1 * b2;
out[1] = a0 * b1 + a1 * b3;
out[2] = a2 * b0 + a3 * b2;
out[3] = a2 * b1 + a3 * b3;
return out;
};
/**
* Alias for {@link mat2.multiply}
* @function
*/
mat2.mul = mat2.multiply;
/**
* Rotates a mat2 by the given angle
*
* @param {mat2} out the receiving matrix
* @param {mat2} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat2} out
*/
mat2.rotate = function (out, a, rad) {
var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3],
s = Math.sin(rad),
c = Math.cos(rad);
out[0] = a0 * c + a1 * s;
out[1] = a0 * -s + a1 * c;
out[2] = a2 * c + a3 * s;
out[3] = a2 * -s + a3 * c;
return out;
};
/**
* Scales the mat2 by the dimensions in the given vec2
*
* @param {mat2} out the receiving matrix
* @param {mat2} a the matrix to rotate
* @param {vec2} v the vec2 to scale the matrix by
* @returns {mat2} out
**/
mat2.scale = function(out, a, v) {
var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3],
v0 = v[0], v1 = v[1];
out[0] = a0 * v0;
out[1] = a1 * v1;
out[2] = a2 * v0;
out[3] = a3 * v1;
return out;
};
/**
* Returns a string representation of a mat2
*
* @param {mat2} mat matrix to represent as a string
* @returns {String} string representation of the matrix
*/
mat2.str = function (a) {
return 'mat2(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ')';
};
if(typeof(exports) !== 'undefined') {
exports.mat2 = mat2;
}
;
/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/**
* @class 2x3 Matrix
* @name mat2d
*
* @description
* A mat2d contains six elements defined as:
* <pre>
* [a, b,
* c, d,
* tx,ty]
* </pre>
* This is a short form for the 3x3 matrix:
* <pre>
* [a, b, 0
* c, d, 0
* tx,ty,1]
* </pre>
* The last column is ignored so the array is shorter and operations are faster.
*/
var mat2d = {};
/**
* Creates a new identity mat2d
*
* @returns {mat2d} a new 2x3 matrix
*/
mat2d.create = function() {
var out = new GLMAT_ARRAY_TYPE(6);
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 1;
out[4] = 0;
out[5] = 0;
return out;
};
/**
* Creates a new mat2d initialized with values from an existing matrix
*
* @param {mat2d} a matrix to clone
* @returns {mat2d} a new 2x3 matrix
*/
mat2d.clone = function(a) {
var out = new GLMAT_ARRAY_TYPE(6);
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
out[4] = a[4];
out[5] = a[5];
return out;
};
/**
* Copy the values from one mat2d to another
*
* @param {mat2d} out the receiving matrix
* @param {mat2d} a the source matrix
* @returns {mat2d} out
*/
mat2d.copy = function(out, a) {
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
out[4] = a[4];
out[5] = a[5];
return out;
};
/**
* Set a mat2d to the identity matrix
*
* @param {mat2d} out the receiving matrix
* @returns {mat2d} out
*/
mat2d.identity = function(out) {
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 1;
out[4] = 0;
out[5] = 0;
return out;
};
/**
* Inverts a mat2d
*
* @param {mat2d} out the receiving matrix
* @param {mat2d} a the source matrix
* @returns {mat2d} out
*/
mat2d.invert = function(out, a) {
var aa = a[0], ab = a[1], ac = a[2], ad = a[3],
atx = a[4], aty = a[5];
var det = aa * ad - ab * ac;
if(!det){
return null;
}
det = 1.0 / det;
out[0] = ad * det;
out[1] = -ab * det;
out[2] = -ac * det;
out[3] = aa * det;
out[4] = (ac * aty - ad * atx) * det;
out[5] = (ab * atx - aa * aty) * det;
return out;
};
/**
* Calculates the determinant of a mat2d
*
* @param {mat2d} a the source matrix
* @returns {Number} determinant of a
*/
mat2d.determinant = function (a) {
return a[0] * a[3] - a[1] * a[2];
};
/**
* Multiplies two mat2d's
*
* @param {mat2d} out the receiving matrix
* @param {mat2d} a the first operand
* @param {mat2d} b the second operand
* @returns {mat2d} out
*/
mat2d.multiply = function (out, a, b) {
var aa = a[0], ab = a[1], ac = a[2], ad = a[3],
atx = a[4], aty = a[5],
ba = b[0], bb = b[1], bc = b[2], bd = b[3],
btx = b[4], bty = b[5];
out[0] = aa*ba + ab*bc;
out[1] = aa*bb + ab*bd;
out[2] = ac*ba + ad*bc;
out[3] = ac*bb + ad*bd;
out[4] = ba*atx + bc*aty + btx;
out[5] = bb*atx + bd*aty + bty;
return out;
};
/**
* Alias for {@link mat2d.multiply}
* @function
*/
mat2d.mul = mat2d.multiply;
/**
* Rotates a mat2d by the given angle
*
* @param {mat2d} out the receiving matrix
* @param {mat2d} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat2d} out
*/
mat2d.rotate = function (out, a, rad) {
var aa = a[0],
ab = a[1],
ac = a[2],
ad = a[3],
atx = a[4],
aty = a[5],
st = Math.sin(rad),
ct = Math.cos(rad);
out[0] = aa*ct + ab*st;
out[1] = -aa*st + ab*ct;
out[2] = ac*ct + ad*st;
out[3] = -ac*st + ct*ad;
out[4] = ct*atx + st*aty;
out[5] = ct*aty - st*atx;
return out;
};
/**
* Scales the mat2d by the dimensions in the given vec2
*
* @param {mat2d} out the receiving matrix
* @param {mat2d} a the matrix to translate
* @param {vec2} v the vec2 to scale the matrix by
* @returns {mat2d} out
**/
mat2d.scale = function(out, a, v) {
var vx = v[0], vy = v[1];
out[0] = a[0] * vx;
out[1] = a[1] * vy;
out[2] = a[2] * vx;
out[3] = a[3] * vy;
out[4] = a[4] * vx;
out[5] = a[5] * vy;
return out;
};
/**
* Translates the mat2d by the dimensions in the given vec2
*
* @param {mat2d} out the receiving matrix
* @param {mat2d} a the matrix to translate
* @param {vec2} v the vec2 to translate the matrix by
* @returns {mat2d} out
**/
mat2d.translate = function(out, a, v) {
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
out[4] = a[4] + v[0];
out[5] = a[5] + v[1];
return out;
};
/**
* Returns a string representation of a mat2d
*
* @param {mat2d} a matrix to represent as a string
* @returns {String} string representation of the matrix
*/
mat2d.str = function (a) {
return 'mat2d(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' +
a[3] + ', ' + a[4] + ', ' + a[5] + ')';
};
if(typeof(exports) !== 'undefined') {
exports.mat2d = mat2d;
}
;
/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/**
* @class 3x3 Matrix
* @name mat3
*/
var mat3 = {};
/**
* Creates a new identity mat3
*
* @returns {mat3} a new 3x3 matrix
*/
mat3.create = function() {
var out = new GLMAT_ARRAY_TYPE(9);
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 1;
out[5] = 0;
out[6] = 0;
out[7] = 0;
out[8] = 1;
return out;
};
/**
* Copies the upper-left 3x3 values into the given mat3.
*
* @param {mat3} out the receiving 3x3 matrix
* @param {mat4} a the source 4x4 matrix
* @returns {mat3} out
*/
mat3.fromMat4 = function(out, a) {
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[4];
out[4] = a[5];
out[5] = a[6];
out[6] = a[8];
out[7] = a[9];
out[8] = a[10];
return out;
};
/**
* Creates a new mat3 initialized with values from an existing matrix
*
* @param {mat3} a matrix to clone
* @returns {mat3} a new 3x3 matrix
*/
mat3.clone = function(a) {
var out = new GLMAT_ARRAY_TYPE(9);
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
out[4] = a[4];
out[5] = a[5];
out[6] = a[6];
out[7] = a[7];
out[8] = a[8];
return out;
};
/**
* Copy the values from one mat3 to another
*
* @param {mat3} out the receiving matrix
* @param {mat3} a the source matrix
* @returns {mat3} out
*/
mat3.copy = function(out, a) {
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
out[4] = a[4];
out[5] = a[5];
out[6] = a[6];
out[7] = a[7];
out[8] = a[8];
return out;
};
/**
* Set a mat3 to the identity matrix
*
* @param {mat3} out the receiving matrix
* @returns {mat3} out
*/
mat3.identity = function(out) {
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 1;
out[5] = 0;
out[6] = 0;
out[7] = 0;
out[8] = 1;
return out;
};
/**
* Transpose the values of a mat3
*
* @param {mat3} out the receiving matrix
* @param {mat3} a the source matrix
* @returns {mat3} out
*/
mat3.transpose = function(out, a) {
// If we are transposing ourselves we can skip a few steps but have to cache some values
if (out === a) {
var a01 = a[1], a02 = a[2], a12 = a[5];
out[1] = a[3];
out[2] = a[6];
out[3] = a01;
out[5] = a[7];
out[6] = a02;
out[7] = a12;
} else {
out[0] = a[0];
out[1] = a[3];
out[2] = a[6];
out[3] = a[1];
out[4] = a[4];
out[5] = a[7];
out[6] = a[2];
out[7] = a[5];
out[8] = a[8];
}
return out;
};
/**
* Inverts a mat3
*
* @param {mat3} out the receiving matrix
* @param {mat3} a the source matrix
* @returns {mat3} out
*/
mat3.invert = function(out, a) {
var a00 = a[0], a01 = a[1], a02 = a[2],
a10 = a[3], a11 = a[4], a12 = a[5],
a20 = a[6], a21 = a[7], a22 = a[8],
b01 = a22 * a11 - a12 * a21,
b11 = -a22 * a10 + a12 * a20,
b21 = a21 * a10 - a11 * a20,
// Calculate the determinant
det = a00 * b01 + a01 * b11 + a02 * b21;
if (!det) {
return null;
}
det = 1.0 / det;
out[0] = b01 * det;
out[1] = (-a22 * a01 + a02 * a21) * det;
out[2] = (a12 * a01 - a02 * a11) * det;
out[3] = b11 * det;
out[4] = (a22 * a00 - a02 * a20) * det;
out[5] = (-a12 * a00 + a02 * a10) * det;
out[6] = b21 * det;
out[7] = (-a21 * a00 + a01 * a20) * det;
out[8] = (a11 * a00 - a01 * a10) * det;
return out;
};
/**
* Calculates the adjugate of a mat3
*
* @param {mat3} out the receiving matrix
* @param {mat3} a the source matrix
* @returns {mat3} out
*/
mat3.adjoint = function(out, a) {
var a00 = a[0], a01 = a[1], a02 = a[2],
a10 = a[3], a11 = a[4], a12 = a[5],
a20 = a[6], a21 = a[7], a22 = a[8];
out[0] = (a11 * a22 - a12 * a21);
out[1] = (a02 * a21 - a01 * a22);
out[2] = (a01 * a12 - a02 * a11);
out[3] = (a12 * a20 - a10 * a22);
out[4] = (a00 * a22 - a02 * a20);
out[5] = (a02 * a10 - a00 * a12);
out[6] = (a10 * a21 - a11 * a20);
out[7] = (a01 * a20 - a00 * a21);
out[8] = (a00 * a11 - a01 * a10);
return out;
};
/**
* Calculates the determinant of a mat3
*
* @param {mat3} a the source matrix
* @returns {Number} determinant of a
*/
mat3.determinant = function (a) {
var a00 = a[0], a01 = a[1], a02 = a[2],
a10 = a[3], a11 = a[4], a12 = a[5],
a20 = a[6], a21 = a[7], a22 = a[8];
return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);
};
/**
* Multiplies two mat3's
*
* @param {mat3} out the receiving matrix
* @param {mat3} a the first operand
* @param {mat3} b the second operand
* @returns {mat3} out
*/
mat3.multiply = function (out, a, b) {
var a00 = a[0], a01 = a[1], a02 = a[2],
a10 = a[3], a11 = a[4], a12 = a[5],
a20 = a[6], a21 = a[7], a22 = a[8],
b00 = b[0], b01 = b[1], b02 = b[2],
b10 = b[3], b11 = b[4], b12 = b[5],
b20 = b[6], b21 = b[7], b22 = b[8];
out[0] = b00 * a00 + b01 * a10 + b02 * a20;
out[1] = b00 * a01 + b01 * a11 + b02 * a21;
out[2] = b00 * a02 + b01 * a12 + b02 * a22;
out[3] = b10 * a00 + b11 * a10 + b12 * a20;
out[4] = b10 * a01 + b11 * a11 + b12 * a21;
out[5] = b10 * a02 + b11 * a12 + b12 * a22;
out[6] = b20 * a00 + b21 * a10 + b22 * a20;
out[7] = b20 * a01 + b21 * a11 + b22 * a21;
out[8] = b20 * a02 + b21 * a12 + b22 * a22;
return out;
};
/**
* Alias for {@link mat3.multiply}
* @function
*/
mat3.mul = mat3.multiply;
/**
* Translate a mat3 by the given vector
*
* @param {mat3} out the receiving matrix
* @param {mat3} a the matrix to translate
* @param {vec2} v vector to translate by
* @returns {mat3} out
*/
mat3.translate = function(out, a, v) {
var a00 = a[0], a01 = a[1], a02 = a[2],
a10 = a[3], a11 = a[4], a12 = a[5],
a20 = a[6], a21 = a[7], a22 = a[8],
x = v[0], y = v[1];
out[0] = a00;
out[1] = a01;
out[2] = a02;
out[3] = a10;
out[4] = a11;
out[5] = a12;
out[6] = x * a00 + y * a10 + a20;
out[7] = x * a01 + y * a11 + a21;
out[8] = x * a02 + y * a12 + a22;
return out;
};
/**
* Rotates a mat3 by the given angle
*
* @param {mat3} out the receiving matrix
* @param {mat3} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat3} out
*/
mat3.rotate = function (out, a, rad) {
var a00 = a[0], a01 = a[1], a02 = a[2],
a10 = a[3], a11 = a[4], a12 = a[5],
a20 = a[6], a21 = a[7], a22 = a[8],
s = Math.sin(rad),
c = Math.cos(rad);
out[0] = c * a00 + s * a10;
out[1] = c * a01 + s * a11;
out[2] = c * a02 + s * a12;
out[3] = c * a10 - s * a00;
out[4] = c * a11 - s * a01;
out[5] = c * a12 - s * a02;
out[6] = a20;
out[7] = a21;
out[8] = a22;
return out;
};
/**
* Scales the mat3 by the dimensions in the given vec2
*
* @param {mat3} out the receiving matrix
* @param {mat3} a the matrix to rotate
* @param {vec2} v the vec2 to scale the matrix by
* @returns {mat3} out
**/
mat3.scale = function(out, a, v) {
var x = v[0], y = v[1];
out[0] = x * a[0];
out[1] = x * a[1];
out[2] = x * a[2];
out[3] = y * a[3];
out[4] = y * a[4];
out[5] = y * a[5];
out[6] = a[6];
out[7] = a[7];
out[8] = a[8];
return out;
};
/**
* Copies the values from a mat2d into a mat3
*
* @param {mat3} out the receiving matrix
* @param {mat2d} a the matrix to copy
* @returns {mat3} out
**/
mat3.fromMat2d = function(out, a) {
out[0] = a[0];
out[1] = a[1];
out[2] = 0;
out[3] = a[2];
out[4] = a[3];
out[5] = 0;
out[6] = a[4];
out[7] = a[5];
out[8] = 1;
return out;
};
/**
* Calculates a 3x3 matrix from the given quaternion
*
* @param {mat3} out mat3 receiving operation result
* @param {quat} q Quaternion to create matrix from
*
* @returns {mat3} out
*/
mat3.fromQuat = function (out, q) {
var x = q[0], y = q[1], z = q[2], w = q[3],
x2 = x + x,
y2 = y + y,
z2 = z + z,
xx = x * x2,
yx = y * x2,
yy = y * y2,
zx = z * x2,
zy = z * y2,
zz = z * z2,
wx = w * x2,
wy = w * y2,
wz = w * z2;
out[0] = 1 - yy - zz;
out[3] = yx - wz;
out[6] = zx + wy;
out[1] = yx + wz;
out[4] = 1 - xx - zz;
out[7] = zy - wx;
out[2] = zx - wy;
out[5] = zy + wx;
out[8] = 1 - xx - yy;
return out;
};
/**
* Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix
*
* @param {mat3} out mat3 receiving operation result
* @param {mat4} a Mat4 to derive the normal matrix from
*
* @returns {mat3} out
*/
mat3.normalFromMat4 = function (out, a) {
var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15],
b00 = a00 * a11 - a01 * a10,
b01 = a00 * a12 - a02 * a10,
b02 = a00 * a13 - a03 * a10,
b03 = a01 * a12 - a02 * a11,
b04 = a01 * a13 - a03 * a11,
b05 = a02 * a13 - a03 * a12,
b06 = a20 * a31 - a21 * a30,
b07 = a20 * a32 - a22 * a30,
b08 = a20 * a33 - a23 * a30,
b09 = a21 * a32 - a22 * a31,
b10 = a21 * a33 - a23 * a31,
b11 = a22 * a33 - a23 * a32,
// Calculate the determinant
det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
if (!det) {
return null;
}
det = 1.0 / det;
out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
return out;
};
/**
* Returns a string representation of a mat3
*
* @param {mat3} mat matrix to represent as a string
* @returns {String} string representation of the matrix
*/
mat3.str = function (a) {
return 'mat3(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' +
a[3] + ', ' + a[4] + ', ' + a[5] + ', ' +
a[6] + ', ' + a[7] + ', ' + a[8] + ')';
};
if(typeof(exports) !== 'undefined') {
exports.mat3 = mat3;
}
;
/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/**
* @class 4x4 Matrix
* @name mat4
*/
var mat4 = {};
/**
* Creates a new identity mat4
*
* @returns {mat4} a new 4x4 matrix
*/
mat4.create = function() {
var out = new GLMAT_ARRAY_TYPE(16);
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = 1;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = 1;
out[11] = 0;
out[12] = 0;
out[13] = 0;
out[14] = 0;
out[15] = 1;
return out;
};
/**
* Creates a new mat4 initialized with values from an existing matrix
*
* @param {mat4} a matrix to clone
* @returns {mat4} a new 4x4 matrix
*/
mat4.clone = function(a) {
var out = new GLMAT_ARRAY_TYPE(16);
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
out[4] = a[4];
out[5] = a[5];
out[6] = a[6];
out[7] = a[7];
out[8] = a[8];
out[9] = a[9];
out[10] = a[10];
out[11] = a[11];
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
return out;
};
/**
* Copy the values from one mat4 to another
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the source matrix
* @returns {mat4} out
*/
mat4.copy = function(out, a) {
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
out[4] = a[4];
out[5] = a[5];
out[6] = a[6];
out[7] = a[7];
out[8] = a[8];
out[9] = a[9];
out[10] = a[10];
out[11] = a[11];
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
return out;
};
/**
* Set a mat4 to the identity matrix
*
* @param {mat4} out the receiving matrix
* @returns {mat4} out
*/
mat4.identity = function(out) {
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = 1;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = 1;
out[11] = 0;
out[12] = 0;
out[13] = 0;
out[14] = 0;
out[15] = 1;
return out;
};
/**
* Transpose the values of a mat4
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the source matrix
* @returns {mat4} out
*/
mat4.transpose = function(out, a) {
// If we are transposing ourselves we can skip a few steps but have to cache some values
if (out === a) {
var a01 = a[1], a02 = a[2], a03 = a[3],
a12 = a[6], a13 = a[7],
a23 = a[11];
out[1] = a[4];
out[2] = a[8];
out[3] = a[12];
out[4] = a01;
out[6] = a[9];
out[7] = a[13];
out[8] = a02;
out[9] = a12;
out[11] = a[14];
out[12] = a03;
out[13] = a13;
out[14] = a23;
} else {
out[0] = a[0];
out[1] = a[4];
out[2] = a[8];
out[3] = a[12];
out[4] = a[1];
out[5] = a[5];
out[6] = a[9];
out[7] = a[13];
out[8] = a[2];
out[9] = a[6];
out[10] = a[10];
out[11] = a[14];
out[12] = a[3];
out[13] = a[7];
out[14] = a[11];
out[15] = a[15];
}
return out;
};
/**
* Inverts a mat4
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the source matrix
* @returns {mat4} out
*/
mat4.invert = function(out, a) {
var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15],
b00 = a00 * a11 - a01 * a10,
b01 = a00 * a12 - a02 * a10,
b02 = a00 * a13 - a03 * a10,
b03 = a01 * a12 - a02 * a11,
b04 = a01 * a13 - a03 * a11,
b05 = a02 * a13 - a03 * a12,
b06 = a20 * a31 - a21 * a30,
b07 = a20 * a32 - a22 * a30,
b08 = a20 * a33 - a23 * a30,
b09 = a21 * a32 - a22 * a31,
b10 = a21 * a33 - a23 * a31,
b11 = a22 * a33 - a23 * a32,
// Calculate the determinant
det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
if (!det) {
return null;
}
det = 1.0 / det;
out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
return out;
};
/**
* Calculates the adjugate of a mat4
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the source matrix
* @returns {mat4} out
*/
mat4.adjoint = function(out, a) {
var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
out[0] = (a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22));
out[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22));
out[2] = (a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12));
out[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12));
out[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22));
out[5] = (a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22));
out[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12));
out[7] = (a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12));
out[8] = (a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21));
out[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21));
out[10] = (a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11));
out[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11));
out[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21));
out[13] = (a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21));
out[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11));
out[15] = (a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11));
return out;
};
/**
* Calculates the determinant of a mat4
*
* @param {mat4} a the source matrix
* @returns {Number} determinant of a
*/
mat4.determinant = function (a) {
var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15],
b00 = a00 * a11 - a01 * a10,
b01 = a00 * a12 - a02 * a10,
b02 = a00 * a13 - a03 * a10,
b03 = a01 * a12 - a02 * a11,
b04 = a01 * a13 - a03 * a11,
b05 = a02 * a13 - a03 * a12,
b06 = a20 * a31 - a21 * a30,
b07 = a20 * a32 - a22 * a30,
b08 = a20 * a33 - a23 * a30,
b09 = a21 * a32 - a22 * a31,
b10 = a21 * a33 - a23 * a31,
b11 = a22 * a33 - a23 * a32;
// Calculate the determinant
return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
};
/**
* Multiplies two mat4's
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the first operand
* @param {mat4} b the second operand
* @returns {mat4} out
*/
mat4.multiply = function (out, a, b) {
var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
// Cache only the current line of the second matrix
var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
out[0] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
out[1] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
out[2] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
out[3] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
b0 = b[4]; b1 = b[5]; b2 = b[6]; b3 = b[7];
out[4] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
out[5] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
out[6] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
out[7] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
b0 = b[8]; b1 = b[9]; b2 = b[10]; b3 = b[11];
out[8] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
out[9] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
out[10] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
out[11] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
b0 = b[12]; b1 = b[13]; b2 = b[14]; b3 = b[15];
out[12] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
out[13] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
out[14] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
out[15] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
return out;
};
/**
* Alias for {@link mat4.multiply}
* @function
*/
mat4.mul = mat4.multiply;
/**
* Translate a mat4 by the given vector
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to translate
* @param {vec3} v vector to translate by
* @returns {mat4} out
*/
mat4.translate = function (out, a, v) {
var x = v[0], y = v[1], z = v[2],
a00, a01, a02, a03,
a10, a11, a12, a13,
a20, a21, a22, a23,
a30, a31, a32, a33;
a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3];
a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7];
a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11];
a30 = a[12]; a31 = a[13]; a32 = a[14]; a33 = a[15];
out[0] = a00 + a03*x;
out[1] = a01 + a03*y;
out[2] = a02 + a03*z;
out[3] = a03;
out[4] = a10 + a13*x;
out[5] = a11 + a13*y;
out[6] = a12 + a13*z;
out[7] = a13;
out[8] = a20 + a23*x;
out[9] = a21 + a23*y;
out[10] = a22 + a23*z;
out[11] = a23;
out[12] = a30 + a33*x;
out[13] = a31 + a33*y;
out[14] = a32 + a33*z;
out[15] = a33;
return out;
};
/**
* Scales the mat4 by the dimensions in the given vec3
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to scale
* @param {vec3} v the vec3 to scale the matrix by
* @returns {mat4} out
**/
mat4.scale = function(out, a, v) {
var x = v[0], y = v[1], z = v[2];
out[0] = a[0] * x;
out[1] = a[1] * x;
out[2] = a[2] * x;
out[3] = a[3] * x;
out[4] = a[4] * y;
out[5] = a[5] * y;
out[6] = a[6] * y;
out[7] = a[7] * y;
out[8] = a[8] * z;
out[9] = a[9] * z;
out[10] = a[10] * z;
out[11] = a[11] * z;
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
return out;
};
/**
* Rotates a mat4 by the given angle
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @param {vec3} axis the axis to rotate around
* @returns {mat4} out
*/
mat4.rotate = function (out, a, rad, axis) {
var x = axis[0], y = axis[1], z = axis[2],
len = Math.sqrt(x * x + y * y + z * z),
s, c, t,
a00, a01, a02, a03,
a10, a11, a12, a13,
a20, a21, a22, a23,
b00, b01, b02,
b10, b11, b12,
b20, b21, b22;
if (Math.abs(len) < GLMAT_EPSILON) { return null; }
len = 1 / len;
x *= len;
y *= len;
z *= len;
s = Math.sin(rad);
c = Math.cos(rad);
t = 1 - c;
a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3];
a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7];
a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11];
// Construct the elements of the rotation matrix
b00 = x * x * t + c; b01 = y * x * t + z * s; b02 = z * x * t - y * s;
b10 = x * y * t - z * s; b11 = y * y * t + c; b12 = z * y * t + x * s;
b20 = x * z * t + y * s; b21 = y * z * t - x * s; b22 = z * z * t + c;
// Perform rotation-specific matrix multiplication
out[0] = a00 * b00 + a10 * b01 + a20 * b02;
out[1] = a01 * b00 + a11 * b01 + a21 * b02;
out[2] = a02 * b00 + a12 * b01 + a22 * b02;
out[3] = a03 * b00 + a13 * b01 + a23 * b02;
out[4] = a00 * b10 + a10 * b11 + a20 * b12;
out[5] = a01 * b10 + a11 * b11 + a21 * b12;
out[6] = a02 * b10 + a12 * b11 + a22 * b12;
out[7] = a03 * b10 + a13 * b11 + a23 * b12;
out[8] = a00 * b20 + a10 * b21 + a20 * b22;
out[9] = a01 * b20 + a11 * b21 + a21 * b22;
out[10] = a02 * b20 + a12 * b21 + a22 * b22;
out[11] = a03 * b20 + a13 * b21 + a23 * b22;
if (a !== out) { // If the source and destination differ, copy the unchanged last row
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
}
return out;
};
/**
* Rotates a matrix by the given angle around the X axis
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat4} out
*/
mat4.rotateX = function (out, a, rad) {
var s = Math.sin(rad),
c = Math.cos(rad),
a10 = a[4],
a11 = a[5],
a12 = a[6],
a13 = a[7],
a20 = a[8],
a21 = a[9],
a22 = a[10],
a23 = a[11];
if (a !== out) { // If the source and destination differ, copy the unchanged rows
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
}
// Perform axis-specific matrix multiplication
out[4] = a10 * c + a20 * s;
out[5] = a11 * c + a21 * s;
out[6] = a12 * c + a22 * s;
out[7] = a13 * c + a23 * s;
out[8] = a20 * c - a10 * s;
out[9] = a21 * c - a11 * s;
out[10] = a22 * c - a12 * s;
out[11] = a23 * c - a13 * s;
return out;
};
/**
* Rotates a matrix by the given angle around the Y axis
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat4} out
*/
mat4.rotateY = function (out, a, rad) {
var s = Math.sin(rad),
c = Math.cos(rad),
a00 = a[0],
a01 = a[1],
a02 = a[2],
a03 = a[3],
a20 = a[8],
a21 = a[9],
a22 = a[10],
a23 = a[11];
if (a !== out) { // If the source and destination differ, copy the unchanged rows
out[4] = a[4];
out[5] = a[5];
out[6] = a[6];
out[7] = a[7];
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
}
// Perform axis-specific matrix multiplication
out[0] = a00 * c - a20 * s;
out[1] = a01 * c - a21 * s;
out[2] = a02 * c - a22 * s;
out[3] = a03 * c - a23 * s;
out[8] = a00 * s + a20 * c;
out[9] = a01 * s + a21 * c;
out[10] = a02 * s + a22 * c;
out[11] = a03 * s + a23 * c;
return out;
};
/**
* Rotates a matrix by the given angle around the Z axis
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat4} out
*/
mat4.rotateZ = function (out, a, rad) {
var s = Math.sin(rad),
c = Math.cos(rad),
a00 = a[0],
a01 = a[1],
a02 = a[2],
a03 = a[3],
a10 = a[4],
a11 = a[5],
a12 = a[6],
a13 = a[7];
if (a !== out) { // If the source and destination differ, copy the unchanged last row
out[8] = a[8];
out[9] = a[9];
out[10] = a[10];
out[11] = a[11];
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
}
// Perform axis-specific matrix multiplication
out[0] = a00 * c + a10 * s;
out[1] = a01 * c + a11 * s;
out[2] = a02 * c + a12 * s;
out[3] = a03 * c + a13 * s;
out[4] = a10 * c - a00 * s;
out[5] = a11 * c - a01 * s;
out[6] = a12 * c - a02 * s;
out[7] = a13 * c - a03 * s;
return out;
};
/**
* Creates a matrix from a quaternion rotation and vector translation
* This is equivalent to (but much faster than):
*
* mat4.identity(dest);
* mat4.translate(dest, vec);
* var quatMat = mat4.create();
* quat4.toMat4(quat, quatMat);
* mat4.multiply(dest, quatMat);
*
* @param {mat4} out mat4 receiving operation result
* @param {quat4} q Rotation quaternion
* @param {vec3} v Translation vector
* @returns {mat4} out
*/
mat4.fromRotationTranslation = function (out, q, v) {
// Quaternion math
var x = q[0], y = q[1], z = q[2], w = q[3],
x2 = x + x,
y2 = y + y,
z2 = z + z,
xx = x * x2,
xy = x * y2,
xz = x * z2,
yy = y * y2,
yz = y * z2,
zz = z * z2,
wx = w * x2,
wy = w * y2,
wz = w * z2;
out[0] = 1 - (yy + zz);
out[1] = xy + wz;
out[2] = xz - wy;
out[3] = 0;
out[4] = xy - wz;
out[5] = 1 - (xx + zz);
out[6] = yz + wx;
out[7] = 0;
out[8] = xz + wy;
out[9] = yz - wx;
out[10] = 1 - (xx + yy);
out[11] = 0;
out[12] = v[0];
out[13] = v[1];
out[14] = v[2];
out[15] = 1;
return out;
};
mat4.fromQuat = function (out, q) {
var x = q[0], y = q[1], z = q[2], w = q[3],
x2 = x + x,
y2 = y + y,
z2 = z + z,
xx = x * x2,
yx = y * x2,
yy = y * y2,
zx = z * x2,
zy = z * y2,
zz = z * z2,
wx = w * x2,
wy = w * y2,
wz = w * z2;
out[0] = 1 - yy - zz;
out[1] = yx + wz;
out[2] = zx - wy;
out[3] = 0;
out[4] = yx - wz;
out[5] = 1 - xx - zz;
out[6] = zy + wx;
out[7] = 0;
out[8] = zx + wy;
out[9] = zy - wx;
out[10] = 1 - xx - yy;
out[11] = 0;
out[12] = 0;
out[13] = 0;
out[14] = 0;
out[15] = 1;
return out;
};
/**
* Generates a frustum matrix with the given bounds
*
* @param {mat4} out mat4 frustum matrix will be written into
* @param {Number} left Left bound of the frustum
* @param {Number} right Right bound of the frustum
* @param {Number} bottom Bottom bound of the frustum
* @param {Number} top Top bound of the frustum
* @param {Number} near Near bound of the frustum
* @param {Number} far Far bound of the frustum
* @returns {mat4} out
*/
mat4.frustum = function (out, left, right, bottom, top, near, far) {
var rl = 1 / (right - left),
tb = 1 / (top - bottom),
nf = 1 / (near - far);
out[0] = (near * 2) * rl;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = (near * 2) * tb;
out[6] = 0;
out[7] = 0;
out[8] = (right + left) * rl;
out[9] = (top + bottom) * tb;
out[10] = (far + near) * nf;
out[11] = -1;
out[12] = 0;
out[13] = 0;
out[14] = (far * near * 2) * nf;
out[15] = 0;
return out;
};
/**
* Generates a perspective projection matrix with the given bounds
*
* @param {mat4} out mat4 frustum matrix will be written into
* @param {number} fovy Vertical field of view in radians
* @param {number} aspect Aspect ratio. typically viewport width/height
* @param {number} near Near bound of the frustum
* @param {number} far Far bound of the frustum
* @returns {mat4} out
*/
mat4.perspective = function (out, fovy, aspect, near, far) {
var f = 1.0 / Math.tan(fovy / 2),
nf = 1 / (near - far);
out[0] = f / aspect;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = f;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = (far + near) * nf;
out[11] = -1;
out[12] = 0;
out[13] = 0;
out[14] = (2 * far * near) * nf;
out[15] = 0;
return out;
};
/**
* Generates a orthogonal projection matrix with the given bounds
*
* @param {mat4} out mat4 frustum matrix will be written into
* @param {number} left Left bound of the frustum
* @param {number} right Right bound of the frustum
* @param {number} bottom Bottom bound of the frustum
* @param {number} top Top bound of the frustum
* @param {number} near Near bound of the frustum
* @param {number} far Far bound of the frustum
* @returns {mat4} out
*/
mat4.ortho = function (out, left, right, bottom, top, near, far) {
var lr = 1 / (left - right),
bt = 1 / (bottom - top),
nf = 1 / (near - far);
out[0] = -2 * lr;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = -2 * bt;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = 2 * nf;
out[11] = 0;
out[12] = (left + right) * lr;
out[13] = (top + bottom) * bt;
out[14] = (far + near) * nf;
out[15] = 1;
return out;
};
/**
* Generates a look-at matrix with the given eye position, focal point, and up axis
*
* @param {mat4} out mat4 frustum matrix will be written into
* @param {vec3} eye Position of the viewer
* @param {vec3} center Point the viewer is looking at
* @param {vec3} up vec3 pointing up
* @returns {mat4} out
*/
mat4.lookAt = function (out, eye, center, up) {
var x0, x1, x2, y0, y1, y2, z0, z1, z2, len,
eyex = eye[0],
eyey = eye[1],
eyez = eye[2],
upx = up[0],
upy = up[1],
upz = up[2],
centerx = center[0],
centery = center[1],
centerz = center[2];
if (Math.abs(eyex - centerx) < GLMAT_EPSILON &&
Math.abs(eyey - centery) < GLMAT_EPSILON &&
Math.abs(eyez - centerz) < GLMAT_EPSILON) {
return mat4.identity(out);
}
z0 = eyex - centerx;
z1 = eyey - centery;
z2 = eyez - centerz;
len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2);
z0 *= len;
z1 *= len;
z2 *= len;
x0 = upy * z2 - upz * z1;
x1 = upz * z0 - upx * z2;
x2 = upx * z1 - upy * z0;
len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2);
if (!len) {
x0 = 0;
x1 = 0;
x2 = 0;
} else {
len = 1 / len;
x0 *= len;
x1 *= len;
x2 *= len;
}
y0 = z1 * x2 - z2 * x1;
y1 = z2 * x0 - z0 * x2;
y2 = z0 * x1 - z1 * x0;
len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2);
if (!len) {
y0 = 0;
y1 = 0;
y2 = 0;
} else {
len = 1 / len;
y0 *= len;
y1 *= len;
y2 *= len;
}
out[0] = x0;
out[1] = y0;
out[2] = z0;
out[3] = 0;
out[4] = x1;
out[5] = y1;
out[6] = z1;
out[7] = 0;
out[8] = x2;
out[9] = y2;
out[10] = z2;
out[11] = 0;
out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
out[15] = 1;
return out;
};
/**
* Returns a string representation of a mat4
*
* @param {mat4} mat matrix to represent as a string
* @returns {String} string representation of the matrix
*/
mat4.str = function (a) {
return 'mat4(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ', ' +
a[4] + ', ' + a[5] + ', ' + a[6] + ', ' + a[7] + ', ' +
a[8] + ', ' + a[9] + ', ' + a[10] + ', ' + a[11] + ', ' +
a[12] + ', ' + a[13] + ', ' + a[14] + ', ' + a[15] + ')';
};
if(typeof(exports) !== 'undefined') {
exports.mat4 = mat4;
}
;
/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/**
* @class Quaternion
* @name quat
*/
var quat = {};
/**
* Creates a new identity quat
*
* @returns {quat} a new quaternion
*/
quat.create = function() {
var out = new GLMAT_ARRAY_TYPE(4);
out[0] = 0;
out[1] = 0;
out[2] = 0;
out[3] = 1;
return out;
};
/**
* Sets a quaternion to represent the shortest rotation from one
* vector to another.
*
* Both vectors are assumed to be unit length.
*
* @param {quat} out the receiving quaternion.
* @param {vec3} a the initial vector
* @param {vec3} b the destination vector
* @returns {quat} out
*/
quat.rotationTo = (function() {
var tmpvec3 = vec3.create();
var xUnitVec3 = vec3.fromValues(1,0,0);
var yUnitVec3 = vec3.fromValues(0,1,0);
return function(out, a, b) {
var dot = vec3.dot(a, b);
if (dot < -0.999999) {
vec3.cross(tmpvec3, xUnitVec3, a);
if (vec3.length(tmpvec3) < 0.000001)
vec3.cross(tmpvec3, yUnitVec3, a);
vec3.normalize(tmpvec3, tmpvec3);
quat.setAxisAngle(out, tmpvec3, Math.PI);
return out;
} else if (dot > 0.999999) {
out[0] = 0;
out[1] = 0;
out[2] = 0;
out[3] = 1;
return out;
} else {
vec3.cross(tmpvec3, a, b);
out[0] = tmpvec3[0];
out[1] = tmpvec3[1];
out[2] = tmpvec3[2];
out[3] = 1 + dot;
return quat.normalize(out, out);
}
};
})();
/**
* Sets the specified quaternion with values corresponding to the given
* axes. Each axis is a vec3 and is expected to be unit length and
* perpendicular to all other specified axes.
*
* @param {vec3} view the vector representing the viewing direction
* @param {vec3} right the vector representing the local "right" direction
* @param {vec3} up the vector representing the local "up" direction
* @returns {quat} out
*/
quat.setAxes = (function() {
var matr = mat3.create();
return function(out, view, right, up) {
matr[0] = right[0];
matr[3] = right[1];
matr[6] = right[2];
matr[1] = up[0];
matr[4] = up[1];
matr[7] = up[2];
matr[2] = -view[0];
matr[5] = -view[1];
matr[8] = -view[2];
return quat.normalize(out, quat.fromMat3(out, matr));
};
})();
/**
* Creates a new quat initialized with values from an existing quaternion
*
* @param {quat} a quaternion to clone
* @returns {quat} a new quaternion
* @function
*/
quat.clone = vec4.clone;
/**
* Creates a new quat initialized with the given values
*
* @param {Number} x X component
* @param {Number} y Y component
* @param {Number} z Z component
* @param {Number} w W component
* @returns {quat} a new quaternion
* @function
*/
quat.fromValues = vec4.fromValues;
/**
* Copy the values from one quat to another
*
* @param {quat} out the receiving quaternion
* @param {quat} a the source quaternion
* @returns {quat} out
* @function
*/
quat.copy = vec4.copy;
/**
* Set the components of a quat to the given values
*
* @param {quat} out the receiving quaternion
* @param {Number} x X component
* @param {Number} y Y component
* @param {Number} z Z component
* @param {Number} w W component
* @returns {quat} out
* @function
*/
quat.set = vec4.set;
/**
* Set a quat to the identity quaternion
*
* @param {quat} out the receiving quaternion
* @returns {quat} out
*/
quat.identity = function(out) {
out[0] = 0;
out[1] = 0;
out[2] = 0;
out[3] = 1;
return out;
};
/**
* Sets a quat from the given angle and rotation axis,
* then returns it.
*
* @param {quat} out the receiving quaternion
* @param {vec3} axis the axis around which to rotate
* @param {Number} rad the angle in radians
* @returns {quat} out
**/
quat.setAxisAngle = function(out, axis, rad) {
rad = rad * 0.5;
var s = Math.sin(rad);
out[0] = s * axis[0];
out[1] = s * axis[1];
out[2] = s * axis[2];
out[3] = Math.cos(rad);
return out;
};
/**
* Adds two quat's
*
* @param {quat} out the receiving quaternion
* @param {quat} a the first operand
* @param {quat} b the second operand
* @returns {quat} out
* @function
*/
quat.add = vec4.add;
/**
* Multiplies two quat's
*
* @param {quat} out the receiving quaternion
* @param {quat} a the first operand
* @param {quat} b the second operand
* @returns {quat} out
*/
quat.multiply = function(out, a, b) {
var ax = a[0], ay = a[1], az = a[2], aw = a[3],
bx = b[0], by = b[1], bz = b[2], bw = b[3];
out[0] = ax * bw + aw * bx + ay * bz - az * by;
out[1] = ay * bw + aw * by + az * bx - ax * bz;
out[2] = az * bw + aw * bz + ax * by - ay * bx;
out[3] = aw * bw - ax * bx - ay * by - az * bz;
return out;
};
/**
* Alias for {@link quat.multiply}
* @function
*/
quat.mul = quat.multiply;
/**
* Scales a quat by a scalar number
*
* @param {quat} out the receiving vector
* @param {quat} a the vector to scale
* @param {Number} b amount to scale the vector by
* @returns {quat} out
* @function
*/
quat.scale = vec4.scale;
/**
* Rotates a quaternion by the given angle about the X axis
*
* @param {quat} out quat receiving operation result
* @param {quat} a quat to rotate
* @param {number} rad angle (in radians) to rotate
* @returns {quat} out
*/
quat.rotateX = function (out, a, rad) {
rad *= 0.5;
var ax = a[0], ay = a[1], az = a[2], aw = a[3],
bx = Math.sin(rad), bw = Math.cos(rad);
out[0] = ax * bw + aw * bx;
out[1] = ay * bw + az * bx;
out[2] = az * bw - ay * bx;
out[3] = aw * bw - ax * bx;
return out;
};
/**
* Rotates a quaternion by the given angle about the Y axis
*
* @param {quat} out quat receiving operation result
* @param {quat} a quat to rotate
* @param {number} rad angle (in radians) to rotate
* @returns {quat} out
*/
quat.rotateY = function (out, a, rad) {
rad *= 0.5;
var ax = a[0], ay = a[1], az = a[2], aw = a[3],
by = Math.sin(rad), bw = Math.cos(rad);
out[0] = ax * bw - az * by;
out[1] = ay * bw + aw * by;
out[2] = az * bw + ax * by;
out[3] = aw * bw - ay * by;
return out;
};
/**
* Rotates a quaternion by the given angle about the Z axis
*
* @param {quat} out quat receiving operation result
* @param {quat} a quat to rotate
* @param {number} rad angle (in radians) to rotate
* @returns {quat} out
*/
quat.rotateZ = function (out, a, rad) {
rad *= 0.5;
var ax = a[0], ay = a[1], az = a[2], aw = a[3],
bz = Math.sin(rad), bw = Math.cos(rad);
out[0] = ax * bw + ay * bz;
out[1] = ay * bw - ax * bz;
out[2] = az * bw + aw * bz;
out[3] = aw * bw - az * bz;
return out;
};
/**
* Calculates the W component of a quat from the X, Y, and Z components.
* Assumes that quaternion is 1 unit in length.
* Any existing W component will be ignored.
*
* @param {quat} out the receiving quaternion
* @param {quat} a quat to calculate W component of
* @returns {quat} out
*/
quat.calculateW = function (out, a) {
var x = a[0], y = a[1], z = a[2];
out[0] = x;
out[1] = y;
out[2] = z;
out[3] = -Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z));
return out;
};
/**
* Calculates the dot product of two quat's
*
* @param {quat} a the first operand
* @param {quat} b the second operand
* @returns {Number} dot product of a and b
* @function
*/
quat.dot = vec4.dot;
/**
* Performs a linear interpolation between two quat's
*
* @param {quat} out the receiving quaternion
* @param {quat} a the first operand
* @param {quat} b the second operand
* @param {Number} t interpolation amount between the two inputs
* @returns {quat} out
* @function
*/
quat.lerp = vec4.lerp;
/**
* Performs a spherical linear interpolation between two quat
*
* @param {quat} out the receiving quaternion
* @param {quat} a the first operand
* @param {quat} b the second operand
* @param {Number} t interpolation amount between the two inputs
* @returns {quat} out
*/
quat.slerp = function (out, a, b, t) {
// benchmarks:
// http://jsperf.com/quaternion-slerp-implementations
var ax = a[0], ay = a[1], az = a[2], aw = a[3],
bx = b[0], by = b[1], bz = b[2], bw = b[3];
var omega, cosom, sinom, scale0, scale1;
// calc cosine
cosom = ax * bx + ay * by + az * bz + aw * bw;
// adjust signs (if necessary)
if ( cosom < 0.0 ) {
cosom = -cosom;
bx = - bx;
by = - by;
bz = - bz;
bw = - bw;
}
// calculate coefficients
if ( (1.0 - cosom) > 0.000001 ) {
// standard case (slerp)
omega = Math.acos(cosom);
sinom = Math.sin(omega);
scale0 = Math.sin((1.0 - t) * omega) / sinom;
scale1 = Math.sin(t * omega) / sinom;
} else {
// "from" and "to" quaternions are very close
// ... so we can do a linear interpolation
scale0 = 1.0 - t;
scale1 = t;
}
// calculate final values
out[0] = scale0 * ax + scale1 * bx;
out[1] = scale0 * ay + scale1 * by;
out[2] = scale0 * az + scale1 * bz;
out[3] = scale0 * aw + scale1 * bw;
return out;
};
/**
* Calculates the inverse of a quat
*
* @param {quat} out the receiving quaternion
* @param {quat} a quat to calculate inverse of
* @returns {quat} out
*/
quat.invert = function(out, a) {
var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3],
dot = a0*a0 + a1*a1 + a2*a2 + a3*a3,
invDot = dot ? 1.0/dot : 0;
// TODO: Would be faster to return [0,0,0,0] immediately if dot == 0
out[0] = -a0*invDot;
out[1] = -a1*invDot;
out[2] = -a2*invDot;
out[3] = a3*invDot;
return out;
};
/**
* Calculates the conjugate of a quat
* If the quaternion is normalized, this function is faster than quat.inverse and produces the same result.
*
* @param {quat} out the receiving quaternion
* @param {quat} a quat to calculate conjugate of
* @returns {quat} out
*/
quat.conjugate = function (out, a) {
out[0] = -a[0];
out[1] = -a[1];
out[2] = -a[2];
out[3] = a[3];
return out;
};
/**
* Calculates the length of a quat
*
* @param {quat} a vector to calculate length of
* @returns {Number} length of a
* @function
*/
quat.length = vec4.length;
/**
* Alias for {@link quat.length}
* @function
*/
quat.len = quat.length;
/**
* Calculates the squared length of a quat
*
* @param {quat} a vector to calculate squared length of
* @returns {Number} squared length of a
* @function
*/
quat.squaredLength = vec4.squaredLength;
/**
* Alias for {@link quat.squaredLength}
* @function
*/
quat.sqrLen = quat.squaredLength;
/**
* Normalize a quat
*
* @param {quat} out the receiving quaternion
* @param {quat} a quaternion to normalize
* @returns {quat} out
* @function
*/
quat.normalize = vec4.normalize;
/**
* Creates a quaternion from the given 3x3 rotation matrix.
*
* NOTE: The resultant quaternion is not normalized, so you should be sure
* to renormalize the quaternion yourself where necessary.
*
* @param {quat} out the receiving quaternion
* @param {mat3} m rotation matrix
* @returns {quat} out
* @function
*/
quat.fromMat3 = function(out, m) {
// Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
// article "Quaternion Calculus and Fast Animation".
var fTrace = m[0] + m[4] + m[8];
var fRoot;
if ( fTrace > 0.0 ) {
// |w| > 1/2, may as well choose w > 1/2
fRoot = Math.sqrt(fTrace + 1.0); // 2w
out[3] = 0.5 * fRoot;
fRoot = 0.5/fRoot; // 1/(4w)
out[0] = (m[7]-m[5])*fRoot;
out[1] = (m[2]-m[6])*fRoot;
out[2] = (m[3]-m[1])*fRoot;
} else {
// |w| <= 1/2
var i = 0;
if ( m[4] > m[0] )
i = 1;
if ( m[8] > m[i*3+i] )
i = 2;
var j = (i+1)%3;
var k = (i+2)%3;
fRoot = Math.sqrt(m[i*3+i]-m[j*3+j]-m[k*3+k] + 1.0);
out[i] = 0.5 * fRoot;
fRoot = 0.5 / fRoot;
out[3] = (m[k*3+j] - m[j*3+k]) * fRoot;
out[j] = (m[j*3+i] + m[i*3+j]) * fRoot;
out[k] = (m[k*3+i] + m[i*3+k]) * fRoot;
}
return out;
};
/**
* Returns a string representation of a quatenion
*
* @param {quat} vec vector to represent as a string
* @returns {String} string representation of the vector
*/
quat.str = function (a) {
return 'quat(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ')';
};
if(typeof(exports) !== 'undefined') {
exports.quat = quat;
}
;
})(shim.exports);
})(this);
});
require.register("the-gss-preparser/component.json", function(exports, require, module){
module.exports = {
"name": "gss-preparser",
"description": "GSS preparser",
"author": "Dan Tocchini <d4@thegrid.io>",
"repo": "the-gss/preparser",
"version": "1.0.5-beta",
"json": [
"component.json"
],
"remotes": [
"https://raw.githubusercontent.com"
],
"scripts": [
"lib/gss-preparser.js"
],
"main": "lib/gss-preparser.js"
}
});
require.register("the-gss-ccss-compiler/component.json", function(exports, require, module){
module.exports = {
"name": "ccss-compiler",
"description": "Constraint Cascading Style Sheets compiler",
"author": "Dan Tocchini <d4@thegrid.io>",
"repo": "the-gss/ccss-compiler",
"version": "1.0.7-beta",
"json": [
"component.json"
],
"remotes": [
"https://raw.githubusercontent.com"
],
"scripts": [
"lib/ccss-compiler.js"
],
"main": "lib/ccss-compiler.js"
}
});
require.register("the-gss-compiler/component.json", function(exports, require, module){
module.exports = {
"name": "gss-compiler",
"description": "GSS rule compiler",
"version": "0.8.2",
"author": "Dan Tocchini <d4@thegrid.io>",
"repo": "the-gss/compiler",
"scripts": [
"lib/gss-compiler.js"
],
"remotes": [
"https://raw.githubusercontent.com"
],
"json": [
"component.json"
],
"dependencies": {
"the-gss/preparser": "*",
"the-gss/ccss-compiler": "*",
"the-gss/vfl-compiler": "*",
"the-gss/vgl-compiler": "*"
},
"main": "lib/gss-compiler.js"
}
});
require.register("gss/component.json", function(exports, require, module){
module.exports = {
"name": "gss",
"repo": "the-gss/engine",
"description": "GSS runtime",
"version": "1.0.2-beta",
"author": "Dan Tocchini <d4@thegrid.io>",
"repo": "the-gss/engine",
"json": [
"component.json"
],
"remotes": [
"https://raw.githubusercontent.com"
],
"scripts": [
"lib/GSS-with-compiler.js",
"lib/GSS.js",
"lib/_.js",
"lib/EventTrigger.js",
"lib/dom/Query.js",
"lib/dom/View.js",
"lib/dom/Observer.js",
"lib/gssom/Node.js",
"lib/gssom/StyleSheet.js",
"lib/gssom/Rule.js",
"lib/Engine.js",
"lib/Commander.js",
"lib/Thread.js",
"lib/dom/Getter.js",
"lib/dom/IdMixin.js",
"vendor/gl-matrix.js"
],
"dependencies": {
"the-gss/compiler": "*",
"d4tocchini/customevent-polyfill": "*",
"slightlyoff/cassowary.js": "*"
},
"files": [
"vendor/observe.js",
"vendor/sidetable.js",
"vendor/MutationObserver.js"
],
"main": "lib/GSS-with-compiler.js"
}
});
require.alias("the-gss-compiler/lib/gss-compiler.js", "gss/deps/gss-compiler/lib/gss-compiler.js");
require.alias("the-gss-compiler/lib/gss-compiler.js", "gss/deps/gss-compiler/index.js");
require.alias("the-gss-compiler/lib/gss-compiler.js", "gss-compiler/index.js");
require.alias("the-gss-preparser/lib/gss-preparser.js", "the-gss-compiler/deps/gss-preparser/lib/gss-preparser.js");
require.alias("the-gss-preparser/lib/gss-preparser.js", "the-gss-compiler/deps/gss-preparser/index.js");
require.alias("the-gss-preparser/lib/gss-preparser.js", "the-gss-preparser/index.js");
require.alias("the-gss-ccss-compiler/lib/ccss-compiler.js", "the-gss-compiler/deps/ccss-compiler/lib/ccss-compiler.js");
require.alias("the-gss-ccss-compiler/lib/ccss-compiler.js", "the-gss-compiler/deps/ccss-compiler/index.js");
require.alias("the-gss-ccss-compiler/lib/ccss-compiler.js", "the-gss-ccss-compiler/index.js");
require.alias("the-gss-vfl-compiler/lib/vfl-compiler.js", "the-gss-compiler/deps/vfl-compiler/lib/vfl-compiler.js");
require.alias("the-gss-vfl-compiler/lib/compiler.js", "the-gss-compiler/deps/vfl-compiler/lib/compiler.js");
require.alias("the-gss-vfl-compiler/lib/compiler.js", "the-gss-compiler/deps/vfl-compiler/index.js");
require.alias("the-gss-vfl-compiler/lib/compiler.js", "the-gss-vfl-compiler/index.js");
require.alias("the-gss-vgl-compiler/lib/vgl-compiler.js", "the-gss-compiler/deps/vgl-compiler/lib/vgl-compiler.js");
require.alias("the-gss-vgl-compiler/lib/compiler.js", "the-gss-compiler/deps/vgl-compiler/lib/compiler.js");
require.alias("the-gss-vgl-compiler/lib/compiler.js", "the-gss-compiler/deps/vgl-compiler/index.js");
require.alias("the-gss-vgl-compiler/lib/compiler.js", "the-gss-vgl-compiler/index.js");
require.alias("the-gss-compiler/lib/gss-compiler.js", "the-gss-compiler/index.js");
require.alias("d4tocchini-customevent-polyfill/CustomEvent.js", "gss/deps/customevent-polyfill/CustomEvent.js");
require.alias("d4tocchini-customevent-polyfill/CustomEvent.js", "gss/deps/customevent-polyfill/index.js");
require.alias("d4tocchini-customevent-polyfill/CustomEvent.js", "customevent-polyfill/index.js");
require.alias("d4tocchini-customevent-polyfill/CustomEvent.js", "d4tocchini-customevent-polyfill/index.js");
require.alias("slightlyoff-cassowary.js/index.js", "gss/deps/cassowary/index.js");
require.alias("slightlyoff-cassowary.js/src/c.js", "gss/deps/cassowary/src/c.js");
require.alias("slightlyoff-cassowary.js/src/HashTable.js", "gss/deps/cassowary/src/HashTable.js");
require.alias("slightlyoff-cassowary.js/src/HashSet.js", "gss/deps/cassowary/src/HashSet.js");
require.alias("slightlyoff-cassowary.js/src/Error.js", "gss/deps/cassowary/src/Error.js");
require.alias("slightlyoff-cassowary.js/src/SymbolicWeight.js", "gss/deps/cassowary/src/SymbolicWeight.js");
require.alias("slightlyoff-cassowary.js/src/Strength.js", "gss/deps/cassowary/src/Strength.js");
require.alias("slightlyoff-cassowary.js/src/Variable.js", "gss/deps/cassowary/src/Variable.js");
require.alias("slightlyoff-cassowary.js/src/Point.js", "gss/deps/cassowary/src/Point.js");
require.alias("slightlyoff-cassowary.js/src/Expression.js", "gss/deps/cassowary/src/Expression.js");
require.alias("slightlyoff-cassowary.js/src/Constraint.js", "gss/deps/cassowary/src/Constraint.js");
require.alias("slightlyoff-cassowary.js/src/EditInfo.js", "gss/deps/cassowary/src/EditInfo.js");
require.alias("slightlyoff-cassowary.js/src/Tableau.js", "gss/deps/cassowary/src/Tableau.js");
require.alias("slightlyoff-cassowary.js/src/SimplexSolver.js", "gss/deps/cassowary/src/SimplexSolver.js");
require.alias("slightlyoff-cassowary.js/src/Timer.js", "gss/deps/cassowary/src/Timer.js");
require.alias("slightlyoff-cassowary.js/src/parser/parser.js", "gss/deps/cassowary/src/parser/parser.js");
require.alias("slightlyoff-cassowary.js/src/parser/api.js", "gss/deps/cassowary/src/parser/api.js");
require.alias("slightlyoff-cassowary.js/index.js", "cassowary/index.js");
require.alias("gss/lib/GSS-with-compiler.js", "gss/index.js");if (typeof exports == "object") {
module.exports = require("gss");
} else if (typeof define == "function" && define.amd) {
define([], function(){ return require("gss"); });
} else {
this["gss"] = require("gss");
}})(); |
var VisionTools = VisionTools || (function() {
"use strict";
// Version Number
var this_version = 0.9;
// Date: (Subtract 1 from the month component)
var this_lastUpdate = new Date(2016, 10, 2, 0, 34);
// Verbose (print messages)
var this_verbose = false;
// Auto-size "tiny" and smaller tokens below unit size
var this_enableSubunitTokens = true;
// Grid size
var GRID_SIZE = 70;
//
// General Functions
// Return a collection of tokens for the specified character.
// charId: character object ID
function tokensFor(charId)
{
var toks = findObjs({
_type : "graphic",
_subtype : "token",
represents : charId,
});
return toks;
}
// Return the character that the specified token represents.
// token: Roll20 token object
function characterFor(token)
{
var represents = token.get("represents");
return getObj("character", represents);
}
// Find the torch token corresponding to the specified token.
// token: Roll20 token object
function findTorch(token)
{
// Search for the object in the state object.
var torch = state.VisionTools.torches[token.id];
return torch;
}
// Set the vision of a token.
// token: Roll20 token object
// llv: low-light vision flag
// dv: darkvision range, feet
function setVision(token, llv, dv)
{
// Halve DV if LLV present, since Roll20 doubles that (as any
// other light source).
dv = llv ? Math.floor(dv / 2) : dv;
token.set({
light_radius : dv > 0 ? dv : "",
light_dimradius : "",
light_otherplayers : false,
light_angle : "360",
light_hassight : true,
light_multiplier : (llv ? 2 : 1)
});
}
// Set the size of a token.
// token: Roll20 token object
// size: x and y dimensions
function setSize(token, size)
{
token.set({
width : size,
height : size
});
}
// Register a torch so it can be removed later.
// token: Roll20 token object
function registerTorch(token)
{
if (this_verbose) {
log("registerTorch(" + token.id + ")");
}
// If there is an existing torch entry, delete the old token.
var torch = findTorch(token);
if (torch) {
var oldTorchToken = getObj("graphic", torch.id);
if (oldTorchToken) { oldTorchToken.remove(); }
}
// Create a new torch.
torch = createObj("graphic", {
subtype : "token",
pageid : token.get("pageid"),
layer : "walls",
imgsrc : state.VisionTools.imgsrc,
name : "VisionTools torch",
left : token.get("left"),
top : token.get("top"),
width : token.get("width"),
height : token.get("height"),
// DO NOT SET gmnotes in createObj
aura1_radius : 40,
auro1_color : "#fff99",
light_radius : 40,
light_dimradius : 20,
light_otherplayers : true
});
// Present or not, we're going to replace the entry.
state.VisionTools.torches[token.id] = {
// ID of the torch object
id : torch.id,
// ID of the torch's owner
owner : token.id
};
}
// Unregister a torch.
// token: Roll20 token object
function unregisterTorch(token)
{
if (this_verbose) {
log("unregisterTorch(" + token.id + ")" );
}
var torch = findTorch(token);
if (torch) {
if (this_verbose) {
log("deleting torch token");
}
var oldTorchToken = getObj("graphic", torch.id);
if (oldTorchToken) { oldTorchToken.remove(); }
}
delete state.VisionTools.torches[token.id];
}
// Basic "torch" by setting all-player-visible light.
// token: Roll20 token object
// enable: turn on or off the torch corresponding to 'token'
function toggleTorch(token, enable)
{
// Can't do this if there's no image.
if (state.VisionTools.imgsrc.length == 0) {
sendChat("VisionTools API", "Set an image source with !mcvis-set-imgsrc first");
return;
}
if (this_verbose) {
log("toggleTorch: " + token.id + ", en: " + enable);
}
// If we're turning on a light, make a new token.
if (enable) {
// Create and register a torch.
registerTorch(token);
}
else {
// Unregister a torch.
unregisterTorch(token);
}
}
//
// Specific Event Handlers
// Obtain a character's vision from a Character object, and see if
// there are special vision modes that need to be incorporated.
// char: Roll20 character object
function onCharacterVisionChanged(char)
{
if (!char) { return; }
if (this_verbose) {
log("onCharacterVisionChanged(" + char + ")");
log("Checking vis for " + char.get("name"));
}
// ID of the character
var charId = char.get("_id");
// Vision regexes
var darkvision1_re = /darkvision\s*\(\s*(\d+)\s*(ft|'|)\s*\)\s*/;
var darkvision2_re = /darkvision\s*(\d+)/;
var lowlight1_re = /low-light\s*vision|lowlight\s*vision/;
// Get the vision attribute.
// We don't have the ID, so we have to get "all" of them.
// We could assume just one is returned, but we'll pretend there could be
// more (or zero, which is a possibility that is more likely).
var visionAttrs = findObjs({
_type : "attribute",
_characterid : charId,
name : "vision"
});
_.each(visionAttrs, function(attr) {
var visions = attr.get("current").toLowerCase().split(",");
var dv = 0;
var llv = 0;
_.each(visions, function(vis) {
var mr = vis.match(darkvision1_re);
if (mr) {
dv = mr[1];
}
mr = vis.match(darkvision2_re);
if (mr) {
dv = mr[1];
}
mr = vis.match(lowlight1_re);
if (mr) {
llv = 1;
}
});
_.each(tokensFor(charId), function(token) {
setVision(token, llv, dv);
});
});
}
// Obtain a character's size from a Character object, and set its token sizes.
// character: Roll20 character object
function onCharacterSizeChanged(character)
{
if (!character) { return; }
// Synonym
var charId = character.id;
// Get the size attribute.
// We don't have the ID, so we have to get "all" of them.
// We could assume just one is returned, but we'll pretend there could be
// more (or zero, which is a possibility that is more likely).
var sizeAttrs = findObjs({
_type : "attribute",
_characterid : charId,
name : "size"
});
_.each(sizeAttrs, function(attr) {
//log("Size is " + attr.get("current"));
var size = parseInt(attr.get("current"), 10);
var dimension = 0;
switch (size) {
// Any tiny or smaller can be 1/4x or 1x.
case 8: // fine
case 4: // diminutive
case 2: // tiny
dimension = this_enableSubunitTokens ? GRID_SIZE / 2 : GRID_SIZE;
break
case 1: // small
dimension = GRID_SIZE;
break;
case 0: // medium
dimension = GRID_SIZE;
break;
case -1: // large
dimension = GRID_SIZE * 2;
break;
case -2: // huge
dimension = GRID_SIZE * 3;
break;
case -4: // gargantuan
dimension = GRID_SIZE * 4;
break;
case -8: // colossal
dimension = GRID_SIZE * 5;
break;
}
if (dimension > 0) {
var toks = tokensFor(charId);
log("tokens for " + charId + " count is " + 0);//toks.length);
_.each(tokensFor(charId), function(token) {
setSize(token, dimension);
});
}
});
}
//
// Roll20 Event Handlers
// Handle an attribute [vision] changing.
// obj: Roll20 character object
function onCharacterChanged(obj)
{
// If the vision changed, update the token(s)
var character = getObj("character", obj.get("_characterid"));
if (obj.get("name") === "vision") {
//log("Vision changed for " + character.get("name"));
onCharacterVisionChanged(character);
}
else if (obj.get("name") === "size") {
//log("Size changed for " + character.get("name"));
onCharacterSizeChanged(character);
}
}
// Change Page
function onPlayerPageChanged(obj, prev)
{
// The page ID of the object seems to be bad.
var pageId = Campaign().get("playerpageid");
// Update the obj reference.
obj = getObj("page", pageId);
//log("Player page changed, id: " + obj.id);
// Get all the tokens on the page and update their vision.
var tokens = findObjs({
_type : "graphic",
_subtype : "token",
_pageid : obj.get("_id")
});
//log("Page: " + obj.get("name") + ", Tokens: " + tokens.length);
_.each(tokens, function(token){
onCharacterVisionChanged(characterFor(token));
});
}
// Hanhdle yellow marker to toggle the light source.
function onTokenStatus(obj, prev)
{
//log("status changed");
var yellowIsOn = obj.get("status_yellow");
var yellowWasOn = prev["statusmarkers"].includes("yellow");
//log ("YIO " + yellowIsOn + " YWO " + yellowWasOn);
if (!yellowWasOn && yellowIsOn) {
//log("turning light on");
toggleTorch(obj, true);
}
else if (yellowWasOn && !yellowIsOn) {
//log("turning light off");
toggleTorch(obj, false);
}
}
function onTokenMove(obj, prev)
{
// If the token has a torch, move it as well.
var torch = findTorch(obj);
if (torch) {
var torch = getObj("graphic", torch.id);
if (torch) {
torch.set({
left : obj.get("left"),
top : obj.get("top")
});
}
}
}
function onTokenAdded(obj)
{
var character = getObj("character", obj.get("represents"));
onCharacterVisionChanged(character);
onCharacterSizeChanged(character);
}
function onTokenDestroy(obj)
{
// If the token has a torch, unregister it.
unregisterTorch(obj);
}
function onChatMessage(msg)
{
if (msg.type == "api") {
var args = msg.content.split(" ");
if (args[0] == "!mcvis-set-imgsrc") {
state.VisionTools.imgsrc = args[1];
}
}
}
function initialize()
{
log("-=> VisionTools v" + this_version + " <=- [" + this_lastUpdate + "]");
// Set up the state object.
if (!_.has(state, "VisionTools")) {
state.VisionTools = {
imgsrc : "",
torches : {}
};
}
if (this_verbose) {
if (state.VisionTools.imgsrc.length > 0) {
log("VisionTools imgsrc: " + state.VisionTools.imgsrc);
}
else {
log("VisionTools imgsrc not set, use !mcvis-set-imgsrc <URL>");
}
}
// Set up the event listeners.
// Quick light
on("change:graphic:statusmarkers", onTokenStatus);
on("change:graphic:left", onTokenMove);
on("change:graphic:top", onTokenMove);
on("destroy:graphic", onTokenDestroy);
on("chat:message", onChatMessage);
// Auto Vision
on("change:attribute:current", onCharacterChanged);
on("change:campaign:playerpageid", onPlayerPageChanged);
on("add:token", onTokenAdded);
// Now check for existing things on the current page.
// No way to get the GM page, but we'll let the player page suffice.
var playerPageId = Campaign().get("playerpageid");
var playerPage = getObj("page", playerPageId);
// (We actually determine the page in the function, but we'll pretend we
// don't.)
onPlayerPageChanged(playerPage);
}
// Initialize.
on("ready", initialize);
return {
};
}());
|
// Expose modules in ./support for demo purposes
require.paths.unshift(__dirname + '/../../support');
/**
* Module dependencies.
*/
var express = require('../../lib/express');
var app = express.createServer();
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
// Serve default connect favicon
app.use(express.favicon());
// Logger is placed below favicon, so favicon.ico
// requests will not be logged
app.use(express.logger('":method :url" :status'));
// "app.router" positions our routes
// specifically above the middleware
// assigned below
app.use(app.router);
// Since this is the last non-error-handling
// middleware use()d, we assume 404, as nothing else
// responded.
app.use(function(req, res, next){
// the status option, or res.statusCode = 404
// are equivalent, however with the option we
// get the "status" local available as well
res.render('404', { status: 404, url: req.url });
});
// error-handling middleware, take the same form
// as regular middleware, however they require an
// arity of 4, aka the signature (err, req, res, next).
// when connect has an error, it will invoke ONLY error-handling
// middleware.
// If we were to next() here any remaining non-error-handling
// middleware would then be executed, or if we next(err) to
// continue passing the error, only error-handling middleware
// would remain being executed, however here
// we simply respond with an error page.
app.use(function(err, req, res, next){
// we may use properties of the error object
// here and next(err) appropriately, or if
// we possibly recovered from the error, simply next().
res.render('500', {
status: err.status || 500
, error: err
});
});
// Routes
app.get('/', function(req, res){
res.render('index.jade');
});
app.get('/404', function(req, res, next){
next();
});
app.get('/403', function(req, res, next){
var err = new Error('not allowed!');
err.status = 403;
next(err);
});
app.get('/500', function(req, res, next){
next(new Error('keyboard cat!'));
});
app.listen(3000);
console.log('Express app started on port 3000'); |
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery.SPServices/0.7.1a/jquery.SPServices-0.7.1a.min.js"></script>
<script type="text/javascript" src="http://www.sharepointhillbilly.com/demos/SiteAssets/jquery.Forms7-0.0.07.js"></script>
<link type="text/css" rel="stylesheet" href="http://www.sharepointhillbilly.com/demos/SiteAssets/modern-grid.css" />
<style type="text/css">
.label
{
vertical-align:top;
horizontal-align:left;
font-size:large;
}
</style>
<script type="text/javascript">
function InstallF7()
{
if ($("#listName").val().length == 0)
{
alert("Seriously?? Enter a list name... I think that much is pretty obvious.");
return;
}
$().Forms7Install ({
listName: $("#listName").val()
});
listName = $("#listName").val();
$("#minimalForm").val($("#minformRaw").val().replace(/F7_LIST_NAME/g,'"'+listName+'"'));
}
</script>
<div class="row">
<div class="column five label">List Name:<input id="listName" type="text"> <input type="button" value="Install Forms7" onclick="InstallF7();"></div>
</div>
<div class="row">
<div class="column five label">Minimal Form:<br><textarea id="minimalForm" cols="100" rows="25"></textarea></div>
</div>
<textarea style="display:none" id="minformRaw">
<link type="text/css" rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/themes/start/jquery-ui.css" />
<!-- Reference jQuery on the Google CDN -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<!-- Reference jQueryUI on the Google CDN -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery.SPServices/0.7.1a/jquery.SPServices-0.7.1a.min.js"></script>
<!-- if you put Forms7 in a location other than SiteAssets of your current site, be sure to update this reference -->
<script src="../SiteAssets/jQuery.Forms7-0.0.03.js"></script>
<style type="text/css">
.error
{font-family:'Tahoma',sans-serif;font-size:10px;text-align:left;color:red;}
</style>
<script type="text/javascript">
$(document).ready(function() {
//Initialization function. Tells Forms7 which Query String Variable
//has the ID of the form, and the name of the list to read data from
$("#minimalForm").Forms7Initialize({
queryStringVar: "formID",
listName: F7_LIST_NAME
});
});
function SubmitForm()
{
//When the form is submitted store it to the specified list
//also pasas in the x and y offset of error messages for elements
//this allows you to change their location in reference to the form field
$("#minimalForm").Forms7Submit({
listName: F7_LIST_NAME,
errorOffsetTop: 10,
errorOffsetLeft: 5,
completefunc: function(id) {
alert("Save was successful. ID = " + id);
window.location = window.location.pathname + "?formID=" + id;
}
});
}
</script>
<div id="minimalForm" >
Title: <input type="text" id="TitleField" listFieldName='Title' class='required formInput' >
</div>
<input type="button" value="Submit/Update Form" onclick="SubmitForm();">
</textarea> |
/**
*
* .City Web of Things Framework
*
* Copyright 2015 Jollen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
"use strict";
/**
* Module dependencies.
*/
var coap = require('coap')
, url = require("url")
, EventEmitter = require('events').EventEmitter
, util = require('util');
/**
* Expose `CoapServer` constructor.
*/
if (typeof(module) != "undefined" && typeof(exports) != "undefined") {
exports = module.exports = CoapServer;
}
/**
* Initialize a new `CoapServer` with the given `options`.
*
* @param {Object} options
* @api private
*/
function CoapServer(options) {
// Superclass Constructor
EventEmitter.call(this);
options = options || {};
this.clientsPath = [];
this.host = options.host ? String(options.host) : 'localhost';
this.port = options.port ? options.port : 8000;
}
util.inherits(CoapServer, EventEmitter);
/**
* Initialize a new `CoapServer` with the given `options`.
*
* @param {Object} request
* @param {Object} response
* @api private
*/
CoapServer.prototype.onRequest = function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end();
};
/**
* Start websocket server.
*
* @param {Object} route
* @return {}
* @api public
*/
CoapServer.prototype.start = function(route, handlers) {
var self = this;
var server = coap.createServer().listen(this.port, function() {
console.info('WoT.City/CoAP server is listening at coap://' + self.host + ':' + self.port);
});
/**
* handlers
*/
var onCoapRequest = function(request, response) {
var url = request.url;
route(url, request, response, handlers);
};
server.on('request', onCoapRequest);
};
|
import React from 'react'
export const BioItem = ({ name, value }) => (
<div className='form-group'>
<label className='col-sm-6 control-label'>{name}</label>
<div className='col-sm-6'>
<p className='form-control-static'>{value}</p>
</div>
</div>
)
BioItem.propTypes = {
name: React.PropTypes.string,
value: React.PropTypes.string
}
export default BioItem
|
/*globals __dirname:false */
"use strict";
var webpack = require("webpack");
module.exports = {
devServer: {
contentBase: __dirname,
noInfo: false
},
output: {
path: __dirname,
filename: "main.js",
publicPath: "/assets/"
},
cache: true,
devtool: "source-map",
entry: {
app: ["./demo/app.js"]
},
stats: {
colors: true,
reasons: true
},
plugins: [
new webpack.NoErrorsPlugin()
]
};
|
/**
* Test dependencies
*/
var assert = require('assert')
, fs = require('fs')
, common = require('./common')
, Memcached = require('../');
global.testnumbers = global.testnumbers || +(Math.random(10) * 1000000).toFixed();
/**
* Expresso test suite for all `get` related
* memcached commands
*/
describe("Memcached GET SET", function() {
/**
* Make sure that the string that we send to the server is correctly
* stored and retrieved. We will be storing random strings to ensure
* that we are not retrieving old data.
*/
it("set and get a regular string", function(done) {
var memcached = new Memcached(common.servers.single)
, message = common.alphabet(256)
, testnr = ++global.testnumbers
, callbacks = 0;
memcached.set("test:" + testnr, message, 1000, function(error, ok){
++callbacks;
assert.ok(!error);
ok.should.be.true;
memcached.get("test:" + testnr, function(error, answer){
++callbacks;
assert.ok(!error);
assert.ok(typeof answer === 'string');
answer.should.eql(message);
memcached.end(); // close connections
assert.equal(callbacks, 2);
done();
});
});
});
it("set and get an empty string", function(done) {
var memcached = new Memcached(common.servers.single)
, testnr = ++global.testnumbers
, callbacks = 0;
memcached.set("test:" + testnr, "", 1000, function(error, ok){
++callbacks;
assert.ok(!error);
ok.should.be.true;
memcached.get("test:" + testnr, function(error, answer){
++callbacks;
assert.ok(!error);
assert.ok(typeof answer === 'string');
answer.should.eql("");
memcached.end(); // close connections
assert.equal(callbacks, 2);
done();
});
});
});
/**
* Set a stringified JSON object, and make sure we only return a string
* this should not be flagged as JSON object
*/
it("set and get a JSON.stringify string", function(done) {
var memcached = new Memcached(common.servers.single)
, message = JSON.stringify({numbers:common.numbers(256),alphabet:common.alphabet(256),dates:new Date(),arrays: [1,2,3, 'foo', 'bar']})
, testnr = ++global.testnumbers
, callbacks = 0;
memcached.set("test:" + testnr, message, 1000, function(error, ok){
++callbacks;
assert.ok(!error);
ok.should.be.true;
memcached.get("test:" + testnr, function(error, answer){
++callbacks;
assert.ok(!error);
assert.ok(typeof answer === 'string');
answer.should.eql(message);
memcached.end(); // close connections
assert.equal(callbacks, 2);
done();
});
});
});
/**
* Setting and getting a unicode value should just work, we need to make sure
* that we send the correct byteLength because utf8 chars can contain more bytes
* than "str".length would show, causing the memcached server to complain.
*/
it("set and get a regular string", function(done) {
var memcached = new Memcached(common.servers.single)
, message = 'привет мир, Memcached и nodejs для победы'
, testnr = ++global.testnumbers
, callbacks = 0;
memcached.set("test:" + testnr, message, 1000, function(error, ok){
++callbacks;
assert.ok(!error);
ok.should.be.true;
memcached.get("test:" + testnr, function(error, answer){
++callbacks;
assert.ok(!error);
assert.ok(typeof answer === 'string');
answer.should.eql(message);
memcached.end(); // close connections
assert.equal(callbacks, 2);
done();
});
});
});
/**
* A common action when working with memcached servers, getting a key
* that does not exist anymore.
*/
it("get a non existing key", function(done) {
var memcached = new Memcached(common.servers.single)
, testnr = ++global.testnumbers
, callbacks = 0;
memcached.get("test:" + testnr, function(error, answer){
++callbacks;
assert.ok(!error);
assert.ok(answer===undefined);
memcached.end(); // close connections
assert.equal(callbacks, 1);
done();
});
});
/**
* Make sure that Numbers are correctly send and stored on the server
* retrieval of the number based values can be tricky as the client might
* think that it was a INCR and not a SET operation.. So just to make sure..
*/
it("set and get a regular number", function(done) {
var memcached = new Memcached(common.servers.single)
, message = common.numbers(256)
, testnr = ++global.testnumbers
, callbacks = 0;
memcached.set("test:" + testnr, message, 1000, function(error, ok){
++callbacks;
assert.ok(!error);
ok.should.be.true;
memcached.get("test:" + testnr, function(error, answer){
++callbacks;
assert.ok(!error);
assert.ok(typeof answer === 'number');
answer.should.eql(message);
memcached.end(); // close connections
assert.equal(callbacks, 2);
done();
});
});
});
/**
* Objects should be converted to a JSON string, send to the server
* and be automagically JSON.parsed when they are retrieved.
*/
it("set and get a object", function(done) {
var memcached = new Memcached(common.servers.single)
, message = {
numbers: common.numbers(256)
, alphabet: common.alphabet(256)
, dates: new Date()
, arrays: [1,2,3, 'foo', 'bar']
}
, testnr = ++global.testnumbers
, callbacks = 0;
memcached.set("test:" + testnr, message, 1000, function(error, ok){
++callbacks;
assert.ok(!error);
ok.should.be.true;
memcached.get("test:" + testnr, function(error, answer){
++callbacks;
assert.ok(!error);
assert.ok(!Array.isArray(answer) && typeof answer === 'object');
assert.ok(JSON.stringify(message) === JSON.stringify(answer));
memcached.end(); // close connections
assert.equal(callbacks, 2);
done();
});
});
});
/**
* Arrays should be converted to a JSON string, send to the server
* and be automagically JSON.parsed when they are retrieved.
*/
it("set and get a array", function(done) {
var memcached = new Memcached(common.servers.single)
, message = [{
numbers: common.numbers(256)
, alphabet: common.alphabet(256)
, dates: new Date()
, arrays: [1,2,3, 'foo', 'bar']
}, {
numbers: common.numbers(256)
, alphabet: common.alphabet(256)
, dates: new Date()
, arrays: [1,2,3, 'foo', 'bar']
}]
, testnr = ++global.testnumbers
, callbacks = 0;
memcached.set("test:" + testnr, message, 1000, function(error, ok){
++callbacks;
assert.ok(!error);
ok.should.be.true;
memcached.get("test:" + testnr, function(error, answer){
++callbacks;
assert.ok(!error);
assert.ok(Array.isArray(answer));
assert.ok(JSON.stringify(answer) === JSON.stringify(message));
memcached.end(); // close connections
assert.equal(callbacks, 2);
done();
});
});
});
/**
* Buffers are commonly used for binary transports So we need to make sure
* we support them properly. But please note, that we need to compare the
* strings on a "binary" level, because that is the encoding the Memcached
* client will be using, as there is no indication of what encoding the
* buffer is in.
*/
it("set and get <buffers> with a binary image", function(done) {
var memcached = new Memcached(common.servers.single)
, message = fs.readFileSync(__dirname + '/fixtures/hotchicks.jpg')
, testnr = ++global.testnumbers
, callbacks = 0;
memcached.set("test:" + testnr, message, 1000, function(error, ok){
++callbacks;
assert.ok(!error);
ok.should.be.true;
memcached.get("test:" + testnr, function(error, answer){
++callbacks;
assert.ok(!error);
assert.ok(answer.toString('binary') === message.toString('binary'));
memcached.end(); // close connections
assert.equal(callbacks, 2);
done();
});
});
});
/**
* Get binary of the lipsum.txt, send it over the connection and see
* if after we retrieved it, it's still the same when we compare the
* original with the memcached based version.
*
* A use case for this would be storing <buffers> with HTML data in
* memcached as a single cache pool..
*/
it("set and get <buffers> with a binary text file", function(done) {
var memcached = new Memcached(common.servers.single)
, message = fs.readFileSync(__dirname + '/fixtures/lipsum.txt')
, testnr = ++global.testnumbers
, callbacks = 0;
memcached.set("test:" + testnr, message, 1000, function(error, ok){
++callbacks;
assert.ok(!error);
ok.should.be.true;
memcached.get("test:" + testnr, function(error, answer){
++callbacks;
assert.ok(!error);
assert.ok(answer.toString('utf8') === answer.toString('utf8'));
assert.ok(answer.toString('ascii') === answer.toString('ascii'));
memcached.end(); // close connections
assert.equal(callbacks, 2);
done();
});
});
});
/**
* Set maximum amount of data (1MB), should trigger error, not crash.
*/
it("set maximum data and check for correct error handling", function(done) {
var memcached = new Memcached(common.servers.single)
, message = fs.readFileSync(__dirname + '/fixtures/lipsum.txt').toString()
, testnr = ++global.testnumbers
, callbacks = 0;
memcached.set("test:" + testnr, new Array(100).join(message), 1000, function(error, ok){
++callbacks;
assert.equal(error, 'Error: The length of the value is greater than 1048576');
ok.should.be.false;
memcached.end(); // close connections
assert.equal(callbacks, 1);
done();
});
});
/**
* Not only small strings, but also large strings should be processed
* without any issues.
*/
it("set and get large text files", function(done) {
var memcached = new Memcached(common.servers.single)
, message = fs.readFileSync(__dirname + '/fixtures/lipsum.txt', 'utf8')
, testnr = ++global.testnumbers
, callbacks = 0;
memcached.set("test:" + testnr, message, 1000, function(error, ok){
++callbacks;
assert.ok(!error);
ok.should.be.true;
memcached.get("test:" + testnr, function(error, answer){
++callbacks;
assert.ok(!error);
assert.ok(typeof answer === 'string');
answer.should.eql(message);
memcached.end(); // close connections
assert.equal(callbacks, 2);
done();
});
});
});
/**
* A multi get on a single server is different than a multi server multi get
* as a multi server multi get will need to do a multi get over multiple servers
* yes, that's allot of multi's in one single sentence thanks for noticing
*/
it("multi get single server", function(done) {
var memcached = new Memcached(common.servers.single)
, message = common.alphabet(256)
, message2 = common.alphabet(256)
, testnr = ++global.testnumbers
, callbacks = 0;
memcached.set("test1:" + testnr, message, 1000, function(error, ok){
++callbacks;
assert.ok(!error);
ok.should.be.true;
memcached.set("test2:" + testnr, message2, 1000, function(error, ok){
++callbacks;
assert.ok(!error);
ok.should.be.true;
memcached.get(["test1:" + testnr, "test2:" + testnr], function(error, answer){
++callbacks;
assert.ok(!error);
assert.ok(typeof answer === 'object');
answer["test1:" + testnr].should.eql(message);
answer["test2:" + testnr].should.eql(message2);
memcached.end(); // close connections
assert.equal(callbacks, 3);
done();
});
});
});
});
/**
* A multi get on a single server is different than a multi server multi get
* as a multi server multi get will need to do a multi get over multiple servers
* yes, that's allot of multi's in one single sentence thanks for noticing
*/
it("multi get multi server", function(done) {
var memcached = new Memcached(common.servers.multi)
, message = common.alphabet(256)
, message2 = common.alphabet(256)
, testnr = ++global.testnumbers
, callbacks = 0;
memcached.set("test1:" + testnr, message, 1000, function(error, ok){
++callbacks;
assert.ok(!error);
ok.should.be.true;
memcached.set("test2:" + testnr, message2, 1000, function(error, ok){
++callbacks;
assert.ok(!error);
ok.should.be.true;
memcached.get(["test1:" + testnr,"test2:" + testnr], function(error, answer){
++callbacks;
assert.ok(!error);
assert.ok(typeof answer === 'object');
answer["test1:" + testnr].should.eql(message);
answer["test2:" + testnr].should.eql(message2);
memcached.end(); // close connections
assert.equal(callbacks, 3);
done();
});
});
});
});
/**
* Make sure that a string beginning with OK is not interpreted as
* a command response.
*/
it("set and get a string beginning with OK", function(done) {
var memcached = new Memcached(common.servers.single)
, message = 'OK123456'
, testnr = ++global.testnumbers
, callbacks = 0;
memcached.set("test:" + testnr, message, 1000, function(error, ok){
++callbacks;
assert.ok(!error);
ok.should.be.true;
memcached.get("test:" + testnr, function(error, answer){
++callbacks;
assert.ok(!error);
assert.ok(typeof answer === 'string');
answer.should.eql(message);
memcached.end(); // close connections
assert.equal(callbacks, 2);
done();
});
});
});
/**
* Make sure that a string beginning with OK is not interpreted as
* a command response.
*/
it("set and get a string beginning with VALUE", function(done) {
var memcached = new Memcached(common.servers.single)
, message = 'VALUE hello, I\'m not really a value.'
, testnr = ++global.testnumbers
, callbacks = 0;
memcached.set("test:" + testnr, message, 1000, function(error, ok){
++callbacks;
assert.ok(!error);
ok.should.be.true;
memcached.get("test:" + testnr, function(error, answer){
++callbacks;
assert.ok(!error);
assert.ok(typeof answer === 'string');
answer.should.eql(message);
memcached.end(); // close connections
assert.equal(callbacks, 2);
done();
});
});
});
/**
* Make sure that a string containing line breaks are escaped and
* unescaped correctly.
*/
it("set and get a string with line breaks", function(done) {
var memcached = new Memcached(common.servers.single)
, message = '1\n2\r\n3\n\r4\\n5\\r\\n6\\n\\r7'
, testnr = ++global.testnumbers
, callbacks = 0;
memcached.set("test:" + testnr, message, 1000, function(error, ok){
++callbacks;
assert.ok(!error);
ok.should.be.true;
memcached.get("test:" + testnr, function(error, answer){
++callbacks;
assert.ok(!error);
assert.ok(typeof answer === 'string');
answer.should.eql(message);
memcached.end(); // close connections
assert.equal(callbacks, 2);
done();
});
});
});
/**
* Make sure long keys are hashed
*/
it("make sure you can get really long strings", function(done) {
var memcached = new Memcached(common.servers.single)
, message = 'VALUE hello, I\'m not really a value.'
, testnr = "01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"+(++global.testnumbers)
, callbacks = 0;
memcached.set("test:" + testnr, message, 1000, function(error, ok){
++callbacks;
assert.ok(!error);
ok.should.be.true;
memcached.get("test:" + testnr, function(error, answer){
++callbacks;
assert.ok(!error);
assert.ok(typeof answer === 'string');
answer.should.eql(message);
memcached.end(); // close connections
assert.equal(callbacks, 2);
done();
});
});
});
/**
* Make sure keys with spaces return an error
*/
it("errors on spaces in strings", function(done) {
var memcached = new Memcached(common.servers.single)
, message = 'VALUE hello, I\'m not really a value.'
, testnr = " "+(++global.testnumbers)
, callbacks = 0;
memcached.set("test:" + testnr, message, 1000, function(error, ok){
++callbacks;
assert.ok(error);
assert.ok(error.message === 'The key should not contain any whitespace or new lines');
done();
});
});
/*
Make sure that getMulti calls work for very long keys.
If the keys aren't hashed because they are too long, memcached will throw exceptions, so we need to make sure that exceptions aren't thrown.
*/
it("make sure you can getMulti really long keys", function(done) {
var memcached = new Memcached(common.servers.single)
, message = 'My value is not relevant'
, testnr1 = "01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"+(++global.testnumbers)
, testnr2 = "01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"+(global.testnumbers)+"a"
, callbacks = 0;
memcached.getMulti([ testnr1, testnr2 ], function(error, ok) {
++callbacks;
assert.ok(!error);
memcached.end();
assert.equal(callbacks, 1);
done();
});
});
/**
* Set value size just under maximum amount of data (1MB),
* should trigger error, not crash. The actual value size to trigger the
* error should be value length + key length + length of metadata stored with the
* key value pair.
*/
it("set value length just under maximum data and check for correct error handling", function(done) {
var memcached = new Memcached(common.servers.single)
, message = new Array(32767).join('ThisIsMyTestMessageForThisData32')
, testnr = ++global.testnumbers
, callbacks = 0;
//Length of message is 1048512
memcached.set("test:" + testnr, message, 1000, function(error, ok){
++callbacks;
assert.equal(error, 'Error: The length of the value is greater than 1048576');
ok.should.be.false;
memcached.end(); // close connections
assert.equal(callbacks, 1);
done();
});
});
});
|
// MIT © 2017 azu
import PropTypes from "prop-types";
import * as React from "react";
import { BootstrapTable, TableHeaderColumn } from "react-bootstrap-table";
const sortBy = require("lodash.sortby");
const { compute } = require("jser-stat");
require("bootstrap/dist/css/bootstrap.css");
require("react-bootstrap-table/dist/react-bootstrap-table-all.min.css");
export default class TagRankingContainer extends React.Component {
constructor() {
super();
this.state = {
sortName: undefined,
sortOrder: undefined
};
this.onSortChange = (sortName, sortOrder) => {
this.setState({
sortName,
sortOrder
});
};
}
createDate(weeks) {
const groupByTag = compute.countTagsByGroup(weeks);
return sortBy(
Object.entries(groupByTag).map((entry, index) => {
return {
id: String(index + 1),
name: entry[0],
count: entry[1]
};
}),
"count"
).reverse();
}
render() {
const data = this.createDate(this.props.weeks);
const options = {
sizePerPage: 20,
sortName: this.state.sortName,
sortOrder: this.state.sortOrder,
onSortChange: this.onSortChange
};
return (
<div id="TagRankingContainer" className="TagRankingContainer panel panel-default">
<h2 className="TagRankingContainer-title panel-heading">Tagランキング(合計)</h2>
<p className="panel-body">紹介したアイテムのタグを合計数でランキング</p>
<BootstrapTable data={data} options={options} pagination exportCSV>
<TableHeaderColumn dataField="id" isKey={true} hidden>
ID
</TableHeaderColumn>
<TableHeaderColumn dataField="name" dataSort={true}>
Domain
</TableHeaderColumn>
<TableHeaderColumn dataField="count" dataSort={true}>
Count
</TableHeaderColumn>
</BootstrapTable>
,
</div>
);
}
}
TagRankingContainer.propsType = {
items: PropTypes.arrayOf(PropTypes.object)
};
|
var webpack = require('webpack');
var UglifyJsPlugin = webpack.optimize.UglifyJsPlugin;
var path = require('path');
var env = require('yargs').argv.mode;
var libraryName = 'ngImageCrop';
var plugins = [
new webpack.ProvidePlugin({
"window.EXIF": "exif-js",
})
];
var outputFile;
if (env === 'build') {
plugins.push(new UglifyJsPlugin({ minimize: true }));
outputFile = libraryName + '.min.js';
} else {
outputFile = libraryName + '.js';
}
var config = {
entry: __dirname + '/src/index.js',
devtool: 'source-map',
output: {
path: __dirname + '/lib',
filename: outputFile,
library: libraryName,
libraryTarget: 'umd',
umdNamedDefine: true
},
externals: {
croppie: 'croppie',
'window.EXIF': 'exif-js'
},
module: {
loaders: [
{
test: /\.jade$/,
loader: 'jade'
},
{
test: /\.css$/,
loaders: ["style", "css"]
},
{
test: /(\.jsx|\.js)$/,
loader: 'babel',
exclude: /(node_modules|bower_components)/
},
{
test: /(\.jsx|\.js)$/,
loader: "eslint-loader",
exclude: /node_modules/
}
]
},
resolve: {
root: path.resolve('./src'),
extensions: ['', '.js']
},
plugins: plugins
};
module.exports = config;
|
'use strict';
/**
* A registry of all queue instances by their names.
*/
class Registry {
/**
* Registers a queue. Throws an exception if a duplicate is being created.
*
* @param {!Queue} queue
*/
static register(queue) {
var name = queue.name;
if (!Registry.get(name)) {
Registry.instances_[name] = queue;
} else {
throw new Error('A queue with that name already exists');
}
}
/**
* Removes a queue from the registry. No error is thrown if the queue did not exist.
*
* @param {!Queue} queue
*/
static unregister(queue) {
var name = queue.name;
delete Registry.instances_[name];
}
/**
* Returns the instance of the named queue.
*
* @param {string} name The name of the queue.
* @return {!Queue|undefined}
*/
static get(name) {
return Registry.instances_[name];
}
/**
* Returns all the queue names.
*
* @return {!Array<string>}
*/
static getNames() {
return Object.keys(Registry.instances_);
}
}
/**
* A map of name:Queue instance.
*
* @type {!Object<string,!Queue>}
* @private
*/
Registry.instances_ = {}
module.exports = Registry;
|
"use strict";
module.exports = async (argv) => {
const flowIdTag = `step:flow:${argv.id}`;
const defaultCollector = (
criteria,
limit = 1,
name = "artifacts",
collectType = "artifactrepo.artifact"
) => ({
name: name,
collectType: collectType,
criteria: criteria,
limit: limit,
latest: false
});
const defaultBlSpec = (
name,
script = "",
slaveCriteria = "",
tagScript = "",
parentStepNames = [],
visible = true
) => ({
name: name,
flow: {
_ref: true,
id: argv.id,
type: "flowctrl.flow"
},
concurrency: 1,
baseline: {
_ref: true,
id: name, // Use baseline with same name as step
type: "baselinegen.specification"
},
criteria: slaveCriteria,
script: script,
tagScript: tagScript,
parentStepNames: parentStepNames,
visible: visible
});
const tagBlSpec = (
name,
tagScript = "",
parentStepNames = [],
visible = true
) => defaultBlSpec(name, "", "", tagScript, parentStepNames, visible);
const slaveScriptBlSpec = (
name,
script = "",
slaveCriteria = "",
parentStepNames = [],
visible = true
) => defaultBlSpec(name, script, slaveCriteria, "", parentStepNames, visible);
const baselineSpecs = [
{
_id: "ArtSelect",
collectors: [
defaultCollector(`!${flowIdTag}`)
]
}, {
_id: "DC",
collectors: [
defaultCollector(`${flowIdTag} AND !step:DC:success`)
]
}, {
_id: "Integrate",
collectors: [
defaultCollector(`${flowIdTag} AND step:DC:success`)
]
}, {
_id: "ShortTest",
collectors: [
defaultCollector(`${flowIdTag} AND step:Integrate:success`)
]
}, {
_id: "LongTest",
collectors: [
defaultCollector(`${flowIdTag} AND step:ShortTest:success`)
]
}
];
const randomDelayScript = `
#!/bin/bash
delay=$(shuf -i3-10 -n 1)
echo "I will sleep $delay seconds"
sleep $delay
exit 0
`;
const defaultSlaveCriteria = "slave1";
const steps = [
tagBlSpec(
"ArtSelect", `tags.push("${flowIdTag}");`, [], false
),
slaveScriptBlSpec(
"DC", randomDelayScript, defaultSlaveCriteria
),
slaveScriptBlSpec(
"Integrate", randomDelayScript, defaultSlaveCriteria, [ "DC" ]
),
slaveScriptBlSpec(
"ShortTest", randomDelayScript, defaultSlaveCriteria, [ "Integrate" ]
),
slaveScriptBlSpec(
"LongTest", randomDelayScript, defaultSlaveCriteria, [ "ShortTest" ]
)
];
return {
flow: {
_id: argv.id,
description: `Flow with id ${argv.id}`
},
specifications: baselineSpecs,
steps: steps
};
};
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M3 2h18v2H3zm0 18h18v2H3zm0-6h18v2H3zm0-6h18v2H3z"
}), 'DensitySmall');
exports.default = _default; |
import React from 'react'
import Post from '../src/scenes/Post'
import renderer from 'react-test-renderer'
|
var activeTab = null;
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log(sender);
console.log(request);
if (sender.tab) {
activeTab = sender.tab;
}
});
var ws = null;
var addr = "ws://localhost:42050/ws"
function init() {
try {
ws = new WebSocket(addr);
} catch(err) {
console.log(err);
setTimeout(function() { this.connect(addr); }, 5000);
return
}
setup(ws);
};
function setup(ws) {
ws.onmessage = function (evt) {
console.log(evt);
var data = JSON.parse(evt.data);
if (activeTab === null) {
return
}
chrome.tabs.sendMessage(activeTab.id, {command: data.command}, function(response) {
console.log(response);
});
};
ws.onclose = function(err) {
console.log(err);
setTimeout(function() { init(); }, 5000);
}
}
init(); |
define(['exports', 'core-js'], function (exports, _coreJs) {
'use strict';
exports.__esModule = true;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var theGlobal = (function () {
if (typeof self !== 'undefined') {
return self;
}
if (typeof global !== 'undefined') {
return global;
}
return new Function('return this')();
})();
var emptyMetadata = Object.freeze({});
var metadataContainerKey = '__metadata__';
if (typeof theGlobal.System === 'undefined') {
theGlobal.System = { isFake: true };
}
if (typeof theGlobal.System.forEachModule === 'undefined') {
theGlobal.System.forEachModule = function () {};
}
if (typeof theGlobal.Reflect === 'undefined') {
theGlobal.Reflect = {};
}
if (typeof theGlobal.Reflect.getOwnMetadata === 'undefined') {
Reflect.getOwnMetadata = function (metadataKey, target, targetKey) {
return ((target[metadataContainerKey] || emptyMetadata)[targetKey] || emptyMetadata)[metadataKey];
};
}
if (typeof theGlobal.Reflect.defineMetadata === 'undefined') {
Reflect.defineMetadata = function (metadataKey, metadataValue, target, targetKey) {
var metadataContainer = target.hasOwnProperty(metadataContainerKey) ? target[metadataContainerKey] : target[metadataContainerKey] = {};
var targetContainer = metadataContainer[targetKey] || (metadataContainer[targetKey] = {});
targetContainer[metadataKey] = metadataValue;
};
}
if (typeof theGlobal.Reflect.metadata === 'undefined') {
Reflect.metadata = function (metadataKey, metadataValue) {
return function (target, targetKey) {
Reflect.defineMetadata(metadataKey, metadataValue, target, targetKey);
};
};
}
function ensureDecorators(target) {
var applicator;
if (typeof target.decorators === 'function') {
applicator = target.decorators();
} else {
applicator = target.decorators;
}
if (typeof applicator._decorate === 'function') {
delete target.decorators;
applicator._decorate(target);
} else {
throw new Error('The return value of your decorator\'s method was not valid.');
}
}
var Metadata = {
global: theGlobal,
resource: 'aurelia:resource',
paramTypes: 'design:paramtypes',
properties: 'design:properties',
get: function get(metadataKey, target, targetKey) {
if (!target) {
return undefined;
}
var result = Metadata.getOwn(metadataKey, target, targetKey);
return result === undefined ? Metadata.get(metadataKey, Object.getPrototypeOf(target), targetKey) : result;
},
getOwn: function getOwn(metadataKey, target, targetKey) {
if (!target) {
return undefined;
}
if (target.hasOwnProperty('decorators')) {
ensureDecorators(target);
}
return Reflect.getOwnMetadata(metadataKey, target, targetKey);
},
define: function define(metadataKey, metadataValue, target, targetKey) {
Reflect.defineMetadata(metadataKey, metadataValue, target, targetKey);
},
getOrCreateOwn: function getOrCreateOwn(metadataKey, Type, target, targetKey) {
var result = Metadata.getOwn(metadataKey, target, targetKey);
if (result === undefined) {
result = new Type();
Reflect.defineMetadata(metadataKey, result, target, targetKey);
}
return result;
}
};
exports.Metadata = Metadata;
var originStorage = new Map(),
unknownOrigin = Object.freeze({ moduleId: undefined, moduleMember: undefined });
var Origin = (function () {
function Origin(moduleId, moduleMember) {
_classCallCheck(this, Origin);
this.moduleId = moduleId;
this.moduleMember = moduleMember;
}
Origin.get = function get(fn) {
var origin = originStorage.get(fn);
if (origin === undefined) {
System.forEachModule(function (key, value) {
for (var name in value) {
var exp = value[name];
if (exp === fn) {
originStorage.set(fn, origin = new Origin(key, name));
return true;
}
}
if (value === fn) {
originStorage.set(fn, origin = new Origin(key, 'default'));
return true;
}
});
}
return origin || unknownOrigin;
};
Origin.set = function set(fn, origin) {
originStorage.set(fn, origin);
};
return Origin;
})();
exports.Origin = Origin;
var DecoratorApplicator = (function () {
function DecoratorApplicator() {
_classCallCheck(this, DecoratorApplicator);
this._first = null;
this._second = null;
this._third = null;
this._rest = null;
}
DecoratorApplicator.prototype.decorator = function decorator(_decorator) {
if (this._first === null) {
this._first = _decorator;
return this;
}
if (this._second === null) {
this._second = _decorator;
return this;
}
if (this._third === null) {
this._third = _decorator;
return this;
}
if (this._rest === null) {
this._rest = [];
}
this._rest.push(_decorator);
return this;
};
DecoratorApplicator.prototype._decorate = function _decorate(target) {
var i, ii, rest;
if (this._first !== null) {
this._first(target);
}
if (this._second !== null) {
this._second(target);
}
if (this._third !== null) {
this._third(target);
}
rest = this._rest;
if (rest !== null) {
for (i = 0, ii = rest.length; i < ii; ++i) {
rest[i](target);
}
}
};
return DecoratorApplicator;
})();
exports.DecoratorApplicator = DecoratorApplicator;
var Decorators = {
configure: {
parameterizedDecorator: function parameterizedDecorator(name, decorator) {
Decorators[name] = function () {
var applicator = new DecoratorApplicator();
return applicator[name].apply(applicator, arguments);
};
DecoratorApplicator.prototype[name] = function () {
var result = decorator.apply(null, arguments);
return this.decorator(result);
};
},
simpleDecorator: function simpleDecorator(name, decorator) {
Decorators[name] = function () {
return new DecoratorApplicator().decorator(decorator);
};
DecoratorApplicator.prototype[name] = function () {
return this.decorator(decorator);
};
}
}
};
exports.Decorators = Decorators;
}); |
const Lib = require("@effectful/serialization");
require("../src/main");
const assert = require("assert");
const React = require("react");
describe("serializable react element", function() {
it("should be convertible to/from JSON", function() {
const el = (
<div class="myClass" style={{ paddingLeft: 10 }}>
hi
</div>
);
const elJson = Lib.write({ el });
assert.deepStrictEqual(elJson, {
f: [
[
"el",
{
$: "ReactElement",
props: {
f: [
["class", "myClass"],
["style", { f: [["paddingLeft", 10]] }],
["children", { $: "undefined" }]
]
},
children: ["hi"],
type: "div"
}
]
]
});
const rel = Lib.read(elJson);
assert.notStrictEqual(el, rel.el);
assert.deepStrictEqual(el, rel.el);
});
});
|
import { stopAndPrevent } from '../utils/event.js'
import cache from '../utils/cache.js'
function filterFiles (files, rejectedFiles, failedPropValidation, filterFn) {
const acceptedFiles = []
files.forEach(file => {
if (filterFn(file) === true) {
acceptedFiles.push(file)
}
else {
rejectedFiles.push({ failedPropValidation, file })
}
})
return acceptedFiles
}
function stopAndPreventDrag (e) {
e && e.dataTransfer && (e.dataTransfer.dropEffect = 'copy')
stopAndPrevent(e)
}
export default {
props: {
multiple: Boolean,
accept: String,
capture: String,
maxFileSize: [ Number, String ],
maxTotalSize: [ Number, String ],
maxFiles: [ Number, String ],
filter: Function
},
computed: {
extensions () {
if (this.accept !== void 0) {
return this.accept.split(',').map(ext => {
ext = ext.trim()
if (ext === '*') { // support "*"
return '*/'
}
else if (ext.endsWith('/*')) { // support "image/*" or "*/*"
ext = ext.slice(0, ext.length - 1)
}
return ext.toUpperCase()
})
}
},
maxFilesNumber () {
return parseInt(this.maxFiles, 10)
},
maxTotalSizeNumber () {
return parseInt(this.maxTotalSize, 10)
}
},
methods: {
pickFiles (e) {
if (this.editable) {
const input = this.__getFileInput()
input && input.click(e)
}
},
addFiles (files) {
if (this.editable && files) {
this.__addFiles(null, files)
}
},
__processFiles (e, filesToProcess, currentFileList, append) {
let files = Array.from(filesToProcess || e.target.files)
const rejectedFiles = []
const done = () => {
if (rejectedFiles.length > 0) {
this.$emit('rejected', rejectedFiles)
}
}
// filter file types
if (this.accept !== void 0 && this.extensions.indexOf('*/') === -1) {
files = filterFiles(files, rejectedFiles, 'accept', file => {
return this.extensions.some(ext => (
file.type.toUpperCase().startsWith(ext) ||
file.name.toUpperCase().endsWith(ext)
))
})
if (files.length === 0) { return done() }
}
// filter max file size
if (this.maxFileSize !== void 0) {
const maxFileSize = parseInt(this.maxFileSize, 10)
files = filterFiles(files, rejectedFiles, 'max-file-size', file => {
return file.size <= maxFileSize
})
if (files.length === 0) { return done() }
}
// Cordova/iOS allows selecting multiple files even when the
// multiple attribute is not specified. We also normalize drag'n'dropped
// files here:
if (this.multiple !== true) {
files = [ files[0] ]
}
if (this.maxTotalSize !== void 0) {
let size = append === true
? currentFileList.reduce((total, file) => total + file.size, 0)
: 0
files = filterFiles(files, rejectedFiles, 'max-total-size', file => {
size += file.size
return size <= this.maxTotalSizeNumber
})
if (files.length === 0) { return done() }
}
// do we have custom filter function?
if (typeof this.filter === 'function') {
const filteredFiles = this.filter(files)
files = filterFiles(files, rejectedFiles, 'filter', file => {
return filteredFiles.includes(file)
})
}
if (this.maxFiles !== void 0) {
let filesNumber = append === true
? currentFileList.length
: 0
files = filterFiles(files, rejectedFiles, 'max-files', () => {
filesNumber++
return filesNumber <= this.maxFilesNumber
})
if (files.length === 0) { return done() }
}
done()
if (files.length > 0) {
return files
}
},
__onDragOver (e) {
stopAndPreventDrag(e)
this.dnd !== true && (this.dnd = true)
},
__onDragLeave (e) {
stopAndPrevent(e)
this.dnd = false
},
__onDrop (e) {
stopAndPreventDrag(e)
const files = e.dataTransfer.files
if (files.length > 0) {
this.__addFiles(null, files)
}
this.dnd = false
},
__getDnd (h, type) {
if (this.dnd === true) {
return h('div', {
staticClass: `q-${type}__dnd absolute-full`,
on: cache(this, 'dnd', {
dragenter: stopAndPreventDrag,
dragover: stopAndPreventDrag,
dragleave: this.__onDragLeave,
drop: this.__onDrop
})
})
}
}
}
}
export const FileValueMixin = {
computed: {
formDomProps () {
if (this.type !== 'file') {
return
}
try {
const dt = 'DataTransfer' in window
? new DataTransfer()
: ('ClipboardEvent' in window
? new ClipboardEvent('').clipboardData
: void 0
)
if (Object(this.value) === this.value) {
('length' in this.value
? Array.from(this.value)
: [ this.value ]
).forEach(file => {
dt.items.add(file)
})
}
return {
files: dt.files
}
}
catch (e) {
return {
files: void 0
}
}
}
}
}
|
import Hapi from 'hapi'
import inert from 'inert'
import Query from './query'
import { url } from './resources'
const server = new Hapi.Server()
server.connection({ port: 3000, host: 'localhost' })
server.register(inert, function (err) {
server.route({
method: 'GET',
path: url + '{filter?}',
handler: function (request, reply) {
reply(Query.getAll())
}
})
server.route({
method: 'POST',
path: url,
handler: function (request, reply) {
let task = Query.create(request.payload)
.then((task) => { reply(task) })
.error((error) => { console.log(error) })
}
})
server.route({
method: 'PUT',
path: url,
handler: function (request, reply) {
Query.update(request.payload).then((task) => {
reply(request.payload)
})
}
})
server.route({
method: 'DELETE',
path: url + '{id}',
handler: function (request, reply) {
Query.delete(request.params.id).then((value) => {
reply()
})
}
})
server.route({
method: 'GET',
path: '/{param*}',
handler: {
directory: {
path: 'public',
listing: true
}
}
}
)
server.start((err) => {
if (err) {
throw err
}
console.log('Server running at:', server.info.uri)
})
})
export default server
|
var app = angular.module("app", ['angular-loading-bar']);
app.controller("AppTest", function($scope, $http, $location, $anchorScroll){
/**
global vars
**/
app=this;
$scope.hackerTop = "";
$scope.lobTop = "";
$scope.rTop = "";
$scope.hackerNew = "";
$scope.lobNew = "";
$scope.rNew = "";
$scope.content="first";
/**
For top posts
**/
$http.get('/ycomb').success(function(data) {
$scope.hackerTop = data.Crawls;
});
$http.get('/lobster').success(function(data) {
$scope.lobTop = data.Crawls;
});
$http.get('/rp').success(function(data) {
$scope.rTop = data.Crawls;
});
/**
For new posts
**/
$http.get('/ynew').success(function(data) {
$scope.hackerNew = data.Crawls;
});
$http.get('/lnew').success(function(data) {
$scope.lNew = data.Crawls;
});
$http.get('/rnew').success(function(data) {
$scope.rNew = data.Crawls;
});
$scope.refresh = function(){
$http.get('/ycomb').success(function(data) {
$scope.hackerTop = data.Crawls;
});
$http.get('/lobster').success(function(data) {
$scope.lobTop = data.Crawls;
});
$http.get('/rp').success(function(data) {
$scope.rTop = data.Crawls;
});
/**
For new posts
**/
$http.get('/ynew').success(function(data) {
$scope.hackerNew = data.Crawls;
});
$http.get('/lnew').success(function(data) {
$scope.lNew = data.Crawls;
});
$http.get('/rnew').success(function(data) {
$scope.rNew = data.Crawls;
});
};
$scope.goToTop = function(){
$location.hash('refresh');
$anchorScroll();
};
});
|
import * as React from 'react';
import expect from 'expect';
import {renderIntoDocument} from 'react-addons-test-utils';
import App from './';
describe('/components/App', () => {
it('<App> component should render', () => {
const wrapper = renderIntoDocument(<App />);
expect(wrapper).toExist();
});
}); |
exports.downloadModal = function downloadModal() {
return {
restrict: 'E',
templateUrl: './app/components/download/downloadModal.template.html',
};
};
|
var assert = require('assert');
var R = require('..');
describe('mapAccumR', function() {
var add = function(a, b) {return [a + b, a + b];};
var mult = function(a, b) {return [a * b, a * b];};
it('map and accumulate simple functions over arrays with the supplied accumulator', function() {
assert.deepEqual(R.mapAccumR(add, 0, [1, 2, 3, 4]), [10, [10, 9, 7, 4]]);
assert.deepEqual(R.mapAccumR(mult, 1, [1, 2, 3, 4]), [24, [24, 24, 12, 4]]);
});
it('returns the list and accumulator for an empty array', function() {
assert.deepEqual(R.mapAccumR(add, 0, []), [0, []]);
assert.deepEqual(R.mapAccumR(mult, 1, []), [1, []]);
assert.deepEqual(R.mapAccumR(R.concat, [], []), [[], []]);
});
it('is automatically curried', function() {
var addOrConcat = R.mapAccumR(add);
var sum = addOrConcat(0);
var cat = addOrConcat('');
assert.deepEqual(sum([1, 2, 3, 4]), [10, [10, 9, 7, 4]]);
assert.deepEqual(cat(['1', '2', '3', '4']), ['4321', ['4321', '432', '43', '4']]);
});
it('correctly reports the arity of curried versions', function() {
var sum = R.mapAccumR(add, 0);
assert.strictEqual(sum.length, 1);
});
it('throws on zero arguments', function() {
assert.throws(R.mapAccumR, TypeError);
assert.throws(R.mapAccumR(add), TypeError);
});
});
|
var Q = require('kew')
var R = require('ramda')
var path = require('path')
var proc = require('child_process')
var u = require('util')
var http = require('http')
// speak
function log(what, cwd, cmd) {
var c = cwd ? u.format('[%s] ', cwd) : '';
console.log(u.format('%s %s=> %s', what, c, (cmd || []).join(' ')))
}
// relative dir
function relative(x) {
return path.join(__dirname, x)
}
// turn 'lala %s' into function
var template = R.curry(function(s, x){
return u.format(s, x).split(' ');
})
// execute command in cwd
// command is array ['echo', 'foo', 'bar']
// cwd may be false
function exec(cmd, cwd) {
var d = Q.defer()
log('RUNNING', cwd, cmd);
var opts = (cwd && {cwd: relative(cwd)}) || {}
proc.execFile(R.head(cmd), R.tail(cmd), opts, function(err,stdout,stderr){
if(stdout) console.log(stdout.trim())
if(stderr) console.log(stderr.trim())
if(err) d.reject(err)
else d.resolve(stdout.trim())
})
return d.promise;
}
// run command as subprocess
// command is array ['echo', 'foo', 'bar']
// cwd may be false
function spawn(cmd, cwd) {
log('DAEMON', cwd, cmd);
var opts = { stdio: ['ignore','inherit','inherit'] }
if(cwd) opts.cwd = relative(cwd)
proc.spawn(R.head(cmd), R.tail(cmd), opts)
}
// returns function when applied to x exec's the template with x substituted
function runTemplate(s, cwd) {
return R.compose(
R.flip(R.curry(exec))(cwd),
template(s)
)
}
// returns function when applied to x runs command in that dir x
function runDir(s) {
return R.curry(exec)(s.split(' '))
}
// API host
process.env.HISTOGRAPH_CONFIG = path.join(__dirname, 'config.yaml')
var conf = require('histograph-config');
// promise that rejects when API is done
function isUp() {
var d = Q.defer()
var r = http.request(conf.api.baseUrl, function(res) {
if(res.statusCode === 200) d.resolve(true)
else d.reject(res.statusCode)
})
r.on('error', d.reject.bind(d))
r.end()
return d.promise;
}
// spin failing promise
function retryPromise(n, mkPromise) {
if(n > 0)
return mkPromise()
.fail(function(){
return retryPromise(n - 1, mkPromise);
});
return mkPromise();
}
function up_check()
{
// 10 tries, with 1 second delay
return retryPromise(10, function() {
process.stdout.write('.');
return Q.delay(1000).then(isUp)
})
}
// collection of commands
var $ = {
projects: 'api core import data'.split(' '),
rimraf: runTemplate('rm -rf %s', false),
gitClone: runTemplate('git clone https://github.com/histograph/%s', false),
npmInstall: runDir('npm i'),
nodeRun: runDir('node index.js'),
daemon: R.curry(spawn)('node index.js'.split(' ')),
}
// install script
console.log('cleaning')
Q.all(R.map($.rimraf, $.projects))
.then(function(){
log('git clone')
return Q.all(R.map($.gitClone, $.projects))
})
.then(function(){
log('npm install')
return Q.all(R.map($.npmInstall, $.projects))
})
.then(function(){
log('download and convert data')
return $.nodeRun('data')
})
.then(function(){
log('clear neo4j edges')
return exec(['neo4j-shell', '-c',
'match ()-[e]-() delete e;'], false)
})
.then(function(){
log('clear neo4j nodes')
return exec(['neo4j-shell', '-c',
'match (n) delete n;'], false)
})
.then(function(){
log('create neo4j schema')
return exec(['neo4j-shell', '-c',
'create constraint on (n:_) assert n.id is unique'], false)
})
.then(function(){
log('starting api, core')
R.map($.daemon, ['api','core'])
return up_check()
})
.then(function(){
log('importing data')
return $.nodeRun('import')
})
.fail(function(err){
console.error(err && err.stack || err)
})
|
define(['knockout', 'knockout-mapping'], function(ko, koMapping) {
return function(data, mapping) {
var that = this;
koMapping.fromJS(data, mapping || {}, that);
that.fqn = 'ACME.Blog.Entities.ContentStream.TextBlock';
};
}); |
//~ name c39
alert(c39);
//~ component c40.js
|
version https://git-lfs.github.com/spec/v1
oid sha256:ec550c327e183b1f8932d33980c89b05d470c36cbd1997c0ddb2e8becb12d9a5
size 1025
|
Router.route("html",{
path: "/admin/html",
template: "html",
controller: "AdminController",
onAfterAction: function(){
Session.set('admin_title', '生成静态');
Session.set('admin_subtitle', 'Generation the HTML files.');
}
})
Router.route("gen",{
path: "/admin/html/gen",
template: "htmlGen",
controller: "AdminController",
onAfterAction: function(){
Session.set('admin_title', '生成静态');
Session.set('admin_subtitle', 'Generation the HTML files.');
}
})
// Router.route("templates",{
// path: "/admin/templates",
// template: "templates",
// controller: "AdminController",
// onAfterAction: function(){
// Session.set('admin_title', '模板管理');
// Session.set('admin_subtitle', 'Manage all templates.');
// },
// // data: function(){
// // return {
// // // admin_table: AdminTables.Users
// // }
// // }
// }) |
/**
* @file Manages Salesforce OAuth2 operations
* @author Shinichi Tomita <shinichi.tomita@gmail.com>
*/
var querystring = require('querystring'),
_ = require('underscore'),
Transport = require('./transport');
var defaults = {
loginUrl : "https://login.salesforce.com"
};
/**
* OAuth2 class
*
* @class
* @constructor
* @param {Object} options - OAuth2 config options
* @param {String} [options.loginUrl] - Salesforce login server URL
* @param {String} [options.authzServiceUrl] - OAuth2 authorization service URL. If not specified, it generates from default by adding to login server URL.
* @param {String} [options.tokenServiceUrl] - OAuth2 token service URL. If not specified it generates from default by adding to login server URL.
* @param {String} options.clientId - OAuth2 client ID.
* @param {String} options.clientSecret - OAuth2 client secret.
* @param {String} options.redirectUri - URI to be callbacked from Salesforce OAuth2 authorization service.
*/
var OAuth2 = module.exports = function(options) {
if (options.authzServiceUrl && options.tokenServiceUrl) {
this.loginUrl = options.authzServiceUrl.split('/').slice(0, 3).join('/');
this.authzServiceUrl = options.authzServiceUrl;
this.tokenServiceUrl = options.tokenServiceUrl;
this.revokeServiceUrl = options.revokeServiceUrl;
} else {
this.loginUrl = options.loginUrl || defaults.loginUrl;
this.authzServiceUrl = this.loginUrl + "/services/oauth2/authorize";
this.tokenServiceUrl = this.loginUrl + "/services/oauth2/token";
this.revokeServiceUrl = this.loginUrl + "/services/oauth2/revoke";
}
this.clientId = options.clientId;
this.clientSecret = options.clientSecret;
this.redirectUri = options.redirectUri;
this._transport =
options.proxyUrl ? new Transport.ProxyTransport(options.proxyUrl) : new Transport();
};
/**
*
*/
_.extend(OAuth2.prototype, /** @lends OAuth2.prototype **/ {
/**
* Get Salesforce OAuth2 authorization page URL to redirect user agent.
*
* @param {Object} params - Parameters
* @param {String} params.scope - Scope values in space-separated string
* @param {String} params.state - State parameter
* @returns {String} Authorization page URL
*/
getAuthorizationUrl : function(params) {
params = _.extend({
response_type : "code",
client_id : this.clientId,
redirect_uri : this.redirectUri
}, params || {});
return this.authzServiceUrl +
(this.authzServiceUrl.indexOf('?') >= 0 ? "&" : "?") +
querystring.stringify(params);
},
/**
* @typedef TokenResponse
* @type {Object}
* @property {String} access_token
* @property {String} refresh_token
*/
/**
* OAuth2 Refresh Token Flow
*
* @param {String} refreshToken - Refresh token
* @param {Callback.<TokenResponse>} [callback] - Callback function
* @returns {Promise.<TokenResponse>}
*/
refreshToken : function(refreshToken, callback) {
return this._postParams({
grant_type : "refresh_token",
refresh_token : refreshToken,
client_id : this.clientId,
client_secret : this.clientSecret
}, callback);
},
/**
* OAuth2 Web Server Authentication Flow (Authorization Code)
* Access Token Request
*
* @param {String} code - Authorization code
* @param {Callback.<TokenResponse>} [callback] - Callback function
* @returns {Promise.<TokenResponse>}
*/
requestToken : function(code, callback) {
return this._postParams({
grant_type : "authorization_code",
code : code,
client_id : this.clientId,
client_secret : this.clientSecret,
redirect_uri : this.redirectUri
}, callback);
},
/**
* OAuth2 Username-Password Flow (Resource Owner Password Credentials)
*
* @param {String} username - Salesforce username
* @param {String} password - Salesforce password
* @param {Callback.<TokenResponse>} [callback] - Callback function
* @returns {Promise.<TokenResponse>}
*/
authenticate : function(username, password, callback) {
return this._postParams({
grant_type : "password",
username : username,
password : password,
client_id : this.clientId,
client_secret : this.clientSecret,
redirect_uri : this.redirectUri
}, callback);
},
/**
* OAuth2 Revoke Session Token
*
* @param {String} accessToken - Access token to revoke
* @param {Callback.<undefined>} [callback] - Callback function
* @returns {Promise.<undefined>}
*/
revokeToken : function(accessToken, callback) {
return this._transport.httpRequest({
method : 'POST',
url : this.revokeServiceUrl,
body: querystring.stringify({ token: accessToken }),
headers: {
"content-type" : "application/x-www-form-urlencoded"
}
}).then(function(response) {
if (response.statusCode >= 400) {
var res = querystring.parse(response.body);
if (!res || !res.error) {
res = { error: "ERROR_HTTP_"+response.statusCode, error_description: response.body };
}
var err = new Error(res.error_description);
err.name = res.error;
throw err;
}
}).thenCall(callback);
},
/**
* @private
*/
_postParams : function(params, callback) {
return this._transport.httpRequest({
method : 'POST',
url : this.tokenServiceUrl,
body : querystring.stringify(params),
headers : {
"content-type" : "application/x-www-form-urlencoded"
}
}).then(function(response) {
var res;
try {
res = JSON.parse(response.body);
} catch(e) {}
if (response.statusCode >= 400) {
res = res || { error: "ERROR_HTTP_"+response.statusCode, error_description: response.body };
var err = new Error(res.error_description);
err.name = res.error;
throw err;
}
return res;
}).thenCall(callback);
}
});
|
(function () {
'use strict';
angular
.module('spaStore')
.controller('ProductController', function ($stateParams, productService) {
var vm = this;
vm.getProductById = function () {
var id = $stateParams.id;
productService
.getProductsById(id)
.then(function (res) {
vm.product = res[0];
console.log(vm.product)
}, function (err) {})
}
// vm.product = { name: 'Крем Аква Витал', heading: 'Професионална емулсия
// за почистване на грим', description: '<div>Лека и деликатна емулсия,
// обогатена с екстракт от бадемов протеин, нежно премахв' + 'а дори и
// най-устойчивия грим (включително водоустойчивият грим). Включва ултра н' +
// 'ежни почистващи агенти, като Fucogel, екстракт от Невен и
// Bisabolol.<strong>Test</strong></div>', category: 'За козметици',
// subCategory: ['Лице-Хидратация'], inventoryId: 121, picturePreview: '',
// picturesOthers: [], price: 40, quantity: '400ml' };
if ($stateParams.id) {
vm.getProductById();
}
if($stateParams.category){
// vm.getProductByCategory();
}
});
})();
|
'use strict';
// Configuring the Articles module
angular.module('articulos').run(['Menus',
function(Menus) {
// Set top bar menu items
/*Menus.addMenuItem('topbar', 'Articulos', 'articulos', 'dropdown', '/articulos(/create)?');
Menus.addSubMenuItem('topbar', 'articulos', 'List Articulos', 'articulos');
Menus.addSubMenuItem('topbar', 'articulos', 'New Articulo', 'articulos/create');*/
}
]); |
var Node = require('./Node');
module.exports = Vector4Node;
// A vector with four components/values.
function Vector4Node(options){
options = options || {};
Node.call(this, options);
this.value = options.value ? options.value.slice(0) : [0,0,0,0];
}
Vector4Node.prototype = Object.create(Node.prototype);
Vector4Node.prototype.constructor = Vector4Node;
Node.registerClass('vec4', Vector4Node);
Vector4Node.prototype.getInputPorts = function(){
return [];
};
Vector4Node.prototype.getOutputPorts = function(){
return ['rgba'];
};
Vector4Node.prototype.getOutputTypes = function(key){
return key === 'rgba' ? ['vec4'] : [];
};
Vector4Node.prototype.render = function(){
var outVarName = this.getOutputVariableNames('rgba')[0];
return outVarName ? outVarName + ' = vec4(' + this.value.join(',') + ');' : '';
};
|
$.ExplosionDrawable = function(e){
var explosion;
function init(){
explosion = e;
}
function draw(ctx){
for(var i = 0; i < explosion.particles.length; i++) {
var current = explosion.particles[i];
ctx.beginPath();
ctx.fillStyle = explosion.color;
if (current.radius > 0) {
ctx.arc(current.x, current.y, current.radius, 0, $.PI2, false);
}
ctx.fill();
current.move();
}
}
init();
return {
draw: draw
}
}; |
#!/usr/bin/env node
import CLI from './cli.js'
CLI(process.argv.slice(2), process.stdout)
.catch((err) => {
console.error(err)
})
|
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
const { join } = require('path');
const getBaseKarmaConfig = require('../../karma.conf');
module.exports = function(config) {
const baseConfig = getBaseKarmaConfig();
config.set({
...baseConfig,
logLevel: config.LOG_INFO,
coverageIstanbulReporter: {
...baseConfig.coverageIstanbulReporter,
dir: join(__dirname, '../../coverage/apps/client')
}
});
};
|
import Ember from 'ember';
export default Ember.Component.extend({
videoLengthInSeconds: null,
dragging: false,
//our parent slice component is kind enough to keep track of the mouse X
//and give it to us so we can use it.
//we NEED this because the user should be able to go crazy with the handles,
//not just move them a tiny bit
mouseX: null,
classNames: ['video-player-slice-adjuster'],
classNameBindings: ['side'],
side:'',
attributeBindings: ['title'],
title: 'Click & drag to adjust size.',
mouseDown: function(e){
e.preventDefault();
this.set('dragging',true);
},
mouseUp: function(){
this.set('dragging',false);
this.sendAction('save');
},
convertPercentageToSeconds: function(percentage) {
return percentage/100 * this.get('videoLengthInSeconds');
},
_triggerSizeUpdate: Ember.observer('dragging','mouseX',function(){
if(!this.get('dragging')) {
return;
}
var relativeX = this.get('mouseX') - this.$().offset().left;
this.sendAction('updateSize',relativeX,this.get('side') === 'left');
})
});
|
require('proof')(1, async (okay) => {
const prolific = require('..')
const path = require('path')
const stream = require('stream')
const program = path.join(__dirname, 'program.js')
const processor = path.join(__dirname, 'prolific.bin.prolific.js')
const child = prolific([ '--inherit', '99', '--processor', processor, 'node', program ])
await new Promise(resolve => setTimeout(resolve, 1000))
child.destroy()
okay(0, await child.exit, 'ran')
})
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = stripTags;
function stripTags() {
return function (input) {
return input.replace(/(<([^>]+)>)/ig, '');
};
}
stripTags.$inject = [];
module.exports = exports['default'];
//# sourceMappingURL=StripTags.js.map |
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.4.4.21-1-3
description: Array.prototype.reduce applied to boolean primitive
includes: [runTestCase.js]
---*/
function testcase() {
function callbackfn(prevVal, curVal, idx, obj) {
return obj instanceof Boolean;
}
try {
Boolean.prototype[0] = true;
Boolean.prototype.length = 1;
return Array.prototype.reduce.call(false, callbackfn, 1);
} finally {
delete Boolean.prototype[0];
delete Boolean.prototype.length;
}
}
runTestCase(testcase);
|
var NodeAdapter = require("../../../base/adapter.js").NodeAdapter;
var RenderAdapter = function (factory, node) {
NodeAdapter.call(this, factory, node);
};
XML3D.createClass(RenderAdapter, NodeAdapter);
RenderAdapter.prototype.getParentRenderAdapter = function () {
return this.factory.getAdapter(this.node.parentNode, RenderAdapter);
};
/**
* @param element
*/
RenderAdapter.prototype.initElement = function (element) {
this.factory.getAdapter(element);
this.initChildElements(element);
};
/**
* @param {Element} element
*/
RenderAdapter.prototype.initChildElements = function (element) {
var child = element.firstElementChild;
while (child) {
this.initElement(child);
child = child.nextElementSibling;
}
};
RenderAdapter.prototype.applyTransformMatrix = function (transform) {
return transform;
};
RenderAdapter.prototype.getScene = function () {
return this.factory.renderer.scene;
};
module.exports = RenderAdapter;
|
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
import ButtonBase from '../ButtonBase';
import { capitalize } from '../utils/helpers';
export const styles = theme => ({
/* Styles applied to the root element. */
root: {
...theme.typography.button,
boxSizing: 'border-box',
minHeight: 36,
transition: theme.transitions.create(['background-color', 'box-shadow', 'border'], {
duration: theme.transitions.duration.short,
}),
borderRadius: '50%',
padding: 0,
minWidth: 0,
width: 56,
height: 56,
boxShadow: theme.shadows[6],
'&:active': {
boxShadow: theme.shadows[12],
},
color: theme.palette.getContrastText(theme.palette.grey[300]),
backgroundColor: theme.palette.grey[300],
'&$focusVisible': {
boxShadow: theme.shadows[6],
},
'&:hover': {
backgroundColor: theme.palette.grey.A100,
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: theme.palette.grey[300],
},
'&$disabled': {
backgroundColor: theme.palette.action.disabledBackground,
},
textDecoration: 'none',
},
'&$disabled': {
color: theme.palette.action.disabled,
boxShadow: theme.shadows[0],
backgroundColor: theme.palette.action.disabledBackground,
},
},
/* Styles applied to the span element that wraps the children. */
label: {
width: '100%', // assure the correct width for iOS Safari
display: 'inherit',
alignItems: 'inherit',
justifyContent: 'inherit',
},
/* Styles applied to the root element if `color="primary"`. */
primary: {
color: theme.palette.primary.contrastText,
backgroundColor: theme.palette.primary.main,
'&:hover': {
backgroundColor: theme.palette.primary.dark,
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: theme.palette.primary.main,
},
},
},
/* Styles applied to the root element if `color="secondary"`. */
secondary: {
color: theme.palette.secondary.contrastText,
backgroundColor: theme.palette.secondary.main,
'&:hover': {
backgroundColor: theme.palette.secondary.dark,
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: theme.palette.secondary.main,
},
},
},
/* Styles applied to the root element if `variant="extended"`. */
extended: {
borderRadius: 48 / 2,
padding: '0 16px',
width: 'auto',
minHeight: 'auto',
minWidth: 48,
height: 48,
'&$sizeSmall': {
width: 'auto',
padding: '0 8px',
borderRadius: 34 / 2,
minWidth: 34,
height: 34,
},
'&$sizeMedium': {
width: 'auto',
padding: '0 16px',
borderRadius: 40 / 2,
minWidth: 40,
height: 40,
},
},
/* Pseudo-class applied to the ButtonBase root element if the button is keyboard focused. */
focusVisible: {},
/* Pseudo-class applied to the root element if `disabled={true}`. */
disabled: {},
/* Styles applied to the root element if `color="inherit"`. */
colorInherit: {
color: 'inherit',
},
/* Styles applied to the root element if `size="small"``. */
sizeSmall: {
width: 40,
height: 40,
},
/* Styles applied to the root element if `size="medium"``. */
sizeMedium: {
width: 48,
height: 48,
},
});
const Fab = React.forwardRef(function Fab(props, ref) {
const {
children,
classes,
className,
color = 'default',
component = 'button',
disabled = false,
disableFocusRipple = false,
focusVisibleClassName,
size = 'large',
variant = 'round',
...other
} = props;
return (
<ButtonBase
className={clsx(
classes.root,
{
[classes.extended]: variant === 'extended',
[classes.primary]: color === 'primary',
[classes.secondary]: color === 'secondary',
[classes[`size${capitalize(size)}`]]: size !== 'large',
[classes.disabled]: disabled,
[classes.colorInherit]: color === 'inherit',
},
className,
)}
component={component}
disabled={disabled}
focusRipple={!disableFocusRipple}
focusVisibleClassName={clsx(classes.focusVisible, focusVisibleClassName)}
ref={ref}
{...other}
>
<span className={classes.label}>{children}</span>
</ButtonBase>
);
});
Fab.propTypes = {
/**
* The content of the button.
*/
children: PropTypes.node.isRequired,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The color of the component. It supports those theme colors that make sense for this component.
*/
color: PropTypes.oneOf(['default', 'inherit', 'primary', 'secondary']),
/**
* The component used for the root node.
* Either a string to use a DOM element or a component.
*/
component: PropTypes.elementType,
/**
* If `true`, the button will be disabled.
*/
disabled: PropTypes.bool,
/**
* If `true`, the keyboard focus ripple will be disabled.
* `disableRipple` must also be true.
*/
disableFocusRipple: PropTypes.bool,
/**
* If `true`, the ripple effect will be disabled.
*/
disableRipple: PropTypes.bool,
/**
* @ignore
*/
focusVisibleClassName: PropTypes.string,
/**
* The URL to link to when the button is clicked.
* If defined, an `a` element will be used as the root node.
*/
href: PropTypes.string,
/**
* The size of the button.
* `small` is equivalent to the dense button styling.
*/
size: PropTypes.oneOf(['small', 'medium', 'large']),
/**
* @ignore
*/
type: PropTypes.string,
/**
* The variant to use.
*/
variant: PropTypes.oneOf(['round', 'extended']),
};
export default withStyles(styles, { name: 'MuiFab' })(Fab);
|
'use strict';
angular.module('whatGruntMobile.routes.indexRoute', [])
.config([
'$routeProvider',
function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'routes/index/index.html'
});
}
]);
|
"use strict";
/**
* Module dependencies
*/
var Resource = require('deployd/lib/resource'),
util = require('util'),
path = require('path'),
debug = require('debug')('dpd-fileupload'),
formidable = require('formidable'),
fs = require('fs'),
md5 = require('MD5'),
mime = require('mime'),
env = process.server.options && process.server.options.env || null,
publicDir = "/../../public";
/**
* Module setup.
*/
function Fileupload(options) {
Resource.apply(this, arguments);
this.store = process.server.createStore(this.name + "fileupload");
if(env){
var dirToCheck = publicDir + "-" + env,
publicDirExists = fs.existsSync(__dirname + dirToCheck);
if(publicDirExists) {
publicDir = dirToCheck;
}
}
this.config = {
directory: this.config.directory || 'upload',
fullDirectory: path.join(__dirname, publicDir, (this.config.directory || 'upload'))
};
if (this.name === this.config.directory) {
this.config.directory = this.config.directory + "_";
}
// If the directory doesn't exists, we'll create it
try {
fs.statSync(this.config.fullDirectory).isDirectory();
} catch (er) {
fs.mkdir(this.config.fullDirectory);
}
}
util.inherits(Fileupload, Resource);
Fileupload.label = "File upload";
Fileupload.events = ["get", "upload", "delete"];
Fileupload.prototype.clientGeneration = true;
Fileupload.basicDashboard = {
settings: [
{
name: 'directory',
type: 'text',
description: 'Directory to save the uploaded files. Defaults to \'upload\'.'
}
]
};
/**
* Module methods
*/
Fileupload.prototype.handle = function (ctx, next) {
var req = ctx.req,
self = this,
domain = {url: ctx.url};
if (req.method === "POST" || req.method === "PUT") {
var form = new formidable.IncomingForm(),
uploadDir = this.config.fullDirectory,
resultFiles = [],
remainingFile = 0,
storedObject = {},
uniqueFilename = false,
subdir,
creator;
// Will send the response if all files have been processed
var processDone = function(err) {
if (err) return ctx.done(err);
remainingFile--;
if (remainingFile === 0) {
debug("Response sent: ", resultFiles);
return ctx.done(null, resultFiles);
}
}
// If we received params from the request
if (typeof req.query !== 'undefined') {
for (var propertyName in req.query) {
debug("Query param found: { %j:%j } ", propertyName, req.query[propertyName]);
if (propertyName === 'subdir') {
debug("Subdir found: %j", req.query[propertyName]);
uploadDir = path.join(uploadDir, req.query[propertyName]);
// If the sub-directory doesn't exists, we'll create it
try {
fs.statSync(uploadDir).isDirectory();
} catch (er) {
fs.mkdir(uploadDir);
}
} else if (propertyName === 'uniqueFilename') {
debug("uniqueFilename found: %j", req.query[propertyName]);
uniqueFilename = (req.query[propertyName] === 'true');
continue; // skip to the next param since we don't need to store this value
}
// Store any param in the object
try {
storedObject[propertyName] = JSON.parse(req.query[propertyName]);
} catch (e) {
storedObject[propertyName] = req.query[propertyName];
}
}
}
form.uploadDir = uploadDir;
var renameAndStore = function(file) {
fs.rename(file.path, path.join(uploadDir, file.name), function(err) {
if (err) return processDone(err);
debug("File renamed after event.upload.run: %j", err || path.join(uploadDir, file.name));
storedObject.filename = file.name;
if (uniqueFilename) {
storedObject.originalFilename = file.originalFilename;
}
storedObject.filesize = file.size;
storedObject.creationDate = new Date().getTime();
// Store MIME type in object
storedObject.type = mime.lookup(file.name);
self.store.insert(storedObject, function(err, result) {
if (err) return processDone(err);
debug('stored after event.upload.run %j', err || result || 'none');
resultFiles.push(result);
processDone();
});
});
}
form.parse(req)
.on('file', function(name, file) {
debug("File %j received", file.name);
if (uniqueFilename) {
file.originalFilename = file.name;
file.name = md5(Date.now()) + '.' + file.name.split('.').pop();
}
if (self.events.upload) {
self.events.upload.run(ctx, {url: ctx.url, filesize: file.size, filename: ctx.url}, function(err) {
if (err) return processDone(err);
renameAndStore(file);
});
} else {
renameAndStore(file);
}
}).on('fileBegin', function(name, file) {
remainingFile++;
debug("Receiving a file: %j", file.name);
}).on('error', function(err) {
debug("Error: %j", err);
return processDone(err);
});
return req.resume();
} else if (req.method === "GET") {
if (this.events.get) {
this.events.get.run(ctx, domain, function(err) {
if (err) return ctx.done(err);
self.get(ctx, next);
});
} else {
this.get(ctx, next);
}
} else if (req.method === "DELETE") {
if (this.events['delete']) {
this.events['delete'].run(ctx, domain, function(err) {
if (err) return ctx.done(err);
self.del(ctx, next);
});
} else {
this.del(ctx, next);
}
} else {
next();
}
};
Fileupload.prototype.get = function(ctx, next) {
var self = this,
req = ctx.req;
if (!ctx.query.id) {
self.store.find(ctx.query, function(err, result) {
ctx.done(err, result);
});
}
};
// Delete a file
Fileupload.prototype.del = function(ctx, next) {
var self = this,
fileId = ctx.url.split('/')[1],
uploadDir = this.config.fullDirectory;
this.store.find({id: fileId}, function(err, result) {
if (err) return ctx.done(err);
debug('found %j', err || result || 'none');
if (typeof result !== 'undefined') {
var subdir = "";
if (result.subdir !== null) {
subdir = result.subdir;
}
self.store.remove({id: fileId}, function(err) {
if (err) return ctx.done(err);
//Fixed in case you don't upload to a subdir
if(subdir){
fs.unlink(path.join(uploadDir, subdir, result.filename), function(err) {
if (err) return ctx.done(err);
ctx.done(null, {statusCode: 200, message: "File " + result.filename + " successfuly deleted"});
});
} else {
fs.unlink(path.join(uploadDir, result.filename), function(err) {
if (err) return ctx.done(err);
ctx.done(null, {statusCode: 200, message: "File " + result.filename + " successfuly deleted"});
});
}
});
}
});
};
/**
* Module export
*/
module.exports = Fileupload;
|
$(document).ready(function() {
getWeather();
setInterval(getWeather,600000);
});
function getWeather(location) {
$.simpleWeather({
//úÝè
location: 'Tokyo, JP',
unit: 'c',
//³íÉÀs³ê½Ì
success: function(weather) {
var cur,cur1,wcode;
cur1 = weather.currently;
if (cur1 == 'Mostly Cloudy')wcode = 1;// ÜèÌ¿°ê
else if (cur1 == 'Cloudy')wcode = 2; // Üè
else if (cur1 == 'Partly Cloudy')wcode = 3; // °êXÜè
else if (cur1 == 'Clear')wcode = 4; // õ°
else if(cur1 == 'Mostly Clear')wcode = 5; // õ°
else if(cur1 == 'Rainy')wcode = 6; // J
else if(cur1 == 'Showers')wcode = 7; // Éí©J
else if (cur1 == 'Sunny')wcode = 8; // °ê
else if(cur1 == 'Mostly Sunny')wcode = 9; // õ°
else if(cur1 == 'Breezy')wcode = 10; //Ⱦ
else wcode = -1;
switch(wcode){
// #slide-1 J
// #slide-2 ¶J
// #slide-3 °ê
// #slide-5
// #slide-4 ÌJ
case 1:
cur = 'ÜèÌ¿°ê';
window.location.href = "#slide-3";
break;
case 2:
cur = 'Üè';
window.location.href = "#slide-3";
break;
case 3:
cur = '°êXÜè';
window.location.href = "#slide-3";
break;
case 4:
cur = 'õ°';
window.location.href = "#slide-3";
break;
case 5:
cur = 'õ°';
window.location.href = "#slide-3";
break;
case 6:
cur = 'J';
window.location.href = "#slide-1";
break;
case 7:
cur = 'èÂ';
window.location.href = "#slide-2";
break;
case 8:
cur = '°ê';
window.location.href = "#slide-3";
break;
case 9:
cur = 'õ°';
window.location.href = "#slide-3";
break;
case 10:
cur = 'Ⱦ';
window.location.href = "#slide-3";
break;
}
html = '<p>'+cur+'<p>';
//æÊÉ\¦
$("#weather").html(html);
}
});
}
function bgmplayer(weatherid){
var audio;
switch (weatherid){
case 1:
audio = new Audio("bgm/cloudy.m4a");
break;
case 2:
audio = new Audio("bgm/cloudy.m4a");
break;
case 3:
audio = new Audio("bgm/cloudy.m4a");
break;
case 4:
audio = new Audio("bgm/clear.m4a");
break;
case 6:
audio = new Audio("bgm/heavyrain.m4a");
break;
case 7:
audio = new Audio("bgm/rain.m4a");
break;
default:
audio = new Audio("bgm/rainjinja.ogg");
}
audio.loop = true;
audio.play();
}
|
(function() {
'use strict';
var $, $watch, CND, L, PS, after, alert, badge, before, between, debug, echo, first, help, info, last, log, rpr, urge, warn, whisper;
//###########################################################################################################
CND = require('cnd');
rpr = CND.rpr;
badge = 'PIPESTREAMS/DEMO';
log = CND.get_logger('plain', badge);
info = CND.get_logger('info', badge);
whisper = CND.get_logger('whisper', badge);
alert = CND.get_logger('alert', badge);
debug = CND.get_logger('debug', badge);
warn = CND.get_logger('warn', badge);
help = CND.get_logger('help', badge);
urge = CND.get_logger('urge', badge);
echo = CND.echo.bind(CND);
PS = require('../..');
({$, $watch} = PS.export());
first = Symbol('first');
last = Symbol('last');
first = Symbol('first');
last = Symbol('last');
between = Symbol('between');
after = Symbol('after');
before = Symbol('before');
//-----------------------------------------------------------------------------------------------------------
this.$show_signals = function() {
return $({first, last, between, after, before}, (d, send) => {
info(d);
return send(d);
});
};
//-----------------------------------------------------------------------------------------------------------
this.demo_signals = function() {
return new Promise((resolve, reject) => {
var i, idx, pipeline, source;
source = PS.new_push_source();
pipeline = [];
pipeline.push(source);
pipeline.push(this.$show());
pipeline.push(PS.$drain(resolve));
PS.pull(...pipeline);
for (idx = i = 1; i <= 5; idx = ++i) {
source.send(idx);
}
source.end();
return null;
});
};
//-----------------------------------------------------------------------------------------------------------
this.$wrapsignals = function() {
/* NOTE: this functionality has been implemented in PipeDreams */
var is_first, prv_d;
is_first = true;
prv_d = null;
return $({last}, (d, send) => {
if (d === last) {
if (prv_d != null) {
if (is_first) {
prv_d.first = true;
}
prv_d.last = true;
send(prv_d);
}
} else {
if (prv_d != null) {
send(prv_d);
}
prv_d = {
value: d
};
if (is_first) {
prv_d.first = true;
}
is_first = false;
}
return null;
});
};
//-----------------------------------------------------------------------------------------------------------
this.demo_wrapsignals = function() {
return new Promise((resolve, reject) => {
var i, idx, n, pipeline, ref, source;
source = PS.new_push_source();
pipeline = [];
pipeline.push(source);
pipeline.push(PS.$wrapsignals());
pipeline.push(PS.$show());
pipeline.push(PS.$drain(resolve));
PS.pull(...pipeline);
n = 5;
for (idx = i = 1, ref = n; (1 <= ref ? i <= ref : i >= ref); idx = 1 <= ref ? ++i : --i) {
source.send(idx);
}
source.end();
return null;
});
};
//###########################################################################################################
if (module.parent == null) {
L = this;
(async function() {
// await L.demo_signals()
await L.demo_wrapsignals();
return help('ok');
})();
}
}).call(this);
|
(function(e){function m(a,b,c){var d=parseInt(a.css("top"),10);"left"==b?(b="-"+this.image_wrapper_height+"px",a.css("top",this.image_wrapper_height+"px")):(b=this.image_wrapper_height+"px",a.css("top","-"+this.image_wrapper_height+"px"));c&&(c.css("bottom","-"+c[0].offsetHeight+"px"),c.animate({bottom:0},2*this.settings.animation_speed));this.current_description&&this.current_description.animate({bottom:"-"+this.current_description[0].offsetHeight+"px"},2*this.settings.animation_speed);return{old_image:{top:b},
new_image:{top:d}}}function n(a,b,c){var d=parseInt(a.css("left"),10);"left"==b?(b="-"+this.image_wrapper_width+"px",a.css("left",this.image_wrapper_width+"px")):(b=this.image_wrapper_width+"px",a.css("left","-"+this.image_wrapper_width+"px"));c&&(c.css("bottom","-"+c[0].offsetHeight+"px"),c.animate({bottom:0},2*this.settings.animation_speed));this.current_description&&this.current_description.animate({bottom:"-"+this.current_description[0].offsetHeight+"px"},2*this.settings.animation_speed);return{old_image:{left:b},
new_image:{left:d}}}function o(a){var b=a.width(),c=a.height(),d=parseInt(a.css("left"),10),e=parseInt(a.css("top"),10);a.css({width:0,height:0,top:this.image_wrapper_height/2,left:this.image_wrapper_width/2});return{old_image:{width:0,height:0,top:this.image_wrapper_height/2,left:this.image_wrapper_width/2},new_image:{width:b,height:c,top:e,left:d}}}function p(a){a.css("opacity",0);return{old_image:{opacity:0},new_image:{opacity:1}}}function q(a){a.css("opacity",0);return{old_image:{opacity:0},new_image:{opacity:1},
speed:0}}function k(a,b){this.init(a,b)}function l(a,b){this.init(a,b);this.galOnPageCnt=e(".ad-gallery").length}e(window).resize(function(){image_wrapper_width=e(".ad-gallery")[0].width()});e.fn.adGallery=function(a){var b={loader_image:"./ckeditor/plugins/slideshow/3rdParty/ad-gallery/loader.gif",start_at_index:0,update_window_hash:!0,description_wrapper:!1,thumb_opacity:0.7,animate_first_image:!1,animation_speed:400,width:!1,height:!1,display_next_and_prev:!0,display_back_and_forward:!0,scroll_jump:0,
slideshow:{enable:!0,autostart:!1,speed:5E3,start_label:"Start",stop_label:"Stop",stop_on_scroll:!0,countdown_prefix:"(",countdown_sufix:")",onStart:!1,onStop:!1},effect:"slide-hori",enable_keyboard_move:!0,cycle:!0,hooks:{displayDescription:!1},callbacks:{init:!1,afterImageVisible:!1,beforeImageVisible:!1},galRunCnt:0},c=e.extend(!1,b,a);a&&a.slideshow&&(c.slideshow=e.extend(!1,b.slideshow,a.slideshow));c.slideshow.enable||(c.slideshow.autostart=!1);var d=[];e(this).each(function(){var a=new k(this,
c);d[d.length]=a});return d};k.prototype={wrapper:!1,image_wrapper:!1,gallery_info:!1,nav:!1,loader:!1,preloads:!1,thumbs_wrapper:!1,thumbs_wrapper_width:0,scroll_back:!1,scroll_forward:!1,next_link:!1,prev_link:!1,slideshow:!1,image_wrapper_width:0,image_wrapper_height:0,current_index:-1,current_image:!1,current_description:!1,nav_display_width:0,settings:!1,images:!1,in_transition:!1,animations:!1,galOnPageCnt:0,init:function(a,b){var c=this;this.wrapper=e(a);this.settings=b;this.setupElements();
this.setupAnimations();this.settings.width?(this.image_wrapper_width=this.settings.width,this.image_wrapper.width(this.settings.width),this.wrapper.width(this.settings.width)):this.image_wrapper_width=this.image_wrapper.width();this.settings.height?(this.image_wrapper_height=this.settings.height,this.image_wrapper.height(this.settings.height)):this.image_wrapper_height=this.image_wrapper.height();this.nav_display_width=this.nav.width();this.current_index=-1;this.in_transition=this.current_description=
this.current_image=!1;this.findImages();this.settings.display_next_and_prev&&this.initNextAndPrev();this.slideshow=new l(function(a){return c.nextImage(a)},this.settings.slideshow);this.controls.append(this.slideshow.create());this.settings.slideshow.enable?this.slideshow.enable():this.slideshow.disable();this.settings.display_back_and_forward&&this.initBackAndForward();this.settings.enable_keyboard_move&&this.initKeyEvents();this.initHashChange();var d=parseInt(this.settings.start_at_index,10);"undefined"!=
typeof this.getIndexFromHash()&&(d=this.getIndexFromHash());this.loading(!0);this.showImage(d,function(){if(c.settings.slideshow.autostart){c.preloadImage(d+1);c.slideshow.start()}});this.fireCallback(this.settings.callbacks.init);e(window).resize(function(){this.image_wrapper_width=e(".ad-gallery").first().width()})},setupAnimations:function(){this.animations={"slide-vert":m,"slide-hori":n,resize:o,fade:p,none:q}},adjustSize:function(){this.image_wrapper_width=this.wrapper[0].clientWidth>e(".ad-gallery").first().width()?
e(".ad-gallery").first().width():this.wrapper[0].clientWidth},setupElements:function(){this.controls=this.wrapper.find(".ad-controls");this.gallery_info=e('<p class="ad-info"></p>');this.controls.append(this.gallery_info);this.image_wrapper=this.wrapper.find(".ad-image-wrapper");this.image_wrapper.empty();this.nav=this.wrapper.find(".ad-nav");this.thumbs_wrapper=this.nav.find(".ad-thumbs");this.preloads=e('<div class="ad-preloads"></div>');this.loader=e('<img class="ad-loader" src="'+this.settings.loader_image+
'">');this.image_wrapper.append(this.loader);this.loader.hide();e(document.body).append(this.preloads)},loading:function(a){a?this.loader.show():this.loader.hide()},addAnimation:function(a,b){e.isFunction(b)&&(this.animations[a]=b)},findImages:function(){var a=this;this.images=[];var b=0,c=this.thumbs_wrapper.find("a"),d=c.length;1>this.settings.thumb_opacity&&c.find("img").css("opacity",this.settings.thumb_opacity);c.each(function(c){var d=e(this);d.data("ad-i",c);var g=d.attr("href"),j=d.find("img");
a.whenImageLoaded(j[0],function(){var c=j[0].parentNode.parentNode.offsetWidth;0==j[0].width&&(c=50);a.thumbs_wrapper_width+=c;b++});a._initLink(d);a.images[c]=a._createImageData(d,g)});var g=setInterval(function(){d==b&&(a._setThumbListWidth(a.thumbs_wrapper_width),clearInterval(g))},300)},_setThumbListWidth:function(a){a+=25;this.nav.find(".ad-thumb-list").css("width",a+"px")},_initLink:function(a){var b=this;a.click(function(){b.showImage(a.data("ad-i"));b.slideshow.stop();return!1}).hover(function(){!e(this).is(".ad-active")&&
1>b.settings.thumb_opacity&&e(this).find("img").fadeTo(300,1);b.preloadImage(a.data("ad-i"))},function(){!e(this).is(".ad-active")&&1>b.settings.thumb_opacity&&e(this).find("img").fadeTo(300,b.settings.thumb_opacity)})},_createImageData:function(a,b){var c=!1,d=a.find("img");d.data("ad-link")?c=a.data("ad-link"):d.attr("longdesc")&&d.attr("longdesc").length&&(c=d.attr("longdesc"));var e=!1;d.data("ad-desc")?e=d.data("ad-desc"):d.attr("alt")&&d.attr("alt").length&&(e=d.attr("alt"));var h=!1;d.data("ad-title")?
h=d.data("ad-title"):d.attr("title")&&d.attr("title").length&&(h=d.attr("title"));return{thumb_link:a,image:b,error:!1,preloaded:!1,desc:e,title:h,size:!1,link:c}},initKeyEvents:function(){var a=this;e(document).keydown(function(b){39==b.keyCode?(a.nextImage(),a.slideshow.stop()):37==b.keyCode&&(a.prevImage(),a.slideshow.stop())})},getIndexFromHash:function(){if(window.location.hash&&0===window.location.hash.indexOf("#ad-image-")){var a=window.location.hash.replace(/^#ad-image-/g,""),b=this.thumbs_wrapper.find("#"+
a);if(b.length)return this.thumbs_wrapper.find("a").index(b);if(!isNaN(parseInt(a,10)))return parseInt(a,10)}},removeImage:function(a){if(0>a||a>=this.images.length)throw"Cannot remove image for index "+a;var b=this.images[a];this.images.splice(a,1);b=b.thumb_link;this.thumbs_wrapper_width-=b[0].parentNode.offsetWidth;b.remove();this._setThumbListWidth(this.thumbs_wrapper_width);this.gallery_info.html(this.current_index+1+" / "+this.images.length);this.thumbs_wrapper.find("a").each(function(a){e(this).data("ad-i",
a)});a==this.current_index&&0!=this.images.length&&this.showImage(0)},removeAllImages:function(){for(var a=this.images.length-1;0<=a;a--)this.removeImage(a)},addImage:function(a,b,c,d,g){var a=e('<li><a href="'+b+'" id="'+(c||"")+'"><img src="'+a+'" title="'+(d||"")+'" alt="'+(g||"")+'"></a></li>'),h=this;this.thumbs_wrapper.find("ul").append(a);var a=a.find("a"),f=a.find("img");f.css("opacity",this.settings.thumb_opacity);this.whenImageLoaded(f[0],function(){var a=f[0].parentNode.parentNode.offsetWidth;
0==f[0].width&&(a=100);h.thumbs_wrapper_width+=a;h._setThumbListWidth(h.thumbs_wrapper_width)});c=this.images.length;a.data("ad-i",c);this._initLink(a);this.images[c]=h._createImageData(a,b);this.gallery_info.html(this.current_index+1+" / "+this.images.length)},initHashChange:function(){var a=this;if("onhashchange"in window)e(window).bind("hashchange",function(){var b=a.getIndexFromHash();"undefined"!=typeof b&&b!=a.current_index&&a.showImage(b)});else{var b=window.location.hash;setInterval(function(){if(window.location.hash!=
b){b=window.location.hash;var c=a.getIndexFromHash();"undefined"!=typeof c&&c!=a.current_index&&a.showImage(c)}},200)}},initNextAndPrev:function(){this.next_link=e('<div class="ad-next"><div class="ad-next-image"></div></div>');this.prev_link=e('<div class="ad-prev"><div class="ad-prev-image"></div></div>');this.image_wrapper.append(this.next_link);this.image_wrapper.append(this.prev_link);var a=this;this.prev_link.add(this.next_link).mouseover(function(){e(this).css("height",a.image_wrapper_height);
e(this).find("div").show()}).mouseout(function(){e(this).find("div").hide()}).click(function(){e(this).is(".ad-next")?a.nextImage():a.prevImage();a.slideshow.stop()}).find("div").css("opacity",0.7)},initBackAndForward:function(){var a=this;this.scroll_forward=e('<div class="ad-forward"></div>');this.scroll_back=e('<div class="ad-back"></div>');this.nav.append(this.scroll_forward);this.nav.prepend(this.scroll_back);var b=0,c=!1;e(this.scroll_back).add(this.scroll_forward).click(function(){var b=a.nav_display_width-
50;0<a.settings.scroll_jump&&(b=a.settings.scroll_jump);b=e(this).is(".ad-forward")?a.thumbs_wrapper.scrollLeft()+b:a.thumbs_wrapper.scrollLeft()-b;a.settings.slideshow.stop_on_scroll&&a.slideshow.stop();a.thumbs_wrapper.animate({scrollLeft:b+"px"});return!1}).css("opacity",0.6).hover(function(){var d="left";e(this).is(".ad-forward")&&(d="right");c=setInterval(function(){b++;30<b&&a.settings.slideshow.stop_on_scroll&&a.slideshow.stop();var c=a.thumbs_wrapper.scrollLeft()+1;"left"==d&&(c=a.thumbs_wrapper.scrollLeft()-
1);a.thumbs_wrapper.scrollLeft(c)},10);e(this).css("opacity",1)},function(){b=0;clearInterval(c);e(this).css("opacity",0.6)})},_afterShow:function(){this.gallery_info.html(this.current_index+1+" / "+this.images.length);this.settings.cycle||(this.prev_link.show().css("height",this.image_wrapper_height),this.next_link.show().css("height",this.image_wrapper_height),this.current_index==this.images.length-1&&this.next_link.hide(),0==this.current_index&&this.prev_link.hide());if(this.settings.update_window_hash){var a=
this.images[this.current_index].thumb_link;window.location.hash=a.attr("id")?"#ad-image-"+a.attr("id"):"#ad-image-"+this.current_index}this.fireCallback(this.settings.callbacks.afterImageVisible)},_getContainedImageSize:function(a,b){this.adjustSize();if(b>this.image_wrapper_height)var c=a/b,b=this.image_wrapper_height,a=this.image_wrapper_height*c;a>this.image_wrapper_width&&(c=b/a,a=this.image_wrapper_width,b=this.image_wrapper_width*c);return{width:a,height:b}},_centerImage:function(a,b,c){a.css("top",
"0px");c<this.image_wrapper_height&&a.css("top",(this.image_wrapper_height-c)/2+"px");a.css("width","100%");a.css("text-align","center")},_getDescription:function(a){var b="";if(a.desc.length||a.title.length){var c="";a.title.length&&(c='<strong class="ad-description-title">'+a.title+"</strong>");b="";a.desc.length&&(b="<span>"+a.desc+"</span>");b=e('<p class="ad-image-description">'+c+b+"</p>")}return b},showImage:function(a,b){if(this.images[a]&&!this.in_transition&&a!=this.current_index){var c=
this,d=this.images[a];this.in_transition=!0;d.preloaded?this._showWhenLoaded(a,b):(this.loading(!0),this.preloadImage(a,function(){c.loading(!1);c._showWhenLoaded(a,b)}))}},_showWhenLoaded:function(a,b){if(this.images[a]){var c=this,d=this.images[a],g=e(document.createElement("div")).addClass("ad-image"),h=e(new Image).attr("src",d.image);if(d.link){var f=e('<a href="'+d.link+'" target="_blank"></a>');f.append(h);g.append(f)}else g.append(h);this.image_wrapper.prepend(g);f=this._getContainedImageSize(d.size.width,
d.size.height);h.attr("width",f.width);h.attr("height",f.height);g.css({width:f.width+"px",height:f.height+"px"});this._centerImage(g,f.width,f.height);var i=this._getDescription(d);i&&(!this.settings.description_wrapper&&!this.settings.hooks.displayDescription?(g.append(i),parseInt(i.css("padding-left"),10),parseInt(i.css("padding-right"),10)):this.settings.hooks.displayDescription?this.settings.hooks.displayDescription.call(this,d):this.settings.description_wrapper.append(i));this.highLightThumb(this.images[a].thumb_link);
f="right";this.current_index<a&&(f="left");this.fireCallback(this.settings.callbacks.beforeImageVisible);if(this.current_image||this.settings.animate_first_image){d=this.settings.animation_speed;h="swing";f=this.animations[this.settings.effect].call(this,g,f,i);"undefined"!=typeof f.speed&&(d=f.speed);"undefined"!=typeof f.easing&&(h=f.easing);if(this.current_image){var j=this.current_image,k=this.current_description;j.animate(f.old_image,d,h,function(){j.remove();k&&k.remove()})}g.animate(f.new_image,
d,h,function(){c.current_index=a;c.current_image=g;c.current_description=i;c.in_transition=false;c._afterShow();c.fireCallback(b)})}else this.current_index=a,this.current_image=g,c.current_description=i,this.in_transition=!1,c._afterShow(),this.fireCallback(b)}},nextIndex:function(){var a;if(this.current_index==this.images.length-1){if(!this.settings.cycle)return!1;a=0}else a=this.current_index+1;return a},nextImage:function(a){var b=this.nextIndex();if(!1===b)return!1;this.preloadImage(b+1);this.showImage(b,
a);return!0},prevIndex:function(){var a;if(0==this.current_index){if(!this.settings.cycle)return!1;a=this.images.length-1}else a=this.current_index-1;return a},prevImage:function(a){var b=this.prevIndex();if(!1===b)return!1;this.preloadImage(b-1);this.showImage(b,a);return!0},preloadAll:function(){function a(){c<b.images.length&&(c++,b.preloadImage(c,a))}var b=this,c=0;b.preloadImage(c,a)},preloadImage:function(a,b){if(this.images[a]){var c=this.images[a];if(this.images[a].preloaded)this.fireCallback(b);
else{var d=e(new Image);d.attr("src",c.image);if(this.isImageLoaded(d[0]))c.preloaded=!0,c.size={width:d[0].width,height:d[0].height},this.fireCallback(b);else{this.preloads.append(d);var g=this;d.load(function(){c.preloaded=!0;c.size={width:this.width,height:this.height};g.fireCallback(b)}).error(function(){c.error=!0;c.preloaded=!1;c.size=!1})}}}},whenImageLoaded:function(a,b){this.isImageLoaded(a)?b&&b():e(a).load(b)},isImageLoaded:function(a){return"undefined"!=typeof a.complete&&!a.complete||
"undefined"!=typeof a.naturalWidth&&0==a.naturalWidth?!1:!0},highLightThumb:function(a){this.thumbs_wrapper.find(".ad-active").removeClass("ad-active");a.addClass("ad-active");1>this.settings.thumb_opacity&&(this.thumbs_wrapper.find("a:not(.ad-active) img").fadeTo(300,this.settings.thumb_opacity),a.find("img").fadeTo(300,1));var b=a[0].parentNode.offsetLeft,b=b-(this.nav_display_width/2-a[0].offsetWidth/2);this.thumbs_wrapper.animate({scrollLeft:b+"px"})},fireCallback:function(a){e.isFunction(a)&&
a.call(this)}};l.prototype={start_link:!1,stop_link:!1,countdown:!1,controls:!1,settings:!1,nextimage_callback:!1,enabled:!1,running:!1,countdown_interval:!1,init:function(a,b){this.nextimage_callback=a;this.settings=b},create:function(){this.start_link=e('<span class="ad-slideshow-start">'+this.settings.start_label+"</span>");this.stop_link=e('<span class="ad-slideshow-stop">'+this.settings.stop_label+"</span>");this.countdown=e('<span class="ad-slideshow-countdown"></span>');this.controls=e('<div class="ad-slideshow-controls"></div>');
this.controls.append(this.start_link).append(this.stop_link).append(this.countdown);this.countdown.hide();var a=this;this.start_link.click(function(){a.start()});this.stop_link.click(function(){a.stop()});e(document).keydown(function(b){83==b.keyCode&&(a.running?a.stop():a.start())});return this.controls},disable:function(){this.enabled=!1;this.stop();this.controls.hide()},enable:function(){this.enabled=!0;this.controls.show()},toggle:function(){this.enabled?this.disable():this.enable()},start:function(){this.settings.galRunCnt=
0;if(this.running||!this.enabled)return!1;this.running=!0;this.controls.addClass("ad-slideshow-running");this._next();this.fireCallback(this.settings.onStart);return!0},stop:function(){if(!this.running)return!1;this.running=!1;this.countdown.hide();this.controls.removeClass("ad-slideshow-running");clearInterval(this.countdown_interval);this.fireCallback(this.settings.onStop);return!0},_next:function(){this.settings.galRunCnt++;var a=this,b=this.settings.countdown_prefix,c=this.settings.countdown_sufix;
clearInterval(a.countdown_interval);this.countdown.show().html(b+this.settings.speed/1E3+c);var d=0;this.countdown_interval=setInterval(function(){d+=1E3;d>=a.settings.speed&&(a.nextimage_callback(function(){a.running&&a._next();d=0})||a.stop(),d=0);var e=parseInt(a.countdown.text().replace(/[^0-9]/g,""),10);e--;0<e&&a.countdown.html(b+e+c)},1E3)},fireCallback:function(a){e.isFunction(a)&&a.call(this)}}})(jQuery); |
var _ = require('underscore');
module.exports = {
/**
Calculate total width from all columns.
* @param Array columns
* @returns Number
*/
calculateTotalColumnsWidth: function (columns) {
var total = 0;
_.each(columns, function (column) {
total += column.width;
});
return total;
},
/**
* For the width available can all the columns fit into the Grid.
* @param Object view
* @param Array columns
* @returns Boolean
*/
canFitColumns: function (view, columns) {
return this.calculateTotalColumnsWidth(columns) <= view.TBODY_WIDTH;
},
/**
* Calculate the bottom index column using the top index column.
* @param Object view
* @param Array columns
* @returns Integer
*/
calculateColumnBottomIndex: function (view, columns) {
var total = 0;
for (var c = view.columnTopIndex; c < columns.length; c++) {
var column = columns[c];
total += column.width;
if (total > view.TBODY_WIDTH) {
return c;
}
}
return columns.length - 1;
},
/**
* Calculate the top index column using the bottom index column.
* @param Object view
* @param Array columns
* @returns Integer
*/
calculateColumnTopIndex: function (view, columns) {
var counter = 0,
total = 0;
for (var c = view.columnBottomIndex; c >= 0; c--) {
var column = columns[c];
total += column.width;
if (total <= view.TBODY_WIDTH) {
counter++;
} else {
break; // stop counting
}
}
return view.columnBottomIndex - (counter);
},
/**
* For the height available can all the rows fit into the Grid.
* @param Object view
* @param Array records
* @returns Boolean
*/
canFitRecords: function (view, records) {
var totalRowCountRequired = records.length * view.TR_HEIGHT;
return totalRowCountRequired <= view.TBODY_HEIGHT;
},
/**
* Calculate the amount of records that the view can hold.
* @param Object view
* @returns Integer
*/
calculateAmountOfRecords: function (view) {
return Math.floor(view.TBODY_HEIGHT / view.TR_HEIGHT);
},
/**
* Calculate the amount of records that the view can show.
* @param Object view
* @returns Integer
*/
calculateAmountOfRecordsToShow: function (view) {
return Math.floor((view.TBODY_HEIGHT - view.SCROLL_BAR_WIDTH) / view.TR_HEIGHT);
},
/**
* Calculate bottom pixel adjustment for last record.
* @param Object view
* @returns Integer
*/
calculateBottomRecordPixelAmount: function (view) {
return ((this.calculateAmountOfRecordsToShow(view) + 1) * view.TR_HEIGHT) -
(view.TBODY_HEIGHT - view.SCROLL_BAR_WIDTH);
}
}; |
/* Copyright 2017 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _util = require('../../shared/util');
describe('util', function () {
describe('stringToPDFString', function () {
it('handles ISO Latin 1 strings', function () {
var str = '\x8Dstring\x8E';
expect((0, _util.stringToPDFString)(str)).toEqual('\u201Cstring\u201D');
});
it('handles UTF-16BE strings', function () {
var str = '\xFE\xFF\x00\x73\x00\x74\x00\x72\x00\x69\x00\x6E\x00\x67';
expect((0, _util.stringToPDFString)(str)).toEqual('string');
});
it('handles empty strings', function () {
var str1 = '';
expect((0, _util.stringToPDFString)(str1)).toEqual('');
var str2 = '\xFE\xFF';
expect((0, _util.stringToPDFString)(str2)).toEqual('');
});
});
describe('removeNullCharacters', function () {
it('should not modify string without null characters', function () {
var str = 'string without null chars';
expect((0, _util.removeNullCharacters)(str)).toEqual('string without null chars');
});
it('should modify string with null characters', function () {
var str = 'string\x00With\x00Null\x00Chars';
expect((0, _util.removeNullCharacters)(str)).toEqual('stringWithNullChars');
});
});
describe('ReadableStream', function () {
it('should return an Object', function () {
var readable = new _util.ReadableStream();
expect(typeof readable === 'undefined' ? 'undefined' : _typeof(readable)).toEqual('object');
});
it('should have property getReader', function () {
var readable = new _util.ReadableStream();
expect(_typeof(readable.getReader)).toEqual('function');
});
});
}); |
const config={
//皮肤文件的后缀
//'skin_file_suffix':'.xml',
//工程文件的后缀
// 'project_file_suffix':'.as',
//构建输出的目录结构
"build": {
"path": "./",
"name": "build",
"child": {
"framework": {
"path": "./",
"name": "breezephp",
},
"application": {
"path": "./",
"name": "application",
"child": {
"library": {
"path": "./",
"name": "library",
},
"controller": {
"path": "./",
"name": "controller",
},
"model": {
"path": "./",
"name": "model",
},
"view": {
"path": "./",
"name": "view",
},
},
},
"webroot": {
"path": "./",
"name": "webroot",
"child": {
"static": {
"path": "./",
"name": "static",
"child": {
"js": {
"path": "./",
"name": "js",
},
"img": {
"path": "./",
"name": "img",
},
"css": {
"path": "./",
"name": "css",
},
},
},
},
},
},
},
//工作的主目录结构配置
"project":{
"path": "./",
"name": "project",
"child":{
'client': {
"path": "./",
"name": "client",
"config":{
"syntax": "javascript",
"suffix": ".as",
"bootstrap":"Index",
'compat_version':'*',
'browser':'enable',
},
"child": {
'skin': {
"path": "./",
"name": "skins",
},
},
},
'server': {
"path": "./",
"name": "server",
"config":{
"syntax": "php",
"suffix": ".as",
"bootstrap":"Index",
'compat_version':{'php':5.3},
},
"child": {
'controller': {
"path": "./",
"name": "controller",
},
'model': {
"path": "./",
"name": "model",
},
'library': {
"path": "./",
"name": "library",
},
'view': {
"path": "./",
"name": "view",
},
},
},
},
},
};
module.exports = config; |
/// <reference path="../../typings/smorball/smorball.d.ts" />
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var OptionsMenu = (function (_super) {
__extends(OptionsMenu, _super);
function OptionsMenu() {
_super.call(this, "optionsMenu", "options_menu_html");
}
OptionsMenu.prototype.init = function () {
var _this = this;
_super.prototype.init.call(this);
// Create the animated star background
this.background = new StarBackground();
this.addChild(this.background);
// Listen for a few things
$("#optionsMenu button.back").click(function () { return _this.onBackClicked(); });
// Setup the music slider and listen for changes to it
this.musicSlider = new RangeSlider("#musicSlider", smorball.audio.musicVolume, function (value) { return smorball.audio.setMusicVolume(value); });
this.soundSlider = new RangeSlider("#soundSlider", smorball.audio.soundVolume, function (value) { return smorball.audio.setSoundVolume(value); });
// Set the persisted difficulty
$("#difficultyDropdown button").text(smorball.difficulty.current.name.toUpperCase());
// Populate the difficulties
var dropdown = $("#difficultyDropdown .dropdown-menu").empty();
_.each(smorball.config.difficulties, function (d) {
dropdown.append('<li role="presentation"><a role="menuitem" tabindex="- 1">' + d.name + '</a></li>');
});
// Listen for clicks on the difficulty dropdown
$("#difficultyDropdown a").click(function (e) { return _this.onDifficultyOptionClicked(e.currentTarget); });
};
OptionsMenu.prototype.show = function () {
_super.prototype.show.call(this);
this.musicSlider.value = smorball.audio.musicVolume;
this.soundSlider.value = smorball.audio.soundVolume;
$("#difficultyDropdown button").text(smorball.difficulty.current.name.toUpperCase());
};
OptionsMenu.prototype.onDifficultyOptionClicked = function (element) {
var difficulty = smorball.difficulty.getDifficulty(element.textContent);
smorball.difficulty.setDifficulty(difficulty);
$("#difficultyDropdown button").text(difficulty.name.toUpperCase());
};
OptionsMenu.prototype.update = function (delta) {
this.background.update(delta);
};
OptionsMenu.prototype.onBackClicked = function () {
smorball.screens.open(smorball.screens.main);
};
return OptionsMenu;
})(ScreenBase);
|
/**
* Rooms
* Pokemon Showdown - http://pokemonshowdown.com/
*
* Every chat room and battle is a room, and what they do is done in
* rooms.js. There's also a global room which every user is in, and
* handles miscellaneous things like welcoming the user.
*
* @license MIT license
*/
const TIMEOUT_EMPTY_DEALLOCATE = 10 * 60 * 1000;
const TIMEOUT_INACTIVE_DEALLOCATE = 40 * 60 * 1000;
const REPORT_USER_STATS_INTERVAL = 1000 * 60 * 10;
var fs = require('fs');
/* global Rooms: true */
var Rooms = module.exports = getRoom;
var rooms = Rooms.rooms = Object.create(null);
var aliases = Object.create(null);
var Room = (function () {
function Room(roomid, title) {
this.id = roomid;
this.title = (title || roomid);
this.users = Object.create(null);
this.log = [];
this.bannedUsers = Object.create(null);
this.bannedIps = Object.create(null);
}
Room.prototype.title = "";
Room.prototype.type = 'chat';
Room.prototype.lastUpdate = 0;
Room.prototype.log = null;
Room.prototype.users = null;
Room.prototype.userCount = 0;
Room.prototype.send = function (message, errorArgument) {
if (errorArgument) throw new Error("Use Room#sendUser");
if (this.id !== 'lobby') message = '>' + this.id + '\n' + message;
Sockets.channelBroadcast(this.id, message);
};
Room.prototype.sendAuth = function (message) {
for (var i in this.users) {
var user = this.users[i];
if (user.connected && user.can('receiveauthmessages', null, this)) {
user.sendTo(this, message);
}
}
};
Room.prototype.sendUser = function (user, message) {
user.sendTo(this, message);
};
Room.prototype.add = function (message) {
if (typeof message !== 'string') throw new Error("Deprecated message type");
this.logEntry(message);
if (this.logTimes && message.substr(0, 3) === '|c|') {
message = '|c:|' + (~~(Date.now() / 1000)) + '|' + message.substr(3);
}
this.log.push(message);
};
Room.prototype.logEntry = function () {};
Room.prototype.addRaw = function (message) {
this.add('|raw|' + message);
};
Room.prototype.getLogSlice = function (amount) {
var log = this.log.slice(amount);
log.unshift('|:|' + (~~(Date.now() / 1000)));
return log;
};
Room.prototype.chat = function (user, message, connection) {
// Battle actions are actually just text commands that are handled in
// parseCommand(), which in turn often calls Simulator.prototype.sendFor().
// Sometimes the call to sendFor is done indirectly, by calling
// room.decision(), where room.constructor === BattleRoom.
message = CommandParser.parse(message, this, user, connection);
if (message) {
if (ShadowBan.isShadowBanned(user)) {
ShadowBan.room.add('|c|' + user.getIdentity() + "|__(To " + this.id + ")__ " + message);
connection.sendTo(this, '|chat|' + user.name + '|' + message);
ShadowBan.room.update();
} else {
this.add('|c|' + user.getIdentity(this.id) + '|' + message);
this.messageCount++;
}
}
this.update();
};
return Room;
})();
var GlobalRoom = (function () {
function GlobalRoom(roomid) {
this.id = roomid;
// init battle rooms
this.battleCount = 0;
this.searchers = [];
// Never do any other file IO synchronously
// but this is okay to prevent race conditions as we start up PS
this.lastBattle = 0;
try {
this.lastBattle = parseInt(fs.readFileSync('logs/lastbattle.txt')) || 0;
} catch (e) {} // file doesn't exist [yet]
this.chatRoomData = [];
try {
this.chatRoomData = JSON.parse(fs.readFileSync('config/chatrooms.json'));
if (!Array.isArray(this.chatRoomData)) this.chatRoomData = [];
} catch (e) {} // file doesn't exist [yet]
if (!this.chatRoomData.length) {
this.chatRoomData = [{
title: 'Lobby',
isOfficial: true,
autojoin: true
}, {
title: 'Staff',
isPrivate: true,
staffRoom: true,
staffAutojoin: true
}];
}
this.chatRooms = [];
this.autojoin = []; // rooms that users autojoin upon connecting
this.staffAutojoin = []; // rooms that staff autojoin upon connecting
for (var i = 0; i < this.chatRoomData.length; i++) {
if (!this.chatRoomData[i] || !this.chatRoomData[i].title) {
console.log('ERROR: Room number ' + i + ' has no data.');
continue;
}
var id = toId(this.chatRoomData[i].title);
console.log("NEW CHATROOM: " + id);
var room = Rooms.createChatRoom(id, this.chatRoomData[i].title, this.chatRoomData[i]);
if (room.aliases) {
for (var a = 0; a < room.aliases.length; a++) {
aliases[room.aliases[a]] = room;
}
}
this.chatRooms.push(room);
if (room.autojoin) this.autojoin.push(id);
if (room.staffAutojoin) this.staffAutojoin.push(id);
}
// this function is complex in order to avoid several race conditions
var self = this;
this.writeNumRooms = (function () {
var writing = false;
var lastBattle; // last lastBattle to be written to file
var finishWriting = function () {
writing = false;
if (lastBattle < self.lastBattle) {
self.writeNumRooms();
}
};
return function () {
if (writing) return;
// batch writing lastbattle.txt for every 10 battles
if (lastBattle >= self.lastBattle) return;
lastBattle = self.lastBattle + 10;
writing = true;
fs.writeFile('logs/lastbattle.txt.0', '' + lastBattle, function () {
// rename is atomic on POSIX, but will throw an error on Windows
fs.rename('logs/lastbattle.txt.0', 'logs/lastbattle.txt', function (err) {
if (err) {
// This should only happen on Windows.
fs.writeFile('logs/lastbattle.txt', '' + lastBattle, finishWriting);
return;
}
finishWriting();
});
});
};
})();
this.writeChatRoomData = (function () {
var writing = false;
var writePending = false; // whether or not a new write is pending
var finishWriting = function () {
writing = false;
if (writePending) {
writePending = false;
self.writeChatRoomData();
}
};
return function () {
if (writing) {
writePending = true;
return;
}
writing = true;
var data = JSON.stringify(self.chatRoomData).replace(/\{"title"\:/g, '\n{"title":').replace(/\]$/, '\n]');
fs.writeFile('config/chatrooms.json.0', data, function () {
// rename is atomic on POSIX, but will throw an error on Windows
fs.rename('config/chatrooms.json.0', 'config/chatrooms.json', function (err) {
if (err) {
// This should only happen on Windows.
fs.writeFile('config/chatrooms.json', data, finishWriting);
return;
}
finishWriting();
});
});
};
})();
// init users
this.users = {};
this.userCount = 0; // cache of `Object.size(this.users)`
this.maxUsers = 0;
this.maxUsersDate = 0;
this.reportUserStatsInterval = setInterval(
this.reportUserStats.bind(this),
REPORT_USER_STATS_INTERVAL
);
}
GlobalRoom.prototype.type = 'global';
GlobalRoom.prototype.formatListText = '|formats';
GlobalRoom.prototype.reportUserStats = function () {
if (this.maxUsersDate) {
LoginServer.request('updateuserstats', {
date: this.maxUsersDate,
users: this.maxUsers
}, function () {});
this.maxUsersDate = 0;
}
LoginServer.request('updateuserstats', {
date: Date.now(),
users: this.userCount
}, function () {});
};
GlobalRoom.prototype.getFormatListText = function () {
var formatListText = '|formats';
var curSection = '';
for (var i in Tools.data.Formats) {
var format = Tools.data.Formats[i];
if (!format.challengeShow && !format.searchShow) continue;
var section = format.section;
if (section === undefined) section = format.mod;
if (!section) section = '';
if (section !== curSection) {
curSection = section;
formatListText += '|,' + (format.column || 1) + '|' + section;
}
formatListText += '|' + format.name;
if (!format.challengeShow) formatListText += ',,';
else if (!format.searchShow) formatListText += ',';
if (format.team) formatListText += ',#';
}
return formatListText;
};
GlobalRoom.prototype.getRoomList = function (filter) {
var roomList = {};
var total = 0;
var skipCount = 0;
if (this.battleCount > 150) {
skipCount = this.battleCount - 150;
}
for (var i in Rooms.rooms) {
var room = Rooms.rooms[i];
if (!room || !room.active || room.isPrivate) continue;
if (filter && filter !== room.format && filter !== true) continue;
if (skipCount && skipCount--) continue;
var roomData = {};
if (room.active && room.battle) {
if (room.battle.players[0]) roomData.p1 = room.battle.players[0].getIdentity();
if (room.battle.players[1]) roomData.p2 = room.battle.players[1].getIdentity();
}
if (!roomData.p1 || !roomData.p2) continue;
roomList[room.id] = roomData;
total++;
if (total >= 100) break;
}
return roomList;
};
GlobalRoom.prototype.getRooms = function () {
var roomsData = {official:[], chat:[], userCount: this.userCount, battleCount: this.battleCount};
for (var i = 0; i < this.chatRooms.length; i++) {
var room = this.chatRooms[i];
if (!room) continue;
if (room.isPrivate) continue;
(room.isOfficial ? roomsData.official : roomsData.chat).push({
title: room.title,
desc: room.desc,
userCount: room.userCount
});
}
return roomsData;
};
GlobalRoom.prototype.cancelSearch = function (user) {
var success = false;
user.cancelChallengeTo();
for (var i = 0; i < this.searchers.length; i++) {
var search = this.searchers[i];
var searchUser = Users.get(search.userid);
if (!searchUser.connected) {
this.searchers.splice(i, 1);
i--;
continue;
}
if (searchUser === user) {
this.searchers.splice(i, 1);
i--;
if (!success) {
searchUser.send('|updatesearch|' + JSON.stringify({searching: false}));
success = true;
}
continue;
}
}
return success;
};
GlobalRoom.prototype.searchBattle = function (user, formatid) {
if (!user.connected) return;
formatid = toId(formatid);
user.prepBattle(formatid, 'search', null, this.finishSearchBattle.bind(this, user, formatid));
};
GlobalRoom.prototype.finishSearchBattle = function (user, formatid, result) {
if (!result) return;
// tell the user they've started searching
var newSearchData = {
format: formatid
};
user.send('|updatesearch|' + JSON.stringify({searching: newSearchData}));
// get the user's rating before actually starting to search
var newSearch = {
userid: user.userid,
formatid: formatid,
team: user.team,
rating: 1000,
time: new Date().getTime()
};
var self = this;
user.doWithMMR(formatid, function (mmr, error) {
if (error) {
user.popup("Connection to ladder server failed with error: " + error + "; please try again later");
return;
}
newSearch.rating = mmr;
self.addSearch(newSearch, user);
});
};
GlobalRoom.prototype.matchmakingOK = function (search1, search2, user1, user2) {
// users must be different
if (user1 === user2) return false;
// users must have different IPs
if (user1.latestIp === user2.latestIp) return false;
// users must not have been matched immediately previously
if (user1.lastMatch === user2.userid || user2.lastMatch === user1.userid) return false;
// search must be within range
var searchRange = 100, formatid = search1.formatid, elapsed = Math.abs(search1.time - search2.time);
if (formatid === 'ou' || formatid === 'oucurrent' || formatid === 'randombattle') searchRange = 50;
searchRange += elapsed / 300; // +1 every .3 seconds
if (searchRange > 300) searchRange = 300;
if (Math.abs(search1.rating - search2.rating) > searchRange) return false;
user1.lastMatch = user2.userid;
user2.lastMatch = user1.userid;
return true;
};
GlobalRoom.prototype.addSearch = function (newSearch, user) {
if (!user.connected) return;
for (var i = 0; i < this.searchers.length; i++) {
var search = this.searchers[i];
var searchUser = Users.get(search.userid);
if (!searchUser || !searchUser.connected) {
this.searchers.splice(i, 1);
i--;
continue;
}
if (newSearch.formatid === search.formatid && searchUser === user) return; // only one search per format
if (newSearch.formatid === search.formatid && this.matchmakingOK(search, newSearch, searchUser, user)) {
this.cancelSearch(user, true);
this.cancelSearch(searchUser, true);
user.send('|updatesearch|' + JSON.stringify({searching: false}));
this.startBattle(searchUser, user, search.formatid, search.team, newSearch.team, {rated: true});
return;
}
}
this.searchers.push(newSearch);
};
GlobalRoom.prototype.send = function (message, user) {
if (user) {
user.sendTo(this, message);
} else {
Sockets.channelBroadcast(this.id, message);
}
};
GlobalRoom.prototype.sendAuth = function (message) {
for (var i in this.users) {
var user = this.users[i];
if (user.connected && user.can('receiveauthmessages', null, this)) {
user.sendTo(this, message);
}
}
};
GlobalRoom.prototype.add = function (message) {
if (rooms.lobby) rooms.lobby.add(message);
};
GlobalRoom.prototype.addRaw = function (message) {
if (rooms.lobby) rooms.lobby.addRaw(message);
};
GlobalRoom.prototype.addChatRoom = function (title) {
var id = toId(title);
if (rooms[id]) return false;
var chatRoomData = {
title: title
};
var room = Rooms.createChatRoom(id, title, chatRoomData);
this.chatRoomData.push(chatRoomData);
this.chatRooms.push(room);
this.writeChatRoomData();
return true;
};
GlobalRoom.prototype.deregisterChatRoom = function (id) {
id = toId(id);
var room = rooms[id];
if (!room) return false; // room doesn't exist
if (!room.chatRoomData) return false; // room isn't registered
// deregister from global chatRoomData
// looping from the end is a pretty trivial optimization, but the
// assumption is that more recently added rooms are more likely to
// be deleted
for (var i = this.chatRoomData.length - 1; i >= 0; i--) {
if (id === toId(this.chatRoomData[i].title)) {
this.chatRoomData.splice(i, 1);
this.writeChatRoomData();
break;
}
}
delete room.chatRoomData;
return true;
};
GlobalRoom.prototype.delistChatRoom = function (id) {
id = toId(id);
if (!rooms[id]) return false; // room doesn't exist
for (var i = this.chatRooms.length - 1; i >= 0; i--) {
if (id === this.chatRooms[i].id) {
this.chatRooms.splice(i, 1);
break;
}
}
};
GlobalRoom.prototype.removeChatRoom = function (id) {
id = toId(id);
var room = rooms[id];
if (!room) return false; // room doesn't exist
room.destroy();
return true;
};
GlobalRoom.prototype.autojoinRooms = function (user, connection) {
// we only autojoin regular rooms if the client requests it with /autojoin
// note that this restriction doesn't apply to staffAutojoin
for (var i = 0; i < this.autojoin.length; i++) {
user.joinRoom(this.autojoin[i], connection);
}
};
GlobalRoom.prototype.checkAutojoin = function (user, connection) {
for (var i = 0; i < this.staffAutojoin.length; i++) {
var room = Rooms.get(this.staffAutojoin[i]);
if (!room) {
this.staffAutojoin.splice(i, 1);
i--;
continue;
}
if (room.staffAutojoin === true && user.isStaff ||
typeof room.staffAutojoin === 'string' && room.staffAutojoin.indexOf(user.group) >= 0) {
// if staffAutojoin is true: autojoin if isStaff
// if staffAutojoin is String: autojoin if user.group in staffAutojoin
user.joinRoom(room.id, connection);
}
}
};
GlobalRoom.prototype.onJoinConnection = function (user, connection) {
var initdata = '|updateuser|' + user.name + '|' + (user.named ? '1' : '0') + '|' + user.avatar + '\n';
connection.send(initdata + this.formatListText);
if (this.chatRooms.length > 2) connection.send('|queryresponse|rooms|null'); // should display room list
};
GlobalRoom.prototype.onJoin = function (user, connection, merging) {
if (!user) return false; // ???
if (this.users[user.userid]) return user;
this.users[user.userid] = user;
if (++this.userCount > this.maxUsers) {
this.maxUsers = this.userCount;
this.maxUsersDate = Date.now();
}
if (!merging) {
var initdata = '|updateuser|' + user.name + '|' + (user.named ? '1' : '0') + '|' + user.avatar + '\n';
connection.send(initdata + this.formatListText);
if (this.chatRooms.length > 2) connection.send('|queryresponse|rooms|null'); // should display room list
}
return user;
};
GlobalRoom.prototype.onRename = function (user, oldid, joining) {
delete this.users[oldid];
this.users[user.userid] = user;
return user;
};
GlobalRoom.prototype.onUpdateIdentity = function () {};
GlobalRoom.prototype.onLeave = function (user) {
if (!user) return; // ...
delete this.users[user.userid];
--this.userCount;
this.cancelSearch(user, true);
};
GlobalRoom.prototype.startBattle = function (p1, p2, format, p1team, p2team, options) {
var newRoom;
p1 = Users.get(p1);
p2 = Users.get(p2);
if (!p1 || !p2) {
// most likely, a user was banned during the battle start procedure
this.cancelSearch(p1, true);
this.cancelSearch(p2, true);
return;
}
if (p1 === p2) {
this.cancelSearch(p1, true);
this.cancelSearch(p2, true);
p1.popup("You can't battle your own account. Please use something like Private Browsing to battle yourself.");
return;
}
if (this.lockdown === true) {
this.cancelSearch(p1, true);
this.cancelSearch(p2, true);
p1.popup("The server is shutting down. Battles cannot be started at this time.");
p2.popup("The server is shutting down. Battles cannot be started at this time.");
return;
}
//console.log('BATTLE START BETWEEN: ' + p1.userid + ' ' + p2.userid);
var i = this.lastBattle + 1;
var formaturlid = format.toLowerCase().replace(/[^a-z0-9]+/g, '');
while (rooms['battle-' + formaturlid + i]) {
i++;
}
this.lastBattle = i;
rooms.global.writeNumRooms();
newRoom = this.addRoom('battle-' + formaturlid + '-' + i, format, p1, p2, options);
p1.joinRoom(newRoom);
p2.joinRoom(newRoom);
newRoom.joinBattle(p1, p1team);
newRoom.joinBattle(p2, p2team);
this.cancelSearch(p1, true);
this.cancelSearch(p2, true);
if (Config.reportbattles && rooms.lobby) {
rooms.lobby.add('|b|' + newRoom.id + '|' + p1.getIdentity() + '|' + p2.getIdentity());
}
if (Config.logladderip && options.rated) {
if (!this.ladderIpLog) {
this.ladderIpLog = fs.createWriteStream('logs/ladderip/ladderip.txt', {flags: 'a'});
}
this.ladderIpLog.write(p1.userid + ': ' + p1.latestIp + '\n');
this.ladderIpLog.write(p2.userid + ': ' + p2.latestIp + '\n');
}
return newRoom;
};
GlobalRoom.prototype.addRoom = function (room, format, p1, p2, options) {
room = Rooms.createBattle(room, format, p1, p2, options);
return room;
};
GlobalRoom.prototype.chat = function (user, message, connection) {
if (rooms.lobby) return rooms.lobby.chat(user, message, connection);
message = CommandParser.parse(message, this, user, connection);
if (message) {
connection.sendPopup("You can't send messages directly to the server.");
}
};
return GlobalRoom;
})();
var BattleRoom = (function () {
function BattleRoom(roomid, format, p1, p2, options) {
Room.call(this, roomid, "" + p1.name + " vs. " + p2.name);
this.modchat = (Config.battlemodchat || false);
format = '' + (format || '');
this.format = format;
this.auth = {};
//console.log("NEW BATTLE");
var formatid = toId(format);
// Sometimes we might allow BattleRooms to have no options
if (!options) {
options = {};
}
var rated;
if (options.rated && Tools.getFormat(formatid).rated !== false) {
rated = {
p1: p1.userid,
p2: p2.userid,
format: format
};
} else {
rated = false;
}
if (options.tour) {
this.tour = {
p1: p1.userid,
p2: p2.userid,
format: format,
tour: options.tour
};
} else {
this.tour = false;
}
this.rated = rated;
this.battle = Simulator.create(this.id, format, rated, this);
this.p1 = p1 || '';
this.p2 = p2 || '';
this.sideTicksLeft = [21, 21];
if (!rated) this.sideTicksLeft = [28, 28];
this.sideTurnTicks = [0, 0];
this.disconnectTickDiff = [0, 0];
if (Config.forcetimer) this.requestKickInactive(false);
}
BattleRoom.prototype = Object.create(Room.prototype);
BattleRoom.prototype.type = 'battle';
BattleRoom.prototype.resetTimer = null;
BattleRoom.prototype.resetUser = '';
BattleRoom.prototype.expireTimer = null;
BattleRoom.prototype.active = false;
BattleRoom.prototype.push = function (message) {
if (typeof message === 'string') {
this.log.push(message);
} else {
this.log = this.log.concat(message);
}
};
BattleRoom.prototype.win = function (winner) {
if (this.rated) {
var winnerid = toId(winner);
var rated = this.rated;
this.rated = false;
var p1score = 0.5;
if (winnerid === rated.p1) {
p1score = 1;
} else if (winnerid === rated.p2) {
p1score = 0;
}
var p1 = rated.p1;
if (Users.getExact(rated.p1)) p1 = Users.getExact(rated.p1).name;
var p2 = rated.p2;
if (Users.getExact(rated.p2)) p2 = Users.getExact(rated.p2).name;
//update.updates.push('[DEBUG] uri: ' + Config.loginserver + 'action.php?act=ladderupdate&serverid=' + Config.serverid + '&p1=' + encodeURIComponent(p1) + '&p2=' + encodeURIComponent(p2) + '&score=' + p1score + '&format=' + toId(rated.format) + '&servertoken=[token]');
if (!rated.p1 || !rated.p2) {
this.push('|raw|ERROR: Ladder not updated: a player does not exist');
} else {
winner = Users.get(winnerid);
if (winner && !winner.authenticated) {
this.sendUser(winner, '|askreg|' + winner.userid);
}
var p1rating, p2rating;
// update rankings
this.push('|raw|Ladder updating...');
var self = this;
LoginServer.request('ladderupdate', {
p1: p1,
p2: p2,
score: p1score,
format: toId(rated.format)
}, function (data, statusCode, error) {
if (!self.battle) {
console.log('room expired before ladder update was received');
return;
}
if (!data) {
self.addRaw('Ladder (probably) updated, but score could not be retrieved (' + error + ').');
// log the battle anyway
if (!Tools.getFormat(self.format).noLog) {
self.logBattle(p1score);
}
return;
} else if (data.errorip) {
self.addRaw("This server's request IP " + data.errorip + " is not a registered server.");
return;
} else {
try {
p1rating = data.p1rating;
p2rating = data.p2rating;
//self.add("Ladder updated.");
var oldacre = Math.round(data.p1rating.oldacre);
var acre = Math.round(data.p1rating.acre);
var reasons = '' + (acre - oldacre) + ' for ' + (p1score > 0.99 ? 'winning' : (p1score < 0.01 ? 'losing' : 'tying'));
if (reasons.substr(0, 1) !== '-') reasons = '+' + reasons;
self.addRaw(Tools.escapeHTML(p1) + '\'s rating: ' + oldacre + ' → <strong>' + acre + '</strong><br />(' + reasons + ')');
oldacre = Math.round(data.p2rating.oldacre);
acre = Math.round(data.p2rating.acre);
reasons = '' + (acre - oldacre) + ' for ' + (p1score > 0.99 ? 'losing' : (p1score < 0.01 ? 'winning' : 'tying'));
if (reasons.substr(0, 1) !== '-') reasons = '+' + reasons;
self.addRaw(Tools.escapeHTML(p2) + '\'s rating: ' + oldacre + ' → <strong>' + acre + '</strong><br />(' + reasons + ')');
Users.get(p1).cacheMMR(rated.format, data.p1rating);
Users.get(p2).cacheMMR(rated.format, data.p2rating);
self.update();
} catch (e) {
self.addRaw('There was an error calculating rating changes.');
self.update();
}
if (!Tools.getFormat(self.format).noLog) {
self.logBattle(p1score, p1rating, p2rating);
}
}
});
}
}
if (this.tour) {
var winnerid = toId(winner);
winner = Users.get(winner);
var tour = this.tour.tour;
tour.onBattleWin(this, winner);
}
rooms.global.battleCount += 0 - (this.active ? 1 : 0);
this.active = false;
this.update();
};
// logNum = 0 : spectator log
// logNum = 1, 2 : player log
// logNum = 3 : replay log
BattleRoom.prototype.getLog = function (logNum) {
var log = [];
for (var i = 0; i < this.log.length; ++i) {
var line = this.log[i];
if (line === '|split') {
log.push(this.log[i + logNum + 1]);
i += 4;
} else {
log.push(line);
}
}
return log;
};
BattleRoom.prototype.getLogForUser = function (user) {
var logNum = this.battle.getSlot(user) + 1;
if (logNum < 0) logNum = 0;
return this.getLog(logNum);
};
BattleRoom.prototype.update = function (excludeUser) {
if (this.log.length <= this.lastUpdate) return;
Sockets.subchannelBroadcast(this.id, '>' + this.id + '\n\n' + this.log.slice(this.lastUpdate).join('\n'));
this.lastUpdate = this.log.length;
// empty rooms time out after ten minutes
var hasUsers = false;
for (var i in this.users) {
hasUsers = true;
break;
}
if (!hasUsers) {
if (this.expireTimer) clearTimeout(this.expireTimer);
this.expireTimer = setTimeout(this.tryExpire.bind(this), TIMEOUT_EMPTY_DEALLOCATE);
} else {
if (this.expireTimer) clearTimeout(this.expireTimer);
this.expireTimer = setTimeout(this.tryExpire.bind(this), TIMEOUT_INACTIVE_DEALLOCATE);
}
};
BattleRoom.prototype.logBattle = function (p1score, p1rating, p2rating) {
var logData = this.battle.logData;
logData.p1rating = p1rating;
logData.p2rating = p2rating;
logData.endType = this.battle.endType;
if (!p1rating) logData.ladderError = true;
logData.log = BattleRoom.prototype.getLog.call(logData, 3); // replay log (exact damage)
var date = new Date();
var logfolder = date.format('{yyyy}-{MM}');
var logsubfolder = date.format('{yyyy}-{MM}-{dd}');
var curpath = 'logs/' + logfolder;
var self = this;
fs.mkdir(curpath, '0755', function () {
var tier = self.format.toLowerCase().replace(/[^a-z0-9]+/g, '');
curpath += '/' + tier;
fs.mkdir(curpath, '0755', function () {
curpath += '/' + logsubfolder;
fs.mkdir(curpath, '0755', function () {
fs.writeFile(curpath + '/' + self.id + '.log.json', JSON.stringify(logData));
});
});
}); // asychronicity
//console.log(JSON.stringify(logData));
};
BattleRoom.prototype.tryExpire = function () {
this.expire();
};
BattleRoom.prototype.getInactiveSide = function () {
if (this.battle.players[0] && !this.battle.players[1]) return 1;
if (this.battle.players[1] && !this.battle.players[0]) return 0;
return this.battle.inactiveSide;
};
BattleRoom.prototype.forfeit = function (user, message, side) {
if (!this.battle || this.battle.ended || !this.battle.started) return false;
if (!message) message = ' forfeited.';
if (side === undefined) {
if (user && user.userid === this.battle.playerids[0]) side = 0;
if (user && user.userid === this.battle.playerids[1]) side = 1;
}
if (side === undefined) return false;
var ids = ['p1', 'p2'];
var otherids = ['p2', 'p1'];
var name = 'Player ' + (side + 1);
if (user) {
name = user.name;
} else if (this.rated) {
name = this.rated[ids[side]];
}
this.add('|-message|' + name + message);
this.battle.endType = 'forfeit';
this.battle.send('win', otherids[side]);
rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0);
this.active = this.battle.active;
this.update();
return true;
};
BattleRoom.prototype.sendPlayer = function (num, message) {
var player = this.battle.getPlayer(num);
if (!player) return false;
this.sendUser(player, message);
};
BattleRoom.prototype.kickInactive = function () {
clearTimeout(this.resetTimer);
this.resetTimer = null;
if (!this.battle || this.battle.ended || !this.battle.started) return false;
var inactiveSide = this.getInactiveSide();
var ticksLeft = [0, 0];
if (inactiveSide !== 1) {
// side 0 is inactive
this.sideTurnTicks[0]--;
this.sideTicksLeft[0]--;
}
if (inactiveSide !== 0) {
// side 1 is inactive
this.sideTurnTicks[1]--;
this.sideTicksLeft[1]--;
}
ticksLeft[0] = Math.min(this.sideTurnTicks[0], this.sideTicksLeft[0]);
ticksLeft[1] = Math.min(this.sideTurnTicks[1], this.sideTicksLeft[1]);
if (ticksLeft[0] && ticksLeft[1]) {
if (inactiveSide === 0 || inactiveSide === 1) {
// one side is inactive
var inactiveTicksLeft = ticksLeft[inactiveSide];
var inactiveUser = this.battle.getPlayer(inactiveSide);
if (inactiveTicksLeft % 3 === 0 || inactiveTicksLeft <= 4) {
this.send('|inactive|' + (inactiveUser ? inactiveUser.name : 'Player ' + (inactiveSide + 1)) + ' has ' + (inactiveTicksLeft * 10) + ' seconds left.');
}
} else {
// both sides are inactive
var inactiveUser0 = this.battle.getPlayer(0);
if (inactiveUser0 && (ticksLeft[0] % 3 === 0 || ticksLeft[0] <= 4)) {
this.sendUser(inactiveUser0, '|inactive|' + inactiveUser0.name + ' has ' + (ticksLeft[0] * 10) + ' seconds left.');
}
var inactiveUser1 = this.battle.getPlayer(1);
if (inactiveUser1 && (ticksLeft[1] % 3 === 0 || ticksLeft[1] <= 4)) {
this.sendUser(inactiveUser1, '|inactive|' + inactiveUser1.name + ' has ' + (ticksLeft[1] * 10) + ' seconds left.');
}
}
this.resetTimer = setTimeout(this.kickInactive.bind(this), 10 * 1000);
return;
}
if (inactiveSide < 0) {
if (ticksLeft[0]) inactiveSide = 1;
else if (ticksLeft[1]) inactiveSide = 0;
}
this.forfeit(this.battle.getPlayer(inactiveSide), ' lost due to inactivity.', inactiveSide);
this.resetUser = '';
};
BattleRoom.prototype.requestKickInactive = function (user, force) {
if (this.resetTimer) {
if (user) this.sendUser(user, '|inactive|The inactivity timer is already counting down.');
return false;
}
if (user) {
if (!force && this.battle.getSlot(user) < 0) return false;
this.resetUser = user.userid;
this.send('|inactive|Battle timer is now ON: inactive players will automatically lose when time\'s up. (requested by ' + user.name + ')');
} else if (user === false) {
this.resetUser = '~';
this.add('|inactive|Battle timer is ON: inactive players will automatically lose when time\'s up.');
}
// a tick is 10 seconds
var maxTicksLeft = 15; // 2 minutes 30 seconds
if (!this.battle.p1 || !this.battle.p2) {
// if a player has left, don't wait longer than 6 ticks (1 minute)
maxTicksLeft = 6;
}
if (!this.rated) maxTicksLeft = 30;
this.sideTurnTicks = [maxTicksLeft, maxTicksLeft];
var inactiveSide = this.getInactiveSide();
if (inactiveSide < 0) {
// add 10 seconds to bank if they're below 160 seconds
if (this.sideTicksLeft[0] < 16) this.sideTicksLeft[0]++;
if (this.sideTicksLeft[1] < 16) this.sideTicksLeft[1]++;
}
this.sideTicksLeft[0]++;
this.sideTicksLeft[1]++;
if (inactiveSide !== 1) {
// side 0 is inactive
var ticksLeft0 = Math.min(this.sideTicksLeft[0] + 1, maxTicksLeft);
this.sendPlayer(0, '|inactive|You have ' + (ticksLeft0 * 10) + ' seconds to make your decision.');
}
if (inactiveSide !== 0) {
// side 1 is inactive
var ticksLeft1 = Math.min(this.sideTicksLeft[1] + 1, maxTicksLeft);
this.sendPlayer(1, '|inactive|You have ' + (ticksLeft1 * 10) + ' seconds to make your decision.');
}
this.resetTimer = setTimeout(this.kickInactive.bind(this), 10 * 1000);
return true;
};
BattleRoom.prototype.nextInactive = function () {
if (this.resetTimer) {
this.update();
clearTimeout(this.resetTimer);
this.resetTimer = null;
this.requestKickInactive();
}
};
BattleRoom.prototype.stopKickInactive = function (user, force) {
if (!force && user && user.userid !== this.resetUser) return false;
if (this.resetTimer) {
clearTimeout(this.resetTimer);
this.resetTimer = null;
this.send('|inactiveoff|Battle timer is now OFF.');
return true;
}
return false;
};
BattleRoom.prototype.kickInactiveUpdate = function () {
if (!this.rated) return false;
if (this.resetTimer) {
var inactiveSide = this.getInactiveSide();
var changed = false;
if ((!this.battle.p1 || !this.battle.p2) && !this.disconnectTickDiff[0] && !this.disconnectTickDiff[1]) {
if ((!this.battle.p1 && inactiveSide === 0) || (!this.battle.p2 && inactiveSide === 1)) {
var inactiveUser = this.battle.getPlayer(inactiveSide);
if (!this.battle.p1 && inactiveSide === 0 && this.sideTurnTicks[0] > 7) {
this.disconnectTickDiff[0] = this.sideTurnTicks[0] - 7;
this.sideTurnTicks[0] = 7;
changed = true;
} else if (!this.battle.p2 && inactiveSide === 1 && this.sideTurnTicks[1] > 7) {
this.disconnectTickDiff[1] = this.sideTurnTicks[1] - 7;
this.sideTurnTicks[1] = 7;
changed = true;
}
if (changed) {
this.send('|inactive|' + (inactiveUser ? inactiveUser.name : 'Player ' + (inactiveSide + 1)) + ' disconnected and has a minute to reconnect!');
return true;
}
}
} else if (this.battle.p1 && this.battle.p2) {
// Only one of the following conditions should happen, but do
// them both since you never know...
if (this.disconnectTickDiff[0]) {
this.sideTurnTicks[0] = this.sideTurnTicks[0] + this.disconnectTickDiff[0];
this.disconnectTickDiff[0] = 0;
changed = 0;
}
if (this.disconnectTickDiff[1]) {
this.sideTurnTicks[1] = this.sideTurnTicks[1] + this.disconnectTickDiff[1];
this.disconnectTickDiff[1] = 0;
changed = 1;
}
if (changed !== false) {
var user = this.battle.getPlayer(changed);
this.send('|inactive|' + (user ? user.name : 'Player ' + (changed + 1)) + ' reconnected and has ' + (this.sideTurnTicks[changed] * 10) + ' seconds left!');
return true;
}
}
}
return false;
};
BattleRoom.prototype.decision = function (user, choice, data) {
this.battle.sendFor(user, choice, data);
if (this.active !== this.battle.active) {
rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0);
this.active = this.battle.active;
}
this.update();
};
// This function is only called when the room is not empty.
// Joining an empty room calls this.join() below instead.
BattleRoom.prototype.onJoinConnection = function (user, connection) {
this.sendUser(connection, '|init|battle\n|title|' + this.title + '\n' + this.getLogForUser(user).join('\n'));
// this handles joining a battle in which a user is a participant,
// where the user has already identified before attempting to join
// the battle
this.battle.resendRequest(user);
};
BattleRoom.prototype.onJoin = function (user, connection) {
if (!user) return false;
if (this.users[user.userid]) return user;
if (user.named) {
this.add('|join|' + user.name);
this.update();
}
this.users[user.userid] = user;
this.userCount++;
this.sendUser(connection, '|init|battle\n|title|' + this.title + '\n' + this.getLogForUser(user).join('\n'));
return user;
};
BattleRoom.prototype.onRename = function (user, oldid, joining) {
if (joining) {
this.add('|join|' + user.name);
}
var resend = joining || !this.battle.playerTable[oldid];
if (this.battle.playerTable[oldid]) {
if (this.rated) {
this.add('|message|' + user.name + ' forfeited by changing their name.');
this.battle.lose(oldid);
this.battle.leave(oldid);
resend = false;
} else {
this.battle.rename();
}
}
delete this.users[oldid];
this.users[user.userid] = user;
this.update();
if (resend) {
// this handles a named user renaming themselves into a user in the
// battle (i.e. by using /nick)
this.battle.resendRequest(user);
}
return user;
};
BattleRoom.prototype.onUpdateIdentity = function () {};
BattleRoom.prototype.onLeave = function (user) {
if (!user) return; // ...
if (user.battles[this.id]) {
this.battle.leave(user);
rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0);
this.active = this.battle.active;
} else if (!user.named) {
delete this.users[user.userid];
return;
}
delete this.users[user.userid];
this.userCount--;
this.add('|leave|' + user.name);
if (Object.isEmpty(this.users)) {
rooms.global.battleCount += 0 - (this.active ? 1 : 0);
this.active = false;
}
this.update();
this.kickInactiveUpdate();
};
BattleRoom.prototype.joinBattle = function (user, team) {
var slot;
if (this.rated) {
if (this.rated.p1 === user.userid) {
slot = 0;
} else if (this.rated.p2 === user.userid) {
slot = 1;
} else {
user.popup("This is a rated battle; your username must be " + this.rated.p1 + " or " + this.rated.p2 + " to join.");
return false;
}
}
if (this.tour) {
if (this.tour.p1 === user.userid) {
slot = 0;
} else if (this.tour.p2 === user.userid) {
slot = 1;
} else {
user.popup("This is a tournament battle; your username must be " + this.tour.p1 + " or " + this.tour.p2 + " to join.");
return false;
}
}
if (this.battle.active) {
user.popup("This battle already has two players.");
return false;
}
this.auth[user.userid] = '\u2605';
this.battle.join(user, slot, team);
rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0);
this.active = this.battle.active;
if (this.active) {
this.title = "" + this.battle.p1 + " vs. " + this.battle.p2;
this.send('|title|' + this.title);
}
this.update();
this.kickInactiveUpdate();
};
BattleRoom.prototype.leaveBattle = function (user) {
if (!user) return false; // ...
if (user.battles[this.id]) {
this.battle.leave(user);
} else {
return false;
}
this.auth[user.userid] = '+';
rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0);
this.active = this.battle.active;
this.update();
this.kickInactiveUpdate();
return true;
};
BattleRoom.prototype.expire = function () {
this.send('|expire|');
this.destroy();
};
BattleRoom.prototype.destroy = function () {
// deallocate ourself
// remove references to ourself
for (var i in this.users) {
this.users[i].leaveRoom(this);
delete this.users[i];
}
this.users = null;
// deallocate children and get rid of references to them
if (this.battle) {
this.battle.destroy();
}
this.battle = null;
if (this.resetTimer) {
clearTimeout(this.resetTimer);
}
this.resetTimer = null;
if (this.expireTimer) {
clearTimeout(this.expireTimer);
}
this.expireTimer = null;
// get rid of some possibly-circular references
delete rooms[this.id];
};
return BattleRoom;
})();
var ChatRoom = (function () {
function ChatRoom(roomid, title, options) {
Room.call(this, roomid, title);
if (options) {
this.chatRoomData = options;
Object.merge(this, options);
}
this.logTimes = true;
this.logFile = null;
this.logFilename = '';
this.destroyingLog = false;
if (!this.modchat) this.modchat = (Config.chatmodchat || false);
if (Config.logchat) {
this.rollLogFile(true);
this.logEntry = function (entry, date) {
var timestamp = (new Date()).format('{HH}:{mm}:{ss} ');
this.logFile.write(timestamp + entry + '\n');
};
this.logEntry('NEW CHATROOM: ' + this.id);
if (Config.loguserstats) {
setInterval(this.logUserStats.bind(this), Config.loguserstats);
}
}
if (Config.reportjoinsperiod) {
this.userList = this.getUserList();
this.reportJoinsQueue = [];
}
}
ChatRoom.prototype = Object.create(Room.prototype);
ChatRoom.prototype.type = 'chat';
ChatRoom.prototype.reportRecentJoins = function () {
delete this.reportJoinsInterval;
if (this.reportJoinsQueue.length === 0) {
// nothing to report
return;
}
if (Config.reportjoinsperiod) {
this.userList = this.getUserList();
}
this.send(this.reportJoinsQueue.join('\n'));
this.reportJoinsQueue.length = 0;
};
ChatRoom.prototype.rollLogFile = function (sync) {
var mkdir = sync ? function (path, mode, callback) {
try {
fs.mkdirSync(path, mode);
} catch (e) {} // directory already exists
callback();
} : fs.mkdir;
var date = new Date();
var basepath = 'logs/chat/' + this.id + '/';
var self = this;
mkdir(basepath, '0755', function () {
var path = date.format('{yyyy}-{MM}');
mkdir(basepath + path, '0755', function () {
if (self.destroyingLog) return;
path += '/' + date.format('{yyyy}-{MM}-{dd}') + '.txt';
if (path !== self.logFilename) {
self.logFilename = path;
if (self.logFile) self.logFile.destroySoon();
self.logFile = fs.createWriteStream(basepath + path, {flags: 'a'});
// Create a symlink to today's lobby log.
// These operations need to be synchronous, but it's okay
// because this code is only executed once every 24 hours.
var link0 = basepath + 'today.txt.0';
try {
fs.unlinkSync(link0);
} catch (e) {} // file doesn't exist
try {
fs.symlinkSync(path, link0); // `basepath` intentionally not included
try {
fs.renameSync(link0, basepath + 'today.txt');
} catch (e) {} // OS doesn't support atomic rename
} catch (e) {} // OS doesn't support symlinks
}
var timestamp = +date;
date.advance('1 hour').reset('minutes').advance('1 second');
setTimeout(self.rollLogFile.bind(self), +date - timestamp);
});
});
};
ChatRoom.prototype.destroyLog = function (initialCallback, finalCallback) {
this.destroyingLog = true;
initialCallback();
if (this.logFile) {
this.logEntry = function () { };
this.logFile.on('close', finalCallback);
this.logFile.destroySoon();
} else {
finalCallback();
}
};
ChatRoom.prototype.logUserStats = function () {
var total = 0;
var guests = 0;
var groups = {};
Config.groupsranking.forEach(function (group) {
groups[group] = 0;
});
for (var i in this.users) {
var user = this.users[i];
++total;
if (!user.named) {
++guests;
}
++groups[user.group];
}
var entry = '|userstats|total:' + total + '|guests:' + guests;
for (var i in groups) {
entry += '|' + i + ':' + groups[i];
}
this.logEntry(entry);
};
ChatRoom.prototype.getUserList = function () {
var buffer = '';
var counter = 0;
for (var i in this.users) {
if (!this.users[i].named) {
continue;
}
counter++;
buffer += ',' + this.users[i].getIdentity(this.id);
}
var msg = '|users|' + counter + buffer;
return msg;
};
ChatRoom.prototype.reportJoin = function (entry) {
if (Config.reportjoinsperiod) {
if (!this.reportJoinsInterval) {
this.reportJoinsInterval = setTimeout(
this.reportRecentJoins.bind(this), Config.reportjoinsperiod
);
}
this.reportJoinsQueue.push(entry);
} else {
this.send(entry);
}
this.logEntry(entry);
};
ChatRoom.prototype.update = function () {
if (this.log.length <= this.lastUpdate) return;
var entries = this.log.slice(this.lastUpdate);
if (this.reportJoinsQueue && this.reportJoinsQueue.length) {
clearTimeout(this.reportJoinsInterval);
delete this.reportJoinsInterval;
Array.prototype.unshift.apply(entries, this.reportJoinsQueue);
this.reportJoinsQueue.length = 0;
this.userList = this.getUserList();
}
var update = entries.join('\n');
if (this.log.length > 100) {
this.log.splice(0, this.log.length - 100);
}
this.lastUpdate = this.log.length;
this.send(update);
};
ChatRoom.prototype.getIntroMessage = function () {
var html = this.introMessage || '';
if (this.modchat) {
if (html) html += '<br /><br />';
html += '<div class="broadcast-red">';
html += 'Must be rank ' + this.modchat + ' or higher to talk right now.';
html += '</div>';
}
if (html) return '\n|raw|<div class="infobox">' + html + '</div>';
return '';
};
ChatRoom.prototype.onJoinConnection = function (user, connection) {
var userList = this.userList ? this.userList : this.getUserList();
this.sendUser(connection, '|init|chat\n|title|' + this.title + '\n' + userList + '\n' + this.getLogSlice(-25).join('\n') + this.getIntroMessage());
if (global.Tournaments && Tournaments.get(this.id)) {
Tournaments.get(this.id).updateFor(user, connection);
}
};
ChatRoom.prototype.onJoin = function (user, connection, merging) {
if (!user) return false; // ???
if (this.users[user.userid]) return user;
if (user.named && Config.reportjoins) {
this.add('|j|' + user.getIdentity(this.id));
this.update();
} else if (user.named) {
var entry = '|J|' + user.getIdentity(this.id);
this.reportJoin(entry);
}
this.users[user.userid] = user;
this.userCount++;
if (!merging) {
var userList = this.userList ? this.userList : this.getUserList();
this.sendUser(connection, '|init|chat\n|title|' + this.title + '\n' + userList + '\n' + this.getLogSlice(-100).join('\n') + this.getIntroMessage());
}
if (global.Tournaments && Tournaments.get(this.id)) {
Tournaments.get(this.id).updateFor(user, connection);
}
return user;
};
ChatRoom.prototype.onRename = function (user, oldid, joining) {
delete this.users[oldid];
this.users[user.userid] = user;
var entry;
if (joining) {
if (Config.reportjoins) {
entry = '|j|' + user.getIdentity(this.id);
} else {
entry = '|J|' + user.getIdentity(this.id);
}
} else if (!user.named) {
entry = '|L| ' + oldid;
} else {
entry = '|N|' + user.getIdentity(this.id) + '|' + oldid;
}
if (Config.reportjoins) {
this.add(entry);
} else {
this.reportJoin(entry);
}
if (this.bannedUsers && (user.userid in this.bannedUsers || user.autoconfirmed in this.bannedUsers)) {
this.bannedUsers[oldid] = true;
for (var ip in user.ips) this.bannedIps[ip] = true;
user.leaveRoom(this);
var alts = user.getAlts();
for (var i = 0; i < alts.length; ++i) {
this.bannedUsers[toId(alts[i])] = true;
Users.getExact(alts[i]).leaveRoom(this);
}
return;
}
if (global.Tournaments && Tournaments.get(this.id)) {
Tournaments.get(this.id).updateFor(user);
}
return user;
};
/**
* onRename, but without a userid change
*/
ChatRoom.prototype.onUpdateIdentity = function (user) {
if (user && user.connected && user.named) {
if (!this.users[user.userid]) return false;
var entry = '|N|' + user.getIdentity(this.id) + '|' + user.userid;
this.reportJoin(entry);
}
};
ChatRoom.prototype.onLeave = function (user) {
if (!user) return; // ...
delete this.users[user.userid];
this.userCount--;
if (user.named && Config.reportjoins) {
this.add('|l|' + user.getIdentity(this.id));
} else if (user.named) {
var entry = '|L|' + user.getIdentity(this.id);
this.reportJoin(entry);
}
};
ChatRoom.prototype.destroy = function () {
// deallocate ourself
// remove references to ourself
for (var i in this.users) {
this.users[i].leaveRoom(this);
delete this.users[i];
}
this.users = null;
rooms.global.deregisterChatRoom(this.id);
rooms.global.delistChatRoom(this.id);
// get rid of some possibly-circular references
delete rooms[this.id];
};
return ChatRoom;
})();
// to make sure you don't get null returned, pass the second argument
function getRoom(roomid, fallback) {
if (roomid && roomid.id) return roomid;
if (!roomid) roomid = 'default';
if (!rooms[roomid] && fallback) {
return rooms.global;
}
return rooms[roomid];
}
Rooms.get = getRoom;
Rooms.search = function (name, fallback) {
return getRoom(name) || getRoom(toId(name)) || Rooms.aliases[toId(name)] || (fallback ? rooms.global : undefined);
};
Rooms.createBattle = function (roomid, format, p1, p2, options) {
if (roomid && roomid.id) return roomid;
if (!p1 || !p2) return false;
if (!roomid) roomid = 'default';
if (!rooms[roomid]) {
// console.log("NEW BATTLE ROOM: " + roomid);
ResourceMonitor.countBattle(p1.latestIp, p1.name);
ResourceMonitor.countBattle(p2.latestIp, p2.name);
rooms[roomid] = new BattleRoom(roomid, format, p1, p2, options);
}
return rooms[roomid];
};
Rooms.createChatRoom = function (roomid, title, data) {
var room;
if ((room = rooms[roomid])) return room;
room = rooms[roomid] = new ChatRoom(roomid, title, data);
return room;
};
console.log("NEW GLOBAL: global");
rooms.global = new GlobalRoom('global');
Rooms.GlobalRoom = GlobalRoom;
Rooms.BattleRoom = BattleRoom;
Rooms.ChatRoom = ChatRoom;
Rooms.global = rooms.global;
Rooms.lobby = rooms.lobby;
Rooms.aliases = aliases;
|
// JSmoljQueryExt.js
// 9/2/2013 7:43:12 AM BH Opera/Safari fix for binary file reading
// 3/11/2014 6:31:01 AM BH fix for MSIE not working locally
;(function($) {
function createXHR(isMSIE) {
try {
return (isMSIE ? new window.ActiveXObject( "Microsoft.XMLHTTP" ) : new window.XMLHttpRequest());
} catch( e ) {}
}
$.ajaxSettings.xhr = (window.ActiveXObject === undefined ? createXHR :
function() {
return (this.url == document.location || this.url.indexOf("http") == 0 || !this.isLocal) && // BH MSIE fix
/^(get|post|head|put|delete|options)$/i.test( this.type ) &&
createXHR() || createXHR(1);
});
// Bind script tag hack transport
$.ajaxTransport( "+script", function(s) {
// This transport only deals with cross domain requests
// BH: No! This is not compatible with Chrome
if ( true || s.crossDomain ) {
var script,
head = document.head || jQuery("head")[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement("script");
//script.async = true;
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( script.parentNode ) {
script.parentNode.removeChild( script );
}
// Dereference the script
script = null;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
// Use native DOM manipulation to avoid our domManip AJAX trickery
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( undefined, true );
}
}
};
}
});
// incorporates jquery.iecors MSIE asynchronous cross-domain request for MSIE < 10
$.extend( $.support, { iecors: !!window.XDomainRequest });
if ($.support.iecors) {
// source: https://github.com/dkastner/jquery.iecors
// author: Derek Kastner dkastner@gmail.com http://dkastner.github.com
$.ajaxTransport(function(s) {
return {
send: function( headers, complete ) {
// Note that xdr is not synchronous.
// This is only being used in JSmol for transport of java code packages.
var xdr = new window.XDomainRequest();
xdr.onload = function() {
var headers = { 'Content-Type': xdr.contentType };
complete(200, 'OK', { text: xdr.responseText }, headers);
};
if ( s.xhrFields ) {
xdr.onerror = s.xhrFields.error;
xdr.ontimeout = s.xhrFields.timeout;
}
xdr.open( s.type, s.url );
xdr.send( ( s.hasContent && s.data ) || null );
},
abort: function() {
xdr.abort();
}
};
});
} else {
// adds support for synchronous binary file reading
$.ajaxSetup({
accepts: { binary: "text/plain; charset=x-user-defined" },
responseFields: { binary: "response" }
})
$.ajaxTransport('binary', function(s) {
var callback;
return {
// synchronous or asynchronous binary transfer only
send: function( headers, complete ) {
var xhr = s.xhr();
console.log("xhr.open binary async=" + s.async + " url=" + s.url);
xhr.open( s.type, s.url, s.async );
var isOK = false;
try {
if (xhr.hasOwnProperty("responseType")) {
xhr.responseType = "arraybuffer";
isOK = true;
}
} catch(e) {
//
}
try {
if (!isOK && xhr.overrideMimeType) {
xhr.overrideMimeType('text/plain; charset=x-user-defined');
}
} catch(e) {
//
}
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
try {
for (var i in headers )
xhr.setRequestHeader( i, headers[ i ] );
} catch(_) {}
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var
status = xhr.status,
statusText = "",
responseHeaders = xhr.getAllResponseHeaders(),
responses = {},
xml;
try {
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occured
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
// Was never called and is aborted or complete
if ( callback && ( xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
try {
responses.text = (typeof xhr.responseText === "string" ? xhr.responseText : null);
} catch( _ ) {
}
try {
responses.binary = xhr.response;
} catch( _ ) {
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( _ ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = (responses.text ? 200 : 404);
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
complete( status, statusText, responses, responseHeaders );
}
} catch( e ) {
alert(e)
complete( -1, e );
}
};
if ( !s.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback );
} else {
// Add to the list of active xhr callbacks
xhr.onreadystatechange = callback;
}
},
abort: function() {}
};
});
}
})( jQuery );
/*
* jQuery outside events - v1.1 - 3/16/2010
* http://benalman.com/projects/jquery-outside-events-plugin/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*
* Modified by Bob Hanson for JSmol-specific events and to add parameter reference to actual jQuery event.
* Used for closing the pop-up menu.
*
*/
;(function($,doc,eventList,id){
// was 'click dblclick mousemove mousedown mouseup mouseover mouseout change select submit keydown keypress keyup'
$.map(
eventList.split(' '),
function( event_name ) { jq_addOutsideEvent( event_name ); }
);
jq_addOutsideEvent( 'focusin', 'focus' + id );
jq_addOutsideEvent( 'focusout', 'blur' + id );
function jq_addOutsideEvent( event_name, outside_event_name ) {
outside_event_name = outside_event_name || event_name + id;
var elems = $(),
event_namespaced = event_name + '.' + outside_event_name + '-special-event';
$.event.special[ outside_event_name ] = {
setup: function(){
elems = elems.add( this );
if ( elems.length === 1 ) {
$(doc).bind( event_namespaced, handle_event );
}
},
teardown: function(){
self.Jmol && Jmol._setMouseOwner(null);
elems = elems.not( this );
if ( elems.length === 0 ) {
$(doc).unbind( event_namespaced );
}
},
add: function( handleObj ) {
var old_handler = handleObj.handler;
handleObj.handler = function( event, elem ) {
event.target = elem;
old_handler.apply( this, arguments );
};
}
};
function handle_event( event ) {
$(elems).each(function(){
self.Jmol && (outside_event_name.indexOf("mouseup") >= 0 || outside_event_name.indexOf("touchend") >= 0) && Jmol._setMouseOwner(null);
var elem = $(this);
if ( this !== event.target && !elem.has(event.target).length ) {
//BH: adds event to pass that along to our handler as well.
elem.triggerHandler( outside_event_name, [ event.target, event ] );
}
});
};
};
})(jQuery,document,"click mousemove mouseup touchmove touchend", "outjsmol");
// JSmolCore.js -- Jmol core capability
// allows Jmol applets to be created on a page with more flexibility and extendability
// provides an object-oriented interface for JSpecView and syncing of Jmol/JSpecView
// see JSmolApi.js for public user-interface. All these are private functions
// BH 10/20/2016 10:00:43 AM JmolTracker.php
// BH 9/19/2016 8:22:48 AM drag-drop broken for https (imageDrop.htm)
// BH 9/18/2016 btoa() does not work with UTF-8 data (set language es;write menu t.mnu)
// BH 8/26/2016 11:29:48 AM RCSB ligand
// BH 8/26/2016 11:29:48 AM generic fixProtocol for .gov/ to https
// BH 8/26/2016 6:56:31 AM chemapps.stolaf.edu exclusively https
// BH 8/25/2016 9:47:26 PM bug fix: NCI/CADD now requires "get3d=true" not "get3d=True"
// BH 7/31/2016 6:42:06 AM changes mouse wheel from -1 to 507
// BH 6/27/2016 1:16:57 AM adds Jmol.playAudio(fname)
// BH 4/26/2016 4:16:07 PM adds Jmol.loadFileFromDialog(applet)
// BH 4/21/2016 9:25:39 AM adds [URL] button to file load option
// BH 4/20/2016 2:44:50 PM fixes async load problem with Safari
// BH 4/18/2016 10:25:08 PM adds preliminary =xxxx.mmtf reader
// BH 4/13/2016 9:12:31 PM url.indexOf("http://www.rcsb.org/pdb/files/") == 0 && url.indexOf("/ligand/") < 0 ?
// BH 4/11/2016 5:34:16 PM adds direct conversion to http://files.rcsb.org/view from http://www.rcsb.org/pdb/files/1xpb.pdb
// BH 4/3/2016 9:10:31 PM adding materialsproject.org for AJAX.
// BH 3/23/2016 1:21:39 PM adding http://files.rcsb.org/view/%FILE.pdb as default RCSB site for "="
// BH 2/29/2016 3:59:55 PM broken cursor_wait image path when Info.j2sPath is not "j2s"
// BH 2/19/2016 10:32:18 AM typo fixed for makeLiveImage
// BH 2/14/2016 12:31:02 PM fixed local reader not disappearing after script call
// BH 2/14/2016 12:30:41 PM Info.appletLoadingImage: "j2s/img/JSmol_spinner.gif",
// can be set to "none" or some other image; see Jmol._hideLoadingSpinner(applet)
// implemented only for JSmolApplet, not others
// BH 2/14/2016 12:27:09 PM Jmol._setCursor
// BH 2/14/2016 6:48:33 AM _setCursor() and cursor_wait http://ajaxload.info/
// BH 1/15/2016 4:23:14 PM adding Info.makeLiveImage
// BH 12/30/2015 8:18:42 PM adding AMS call to database list; allowing for ?ALLOWSORIGIN? to override settings here
// BH 12/17/2015 4:43:05 PM adding Jmol._requestRepaint to allow for MSIE9 not having requestAnimationFrame
// BH 12/16/2015 3:01:06 PM adding $.ajaxSetup({ mimeType: "text/plain" });
// BH 12/14/2015 6:42:03 PM adding check for MS Edge browser, which does not support dataURI
// BH 12/2/2015 1:18:15 PM adding .dcd as binary file type
// BH 12/1/2015 10:05:55 AM loading identical HTML5 page after Java page causes bad NPObject error
// BH 10/26/2015 12:47:16 PM adding two rcsb sites for direct access
// BH 10/23/2015 9:20:39 PM minor coding adjustment
// BH 10/13/2015 9:32:08 PM adding Jmol.__$ as jquery object used
// BH 15/09/2015 18:06:39 fixing mouse check for swingjs-ui since SVG element className is not a string
// BH 8/12/2015 11:43:52 PM adding isHttps2Http forcing call to server proxy
// BH 8/9/2015 6:33:33 PM correcting bug in load ASYNC for x-domain access
// BH 7/7/2015 1:42:31 PM Jmol._persistentMenu
// BH 6/29/2015 10:14:47 AM adds Jmol.$getSize(obj)
// BH 5/30/2015 9:33:12 AM adds class swingjs-ui to ignore
// BH 5/9/2015 3:38:52 PM adds data-ignoreMouse attribute for JTextField
// BH 3/30/2015 9:46:53 PM adds JSAppletPanel for ready callback
// BH 12/6/2014 3:32:54 PM Jmol.setAppletCss() broken
// BH 9/13/2014 2:15:51 PM embedded JSME loads from SEARCH when Jmol should
// BH 8/14/2014 2:52:38 PM drag-drop cache should not be cleared if SPT file is dropped
// BH 8/5/2014 6:39:54 AM unnecessary messages about binary for PDB finally removed
// BH 8/4/2014 5:30:00 AM automatically switch to no document after page loading
// BH 8/2/2014 5:22:40 PM drag-drop broken in JSmol/HTML5
// BH 7/23/2014 5:34:08 PM setting a parameter such as readyFunction to null stops file loading
// BH 7/3/2014 12:30:28 AM lost drag-drop of models
// BH 7/2/2014 4:47:55 AM adding pdbe.org to direct database calls
// BH 5/30/2014 7:20:07 AM better dragging for console and menu
// BH 4/27/2014 6:31:52 PM allows _USE=SIGNED HTML5 as well as _USE=JAVA HTML5
// BH 3/8/2014 5:50:51 PM adds support for dataURI download in FF and Chrome
// BH 3/8/2014 8:43:10 AM moves PubChem access to https
// BH 3/4/2014 8:40:15 PM adds Jmol.Cache for JSV/Jmol sharing files
// BH 2/10/2014 10:07:14 AM added Info.z and Info.zIndexBase
// BH 2/9/2014 9:56:06 PM updated JSmolCore.js with option to extend Viewer with code PRIOR to loading Viewer classes
// BH 2/6/2014 8:46:25 AM disabled Jmol._tracker for localhost and 127.x.x.x
// BH 1/29/2014 8:02:23 AM Jmol.View and Info.viewSet
// BH 1/21/2014 12:06:59 PM adding Jmol.Info.cacheFiles (applet, true/false) and applet._cacheFiles and Jmol._fileCache
// BH 1/13/2014 2:12:38 PM adding "http://www.nmrdb.org/tools/jmol/predict.php":"%URL", to _DirectDatabaseCalls
// BH 12/21/2013 6:38:35 PM applet sync broken
// BH 12/6/2013 6:18:32 PM cover.htm and coverImage fix
// BH 12/4/2013 7:44:26 PM fix for JME independent search box
// BH 12/3/2013 6:30:08 AM fix for ready function returning Boolean instead of boolean in HTML5 version
// BH 11/30/2013 10:31:37 AM added type:"GET" for jQuery.ajax() requests instead of using defaults
// BH 11/30/2013 10:31:37 AM added cache:true for jQuery.ajax() requests; can override with cache:"NO", not cache:false
// BH 11/28/2013 11:09:27 AM added Jmol._alertNoBinary:true
// BH 11/26/2013 8:19:55 PM fix !xxxx search commmand entry and stop MSIE from duplicating command
// BH 11/25/2013 7:38:31 AM adds Jmol._tracker: option for GoogleAnalytics tracking
// BH 11/25/2013 7:39:03 AM adds URL options _J2S= _JAR= _USE=
// BH 11/23/2013 10:51:37 PM adds JNLP support for local applet
// BH 11/2/2013 12:05:11 PM JSmolJSME fixes; https access fixed
// BH 10/31/2013 7:50:06 PM Jmol.Dialog as SwingController; Jmol._mouseOwner added
// BH 10/19/2013 7:05:04 AM adding Jmol._ajaxCall for Error Contacting Server; database POST method enabled
// BH 10/17/2013 1:40:51 PM adding javajs/swing and Jmol.Dialog
// BH 9/30/2013 6:42:24 PM: pdb.gz switch pdb should only be for www.rcsb.org
// BH 9/17/2013 10:17:51 AM: asynchronous file reading and saving
// BH 8/16/2013 12:02:20 PM: JSmoljQueryExt.js pulled out
// BH 8/16/2013 12:02:20 PM: Jmol._touching used properly
// BH 3/22/2013 5:53:02 PM: Adds noscript option, JSmol.min.core.js
// BH 1/17/2013 5:20:44 PM: Fixed problem with console not getting initial position if no first click
// 1/13/2013 BH: Fixed MSIE not-reading-local-files problem.
// 11/28/2012 BH: Fixed MacOS Safari binary ArrayBuffer problem
// 11/21/2012 BH: restructuring of files as JS... instead of J...
// 11/20/2012 BH: MSIE9 cannot do a synchronous file load cross-domain. See Jmol._getFileData
// 11/4/2012 BH: RCSB REST format change "<structureId>" to "<dimStructure.structureId>"
// 9/13/2012 BH: JmolCore.js changes for JSmol doAjax() method -- _3ata()
// 6/12/2012 BH: JmolApi.js: adds Jmol.setInfo(applet, info, isShown) -- third parameter optional
// 6/12/2012 BH: JmolApi.js: adds Jmol.getInfo(applet)
// 6/12/2012 BH: JmolApplet.js: Fixes for MSIE 8
// 6/5/2012 BH: fixes problem with Jmol "javascript" command not working and getPropertyAsArray not working
// 6/4/2012 BH: corrects problem with MSIE requiring mouse-hover to activate applet
// 5/31/2012 BH: added JSpecView interface and api -- see JmolJSV.js
// also changed "jmolJarPath" to just "jarPath"
// jmolJarFile->jarFile, jmolIsSigned->isSigned, jmolReadyFunction->readyFunction
// also corrects a double-loading issue
// 5/14/2012 BH: added AJAX queue for ChemDoodle option with multiple canvases
// 8/12/2012 BH: adds support for MSIE xdr cross-domain request (jQuery.iecors.js)
// BH 4/25 -- added text option. setAppletCss(null, "style=\"xxxx\"")
// note that since you must add the style keyword, this can be used to add any attribute to these tags, not just css.
// required/optional libraries (preferably in the following order):
// jquery/jquery.js -- at least jQuery.1.9
// js/JSmoljQueryext.js -- required for binary file transfer; otherwise standard jQuery should be OK
// js/JSmolCore.js -- required
// js/j2sjmol.js -- required
// js/JSmol.js -- required
// js/JSmolApplet.js -- required; internal functions for _Applet and _Image; must be after JSmolCore
// js/JSmolControls.js -- optional; internal functions for buttons, links, menus, etc.; must be after JSmolCore
// js/JSmolConsole.js -- optional; for the pop-up console
// js/JSmolApi.js -- required; all user functions; must be after JSmolCore
// js/JSmolTHREE.js -- optional; WebGL library required for JSmolGLmol.js
// js/JSmolGLmol.js -- optional; WebGL version of JSmol.
// js/JSmolJME.js -- optional; JSME (2D editor)
// jsme/jsme/jsme.nocache.js -- required for JSME
// js/JSmolMenu.js -- optional; required for menuing in JSV
// js/JSmolJSV.js -- optional; for creating and interacting with a JSpecView applet
// most of these will be loaded automatically, and for most installations, all you need is JSmol.min.js
// Allows Jmol-like objects to be displayed on Java-challenged (iPad/iPhone)
// or applet-challenged (Android/iPhone) platforms, with automatic switching to
// For your installation, you should consider putting JmolData.jar and jsmol.php
// on your own server. Nothing more than these two files is needed on the server, and this
// allows more options for MSIE and Chrome when working with cross-domain files (such as RCSB or pubChem)
// The NCI and RCSB databases are accessed via direct AJAX if available (xhr2/xdr).
if(typeof(jQuery)=="undefined") alert ("Note -- JSmoljQuery is required for JSmol, but it's not defined.")
// An example of how to extend Jmol with code PRIOR to JSmolCore.js or JSmol.min.js follows:
//
//
// Jmol = {
// z:3000,
// extend: function(what, obj) {if (what == "viewer") { obj._testing = true } }
// }
self.Jmol || (Jmol = {});
if (!Jmol._version)
Jmol = (function(document) {
var z=Jmol.z || 9000;
var getZOrders = function(z) {
return {
rear:z++,
header:z++,
main:z++,
image:z++,
front:z++,
fileOpener:z++,
coverImage:z++,
dialog:z++, // could be several of these, JSV only
menu:z+90000, // way front
console:z+91000, // even more front
consoleImage:z+91001, // bit more front; increments
monitorZIndex:z+99999 // way way front
}
};
var j = {
_version: "$Date: 2016-10-21 06:39:01 -0500 (Fri, 21 Oct 2016) $", // svn.keywords:lastUpdated
_alertNoBinary: true,
// this url is used to Google Analytics tracking of Jmol use. You may remove it or modify it if you wish.
_allowedJmolSize: [25, 2048, 300], // min, max, default (pixels)
/* By setting the Jmol.allowedJmolSize[] variable in the webpage
before calling Jmol.getApplet(), limits for applet size can be overriden.
2048 standard for GeoWall (http://geowall.geo.lsa.umich.edu/home.html)
*/
_appletCssClass: "",
_appletCssText: "",
_fileCache: null, // enabled by Jmol.setFileCaching(applet, true/false)
_jarFile: null, // can be set in URL using _JAR=
_j2sPath: null, // can be set in URL using _J2S=
_use: null, // can be set in URL using _USE=
_j2sLoadMonitorOpacity: 90, // initial opacity for j2s load monitor message
_applets: {},
_asynchronous: true,
_ajaxQueue: [],
_persistentMenu: false,
_getZOrders: getZOrders,
_z:getZOrders(z),
_debugCode: true, // set false in process of minimization
db: {
_databasePrefixes: "$=:",
_fileLoadScript: ";if (_loadScript = '' && defaultLoadScript == '' && _filetype == 'Pdb') { select protein or nucleic;cartoons Only;color structure; select * };",
_nciLoadScript: ";n = ({molecule=1}.length < {molecule=2}.length ? 2 : 1); select molecule=n;display selected;center selected;",
_pubChemLoadScript: "",
_DirectDatabaseCalls:{
// these sites are known to implement access-control-allow-origin *
// null here means no conversion necessary
"cactus.nci.nih.gov": null,
".x3dna.org": null,
"rruff.geo.arizona.edu": null,
".rcsb.org": null,
"ftp.wwpdb.org": null,
"pdbe.org": null,
"materialsproject.org": null,
".ebi.ac.uk": null,
"pubchem.ncbi.nlm.nih.gov":null,
"www.nmrdb.org/tools/jmol/predict.php":null,
"$": "https://cactus.nci.nih.gov/chemical/structure/%FILENCI/file?format=sdf&get3d=True",
"$$": "https://cactus.nci.nih.gov/chemical/structure/%FILENCI/file?format=sdf",
"=": "https://files.rcsb.org/download/%FILE.pdb",
"*": "https://www.ebi.ac.uk/pdbe/entry-files/download/%FILE.cif",
"==": "https://files.rcsb.org/ligands/download/%FILE.cif",
":": "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/%FILE/SDF?record_type=3d"
},
_restQueryUrl: "http://www.rcsb.org/pdb/rest/search",
_restQueryXml: "<orgPdbQuery><queryType>org.pdb.query.simple.AdvancedKeywordQuery</queryType><description>Text Search</description><keywords>QUERY</keywords></orgPdbQuery>",
_restReportUrl: "http://www.pdb.org/pdb/rest/customReport?pdbids=IDLIST&customReportColumns=structureId,structureTitle"
},
_debugAlert: false,
_document: document,
_isXHTML: false,
_lastAppletID: null,
_mousePageX: null,
_mouseOwner: null,
_serverUrl: "https://your.server.here/jsmol.php",
_syncId: ("" + Math.random()).substring(3),
_touching: false,
_XhtmlElement: null,
_XhtmlAppendChild: false
}
var ref = document.location.href.toLowerCase();
j._httpProto = (ref.indexOf("https") == 0 ? "https://" : "http://");
j._isFile = (ref.indexOf("file:") == 0);
if (j._isFile) // ensure no attempt to read XML in local request:
$.ajaxSetup({ mimeType: "text/plain" });
j._ajaxTestSite = j._httpProto + "google.com";
var isLocal = (j._isFile || ref.indexOf("http://localhost") == 0 || ref.indexOf("http://127.") == 0);
j._tracker = (!isLocal && 'https://chemapps.stolaf.edu/jmol/JmolTracker.php?id=UA-45940799-1');
j._isChrome = (navigator.userAgent.toLowerCase().indexOf("chrome") >= 0);
j._isSafari = (!j._isChrome && navigator.userAgent.toLowerCase().indexOf("safari") >= 0);
j._isMsie = (window.ActiveXObject !== undefined);
j._isEdge = (navigator.userAgent.indexOf("Edge/") >= 0);
j._useDataURI = !j._isSafari && !j._isMsie && !j._isEdge; // safari may be OK here -- untested
window.requestAnimationFrame || (window.requestAnimationFrame = window.setTimeout);
for(var i in Jmol) j[i] = Jmol[i]; // allows pre-definition
return j;
})(document, Jmol);
(function (Jmol, $) {
Jmol.__$ = $; // local jQuery object -- important if any other module needs to access it (JSmolMenu, for example)
// this library is organized into the following sections:
// jQuery interface
// protected variables
// feature detection
// AJAX-related core functionality
// applet start-up functionality
// misc core functionality
// mouse events
////////////////////// jQuery interface ///////////////////////
// hooks to jQuery -- if you have a different AJAX tool, feel free to adapt.
// There should be no other references to jQuery in all the JSmol libraries.
// automatically switch to returning HTML after the page is loaded
$(document).ready(function(){ Jmol._document = null });
Jmol.$ = function(objectOrId, subdiv) {
// if a subdiv, then return $("#objectOrId._id_subdiv")
// or if no subdiv, then just $(objectOrId)
if (objectOrId == null)alert (subdiv + arguments.callee.caller.toString());
return $(subdiv ? "#" + objectOrId._id + "_" + subdiv : objectOrId);
}
Jmol._$ = function(id) {
// either the object or $("#" + id)
return (typeof id == "string" ? $("#" + id) : id);
}
/// special functions:
Jmol.$ajax = function(info) {
Jmol._ajaxCall = info.url;
info.cache = (info.cache != "NO");
info.url = Jmol._fixProtocol(info.url);
// don't let jQuery add $_=... to URL unless we
// use cache:"NO"; other packages might use $.ajaxSetup() to set this to cache:false
return $.ajax(info);
}
Jmol._fixProtocol = function(url) {
if (url.indexOf("get3d=True") >= 0)
url = url.replace(/get3d\=True/, "get3d=true"); // NCI/CADD change 08/2016
return (
url.indexOf("http://www.rcsb.org/pdb/files/") == 0 && url.indexOf("/ligand/") < 0 ?
"http://files.rcsb.org/view/" + url.substring(30).replace(/\.gz/,"")
: url.indexOf("http://") == 0 && (
Jmol._httpProto == "https://"
|| url.indexOf(".gov/") > 0
|| url.indexOf("http://www.materialsproject") == 0)
? "https" + url.substring(4) : url);
}
Jmol._getNCIInfo = function(identifier, what, fCallback) {
return Jmol._getFileData("https://cactus.nci.nih.gov/chemical/structure/"+identifier +"/" + (what == "name" ? "names" : what));
}
Jmol.$appEvent = function(app, subdiv, evt, f) {
var o = Jmol.$(app, subdiv);
o.off(evt) && f && o.on(evt, f);
}
Jmol.$resize = function (f) {
return $(window).resize(f);
}
//// full identifier expected (could be "body", for example):
Jmol.$after = function (what, s) {
return $(what).after(s);
}
Jmol.$append = function (what, s) {
return $(what).append(s);
}
Jmol.$bind = function(what, list, f) {
return (f ? $(what).bind(list, f) : $(what).unbind(list));
}
Jmol.$closest = function(what, d) {
return $(what).closest(d);
}
Jmol.$get = function(what, i) {
return $(what).get(i);
}
// element id expected
Jmol.$documentOff = function(evt, id) {
return $(document).off(evt, "#" + id);
}
Jmol.$documentOn = function(evt, id, f) {
return $(document).on(evt, "#" + id, f);
}
Jmol.$getAncestorDiv = function(id, className) {
return $("div." + className + ":has(#" + id + ")")[0];
}
Jmol.$supportsIECrossDomainScripting = function() {
return $.support.iecors;
}
//// element id or jQuery object expected:
Jmol.$attr = function (id, a, val) {
return Jmol._$(id).attr(a, val);
}
Jmol.$css = function(id, style) {
return Jmol._$(id).css(style);
}
Jmol.$find = function(id, d) {
return Jmol._$(id).find(d);
}
Jmol.$focus = function(id) {
return Jmol._$(id).focus();
}
Jmol.$html = function(id, html) {
return Jmol._$(id).html(html);
}
Jmol.$offset = function(id) {
return Jmol._$(id).offset();
}
Jmol.$windowOn = function(evt, f) {
return $(window).on(evt, f);
}
Jmol.$prop = function(id, p, val) {
var o = Jmol._$(id);
return (arguments.length == 3 ? o.prop(p, val) : o.prop(p));
}
Jmol.$remove = function(id) {
return Jmol._$(id).remove();
}
Jmol.$scrollTo = function (id, n) {
var o = Jmol._$(id);
return o.scrollTop(n < 0 ? o[0].scrollHeight : n);
}
Jmol.$setEnabled = function(id, b) {
return Jmol._$(id).attr("disabled", b ? null : "disabled");
}
Jmol.$getSize = function(id) {
var o = Jmol._$(id);
return [ o.width(), o.height() ]
}
Jmol.$setSize = function(id, w, h) {
return Jmol._$(id).width(w).height(h);
}
Jmol.$is = function(id, test) { // e.g. :visible
return Jmol._$(id).is(test);
}
Jmol.$setVisible = function(id, b) {
var o = Jmol._$(id);
return (b ? o.show() : o.hide());
}
Jmol.$submit = function(id) {
return Jmol._$(id).submit();
}
Jmol.$val = function (id, v) {
var o = Jmol._$(id);
return (arguments.length == 1 ? o.val() : o.val(v));
}
////////////// protected variables ///////////
Jmol._clearVars = function() {
// only on page closing -- appears to improve garbage collection
delete jQuery;
delete $;
delete Jmol;
delete SwingController;
delete J;
delete JM;
delete JS;
delete JSV;
delete JU;
delete JV;
delete java;
delete javajs;
delete Clazz;
delete c$; // used in p0p; could be gotten rid of
}
////////////// feature detection ///////////////
Jmol.featureDetection = (function(document, window) {
var features = {};
features.ua = navigator.userAgent.toLowerCase()
features.os = (function(){
var osList = ["linux","unix","mac","win"]
var i = osList.length;
while (i--){
if (features.ua.indexOf(osList[i])!=-1) return osList[i]
}
return "unknown";
})();
features.browser = function(){
var ua = features.ua;
var browserList = ["konqueror","webkit","omniweb","opera","webtv","icab","msie","mozilla"];
for (var i = 0; i < browserList.length; i++)
if (ua.indexOf(browserList[i])>=0)
return browserList[i];
return "unknown";
}
features.browserName = features.browser();
features.browserVersion= parseFloat(features.ua.substring(features.ua.indexOf(features.browserName)+features.browserName.length+1));
features.supportsXhr2 = function() {return ($.support.cors || $.support.iecors)}
features.allowDestroy = (features.browserName != "msie");
features.allowHTML5 = (features.browserName != "msie" || navigator.appVersion.indexOf("MSIE 8") < 0);
features.getDefaultLanguage = function() {
return navigator.language || navigator.userLanguage || "en-US";
};
features._webGLtest = 0;
features.supportsWebGL = function() {
if (!Jmol.featureDetection._webGLtest) {
var canvas;
Jmol.featureDetection._webGLtest = (
window.WebGLRenderingContext
&& ((canvas = document.createElement("canvas")).getContext("webgl")
|| canvas.getContext("experimental-webgl")) ? 1 : -1);
}
return (Jmol.featureDetection._webGLtest > 0);
};
features.supportsLocalization = function() {
//<meta charset="utf-8">
var metas = document.getElementsByTagName('meta');
for (var i= metas.length; --i >= 0;)
if (metas[i].outerHTML.toLowerCase().indexOf("utf-8") >= 0) return true;
return false;
};
features.supportsJava = function() {
if (!Jmol.featureDetection._javaEnabled) {
if (Jmol._isMsie) {
if (!navigator.javaEnabled()) {
Jmol.featureDetection._javaEnabled = -1;
} else {
//more likely -- would take huge testing
Jmol.featureDetection._javaEnabled = 1;
}
} else {
Jmol.featureDetection._javaEnabled = (navigator.javaEnabled() && (!navigator.mimeTypes || navigator.mimeTypes["application/x-java-applet"]) ? 1 : -1);
}
}
return (Jmol.featureDetection._javaEnabled > 0);
};
features.compliantBrowser = function() {
var a = !!document.getElementById;
var os = features.os;
// known exceptions (old browsers):
if (features.browserName == "opera" && features.browserVersion <= 7.54 && os == "mac"
|| features.browserName == "webkit" && features.browserVersion < 125.12
|| features.browserName == "msie" && os == "mac"
|| features.browserName == "konqueror" && features.browserVersion <= 3.3
) a = false;
return a;
}
features.isFullyCompliant = function() {
return features.compliantBrowser() && features.supportsJava();
}
features.useIEObject = (features.os == "win" && features.browserName == "msie" && features.browserVersion >= 5.5);
features.useHtml4Object = (features.browserName == "mozilla" && features.browserVersion >= 5) ||
(features.browserName == "opera" && features.browserVersion >= 8) ||
(features.browserName == "webkit"/* && features.browserVersion >= 412.2 && features.browserVersion < 500*/); // 500 is a guess; required for 536.3
features.hasFileReader = (window.File && window.FileReader);
return features;
})(document, window);
////////////// AJAX-related core functionality //////////////
Jmol._ajax = function(info) {
if (!info.async) {
return Jmol.$ajax(info).responseText;
}
Jmol._ajaxQueue.push(info)
if (Jmol._ajaxQueue.length == 1)
Jmol._ajaxDone()
}
Jmol._ajaxDone = function() {
var info = Jmol._ajaxQueue.shift();
info && Jmol.$ajax(info);
}
Jmol._grabberOptions = [
["$", "NCI(small molecules)"],
[":", "PubChem(small molecules)"],
["=", "RCSB(macromolecules)"],
["*", "PDBe(macromolecules)"]
];
Jmol._getGrabberOptions = function(applet) {
// feel free to adjust this look to anything you want
if (Jmol._grabberOptions.length == 0)
return ""
var s = '<input type="text" id="ID_query" onfocus="jQuery(this).select()" onkeypress="if(13==event.which){Jmol._applets[\'ID\']._search();return false}" size="32" value="" />';
var b = '<button id="ID_submit" onclick="Jmol._applets[\'ID\']._search()">Search</button></nobr>'
if (Jmol._grabberOptions.length == 1) {
s = '<nobr>' + s + '<span style="display:none">';
b = '</span>' + b;
} else {
s += '<br /><nobr>'
}
s += '<select id="ID_select">'
for (var i = 0; i < Jmol._grabberOptions.length; i++) {
var opt = Jmol._grabberOptions[i];
s += '<option value="' + opt[0] + '" ' + (i == 0 ? 'selected' : '') + '>' + opt[1] + '</option>';
}
s = (s + '</select>' + b).replace(/ID/g, applet._id);
return '<br />' + s;
}
Jmol._getScriptForDatabase = function(database) {
return (database == "$" ? Jmol.db._nciLoadScript : database == ":" ? Jmol.db._pubChemLoadScript : Jmol.db._fileLoadScript);
}
// <dataset><record><structureId>1BLU</structureId><structureTitle>STRUCTURE OF THE 2[4FE-4S] FERREDOXIN FROM CHROMATIUM VINOSUM</structureTitle></record><record><structureId>3EUN</structureId><structureTitle>Crystal structure of the 2[4Fe-4S] C57A ferredoxin variant from allochromatium vinosum</structureTitle></record></dataset>
Jmol._setInfo = function(applet, database, data) {
var info = [];
var header = "";
if (data.indexOf("ERROR") == 0)
header = data;
else
switch (database) {
case "=":
var S = data.split("<dimStructure.structureId>");
var info = ["<table>"];
for (var i = 1; i < S.length; i++) {
info.push("<tr><td valign=top><a href=\"javascript:Jmol.search(" + applet._id + ",'=" + S[i].substring(0, 4) + "')\">" + S[i].substring(0, 4) + "</a></td>");
info.push("<td>" + S[i].split("Title>")[1].split("</")[0] + "</td></tr>");
}
info.push("</table>");
header = (S.length - 1) + " matches";
break;
case "$": // NCI
case ":": // pubChem
break;
default:
return;
}
applet._infoHeader = header;
applet._info = info.join("");
applet._showInfo(true);
}
Jmol._loadSuccess = function(a, fSuccess) {
if (!fSuccess)
return;
Jmol._ajaxDone();
fSuccess(a);
}
Jmol._loadError = function(fError){
Jmol._ajaxDone();
Jmol.say("Error connecting to server: " + Jmol._ajaxCall);
null!=fError&&fError()
}
Jmol._isDatabaseCall = function(query) {
return (Jmol.db._databasePrefixes.indexOf(query.substring(0, 1)) >= 0);
}
Jmol._getDirectDatabaseCall = function(query, checkXhr2) {
if (checkXhr2 && !Jmol.featureDetection.supportsXhr2())
return query;
var pt = 2;
var db = query.substring(0,pt)
var call = Jmol.db._DirectDatabaseCalls[db] || Jmol.db._DirectDatabaseCalls[db = query.substring(0,--pt)];
if (call) {
// one of the special set :, =, $, ==
if (db == ":") {
// PubChem
var ql = query.toLowerCase();
if (!isNaN(parseInt(query.substring(1)))) {
query = "cid/" + query.substring(1);
} else if (ql.indexOf(":smiles:") == 0) {
call += "?POST?smiles=" + query.substring(8);
query = "smiles";
} else if (ql.indexOf(":cid:") == 0) {
query = "cid/" + query.substring(5);
} else {
if (ql.indexOf(":name:") == 0)
query = query.substring(5);
else if (ql.indexOf(":cas:") == 0)
query = query.substring(4);
query = "name/" + encodeURIComponent(query.substring(pt));
}
} else {
query = encodeURIComponent(query.substring(pt));
}
if (query.indexOf(".mmtf") >= 0) {
query = "http://mmtf.rcsb.org/full/" + query.replace(/\.mmtf/, "");
} else if (call.indexOf("FILENCI") >= 0) {
query = query.replace(/\%2F/g, "/");
query = call.replace(/\%FILENCI/, query);
} else {
query = call.replace(/\%FILE/, query);
}
}
return query;
}
Jmol._getRawDataFromServer = function(database,query,fSuccess,fError,asBase64,noScript){
// note that this method is now only enabled for "_"
// server-side processing of database queries was too slow and only useful for
// the IMAGE option, which has been abandoned.
var s =
"?call=getRawDataFromDatabase&database=" + database + (query.indexOf("?POST?") >= 0 ? "?POST?" : "")
+ "&query=" + encodeURIComponent(query)
+ (asBase64 ? "&encoding=base64" : "")
+ (noScript ? "" : "&script=" + encodeURIComponent(Jmol._getScriptForDatabase(database)));
return Jmol._contactServer(s, fSuccess, fError);
}
Jmol._checkFileName = function(applet, fileName, isRawRet) {
if (Jmol._isDatabaseCall(fileName)) {
if (isRawRet)
Jmol._setQueryTerm(applet, fileName);
fileName = Jmol._getDirectDatabaseCall(fileName, true);
if (Jmol._isDatabaseCall(fileName)) {
// xhr2 not supported (MSIE)
fileName = Jmol._getDirectDatabaseCall(fileName, false);
isRawRet && (isRawRet[0] = true);
}
}
return fileName;
}
Jmol._checkCache = function(applet, fileName, fSuccess) {
if (applet._cacheFiles && Jmol._fileCache && !fileName.endsWith(".js")) {
var data = Jmol._fileCache[fileName];
if (data) {
System.out.println("using " + data.length + " bytes of cached data for " + fileName);
fSuccess(data);
return null;
} else {
fSuccess = function(fileName, data) { fSuccess(Jmol._fileCache[fileName] = data) };
}
}
return fSuccess;
}
Jmol._playAudio = function(filePath) {
var audio = document.createElement("audio");
audio.controls = "true";
audio.src = filePath;
audio.play();
}
Jmol._loadFileData = function(applet, fileName, fSuccess, fError){
var isRaw = [];
fileName = Jmol._checkFileName(applet, fileName, isRaw);
fSuccess = Jmol._checkCache(applet, fileName, fSuccess);
if (isRaw[0]) {
Jmol._getRawDataFromServer("_",fileName,fSuccess,fError);
return;
}
var info = {
type: "GET",
dataType: "text",
url: fileName,
async: Jmol._asynchronous,
success: function(a) {Jmol._loadSuccess(a, fSuccess)},
error: function() {Jmol._loadError(fError)}
}
Jmol._checkAjaxPost(info);
Jmol._ajax(info);
}
Jmol._getInfoFromDatabase = function(applet, database, query){
if (database == "====") {
var data = Jmol.db._restQueryXml.replace(/QUERY/,query);
var info = {
dataType: "text",
type: "POST",
contentType:"application/x-www-form-urlencoded",
url: Jmol.db._restQueryUrl,
data: encodeURIComponent(data) + "&req=browser",
success: function(data) {Jmol._ajaxDone();Jmol._extractInfoFromRCSB(applet, database, query, data)},
error: function() {Jmol._loadError(null)},
async: Jmol._asynchronous
}
return Jmol._ajax(info);
}
query = "?call=getInfoFromDatabase&database=" + database
+ "&query=" + encodeURIComponent(query);
return Jmol._contactServer(query, function(data) {Jmol._setInfo(applet, database, data)});
}
Jmol._extractInfoFromRCSB = function(applet, database, query, output) {
var n = output.length/5;
if (n == 0)
return;
if (query.length == 4 && n != 1) {
var QQQQ = query.toUpperCase();
var pt = output.indexOf(QQQQ);
if (pt > 0 && "123456789".indexOf(QQQQ.substring(0, 1)) >= 0)
output = QQQQ + "," + output.substring(0, pt) + output.substring(pt + 5);
if (n > 50)
output = output.substring(0, 250);
output = output.replace(/\n/g,",");
var url = Jmol._restReportUrl.replace(/IDLIST/,output);
Jmol._loadFileData(applet, url, function(data) {Jmol._setInfo(applet, database, data) });
}
}
Jmol._checkAjaxPost = function(info) {
var pt = info.url.indexOf("?POST?");
if (pt > 0) {
info.data = info.url.substring(pt + 6);
info.url = info.url.substring(0, pt);
info.type = "POST";
info.contentType = "application/x-www-form-urlencoded";
}
}
Jmol._contactServer = function(data,fSuccess,fError){
var info = {
dataType: "text",
type: "GET",
url: Jmol._serverUrl + data,
success: function(a) {Jmol._loadSuccess(a, fSuccess)},
error:function() { Jmol._loadError(fError) },
async:fSuccess ? Jmol._asynchronous : false
}
Jmol._checkAjaxPost(info);
return Jmol._ajax(info);
}
Jmol._setQueryTerm = function(applet, query) {
if (!query || !applet._hasOptions || query.substring(0, 7) == "http://")
return;
if (Jmol._isDatabaseCall(query)) {
var database = query.substring(0, 1);
query = query.substring(1);
if (query.substring(0,1) == database && "=$".indexOf(database) >= 0)
query = query.substring(1);
var d = Jmol._getElement(applet, "select");
if (d && d.options)
for (var i = 0; i < d.options.length; i++)
if (d[i].value == database)
d[i].selected = true;
}
Jmol.$val(Jmol.$(applet, "query"), query);
}
Jmol._search = function(applet, query, script) {
arguments.length > 1 || (query = null);
Jmol._setQueryTerm(applet, query);
query || (query = Jmol.$val(Jmol.$(applet, "query")))
if (query.indexOf("!") == 0) {
// command prompt in this box as well
// remove exclamation point "immediate" indicator
applet._script(query.substring(1));
return;
}
query && (query = query.replace(/\"/g, ""));
applet._showInfo(false);
Jmol._searchMol(applet, query, script, true);
}
Jmol._searchMol = function(applet, query, script, checkView) {
var database;
if (Jmol._isDatabaseCall(query)) {
database = query.substring(0, 1);
query = query.substring(1);
} else {
database = (applet._hasOptions ? Jmol.$val(Jmol.$(applet, "select")) : "$");
}
if (database == "=" && query.length == 3)
query = "=" + query; // this is a ligand
var dm = database + query;
if (!query || dm.indexOf("?") < 0 && dm == applet._thisJmolModel) {
return;
}
applet._thisJmolModel = dm;
var view;
if (checkView && applet._viewSet != null && (view = Jmol.View.__findView(applet._viewSet, {chemID:dm})) != null) {
Jmol.View.__setView(view, applet, false);
return;
}
if (database == "$" || database == ":")
applet._jmolFileType = "MOL";
else if (database == "=")
applet._jmolFileType = "PDB";
applet._searchDatabase(query, database, script);
}
Jmol._searchDatabase = function(applet, query, database, script) {
applet._showInfo(false);
if (query.indexOf("?") >= 0) {
Jmol._getInfoFromDatabase(applet, database, query.split("?")[0]);
return true;
}
if (Jmol.db._DirectDatabaseCalls[database]) {
applet._loadFile(database + query, script);
return true;
}
return false;
}
Jmol._syncBinaryOK="?";
Jmol._canSyncBinary = function(isSilent) {
if (Jmol._isAsync) return true;
if (self.VBArray) return (Jmol._syncBinaryOK = false);
if (Jmol._syncBinaryOK != "?") return Jmol._syncBinaryOK;
Jmol._syncBinaryOK = true;
try {
var xhr = new window.XMLHttpRequest();
xhr.open( "text", Jmol._ajaxTestSite, false );
if (xhr.hasOwnProperty("responseType")) {
xhr.responseType = "arraybuffer";
} else if (xhr.overrideMimeType) {
xhr.overrideMimeType('text/plain; charset=x-user-defined');
}
} catch( e ) {
var s = "JSmolCore.js: synchronous binary file transfer is requested but not available";
System.out.println(s);
if (Jmol._alertNoBinary && !isSilent)
alert (s)
return Jmol._syncBinaryOK = false;
}
return true;
}
Jmol._binaryTypes = ["mmtf",".gz",".jpg",".gif",".png",".zip",".jmol",".bin",".smol",".spartan",".mrc",".map",".ccp4",".dn6",".delphi",".omap",".pse",".dcd"];
Jmol._isBinaryUrl = function(url) {
for (var i = Jmol._binaryTypes.length; --i >= 0;)
if (url.indexOf(Jmol._binaryTypes[i]) >= 0) return true;
return false;
}
Jmol._getFileData = function(fileName, fSuccess, doProcess) {
// use host-server PHP relay if not from this host
var isBinary = Jmol._isBinaryUrl(fileName);
var isPDB = (fileName.indexOf(".gz") >= 0 && fileName.indexOf("rcsb.org") >= 0);
if (isPDB) {
// avoid unnecessary binary transfer
fileName = fileName.replace(/\.gz/,"");
isBinary = false;
}
var asBase64 = (isBinary && !fSuccess && !Jmol._canSyncBinary(isPDB));
var isPost = (fileName.indexOf("?POST?") >= 0);
if (fileName.indexOf("file:/") == 0 && fileName.indexOf("file:///") != 0)
fileName = "file://" + fileName.substring(5); /// fixes IE problem
var isMyHost = (fileName.indexOf("://") < 0 || fileName.indexOf(document.location.protocol) == 0 && fileName.indexOf(document.location.host) >= 0);
var isHttps2Http = (Jmol._httpProto == "https://" && fileName.indexOf("http://") == 0);
var isDirectCall = Jmol._isDirectCall(fileName);
if (!isDirectCall && fileName.indexOf("?ALLOWSORIGIN?") >= 0) {
isDirectCall = true;
fileName = fileName.replace(/\?ALLOWSORIGIN\?/,"");
}
//if (fileName.indexOf("http://pubchem.ncbi.nlm.nih.gov/") == 0)isDirectCall = false;
var cantDoSynchronousLoad = (!isMyHost && Jmol.$supportsIECrossDomainScripting());
var data = null;
if (isHttps2Http || asBase64 || !isMyHost && !isDirectCall || !fSuccess && cantDoSynchronousLoad ) {
data = Jmol._getRawDataFromServer("_",fileName, fSuccess, fSuccess, asBase64, true);
} else {
fileName = fileName.replace(/file:\/\/\/\//, "file://"); // opera
var info = {dataType:(isBinary ? "binary" : "text"),async:!!fSuccess};
if (isPost) {
info.type = "POST";
info.url = fileName.split("?POST?")[0]
info.data = fileName.split("?POST?")[1]
} else {
info.type = "GET";
info.url = fileName;
}
if (fSuccess) {
info.success = function(data) { fSuccess(Jmol._xhrReturn(info.xhr))};
info.error = function() { fSuccess(info.xhr.statusText)};
}
info.xhr = Jmol.$ajax(info);
if (!fSuccess) {
data = Jmol._xhrReturn(info.xhr);
}
}
if (!doProcess)
return data;
if (data == null) {
data = "";
isBinary = false;
}
isBinary && (isBinary = Jmol._canSyncBinary(true));
return (isBinary ? Jmol._strToBytes(data) : JU.SB.newS(data));
}
Jmol._xhrReturn = function(xhr){
if (!xhr.responseText || self.Clazz && Clazz.instanceOf(xhr.response, self.ArrayBuffer)) {
// Safari or error
return xhr.response || xhr.statusText;
}
return xhr.responseText;
}
Jmol._isDirectCall = function(url) {
if (url.indexOf("?ALLOWSORIGIN?") >= 0)
return true;
for (var key in Jmol.db._DirectDatabaseCalls) {
if (key.indexOf(".") >= 0 && url.indexOf(key) >= 0)
return true;
}
return false;
}
Jmol._cleanFileData = function(data) {
if (data.indexOf("\r") >= 0 && data.indexOf("\n") >= 0) {
return data.replace(/\r\n/g,"\n");
}
if (data.indexOf("\r") >= 0) {
return data.replace(/\r/g,"\n");
}
return data;
};
Jmol._getFileType = function(name) {
var database = name.substring(0, 1);
if (database == "$" || database == ":")
return "MOL";
if (database == "=")
return (name.substring(1,2) == "=" ? "LCIF" : "PDB");
// just the extension, which must be PDB, XYZ..., CIF, or MOL
name = name.split('.').pop().toUpperCase();
return name.substring(0, Math.min(name.length, 3));
};
Jmol._getZ = function(applet, what) {
return applet && applet._z && applet._z[what] || Jmol._z[what];
}
Jmol._incrZ = function(applet, what) {
return applet && applet._z && ++applet._z[what] || ++Jmol._z[what];
}
Jmol._hideLocalFileReader = function(applet, cursor) {
applet._localReader && Jmol.$setVisible(applet._localReader, false);
applet._readingLocal = false;
Jmol._setCursor(applet, 0);
}
Jmol.loadFileFromDialog = function(applet) {
Jmol._loadFileAsynchronously(null, applet, null, null);
}
Jmol._loadFileAsynchronously = function(fileLoadThread, applet, fileName, appData) {
if (fileName && fileName.indexOf("?") != 0) {
// LOAD ASYNC command
var fileName0 = fileName;
fileName = Jmol._checkFileName(applet, fileName);
var fSuccess = function(data) {Jmol._setData(fileLoadThread, fileName, fileName0, data, appData, applet)};
fSuccess = Jmol._checkCache(applet, fileName, fSuccess);
if (fileName.indexOf("|") >= 0)
fileName = fileName.split("|")[0];
return (fSuccess == null ? null : Jmol._getFileData(fileName, fSuccess));
}
// we actually cannot suggest a fileName, I believe.
if (!Jmol.featureDetection.hasFileReader) {
var mst = "Local file reading is not enabled in your browser";
return (fileLoadThread ? fileLoadThread.setData(msg, null, null, appData, applet) : alert(msg));
}
if (!applet._localReader) {
var div = '<div id="ID" style="z-index:'+Jmol._getZ(applet, "fileOpener") + ';position:absolute;background:#E0E0E0;left:10px;top:10px"><div style="margin:5px 5px 5px 5px;"><button id="ID_loadurl">URL</button><input type="file" id="ID_files" /><button id="ID_loadfile">load</button><button id="ID_cancel">cancel</button></div><div>'
Jmol.$after("#" + applet._id + "_appletdiv", div.replace(/ID/g, applet._id + "_localReader"));
applet._localReader = Jmol.$(applet, "localReader");
}
Jmol.$appEvent(applet, "localReader_loadurl", "click");
Jmol.$appEvent(applet, "localReader_loadurl", "click", function(evt) {
var file = prompt("Enter a URL");
if (!file)return
Jmol._hideLocalFileReader(applet, 0);
Jmol._setData(null, file, file, null, appData, applet);
});
Jmol.$appEvent(applet, "localReader_loadfile", "click");
Jmol.$appEvent(applet, "localReader_loadfile", "click", function(evt) {
var file = Jmol.$(applet, "localReader_files")[0].files[0];
var reader = new FileReader();
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
Jmol._hideLocalFileReader(applet, 0);
Jmol._setData(fileLoadThread, file.name, file.name, evt.target.result, appData, applet);
}
};
try {
reader.readAsArrayBuffer(file);
} catch (e) {
alert("You must select a file first.");
}
});
Jmol.$appEvent(applet, "localReader_cancel", "click");
Jmol.$appEvent(applet, "localReader_cancel", "click", function(evt) {
Jmol._hideLocalFileReader(applet);
if (fileLoadThread)
fileLoadThread.setData("#CANCELED#", null, null, appData, applet);
});
Jmol.$setVisible(applet._localReader, true);
applet._readingLocal = true;
}
Jmol._setData = function(fileLoadThread, filename, filename0, data, appData, applet) {
data && (data = Jmol._strToBytes(data));
if (data != null && (fileLoadThread == null || filename.indexOf(".jdx") >= 0))
Jmol.Cache.put("cache://" + filename, data);
if (fileLoadThread == null) {
applet._applet.openFileAsyncSpecial(data == null ? filename : "cache://" + filename, 1);
} else {
fileLoadThread.setData(filename, filename0, data, appData);
}
}
Jmol._doAjax = function(url, postOut, dataOut) {
// called by org.jmol.awtjs2d.JmolURLConnection.doAjax()
url = url.toString();
if (dataOut != null)
return Jmol._saveFile(url, dataOut);
if (postOut)
url += "?POST?" + postOut;
return Jmol._getFileData(url, null, true);
}
// Jmol._localFileSaveFunction -- // do something local here; Maybe try the FileSave interface? return true if successful
Jmol._saveFile = function(filename, data, mimetype, encoding) {
if (Jmol._localFileSaveFunction && Jmol._localFileSaveFunction(filename, data))
return "OK";
var filename = filename.substring(filename.lastIndexOf("/") + 1);
mimetype || (mimetype = (filename.indexOf(".pdf") >= 0 ? "application/pdf"
: filename.indexOf(".png") >= 0 ? "image/png"
: filename.indexOf(".gif") >= 0 ? "image/gif"
: filename.indexOf(".jpg") >= 0 ? "image/jpg" : ""));
var isString = (typeof data == "string");
data = (JU ? JU : J.util).Base64.getBase64(isString ? data.getBytes("UTF-8") : data).toString();
encoding || (encoding = "base64");
var url = Jmol._serverUrl;
url && url.indexOf("your.server") >= 0 && (url = "");
if (Jmol._useDataURI || !url) {
// Asynchronous output generated using an anchor tag
// btoa does not work with UTF-8 data///encoding || (data = btoa(data));
var a = document.createElement("a");
a.href = "data:" + mimetype + ";base64," + data;
a.type = mimetype || (mimetype = "text/plain;charset=utf-8");
a.download = filename;
a.target = "_blank";
$("body").append(a);
a.click();
a.remove();
} else {
// Asynchronous outputto be reflected as a download
if (!Jmol._formdiv) {
var sform = '<div id="__jsmolformdiv__" style="display:none">\
<form id="__jsmolform__" method="post" target="_blank" action="">\
<input name="call" value="saveFile"/>\
<input id="__jsmolmimetype__" name="mimetype" value=""/>\
<input id="__jsmolencoding__" name="encoding" value=""/>\
<input id="__jsmolfilename__" name="filename" value=""/>\
<textarea id="__jsmoldata__" name="data"></textarea>\
</form>\
</div>'
Jmol.$after("body", sform);
Jmol._formdiv = "__jsmolform__";
}
Jmol.$attr(Jmol._formdiv, "action", url + "?" + (new Date()).getMilliseconds());
Jmol.$val("__jsmoldata__", data);
Jmol.$val("__jsmolfilename__", filename);
Jmol.$val("__jsmolmimetype__", mimetype);
Jmol.$val("__jsmolencoding__", encoding);
Jmol.$submit("__jsmolform__");
Jmol.$val("__jsmoldata__", "");
Jmol.$val("__jsmolfilename__", "");
}
return "OK";
}
Jmol._strToBytes = function(s) {
if (Clazz.instanceOf(s, self.ArrayBuffer))
return Clazz.newByteArray(-1, s);
var b = Clazz.newByteArray(s.length, 0);
for (var i = s.length; --i >= 0;)
b[i] = s.charCodeAt(i) & 0xFF;
return b;
}
////////////// applet start-up functionality //////////////
Jmol._setConsoleDiv = function (d) {
if (!self.Clazz)return;
Clazz.setConsoleDiv(d);
}
Jmol._registerApplet = function(id, applet) {
return window[id] = Jmol._applets[id] = Jmol._applets[id + "__" + Jmol._syncId + "__"] = applet;
}
Jmol._readyCallback = function (appId,fullId,isReady,javaApplet,javaAppletPanel) {
appId = appId.split("_object")[0];
var applet = Jmol._applets[appId];
isReady = (isReady.booleanValue ? isReady.booleanValue() : isReady);
// necessary for MSIE in strict mode -- apparently, we can't call
// jmol._readyCallback, but we can call Jmol._readyCallback. Go figure...
if (isReady) {
// when leaving page, Java applet may be dead
applet._appletPanel = (javaAppletPanel || javaApplet);
applet._applet = javaApplet;
}
Jmol._track(applet)._readyCallback(appId, fullId, isReady);
}
Jmol._getWrapper = function(applet, isHeader) {
// id_appletinfotablediv
// id_appletdiv
// id_coverdiv
// id_infotablediv
// id_infoheaderdiv
// id_infoheaderspan
// id_infocheckboxspan
// id_infodiv
// for whatever reason, without DOCTYPE, with MSIE, "height:auto" does not work,
// and the text scrolls off the page.
// So I'm using height:95% here.
// The table was a fix for MSIE with no DOCTYPE tag to fix the miscalculation
// in height of the div when using 95% for height.
// But it turns out the table has problems with DOCTYPE tags, so that's out.
// The 95% is a compromise that we need until the no-DOCTYPE MSIE solution is found.
// (100% does not work with the JME linked applet)
var s;
// ... here are just for clarification in this code; they are removed immediately
if (isHeader) {
var img = "";
if (applet._coverImage){
var more = " onclick=\"Jmol.coverApplet(ID, false)\" title=\"" + (applet._coverTitle) + "\"";
var play = "<image id=\"ID_coverclickgo\" src=\"" + applet._makeLiveImage + "\" style=\"width:25px;height:25px;position:absolute;bottom:10px;left:10px;"
+ "z-index:" + Jmol._getZ(applet, "coverImage")+";opacity:0.5;\"" + more + " />"
img = "<div id=\"ID_coverdiv\" style=\"background-color:red;z-index:" + Jmol._getZ(applet, "coverImage")+";width:100%;height:100%;display:inline;position:absolute;top:0px;left:0px\"><image id=\"ID_coverimage\" src=\""
+ applet._coverImage + "\" style=\"width:100%;height:100%\"" + more + "/>" + play + "</div>";
}
var wait = (applet._isJava ? "" : "<image id=\"ID_waitimage\" src=\"" + applet._j2sPath + "/img/cursor_wait.gif\" style=\"display:none;position:absolute;bottom:10px;left:10px;"
+ "z-index:" + Jmol._getZ(applet, "coverImage")+";\" />");
var css = Jmol._appletCssText.replace(/\'/g,'"');
var spinner = applet._getSpinner && applet._getSpinner();
applet._spinner = spinner = (!spinner || spinner == "none" ? "" : "background-image:url("+spinner + "); background-repeat:no-repeat; background-position:center;");
css = spinner + (css.indexOf("style=\"") >= 0 ? css.split("style=\"")[1] : "\" " + css);
s = "\
...<div id=\"ID_appletinfotablediv\" style=\"width:Wpx;height:Hpx;position:relative;font-size:14px;text-align:left\">IMG WAIT\
......<div id=\"ID_appletdiv\" style=\"z-index:" + Jmol._getZ(applet, "header") + ";width:100%;height:100%;position:absolute;top:0px;left:0px;" + css + ">";
var height = applet._height;
var width = applet._width;
if (typeof height !== "string" || height.indexOf("%") < 0)
height += "px";
if (typeof width !== "string" || width.indexOf("%") < 0)
width += "px";
s = s.replace(/IMG/, img).replace(/WAIT/, wait).replace(/Hpx/g, height).replace(/Wpx/g, width);
} else {
s = "\
......</div>\
......<div id=\"ID_2dappletdiv\" style=\"position:absolute;width:100%;height:100%;overflow:hidden;display:none\"></div>\
......<div id=\"ID_infotablediv\" style=\"width:100%;height:100%;position:absolute;top:0px;left:0px\">\
.........<div id=\"ID_infoheaderdiv\" style=\"height:20px;width:100%;background:yellow;display:none\"><span id=\"ID_infoheaderspan\"></span><span id=\"ID_infocheckboxspan\" style=\"position:absolute;text-align:right;right:1px;\"><a href=\"javascript:Jmol.showInfo(ID,false)\">[x]</a></span></div>\
.........<div id=\"ID_infodiv\" style=\"position:absolute;top:20px;bottom:0px;width:100%;height:100%;overflow:auto\"></div>\
......</div>\
...</div>";
}
return s.replace(/\.\.\./g,"").replace(/[\n\r]/g,"").replace(/ID/g, applet._id);
}
Jmol._hideLoadingSpinner = function(applet) {
if (applet._spinner)
Jmol.$css(Jmol.$(applet, "appletdiv"), {"background-image": ""});
}
Jmol._documentWrite = function(text) {
if (Jmol._document) {
if (Jmol._isXHTML && !Jmol._XhtmlElement) {
var s = document.getElementsByTagName("script");
Jmol._XhtmlElement = s.item(s.length - 1);
Jmol._XhtmlAppendChild = false;
}
if (Jmol._XhtmlElement)
Jmol._domWrite(text);
else
Jmol._document.write(text);
}
return text;
}
Jmol._domWrite = function(data) {
var pt = 0
var Ptr = []
Ptr[0] = 0
while (Ptr[0] < data.length) {
var child = Jmol._getDomElement(data, Ptr);
if (!child)
break;
if (Jmol._XhtmlAppendChild)
Jmol._XhtmlElement.appendChild(child);
else
Jmol._XhtmlElement.parentNode.insertBefore(child, _jmol.XhtmlElement);
}
}
Jmol._getDomElement = function(data, Ptr, closetag, lvel) {
// there is no "document.write" in XHTML
var e = document.createElement("span");
e.innerHTML = data;
Ptr[0] = data.length;
/*
// unnecessary ?
closetag || (closetag = "");
lvel || (lvel = 0);
var pt0 = Ptr[0];
var pt = pt0;
while (pt < data.length && data.charAt(pt) != "<")
pt++
if (pt != pt0) {
var text = data.substring(pt0, pt);
Ptr[0] = pt;
return document.createTextNode(text);
}
pt0 = ++pt;
var ch;
while (pt < data.length && "\n\r\t >".indexOf(ch = data.charAt(pt)) < 0)
pt++;
var tagname = data.substring(pt0, pt);
var e = (tagname == closetag || tagname == "/" ? ""
: document.createElementNS ? document.createElementNS('http://www.w3.org/1999/xhtml', tagname)
: document.createElement(tagname));
if (ch == ">") {
Ptr[0] = ++pt;
return e;
}
while (pt < data.length && (ch = data.charAt(pt)) != ">") {
while (pt < data.length && "\n\r\t ".indexOf(ch = data.charAt(pt)) >= 0)
pt++;
pt0 = pt;
while (pt < data.length && "\n\r\t =/>".indexOf(ch = data.charAt(pt)) < 0)
pt++;
var attrname = data.substring(pt0, pt).toLowerCase();
if (attrname && ch != "=")
e.setAttribute(attrname, "true");
while (pt < data.length && "\n\r\t ".indexOf(ch = data.charAt(pt)) >= 0)
pt++;
if (ch == "/") {
Ptr[0] = pt + 2;
return e;
} else if (ch == "=") {
var quote = data.charAt(++pt);
pt0 = ++pt;
while (pt < data.length && (ch = data.charAt(pt)) != quote)
pt++;
var attrvalue = data.substring(pt0, pt);
e.setAttribute(attrname, attrvalue);
pt++;
}
}
Ptr[0] = ++pt;
while (Ptr[0] < data.length) {
var child = Jmol._getDomElement(data, Ptr, "/" + tagname, lvel+1);
if (!child)
break;
e.appendChild(child);
}
*/
return e;
}
Jmol._setObject = function(obj, id, Info) {
obj._id = id;
obj.__Info = {};
Info.z && Info.zIndexBase && (Jmol._z = Jmol._getZOrders(Info.zIndexBase));
for (var i in Info)
obj.__Info[i] = Info[i];
(obj._z = Info.z) || Info.zIndexBase && (obj._z = obj.__Info.z = Jmol._getZOrders(Info.zIndexBase));
obj._width = Info.width;
obj._height = Info.height;
obj._noscript = !obj._isJava && Info.noscript;
obj._console = Info.console;
obj._cacheFiles = !!Info.cacheFiles;
obj._viewSet = (Info.viewSet == null || obj._isJava ? null : "Set" + Info.viewSet);
if (obj._viewSet != null) {
Jmol.View.__init(obj);
obj._currentView = null;
}
!Jmol._fileCache && obj._cacheFiles && (Jmol._fileCache = {});
if (!obj._console)
obj._console = obj._id + "_infodiv";
if (obj._console == "none")
obj._console = null;
obj._color = (Info.color ? Info.color.replace(/0x/,"#") : "#FFFFFF");
obj._disableInitialConsole = Info.disableInitialConsole;
obj._noMonitor = Info.disableJ2SLoadMonitor;
Jmol._j2sPath && (Info.j2sPath = Jmol._j2sPath);
obj._j2sPath = Info.j2sPath;
obj._coverImage = Info.coverImage;
obj._makeLiveImage = Info.makeLiveImage || Info.j2sPath + "/img/play_make_live.jpg";
obj._isCovered = !!obj._coverImage;
obj._deferApplet = Info.deferApplet || obj._isCovered && obj._isJava; // must do this if covered in Java
obj._deferUncover = Info.deferUncover && !obj._isJava; // can't do this with Java
obj._coverScript = Info.coverScript;
obj._coverTitle = Info.coverTitle;
if (!obj._coverTitle)
obj._coverTitle = (obj._deferApplet ? "activate 3D model" : "3D model is loading...")
obj._containerWidth = obj._width + ((obj._width==parseFloat(obj._width))? "px":"");
obj._containerHeight = obj._height + ((obj._height==parseFloat(obj._height))? "px":"");
obj._info = "";
obj._infoHeader = obj._jmolType + ' "' + obj._id + '"'
obj._hasOptions = Info.addSelectionOptions;
obj._defaultModel = Info.defaultModel;
obj._readyScript = (Info.script ? Info.script : "");
obj._readyFunction = Info.readyFunction;
if (obj._coverImage && !obj._deferApplet)
obj._readyScript += ";javascript " + id + "._displayCoverImage(false)";
obj._src = Info.src;
}
Jmol._addDefaultInfo = function(Info, DefaultInfo) {
for (var x in DefaultInfo)
if (typeof Info[x] == "undefined")
Info[x] = DefaultInfo[x];
Jmol._use && (Info.use = Jmol._use);
if (Info.use.indexOf("SIGNED") >= 0) {
if (Info.jarFile.indexOf("Signed") < 0)
Info.jarFile = Info.jarFile.replace(/Applet/,"AppletSigned");
Info.use = Info.use.replace(/SIGNED/, "JAVA");
Info.isSigned = true;
}
}
Jmol._syncedApplets = [];
Jmol._syncedCommands = [];
Jmol._syncedReady = [];
Jmol._syncReady = false;
Jmol._isJmolJSVSync = false;
Jmol._setReady = function(applet) {
Jmol._syncedReady[applet] = 1;
var n = 0;
for (var i = 0; i < Jmol._syncedApplets.length; i++) {
if (Jmol._syncedApplets[i] == applet._id) {
Jmol._syncedApplets[i] = applet;
Jmol._syncedReady[i] = 1;
} else if (!Jmol._syncedReady[i]) {
continue;
}
n++;
}
if (n != Jmol._syncedApplets.length)
return;
Jmol._setSyncReady();
}
Jmol._setDestroy = function(applet) {
//MSIE bug responds to any link click even if it is just a JavaScript call
if (Jmol.featureDetection.allowDestroy)
Jmol.$windowOn('beforeunload', function () { Jmol._destroy(applet); } );
}
Jmol._destroy = function(applet) {
try {
if (applet._appletPanel) applet._appletPanel.destroy();
applet._applet = null;
Jmol._unsetMouse(applet._canvas)
applet._canvas = null;
var n = 0;
for (var i = 0; i < Jmol._syncedApplets.length; i++) {
if (Jmol._syncedApplets[i] == applet)
Jmol._syncedApplets[i] = null;
if (Jmol._syncedApplets[i])
n++;
}
if (n > 0)
return;
Jmol._clearVars();
} catch(e){}
}
////////////// misc core functionality //////////////
Jmol._setSyncReady = function() {
Jmol._syncReady = true;
var s = ""
for (var i = 0; i < Jmol._syncedApplets.length; i++)
if (Jmol._syncedCommands[i])
s += "Jmol.script(Jmol._syncedApplets[" + i + "], Jmol._syncedCommands[" + i + "]);"
setTimeout(s, 50);
}
Jmol._mySyncCallback = function(appFullName,msg) {
app = Jmol._applets[appFullName];
if (app._viewSet) {
// when can we do this?
// if (app._viewType == "JSV" && !app._currentView.JMOL)
Jmol.View.updateFromSync(app, msg);
return;
}
if(!Jmol._syncReady || !Jmol._isJmolJSVSync)
return 1; // continue processing and ignore me
for (var i = 0; i < Jmol._syncedApplets.length; i++) {
if (msg.indexOf(Jmol._syncedApplets[i]._syncKeyword) >= 0)
Jmol._syncedApplets[i]._syncScript(msg);
}
return 0 // prevents further Jmol sync processing
}
Jmol._getElement = function(applet, what) {
var d = document.getElementById(applet._id + "_" + what);
return (d || {});
}
Jmol._evalJSON = function(s,key){
s = s + "";
if(!s)
return [];
if(s.charAt(0) != "{") {
if(s.indexOf(" | ") >= 0)
s = s.replace(/\ \|\ /g, "\n");
return s;
}
var A = (new Function( "return " + s ) )();
return (!A ? null : key && A[key] != undefined ? A[key] : A);
}
Jmol._sortMessages = function(A){
/*
* private function
*/
function _sortKey0(a,b){
return (a[0]<b[0]?1:a[0]>b[0]?-1:0);
}
if(!A || typeof (A) != "object")
return [];
var B = [];
for(var i = A.length - 1; i >= 0; i--)
for(var j = 0, jj= A[i].length; j < jj; j++)
B[B.length] = A[i][j];
if(B.length == 0)
return;
B = B.sort(_sortKey0);
return B;
}
//////////////////// mouse events //////////////////////
Jmol._setMouseOwner = function(who, tf) {
if (who == null || tf)
Jmol._mouseOwner = who;
else if (Jmol._mouseOwner == who)
Jmol._mouseOwner = null;
}
Jmol._jsGetMouseModifiers = function(ev) {
var modifiers = 0;
switch (ev.button) {
case 0:
modifiers = 16;//J.api.Event.MOUSE_LEFT;
break;
case 1:
modifiers = 8;//J.api.Event.MOUSE_MIDDLE;
break;
case 2:
modifiers = 4;//J.api.Event.MOUSE_RIGHT;
break;
}
if (ev.shiftKey)
modifiers += 1;//J.api.Event.SHIFT_MASK;
if (ev.altKey)
modifiers += 8;//J.api.Event.ALT_MASK;
if (ev.ctrlKey)
modifiers += 2;//J.api.Event.CTRL_MASK;
return modifiers;
}
Jmol._jsGetXY = function(canvas, ev) {
if (!canvas.applet._ready || Jmol._touching && ev.type.indexOf("touch") < 0)
return false;
//ev.preventDefault(); // removed 5/9/2015 -- caused loss of focus on text-box clicking in SwingJS
var offsets = Jmol.$offset(canvas.id);
var x, y;
var oe = ev.originalEvent;
// drag-drop jQuery event is missing pageX
ev.pageX || (ev.pageX = oe.pageX);
ev.pageY || (ev.pageY = oe.pageY);
Jmol._mousePageX = ev.pageX;
Jmol._mousePageY = ev.pageY;
if (oe.targetTouches && oe.targetTouches[0]) {
x = oe.targetTouches[0].pageX - offsets.left;
y = oe.targetTouches[0].pageY - offsets.top;
} else if (oe.changedTouches) {
x = oe.changedTouches[0].pageX - offsets.left;
y = oe.changedTouches[0].pageY - offsets.top;
} else {
x = ev.pageX - offsets.left;
y = ev.pageY - offsets.top;
}
return (x == undefined ? null : [Math.round(x), Math.round(y), Jmol._jsGetMouseModifiers(ev)]);
}
Jmol._setCursor = function(applet, c) {
if (applet._isJava || applet._readingLocal)
return;
var curs;
switch(c) {
case 1:
curs = "crosshair";
break;
case 3: // wait
curs = "wait";
Jmol.$setVisible(Jmol.$(applet, "waitimage"), true);
break;
case 8: // zoom
curs = "ns-resize";
break;
case 12: // hand
curs = "grab";
break;
case 13:
curs = "move";
break;
default:
Jmol.$setVisible(Jmol.$(applet, "waitimage"), false);
curs = "default";
break;
}
applet._canvas.style.cursor = curs;
}
Jmol._gestureUpdate = function(canvas, ev) {
ev.stopPropagation();
ev.preventDefault();
var oe = ev.originalEvent;
switch (ev.type) {
case "touchstart":
Jmol._touching = true;
break;
case "touchend":
Jmol._touching = false;
break;
}
if (!oe.touches || oe.touches.length != 2) return false;
switch (ev.type) {
case "touchstart":
canvas._touches = [[],[]];
break;
case "touchmove":
var offsets = Jmol.$offset(canvas.id);
var t0 = canvas._touches[0];
var t1 = canvas._touches[1];
t0.push([oe.touches[0].pageX - offsets.left, oe.touches[0].pageY - offsets.top]);
t1.push([oe.touches[1].pageX - offsets.left, oe.touches[1].pageY - offsets.top]);
var n = t0.length;
if (n > 3) {
t0.shift();
t1.shift();
}
if (n >= 2)
canvas.applet._processGesture(canvas._touches);
break;
}
return true;
}
Jmol._jsSetMouse = function(canvas) {
var doIgnore = function(ev) { return (!ev.target || ("" + ev.target.className).indexOf("swingjs-ui") >= 0) };
Jmol.$bind(canvas, 'mousedown touchstart', function(ev) {
if (doIgnore(ev))
return true;
Jmol._setMouseOwner(canvas, true);
ev.stopPropagation();
var ui = ev.target["data-UI"];
if (!ui || !ui.handleJSEvent(canvas, 501, ev))
ev.preventDefault();
canvas.isDragging = true;
if ((ev.type == "touchstart") && Jmol._gestureUpdate(canvas, ev))
return !!ui;
Jmol._setConsoleDiv(canvas.applet._console);
var xym = Jmol._jsGetXY(canvas, ev);
if(xym) {
if (ev.button != 2)
Jmol.Swing.hideMenus(canvas.applet);
canvas.applet._processEvent(501, xym); //java.awt.Event.MOUSE_DOWN
}
return !!ui;
});
Jmol.$bind(canvas, 'mouseup touchend', function(ev) {
if (doIgnore(ev))
return true;
Jmol._setMouseOwner(null);
ev.stopPropagation();
var ui = ev.target["data-UI"];
if (!ui || !ui.handleJSEvent(canvas, 502, ev))
ev.preventDefault();
canvas.isDragging = false;
if (ev.type == "touchend" && Jmol._gestureUpdate(canvas, ev))
return !!ui;
var xym = Jmol._jsGetXY(canvas, ev);
if(xym)
canvas.applet._processEvent(502, xym);//java.awt.Event.MOUSE_UP
return !!ui;
});
Jmol.$bind(canvas, 'mousemove touchmove', function(ev) { // touchmove
if (doIgnore(ev))
return true;
// defer to console or menu when dragging within this canvas
if (Jmol._mouseOwner && Jmol._mouseOwner != canvas && Jmol._mouseOwner.isDragging) {
if (!Jmol._mouseOwner.mouseMove)
return true;
Jmol._mouseOwner.mouseMove(ev);
return false;
}
return Jmol._drag(canvas, ev);
});
Jmol._drag = function(canvas, ev) {
ev.stopPropagation();
ev.preventDefault();
var isTouch = (ev.type == "touchmove");
if (isTouch && Jmol._gestureUpdate(canvas, ev))
return false;
var xym = Jmol._jsGetXY(canvas, ev);
if(!xym) return false;
if (!canvas.isDragging)
xym[2] = 0;
var ui = ev.target["data-UI"];
if (canvas.isdragging && (!ui || !ui.handleJSEvent(canvas, 506, ev))) {}
canvas.applet._processEvent((canvas.isDragging ? 506 : 503), xym); // java.awt.Event.MOUSE_DRAG : java.awt.Event.MOUSE_MOVE
return !!ui;
}
Jmol.$bind(canvas, 'DOMMouseScroll mousewheel', function(ev) { // Zoom
if (doIgnore(ev))
return true;
ev.stopPropagation();
ev.preventDefault();
// Webkit or Firefox
canvas.isDragging = false;
var oe = ev.originalEvent;
var scroll = (oe.detail ? oe.detail : (Jmol.featureDetection.os == "mac" ? 1 : -1) * oe.wheelDelta); // Mac and PC are reverse; but
var modifiers = Jmol._jsGetMouseModifiers(ev);
canvas.applet._processEvent(507,[scroll < 0 ? -1 : 1,0,modifiers]);
return false;
});
// context menu is fired on mouse down, not up, and it's handled already anyway.
Jmol.$bind(canvas, "contextmenu", function() {return false;});
Jmol.$bind(canvas, 'mouseout', function(ev) {
if (doIgnore(ev))
return true;
if (Jmol._mouseOwner && !Jmol._mouseOwner.mouseMove)
Jmol._setMouseOwner(null);
if (canvas.applet._appletPanel)
canvas.applet._appletPanel.startHoverWatcher(false);
//canvas.isDragging = false;
var xym = Jmol._jsGetXY(canvas, ev);
if (!xym)
return false;
//canvas.applet._processEvent(502, xym);//J.api.Event.MOUSE_UP
//canvas.applet._processEvent(505, xym);//J.api.Event.MOUSE_EXITED
return false;
});
Jmol.$bind(canvas, 'mouseenter', function(ev) {
if (doIgnore(ev))
return true;
if (canvas.applet._appletPanel)
canvas.applet._appletPanel.startHoverWatcher(true);
if (ev.buttons === 0 || ev.which === 0) {
canvas.isDragging = false;
var xym = Jmol._jsGetXY(canvas, ev);
if (!xym)
return false;
canvas.applet._processEvent(504, xym);//J.api.Event.MOUSE_ENTERED
canvas.applet._processEvent(502, xym);//J.api.Event.MOUSE_UP
return false;
}
});
Jmol.$bind(canvas, 'mousemoveoutjsmol', function(evspecial, target, ev) {
if (doIgnore(ev))
return true;
if (canvas == Jmol._mouseOwner && canvas.isDragging) {
return Jmol._drag(canvas, ev);
}
});
if (canvas.applet._is2D)
Jmol.$resize(function() {
if (!canvas.applet)
return;
canvas.applet._resize();
});
Jmol.$bind('body', 'mouseup touchend', function(ev) {
if (doIgnore(ev))
return true;
if (canvas.applet)
canvas.isDragging = false;
Jmol._setMouseOwner(null);
});
}
Jmol._jsUnsetMouse = function(canvas) {
canvas.applet = null;
Jmol.$bind(canvas, 'mousedown touchstart mousemove touchmove mouseup touchend DOMMouseScroll mousewheel contextmenu mouseout mouseenter', null);
Jmol._setMouseOwner(null);
}
////// Jmol.Swing interface for Javascript implementation of Swing dialogs and menus
Jmol.Swing = {
// a static class
count:0,
menuInitialized:0,
menuCounter:0,
htDialogs:{}
};
(function(Swing) {
SwingController = Swing; // see javajs.api.SwingController
Swing.setDraggable = function(Obj) {
var proto = Obj.prototype;
if (proto.setContainer)
return;
// for menus, console, and
proto.setContainer = function(container) {
this.container = container;
container.obj = this;
this.isDragging = false;
this.ignoreMouse = false;
var me = this;
container.bind('mousedown touchstart', function(ev) {
if (me.ignoreMouse) {
me.ignoreMouse = false;
return true;
}
Jmol._setMouseOwner(me, true);
me.isDragging = true;
me.pageX = ev.pageX;
me.pageY = ev.pageY;
return false;
});
container.bind('mousemove touchmove', function(ev) {
if (me.isDragging && Jmol._mouseOwner == me) {
me.mouseMove(ev);
return false;
}
});
container.bind('mouseup touchend', function(ev) {
me.mouseUp(ev);
Jmol._setMouseOwner(null);
});
};
proto.mouseUp = function(ev) {
if (this.isDragging && Jmol._mouseOwner == this) {
this.pageX0 += (ev.pageX - this.pageX);
this.pageY0 += (ev.pageY - this.pageY);
this.isDragging = false;
return false;
}
Jmol._setMouseOwner(null);
}
proto.setPosition = function() {
if (Jmol._mousePageX === null) {
var id = this.applet._id + "_" + (this.applet._is2D ? "canvas2d" : "canvas");
var offsets = Jmol.$offset(id);
Jmol._mousePageX = offsets.left;
Jmol._mousePageY = offsets.top;
}
this.pageX0 = Jmol._mousePageX;
this.pageY0 = Jmol._mousePageY;
var pos = { top: Jmol._mousePageY + 'px', left: Jmol._mousePageX + 'px' };
this.container.css(pos);
};
proto.mouseMove = function(ev) {
if (this.isDragging && Jmol._mouseOwner == this) {
this.timestamp = System.currentTimeMillis(); // used for menu closure
var x = this.pageX0 + (ev.pageX - this.pageX);
var y = this.pageY0 + (ev.pageY - this.pageY);
Jmol._mousePageX = x;
Jmol._mousePageY = y;
this.container.css({ top: y + 'px', left: x + 'px' })
}
};
proto.dragBind = function(isBind) {
this.applet._ignoreMouse = !isBind;
this.container.unbind('mousemoveoutjsmol');
this.container.unbind('touchmoveoutjsmol');
this.container.unbind('mouseupoutjsmol');
this.container.unbind('touchendoutjsmol');
Jmol._setMouseOwner(null);
if (isBind) {
var me = this;
this.container.bind('mousemoveoutjsmol touchmoveoutjsmol', function(evspecial, target, ev) {
me.mouseMove(ev);
});
this.container.bind('mouseupoutjsmol touchendoutjsmol', function(evspecial, target, ev) {
me.mouseUp(ev);
});
}
};
}
// Dialog //
Swing.JSDialog = function () {
}
Swing.setDraggable(Swing.JSDialog);
///// calls from javajs and other Java-derived packages /////
Swing.getScreenDimensions = function(d) {
d.width = $(window).width();
d.height = $(window).height();
}
Swing.dispose = function(dialog) {
Jmol.$remove(dialog.id + "_mover");
delete Swing.htDialogs[dialog.id]
dialog.container.obj.dragBind(false);
// var btns = $("#" + dialog.id + " *[id^='J']"); // add descendents with id starting with "J"
// for (var i = btns.length; --i >= 0;)
// delete Dialog.htDialogs[btns[i].id]
//System.out.println("JSmolCore.js: dispose " + dialog.id)
}
Swing.register = function(dialog, type) {
dialog.id = type + (++Swing.count);
Swing.htDialogs[dialog.id] = dialog;
//System.out.println("JSmolCore.js: register " + dialog.id)
}
Swing.setDialog = function(dialog) {
Jmol._setMouseOwner(null);
Jmol.$remove(dialog.id);
//System.out.println("removed " + dialog.id)
var id = dialog.id + "_mover";
var container = Jmol._$(id);
var jd;
//System.out.println("JSmolCore.js: setDialog " + dialog.id);
if (container[0]) {
container.html(dialog.html);
jd = container[0].jd;
} else {
Jmol.$after("body","<div id='" + id + "' style='position:absolute;left:0px;top:0px;'>" + dialog.html + "</div>");
var jd = new Swing.JSDialog();
container = Jmol._$(id);
dialog.container = container;
jd.applet = dialog.manager.vwr.html5Applet;
jd.setContainer(container);
jd.dialog = dialog;
jd.setPosition();
jd.dragBind(true);
container[0].jd = jd;
}
Jmol.$bind("#" + dialog.id + " .JButton", "mousedown touchstart", function(event) { jd.ignoreMouse=true });
Jmol.$bind("#" + dialog.id + " .JComboBox", "mousedown touchstart", function(event) { jd.ignoreMouse=true });
Jmol.$bind("#" + dialog.id + " .JCheckBox", "mousedown touchstart", function(event) { jd.ignoreMouse=true });
Jmol.$bind("#" + dialog.id + " .JTextField", "mousedown touchstart", function(event) { jd.ignoreMouse=true });
Jmol.$bind("#" + dialog.id + " .JTable", "mousedown touchstart", function(event) { jd.ignoreMouse=true });
Jmol.$bind("#" + dialog.id + " .JScrollPane", "mousedown touchstart", function(event) { jd.ignoreMouse=true });
Jmol.$bind("#" + dialog.id + " .JEditorPane", "mousedown touchstart", function(event) { jd.ignoreMouse=true });
}
Swing.setSelected = function(chk) {
Jmol.$prop(chk.id, 'checked', !!chk.selected);
}
Swing.setSelectedIndex = function(cmb) {
Jmol.$prop(cmb.id, 'selectedIndex', cmb.selectedIndex);
}
Swing.setText = function(btn) {
Jmol.$prop(btn.id, 'value', btn.text);
}
Swing.setVisible = function(c) {
Jmol.$setVisible(c.id, c.visible);
}
Swing.setEnabled = function(c) {
Jmol.$setEnabled(c.id, c.enabled);
}
/// callbacks from the HTML elements ////
Swing.click = function(element, keyEvent) {
var component = Swing.htDialogs[element.id];
if (component) {
//System.out.println("click " + element + " " + component)
var info = component.toString();
// table cells will have an id but are not registered
if (info.indexOf("JCheck") >= 0) {
component.selected = element.checked;
} else if (info.indexOf("JCombo") >= 0) {
component.selectedIndex = element.selectedIndex;
} else if (component.text != null) { // JButton, JTextField
component.text = element.value;
if (keyEvent && ((keyEvent.charCode || keyEvent.keyCode) != 13))
return;
}
}
var dialog = Swing.htDialogs[Jmol.$getAncestorDiv(element.id, "JDialog").id];
var key = (component ? component.name : dialog.registryKey + "/" + element.id);
//System.out.println("JSmolCore.js: click " + key);
dialog.manager.actionPerformed(key);
}
Swing.setFront = function(dialog) {
var applet = dialog.manager.vwr.html5Applet;
if (dialog.zIndex != Jmol._getZ(applet, "dialog"))
dialog.zIndex = Jmol._incrZ(applet, "dialog");
dialog.container && ((dialog.container[0] || dialog.container).style.zIndex = dialog.zIndex);
}
Swing.hideMenus = function(applet) {
// called from LEFT-DOWN mouse event
var menus = applet._menus;
if (menus)
for (var i in menus)
if (menus[i].visible)
Swing.hideMenu(menus[i]);
}
Swing.windowClosing = function(element) {
var dialog = Swing.htDialogs[Jmol.$getAncestorDiv(element.id, "JDialog").id];
if (dialog.registryKey) {
//System.out.println("JSmolCore.js: windowClosing " + dialog.registryKey);
dialog.manager.processWindowClosing(dialog.registryKey);
} else {
//System.out.println("JSmolCore.js: windowClosing " + dialog.title);
dialog.dispose();
}
}
})(Jmol.Swing);
Jmol._track = function(applet) {
// this function inserts an iFrame that can be used to track your page's applet use.
// By default it tracks to a page at St. Olaf College, but you can change that.
// and you can use
//
// delete Jmol._tracker
//
// yourself to not have you page execute this
//
if (Jmol._tracker){
try {
var url = Jmol._tracker + "&applet=" + applet._jmolType + "&version=" + Jmol._version
+ "&appver=" + Jmol.___JmolVersion + "&url=" + encodeURIComponent(document.location.href);
var s = '<iframe style="display:none" width="0" height="0" frameborder="0" tabindex="-1" src="' + url + '"></iframe>'
Jmol.$after("body", s);
} catch (e) {
// ignore
}
delete Jmol._tracker;
}
return applet;
}
var __profiling;
Jmol.getProfile = function(doProfile) {
if (!self.Clazz || !self.JSON)
return;
if (!__profiling)
Clazz._startProfiling(__profiling = (arguments.length == 0 || doProfile));
return Clazz.getProfile();
}
Jmol._getInChIKey = function(applet, data) {
if (data.indexOf("MOL=") >= 0)
data = data.split("MOL=")[1].split("\"")[0];
}
Jmol._getAttr = function(s, a) {
var pt = s.indexOf(a + "=");
return (pt >= 0 && (pt = s.indexOf('"', pt)) >= 0
? s.substring(pt+1, s.indexOf('"', pt+1)) : null);
}
Jmol.User = {
viewUpdatedCallback: null
}
Jmol.View = {
// The objective of Jmol.View is to coordinate
// asynchronous applet loading and atom/peak picking
// among any combination of Jmol, JME, and JSV.
//
// basic element is a view object:
// view = {
// viewType1: viewRecord1,
// viewType2: viewRecord2,
// viewType3: viewRecord3
// }
// where viewType is one of (Jmol, JME, JSV)
// and a viewRecord is an object
// with elements .chemID, .applet, .data, .script
//
// Jmol.View.sets is a list of cached views[0..n]
// for a given group of applet objects with common Info.viewSet
//
// Bob Hanson 1/22/2014 7:05:38 AM
count: 0,
applets: {},
sets: {}
};
(function(View) {
// methods called from other modules have no "_" in their name
View.resetView = function(applet, appletNot) {
debugger;
if (appletNot) {
if (!appletNot._viewSet)
return;
var set = Jmol.View.applets[appletNot._viewSet]
for (var applet in set) {
if (applet == appletNot)
continue;
Jmol.View.resetView(applet);
}
return;
}
if (applet) {
applet._reset();
Jmol.View.updateView(applet);
}
}
View.updateView = function(applet, Info, _View_updateView) {
// Info.chemID, Info.data, possibly Info.viewID if no chemID
// return from applet after asynchronous download of new data
if (applet._viewSet == null)
return;
Info || (Info = {});
Info.chemID || (applet._searchQuery = null);
Info.data || (Info.data = "N/A");
Info.type = applet._viewType;
if((applet._currentView = View.__findView(applet._viewSet, Info)) == null)
applet._currentView = View.__createViewSet(applet._viewSet, Info.chemID, Info.viewID || Info.chemID);
applet._currentView[Info.type].data = Info.data;
applet._currentView[Info.type].smiles = applet._getSmiles();
if (Jmol.User.viewUpdatedCallback)
Jmol.User.viewUpdatedCallback(applet, "updateView");
View.__setView(applet._currentView, applet, false);
}
View.updateFromSync = function(applet, msg) {
applet._updateMsg = msg;
var id = Jmol._getAttr(msg, "sourceID") || Jmol._getAttr(msg, "file");
if (!id)
return;
var view = View.__findView(applet._viewSet, {viewID:id});
if (view == null)
return Jmol.updateView(applet, msg); // JSV has been updated internally
if (view != applet._currentView)
View.__setView(view, applet, true);
var A = ((id = Jmol._getAttr(msg, "atoms")) && msg.indexOf("selectionhalos ON") >= 0
? eval("[" + id + "]") : []);
setTimeout(function(){if (applet._currentView == view)View.updateAtomPick(applet, A)}, 10);
if (Jmol.User.viewUpdatedCallback)
Jmol.User.viewUpdatedCallback(applet, "updateFromSync");
}
View.updateAtomPick = function(applet, A, _View_updateAtomPick) {
var view = applet._currentView;
if (view == null)
return;
for (var viewType in view) {
if (viewType != "info" && view[viewType].applet != applet)
view[viewType].applet._updateAtomPick(A);
}
if (Jmol.User.viewUpdatedCallback)
Jmol.User.viewUpdatedCallback(applet, "updateAtomPick");
}
View.dumpViews = function(setID) {
var views = View.sets[setID];
if (!views)
return;
var s = "View set " + setID + ":\n";
var applets = View.applets[setID];
for (var i in applets)
s += "\napplet " + applets[i]._id
+ " currentView=" + (applets[i]._currentView ? applets[i]._currentView.info.viewID : null);
for (var i = views.length; --i >= 0;) {
var view = views[i];
s += "\n\n<b>view=" + i
+ " viewID=" + view.info.viewID
+ " chemID=" + view.info.chemID + "</b>\n"
var v;
for (var viewType in view)
if (viewType != "info")
s += "\nview=" + i + " type=" + viewType + " applet="
+ ((v = view[viewType]).applet ? v.applet._id : null)
+ " SMILES=" + v.smiles + "\n"
+ " atomMap=" + JSON.stringify(v.atomMap) + "\n"
+ " data=\n" + v.data + "\n"
}
return s
}
// methods starting with "__" are "private" to JSmolCore.js
View.__init = function(applet) {
var set = applet._viewSet;
var a = View.applets;
a[set] || (a[set] = {});
a[set][applet._viewType] = applet;
}
View.__findView = function(set, Info) {
var views = View.sets[set];
if (views == null)
views = View.sets[set] = [];
for (var i = views.length; --i >= 0;) {
var view = views[i];
if (Info.viewID) {
if (view.info.viewID == Info.viewID)
return view;
} else if (Info.chemID != null && Info.chemID == view.info.chemID) {
return view;
} else {
for (var viewType in view) {
if (viewType != "info") {
if (Info.data != null && view[viewType].data != null ? Info.data == view[viewType].data
: Info.type == viewType)
return view;
}
}
}
}
return null;
}
View.__createViewSet = function(set, chemID, viewID, _createViewSet) {
View.count++;
var view = {info:{chemID: chemID, viewID: viewID || "model_" + View.count}};
for (var id in Jmol._applets) {
var a = Jmol._applets[id];
if (a._viewSet == set)
view[a._viewType] = {applet:a, data: null};
}
View.sets[set].push(view);
return view;
}
View.__setView = function(view, applet, isSwitch, _setView) {
// called from Jmol._searchMol and Jmol.View.setCurrentView
// to notify the applets in the set that there may be new data for them
// skip the originating applet itself and cases where the data has not changed.
// stop at first null data, because that will initiate some sort of asynchronous
// call that will be back here afterward.
for (var viewType in view) {
if (viewType == "info")
continue;
var rec = view[viewType];
var a = rec.applet;
var modified = (isSwitch || a != null && a._molData == "<modified>");
if (a == null || a == applet && !modified)
continue; // may be a mol3d required by JSV but not having a corresponding applet
var wasNull = (rec.data == null);
var haveView = (a._currentView != null);
a._currentView = view;
if (haveView && view[viewType].data == rec.data && !wasNull & !modified)
continue;
a._loadModelFromView(view);
if (wasNull)
break;
}
// Either all are taken care of or one was null,
// in which case we have started an asynchronous
// process to get the data, and we can quit here.
// In either case, we are done.
}
}) (Jmol.View);
Jmol.Cache = {fileCache: {}};
Jmol.Cache.get = function(filename) {
return Jmol.Cache.fileCache[filename];
}
Jmol.Cache.put = function(filename, data) {
Jmol.Cache.fileCache[filename] = data;
}
Jmol.Cache.setDragDrop = function(me) {
Jmol.$appEvent(me, "appletdiv", "dragover", function(e) {
e = e.originalEvent;
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
});
Jmol.$appEvent(me, "appletdiv", "drop", function(e) {
var oe = e.originalEvent;
oe.stopPropagation();
oe.preventDefault();
var file = oe.dataTransfer.files[0];
if (file == null) {
// FF and Chrome will drop an image here
// but it will be only a URL, not an actual file.
try {
file = "" + oe.dataTransfer.getData("text");
if (file.indexOf("file:/") == 0 || file.indexOf("http:/") == 0 || file.indexOf("https:/") == 0) {
me._scriptLoad(file);
return;
}
} catch(e) {
return;
}
// some other format
return;
}
// MSIE will drop an image this way, though, and load it!
var reader = new FileReader();
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) {
var cacheName = "cache://DROP_" + file.name;
var bytes = Clazz.newByteArray(-1, evt.target.result);
if (!cacheName.endsWith(".spt"))
me._appletPanel.cacheFileByName("cache://DROP_*",false);
if (me._viewType == "JSV" || cacheName.endsWith(".jdx")) // shared by Jmol and JSV
Jmol.Cache.put(cacheName, bytes);
else
me._appletPanel.cachePut(cacheName, bytes);
var xym = Jmol._jsGetXY(me._canvas, e);
if(xym && (!me._appletPanel.setStatusDragDropped || me._appletPanel.setStatusDragDropped(0, xym[0], xym[1], cacheName))) {
me._appletPanel.openFileAsyncSpecial(cacheName, 1);
}
}
};
reader.readAsArrayBuffer(file);
});
}
})(Jmol, jQuery);
Jmol._debugCode = false;
// JSmol.js -- Jmol pure JavaScript version
// author: Bob Hanson, hansonr@stolaf.edu 4/16/2012
// author: Takanori Nakane biochem_fan 6/12/2012
// BH 12/17/2015 4:43:05 PM adding Jmol._requestRepaint to allow for MSIE9 not having 3imationFrame
// BH 12/13/2015 11:44:39 AM using requestAnimationFrame instead of setTimeout (fixes Chrome slowness)
// BH 10/12/2015 1:15:39 PM fix for set echo image in JavaScript
// BH 6/12/2015 6:08:08 AM image loading from PNGJ file bytes using data uri not working
// BH 3/28/2015 6:18:33 AM refactoring to generalize for non-Jmol-related SwingJS applications
// BH 9/6/2014 5:42:32 PM two-point gestures broken
// BH 5/8/2014 11:16:40 AM j2sPath starting with "/" fails to add idiom
// BH 1/16/2014 8:44:03 PM __execDelayMS = 100; // FF bug when loading into a tab that is not
// immediately focused and not using jQuery for adding the applet and having
// multiple applets.
// BH 12/6/2013 10:12:30 AM adding corejmoljsv.z.js
// BH 9/17/2013 10:18:40 AM file transfer functions moved to JSmolCore
// BH 3/5/2013 9:54:16 PM added support for a cover image: Info.coverImage, coverScript, coverTitle, deferApplet, deferUncover
// BH 1/3/2013 4:54:01 AM mouse binding should return false -- see d.bind(...), and d.bind("contextmenu") is not necessary
// This library requires prior inclusion of
// jQuery 9 or higher
// JSmoljQueryExt.js
// JSmolCore.js
// j2sjmol.js (Clazz and associated classes)
// these:
//
// JSmolApplet.js
// JSmolApi.js
// JSmolThree.js
// JSmolGLmol.js
//
// are optional
;(function (Jmol) {
Jmol._isAsync = false; // testing only
Jmol._asyncCallbacks = {};
Jmol._coreFiles = []; // required for package.js
///////////////////
// This section provides an asynchronous loading sequence
//
// methods and fields starting with double underscore are private to this .js file
var __clazzLoaded = false;
var __execLog = [];
var __execStack = [];
var __execTimer = 0;
var __coreSet = [];
var __coreMore = [];
var __execDelayMS = 100; // must be > 55 ms for FF
var __nextExecution = function(trigger) {
arguments.length || (trigger = true);
delete __execTimer;
var es = __execStack;
var e;
while (es.length > 0 && (e = es[0])[4] == "done")
es.shift();
if (es.length == 0)
return;
if (!Jmol._isAsync && !trigger) {
setTimeout(__nextExecution,10)
return;
}
e.push("done");
var s = "JSmol exec " + e[0]._id + " " + e[3] + " " + e[2];
if (self.System)
System.out.println(s);
//alert(s)
if (self.console)console.log(s + " -- OK")
__execLog.push(s);
e[1](e[0],e[2]);
};
var __loadClazz = function(applet) {
if (!__clazzLoaded) {
__clazzLoaded = true;
// create the Clazz object
LoadClazz();
if (applet._noMonitor)
Clazz._LoaderProgressMonitor.showStatus = function() {}
LoadClazz = null;
if (applet.__Info.uncompressed)
Clazz.loadClass(); // for now; allows for no compression
Clazz._Loader.onGlobalLoaded = function (file) {
// not really.... just nothing more yet to do yet
Clazz._LoaderProgressMonitor.showStatus("Application loaded.", true);
if (!Jmol._debugCode || !Jmol.haveCore) {
Jmol.haveCore = true;
__nextExecution();
}
};
// load package.js and j2s/core/core.z.js
Clazz._Loader.loadPackageClasspath("java", null, true, __nextExecution);
return;
}
__nextExecution();
};
var __loadClass = function(applet, javaClass) {
Clazz._Loader.loadClass(javaClass, function() {__nextExecution()});
};
Jmol.showExecLog = function() { return __execLog.join("\n") };
Jmol._addExec = function(e) {
e[1] || (e[1] = __loadClass);
var s = "JSmol load " + e[0]._id + " " + e[3];
if (self.console)console.log(s + "...")
__execLog.push(s);
__execStack.push(e);
}
Jmol._addCoreFile = function(type, path, more) {
// BH 3/15: idea here is that when both Jmol and JSV are present,
// we want to load a common core file -- jmoljsv.z.js --
// instead of just one. Otherwise we do a lot of duplication.
// It is not clear how this would play with other concurrent
// apps. So this will take some thinking. But the basic idea is that
// core file to load is
type = type.toLowerCase().split(".")[0]; // package name only
// return if type is already part of the set.
if (__coreSet.join("").indexOf(type) >= 0) return;
// create a concatenated lower-case name for a core file that includes
// all Java applets on the page
__coreSet.push(type);
__coreSet.sort();
Jmol._coreFiles = [path + "/core/core" + __coreSet.join("") + ".z.js" ];
if (more && (more = more.split(" ")))
for (var i = 0; i < more.length; i++)
if (__coreMore.join("").indexOf(more[i]) < 0)
__coreMore.push(path + "/core/core" + more[i] + ".z.js")
for (var i = 0; i < __coreMore.length; i++)
Jmol._coreFiles.push(__coreMore[i]);
}
Jmol._Canvas2D = function(id, Info, type, checkOnly){
// type: Jmol or JSV
this._uniqueId = ("" + Math.random()).substring(3);
this._id = id;
this._is2D = true;
this._isJava = false;
this._jmolType = "Jmol._Canvas2D (" + type + ")";
this._isLayered = Info._isLayered || false;
this._isSwing = Info._isSwing || false;
this._isJSV = Info._isJSV || false;
this._isAstex = Info._isAstex || false;
this._platform = Info._platform || "";
if (checkOnly)
return this;
window[id] = this;
this._createCanvas(id, Info);
if (!Jmol._document || this._deferApplet)
return this;
this._init();
return this;
};
Jmol._setAppletParams = function(availableParams, params, Info, isHashtable) {
for (var i in Info)
if(!availableParams || availableParams.indexOf(";" + i.toLowerCase() + ";") >= 0){
if (Info[i] == null || i == "language" && !Jmol.featureDetection.supportsLocalization())
continue;
if (isHashtable)
params.put(i, (Info[i] === true ? Boolean.TRUE: Info[i] === false ? Boolean.FALSE : Info[i]))
else
params[i] = Info[i];
}
}
Jmol._jsSetPrototype = function(proto) {
proto._init = function() {
this._setupJS();
this._showInfo(true);
if (this._disableInitialConsole)
this._showInfo(false);
};
proto._createCanvas = function(id, Info, glmol) {
Jmol._setObject(this, id, Info);
if (glmol) {
this._GLmol = glmol;
this._GLmol.applet = this;
this._GLmol.id = this._id;
}
var t = Jmol._getWrapper(this, true);
if (this._deferApplet) {
} else if (Jmol._document) {
Jmol._documentWrite(t);
this._newCanvas(false);
t = "";
} else {
this._deferApplet = true;
t += '<script type="text/javascript">' + id + '._cover(false)</script>';
}
t += Jmol._getWrapper(this, false);
if (Info.addSelectionOptions)
t += Jmol._getGrabberOptions(this);
if (Jmol._debugAlert && !Jmol._document)
alert(t);
this._code = Jmol._documentWrite(t);
};
proto._newCanvas = function(doReplace) {
if (this._is2D)
this._createCanvas2d(doReplace);
else
this._GLmol.create();
};
//////// swingjs.api.HTML5Applet interface
proto._getHtml5Canvas = function() { return this._canvas };
proto._getWidth = function() { return this._canvas.width };
proto._getHeight = function() { return this._canvas.height };
proto._getContentLayer = function() { return Jmol.$(this, "contentLayer")[0] };
proto._repaintNow = function() { Jmol._repaint(this, false) };
////////
proto._createCanvas2d = function(doReplace) {
var container = Jmol.$(this, "appletdiv");
//if (doReplace) {
try {
container[0].removeChild(this._canvas);
if (this._canvas.frontLayer)
container[0].removeChild(this._canvas.frontLayer);
if (this._canvas.rearLayer)
container[0].removeChild(this._canvas.rearLayer);
if (this._canvas.contentLayer)
container[0].removeChild(this._canvas.contentLayer);
Jmol._jsUnsetMouse(this._mouseInterface);
} catch (e) {}
//}
var w = Math.round(container.width());
var h = Math.round(container.height());
var canvas = document.createElement( 'canvas' );
canvas.applet = this;
this._canvas = canvas;
canvas.style.width = "100%";
canvas.style.height = "100%";
canvas.width = w;
canvas.height = h; // w and h used in setScreenDimension
canvas.id = this._id + "_canvas2d";
container.append(canvas);
Jmol._$(canvas.id).css({"z-index":Jmol._getZ(this, "main")});
if (this._isLayered){
var img = document.createElement("div");
canvas.contentLayer = img;
img.id = this._id + "_contentLayer";
container.append(img);
Jmol._$(img.id).css({zIndex:Jmol._getZ(this, "image"),position:"absolute",left:"0px",top:"0px",
width:(this._isSwing ? w : 0) + "px", height:(this._isSwing ? h : 0) +"px", overflow:"hidden"});
if (this._isSwing) {
var d = document.createElement("div");
d.id = this._id + "_swingdiv";
Jmol._$(this._id + "_appletinfotablediv").append(d);
Jmol._$(d.id).css({zIndex:Jmol._getZ(this, "rear"),position:"absolute",left:"0px",top:"0px", width:w +"px", height:h+"px", overflow:"hidden"});
this._mouseInterface = canvas.contentLayer;
canvas.contentLayer.applet = this;
} else {
this._mouseInterface = this._getLayer("front", container, w, h, false);
}
//this._getLayer("rear", container, w, h, true);
//Jmol._$(canvas.id).css({background:"rgb(0,0,0,0.001)", "z-index":Jmol._z.main});
} else {
this._mouseInterface = canvas;
}
Jmol._jsSetMouse(this._mouseInterface);
}
proto._getLayer = function(name, container, w, h, isOpaque) {
var c = document.createElement("canvas");
this._canvas[name + "Layer"] = c;
c.style.width = "100%";
c.style.height = "100%";
c.id = this._id + "_" + name + "Layer";
c.width = w;
c.height = h; // w and h used in setScreenDimension
container.append(c);
c.applet = this;
Jmol._$(c.id).css({background:(isOpaque ? "rgb(0,0,0,1)" : "rgb(0,0,0,0.001)"), "z-index": Jmol._getZ(this,name),position:"absolute",left:"0px",top:"0px",overflow:"hidden"});
return c;
}
proto._setupJS = function() {
window["j2s.lib"] = {
base : this._j2sPath + "/",
alias : ".",
console : this._console,
monitorZIndex : Jmol._getZ(this, "monitorZIndex")
};
var isFirst = (__execStack.length == 0);
if (isFirst)
Jmol._addExec([this, __loadClazz, null, "loadClazz"]);
this._addCoreFiles();
Jmol._addExec([this, this.__startAppletJS, null, "start applet"])
this._isSigned = true; // access all files via URL hook
this._ready = false;
this._applet = null;
this._canScript = function(script) {return true;};
this._savedOrientations = [];
__execTimer && clearTimeout(__execTimer);
__execTimer = setTimeout(__nextExecution, __execDelayMS);
};
proto.__startAppletJS = function(applet) {
if (Jmol._version.indexOf("$Date: ") == 0)
Jmol._version = (Jmol._version.substring(7) + " -").split(" -")[0] + " (JSmol/j2s)"
var viewerOptions = Clazz._4Name("java.util.Hashtable").newInstance();
Jmol._setAppletParams(applet._availableParams, viewerOptions, applet.__Info, true);
viewerOptions.put("appletReadyCallback","Jmol._readyCallback");
viewerOptions.put("applet", true);
viewerOptions.put("name", applet._id);// + "_object");
viewerOptions.put("syncId", Jmol._syncId);
if (Jmol._isAsync)
viewerOptions.put("async", true);
if (applet._color)
viewerOptions.put("bgcolor", applet._color);
if (applet._startupScript)
viewerOptions.put("script", applet._startupScript)
if (Jmol._syncedApplets.length)
viewerOptions.put("synccallback", "Jmol._mySyncCallback");
viewerOptions.put("signedApplet", "true");
viewerOptions.put("platform", applet._platform);
if (applet._is2D)
viewerOptions.put("display",applet._id + "_canvas2d");
// viewerOptions.put("repaintManager", "J.render");
viewerOptions.put("documentBase", document.location.href);
var codePath = applet._j2sPath + "/";
if (codePath.indexOf("://") < 0) {
var base = document.location.href.split("#")[0].split("?")[0].split("/");
if (codePath.indexOf("/") == 0)
base = [base[0], codePath.substring(1)];
else
base[base.length - 1] = codePath;
codePath = base.join("/");
}
viewerOptions.put("codePath", codePath);
Jmol._registerApplet(applet._id, applet);
try {
applet._newApplet(viewerOptions);
} catch (e) {
System.out.println((Jmol._isAsync ? "normal async abort from " : "") + e);
return;
}
applet._jsSetScreenDimensions();
__nextExecution();
};
if (!proto._restoreState)
proto._restoreState = function(clazzName, state) {
// applet-dependent
}
proto._jsSetScreenDimensions = function() {
if (!this._appletPanel)return
// strangely, if CTRL+/CTRL- are used repeatedly, then the
// applet div can be not the same size as the canvas if there
// is a border in place.
var d = Jmol._getElement(this, (this._is2D ? "canvas2d" : "canvas"));
this._appletPanel.setScreenDimension(d.width, d.height);
};
proto._show = function(tf) {
Jmol.$setVisible(Jmol.$(this,"appletdiv"), tf);
if (tf)
Jmol._repaint(this, true);
};
proto._canScript = function(script) {return true};
proto.equals = function(a) { return this == a };
proto.clone = function() { return this };
proto.hashCode = function() { return parseInt(this._uniqueId) };
proto._processGesture = function(touches) {
return this._appletPanel.processTwoPointGesture(touches);
}
proto._processEvent = function(type, xym) {
this._appletPanel.processMouseEvent(type,xym[0],xym[1],xym[2],System.currentTimeMillis());
}
proto._resize = function() {
var s = "__resizeTimeout_" + this._id;
// only at end
if (Jmol[s])
clearTimeout(Jmol[s]);
var me = this;
Jmol[s] = setTimeout(function() {Jmol._repaint(me, true);Jmol[s]=null}, 100);
}
return proto;
};
Jmol._repaint = function(applet, asNewThread) {
// JmolObjectInterface
// asNewThread: true is from RepaintManager.repaintNow()
// false is from Repaintmanager.requestRepaintAndWait()
// called from apiPlatform Display.repaint()
//alert("_repaint " + Clazz.getStackTrace())
if (!applet || !applet._appletPanel)return;
// asNewThread = false;
var container = Jmol.$(applet, "appletdiv");
var w = Math.round(container.width());
var h = Math.round(container.height());
if (applet._is2D && (applet._canvas.width != w || applet._canvas.height != h)) {
applet._newCanvas(true);
applet._appletPanel.setDisplay(applet._canvas);
}
applet._appletPanel.setScreenDimension(w, h);
var f = function(){
if (applet._appletPanel.paint)
applet._appletPanel.paint(null);
else
applet._appletPanel.update(null)
};
if (asNewThread) {
requestAnimationFrame(f); // requestAnimationFrame or (MSIE 9) setTimeout
} else {
f();
}
// System.out.println(applet._appletPanel.getFullName())
}
/**
* _loadImage is called for asynchronous image loading.
* If bytes are not null, they are from a ZIP file. They are processed sychronously
* here using an image data URI. Can all browsers handle MB of data in data URI?
*
*/
Jmol._loadImage = function(platform, echoName, path, bytes, fOnload, image) {
// JmolObjectInterface
var id = "echo_" + echoName + path + (bytes ? "_" + bytes.length : "");
var canvas = Jmol._getHiddenCanvas(platform.vwr.html5Applet, id, 0, 0, false, true);
// System.out.println(["JSmol.js loadImage ",id,path,canvas,image])
if (canvas == null) {
if (image == null) {
image = new Image();
if (bytes == null) {
image.onload = function() {Jmol._loadImage(platform, echoName, path, null, fOnload, image)};
image.src = path;
return null;
}
System.out.println("Jsmol.js Jmol._loadImage using data URI for " + id)
image.src = (typeof bytes == "string" ? bytes :
"data:" + JU.Rdr.guessMimeTypeForBytes(bytes) + ";base64," + JU.Base64.getBase64(bytes));
}
var width = image.width;
var height = image.height;
if (echoName == "webgl") {
// will be antialiased
width /= 2;
height /= 2;
}
canvas = Jmol._getHiddenCanvas(platform.vwr.html5Applet, id, width, height, true, false);
canvas.imageWidth = width;
canvas.imageHeight = height;
canvas.id = id;
canvas.image=image;
Jmol._setCanvasImage(canvas, width, height);
// return a null canvas and the error in path if there is a problem
} else {
System.out.println("Jsmol.js Jmol._loadImage reading cached image for " + id)
}
return (bytes == null? fOnload(canvas,path) : canvas);
};
Jmol._canvasCache = {};
Jmol._getHiddenCanvas = function(applet, id, width, height, forceNew, checkOnly) {
id = applet._id + "_" + id;
var d = Jmol._canvasCache[id];
if (checkOnly)
return d;
if (forceNew || !d || d.width != width || d.height != height) {
d = document.createElement( 'canvas' );
// for some reason both these need to be set, or maybe just d.width?
d.width = d.style.width = width;
d.height = d.style.height = height;
d.id = id;
Jmol._canvasCache[id] = d;
//System.out.println("JSmol.js loadImage setting cache" + id + " to " + d)
}
return d;
}
Jmol._setCanvasImage = function(canvas, width, height) {
// called from org.jmol.awtjs2d.Platform
canvas.buf32 = null;
canvas.width = width;
canvas.height = height;
canvas.getContext("2d").drawImage(canvas.image, 0, 0, canvas.image.width, canvas.image.height, 0, 0, width, height);
};
Jmol._apply = function(f,a) {
// JmolObjectInterface
return f(a);
}
})(Jmol);
// JmolApplet.js -- Jmol._Applet and Jmol._Image
// BH 2/14/2016 12:31:02 PM fixed local reader not disappearing after script call
// BH 2/14/2016 12:30:41 PM Info.appletLoadingImage: "j2s/img/JSmol_spinner.gif", // can be set to "none" or some other image
// BH 2/14/2016 12:27:09 PM Jmol._setCursor, proto._getSpinner
// BH 1/15/2016 4:23:14 PM adding Info.makeLiveImage
// BH 4/17/2015 2:33:32 PM update for SwingJS
// BH 10/19/2014 8:08:51 PM moved applet._cover and applet._displayCoverImage to
// BH 5/8/2014 11:20:21 AM trying to fix AH nd JG problem with multiple applets
// BH 1/27/2014 8:36:43 AM adding Info.viewSet
// BH 12/13/2013 9:04:53 AM _evaluate DEPRECATED (see JSmolApi.js Jmol.evaulateVar
// BH 11/24/2013 11:41:31 AM streamlined createApplet, with added JNLP for local reading
// BH 10/11/2013 7:17:10 AM streamlined and made consistent with JSV and JSME
// BH 7/16/2012 1:50:03 PM adds server-side scripting for image
// BH 8/11/2012 11:00:01 AM adds Jmol._readyCallback for MSIE not in Quirks mode
// BH 8/12/2012 3:56:40 AM allows .min.png to be replaced by .all.png in Image file name
// BH 8/13/2012 6:16:55 PM fix for no-java message not displaying
// BH 11/18/2012 1:06:39 PM adds option ">" in database query box for quick command execution
// BH 12/17/2012 6:25:00 AM change ">" option to "!"
;(function (Jmol, document) {
// _Applet -- the main, full-featured, Jmol object
Jmol._Applet = function(id, Info, checkOnly){
window[id] = this;
this._jmolType = "Jmol._Applet" + (Info.isSigned ? " (signed)" : "");
this._viewType = "Jmol";
this._isJava = true;
this._syncKeyword = "Select:";
this._availableParams = ";progressbar;progresscolor;boxbgcolor;boxfgcolor;allowjavascript;boxmessage;\
;messagecallback;pickcallback;animframecallback;appletreadycallback;atommovedcallback;\
;echocallback;evalcallback;hovercallback;language;loadstructcallback;measurecallback;\
;minimizationcallback;resizecallback;scriptcallback;statusform;statustext;statustextarea;\
;synccallback;usecommandthread;syncid;appletid;startupscript;menufile;";
if (checkOnly)
return this;
this._isSigned = Info.isSigned;
this._readyFunction = Info.readyFunction;
this._ready = false;
this._isJava = true;
this._isInfoVisible = false;
this._applet = null;
this._memoryLimit = Info.memoryLimit || 512;
this._canScript = function(script) {return true;};
this._savedOrientations = [];
this._initialize = function(jarPath, jarFile) {
var doReport = false;
Jmol._jarFile && (jarFile = Jmol._jarFile);
if(this._jarFile) {
var f = this._jarFile;
if(f.indexOf("/") >= 0) {
alert ("This web page URL is requesting that the applet used be " + f + ". This is a possible security risk, particularly if the applet is signed, because signed applets can read and write files on your local machine or network.");
var ok = prompt("Do you want to use applet " + f + "? ", "yes or no")
if(ok == "yes") {
jarPath = f.substring(0, f.lastIndexOf("/"));
jarFile = f.substring(f.lastIndexOf("/") + 1);
} else {
doReport = true;
}
} else {
jarFile = f;
}
this_isSigned = Info.isSigned = (jarFile.indexOf("Signed") >= 0);
}
this._jarPath = Info.jarPath = jarPath || ".";
this._jarFile = Info.jarFile = (typeof(jarFile) == "string" ? jarFile : (jarFile ? "JmolAppletSigned" : "JmolApplet") + "0.jar");
if (doReport)
alert ("The web page URL was ignored. Continuing using " + this._jarFile + ' in directory "' + this._jarPath + '"');
Jmol.controls == undefined || Jmol.controls._onloadResetForms();
}
this._create(id, Info);
return this;
}
;(function(Applet, proto) {
Applet._get = function(id, Info, checkOnly) {
// note that the variable name the return is assigned to MUST match the first parameter in quotes
// applet = Jmol.getApplet("applet", Info)
checkOnly || (checkOnly = false);
Info || (Info = {});
var DefaultInfo = {
color: "#FFFFFF", // applet object background color, as for older jmolSetBackgroundColor(s)
width: 300,
height: 300,
addSelectionOptions: false,
serverURL: "http://your.server.here/jsmol.php",
defaultModel: "",
script: null,
src: null,
readyFunction: null,
use: "HTML5",//other options include JAVA, WEBGL, and IMAGE
jarPath: "java",
jarFile: "JmolApplet0.jar",
isSigned: false,
j2sPath: "j2s",
coverImage: null, // URL for image to display
makeLiveImage: null, // URL for small image to click to make live (defaults to j2s/img/play_make_live.jpg)
coverTitle: "", // tip that is displayed before model starts to load
coverCommand: "", // Jmol command executed upon clicking image
deferApplet: false, // true == the model should not be loaded until the image is clicked
deferUncover: false, // true == the image should remain until command execution is complete
disableJ2SLoadMonitor: false,
disableInitialConsole: true, // new default since now we have the spinner 2/14/2016 12:26:28 PM
//appletLoadingImage: "j2s/img/JSmol_spinner.gif", // can be set to "none" or some other image
debug: false
};
Jmol._addDefaultInfo(Info, DefaultInfo);
Jmol._debugAlert = Info.debug;
Info.serverURL && (Jmol._serverUrl = Info.serverURL);
var javaAllowed = false;
var applet = null;
var List = Info.use.toUpperCase().split("#")[0].split(" ");
for (var i = 0; i < List.length; i++) {
switch (List[i]) {
case "JAVA":
javaAllowed = true;
if (Jmol.featureDetection.supportsJava())
applet = new Applet(id, Info, checkOnly);
break;
case "WEBGL":
applet = Applet._getCanvas(id, Info, checkOnly, true);
break;
case "HTML5":
if (Jmol.featureDetection.allowHTML5){
applet = Applet._getCanvas(id, Info, checkOnly, false);
} else {
List.push("JAVA");
}
break;
// case "IMAGE":
// applet = new Jmol._Image(id, Info, checkOnly);
// break;
}
if (applet != null)
break;
}
if (applet == null) {
if (checkOnly || !javaAllowed)
applet = {_jmolType : "none" };
else if (javaAllowed)
applet = new Applet(id, Info);
}
// keyed to both its string id and itself
return (checkOnly ? applet : Jmol._registerApplet(id, applet));
}
Applet._getCanvas = function(id, Info, checkOnly, webGL) {
Info._isLayered = false;
Info._platform = "J.awtjs2d.Platform";
if (webGL && Jmol.featureDetection.supportsWebGL()) {
Jmol._Canvas3D.prototype = Jmol.GLmol.extendApplet(Jmol._jsSetPrototype(new Applet(id, Info, true)));
return new Jmol._Canvas3D(id, Info, "Jmol", checkOnly);
}
if (!webGL) {
Jmol._Canvas2D.prototype = Jmol._jsSetPrototype(new Applet(id, Info, true));
return new Jmol._Canvas2D(id, Info, "Jmol", checkOnly);
}
return null;
};
/* AngelH, mar2007:
By (re)setting these variables in the webpage before calling Jmol.getApplet(),
a custom message can be provided (e.g. localized for user's language) when no Java is installed.
*/
Applet._noJavaMsg =
"Either you do not have Java applets enabled in your web<br />browser or your browser is blocking this applet.<br />\
Check the warning message from your browser and/or enable Java applets in<br />\
your web browser preferences, or install the Java Runtime Environment from <a href='http://www.java.com'>www.java.com</a>";
Applet._setCommonMethods = function(p) {
p._showInfo = proto._showInfo;
p._search = proto._search;
p._getName = proto._getName;
p._readyCallback = proto._readyCallback;
}
Applet._createApplet = function(applet, Info, params) {
applet._initialize(Info.jarPath, Info.jarFile);
var jarFile = applet._jarFile;
var jnlp = ""
if (Jmol._isFile) {
// local installations need jnlp here and should reference JmolApplet(Signed).jar, not JmolApplet(Signed)0.jar
jarFile = jarFile.replace(/0\.jar/,".jar");
//jnlp = " jnlp_href=\"" + jarFile.replace(/\.jar/,".jnlp") + "\"";
}
// size is set to 100% of containers' size, but only if resizable.
// Note that resizability in MSIE requires:
// <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
var w = (applet._containerWidth.indexOf("px") >= 0 ? applet._containerWidth : "100%");
var h = (applet._containerHeight.indexOf("px") >= 0 ? applet._containerHeight : "100%");
var widthAndHeight = " style=\"width:" + w + ";height:" + h + "\" ";
var attributes = "name='" + applet._id + "_object' id='" + applet._id + "_object' " + "\n"
+ widthAndHeight + jnlp + "\n"
params.codebase = applet._jarPath;
params.codePath = params.codebase + "/";
if (params.codePath.indexOf("://") < 0) {
var base = document.location.href.split("#")[0].split("?")[0].split("/");
base[base.length - 1] = params.codePath;
params.codePath = base.join("/");
}
params.archive = jarFile;
params.mayscript = 'true';
params.java_arguments = "-Xmx" + Math.round(Info.memoryLimit || applet._memoryLimit) + "m";
params.permissions = (applet._isSigned ? "all-permissions" : "sandbox");
params.documentLocation = document.location.href;
params.documentBase = document.location.href.split("#")[0].split("?")[0];
params.jarPath = Info.jarPath;
Jmol._syncedApplets.length && (params.synccallback = "Jmol._mySyncCallback");
applet._startupScript && (params.script = applet._startupScript);
var t = "\n";
for (var i in params)
if(params[i])
t += " <param name='"+i+"' value='"+params[i]+"' />\n";
if (Jmol.featureDetection.useIEObject || Jmol.featureDetection.useHtml4Object) {
t = "<object " + attributes
+ (Jmol.featureDetection.useIEObject ?
" classid='clsid:8AD9C840-044E-11D1-B3E9-00805F499D93' codebase='http://java.sun.com/update/1.6.0/jinstall-6u22-windows-i586.cab'>"
: " type='application/x-java-applet'>")
+ t + "<p style='background-color:yellow;" + widthAndHeight.split('"')[1]
+ ";text-align:center;vertical-align:middle;'>\n" + Applet._noJavaMsg + "</p></object>\n";
} else { // use applet tag
t = "<applet " + attributes
+ " code='" + params.code + "' codebase='" + applet._jarPath + "' archive='" + jarFile + "' mayscript='true'>\n"
+ t + "<table bgcolor='yellow'><tr><td align='center' valign='middle' " + widthAndHeight + ">\n"
+ Applet._noJavaMsg + "</td></tr></table></applet>\n";
}
if (applet._deferApplet)
applet._javaCode = t, t="";
t = Jmol._getWrapper(applet, true) + t + Jmol._getWrapper(applet, false)
+ (Info.addSelectionOptions ? Jmol._getGrabberOptions(applet) : "");
if (Jmol._debugAlert)
alert (t);
applet._code = Jmol._documentWrite(t);
}
proto._newApplet = function(viewerOptions) {
if (!this._is2D)
viewerOptions.put("script", (viewerOptions.get("script") || "") + ";set multipleBondSpacing 0.35;");
this._viewerOptions = viewerOptions;
return new J.appletjs.Jmol(viewerOptions);
}
proto._addCoreFiles = function() {
Jmol._addCoreFile("jmol", this._j2sPath, this.__Info.preloadCore);
if (!this._is2D) {
Jmol._addExec([this, null, "J.export.JSExporter","load JSExporter"])
// Jmol._addExec([this, this.__addExportHook, null, "addExportHook"])
}
if (Jmol._debugCode)
Jmol._addExec([this, null, "J.appletjs.Jmol", "load Jmol"]);
}
proto._create = function(id, Info){
Jmol._setObject(this, id, Info);
var params = {
syncId: Jmol._syncId,
progressbar: "true",
progresscolor: "blue",
boxbgcolor: this._color || "black",
boxfgcolor: "white",
boxmessage: "Downloading JmolApplet ...",
script: (this._color ? "background \"" + this._color +"\"": ""),
code: "JmolApplet.class"
};
Jmol._setAppletParams(this._availableParams, params, Info);
function sterilizeInline(model) {
model = model.replace(/\r|\n|\r\n/g, (model.indexOf("|") >= 0 ? "\\/n" : "|")).replace(/'/g, "'");
if(Jmol._debugAlert)
alert ("inline model:\n" + model);
return model;
}
params.loadInline = (Info.inlineModel ? sterilizeInline(Info.inlineModel) : "");
params.appletReadyCallback = "Jmol._readyCallback";
if (Jmol._syncedApplets.length)
params.synccallback = "Jmol._mySyncCallback";
params.java_arguments = "-Xmx" + Math.round(Info.memoryLimit || this._memoryLimit) + "m";
this._initialize(Info.jarPath, Info.jarFile);
Applet._createApplet(this, Info, params);
}
proto._restoreState = function(clazzName, state) {
System.out.println("\n\nasynchronous restore state for " + clazzName + " " + state)
var applet = this;
var vwr = applet._applet && applet._applet.viewer;
switch (state) {
case "setOptions":
return function(_setOptions) {applet.__startAppletJS(applet)};
case "render":
return function() {setTimeout(function(){vwr.refresh(2)},10)};
default:
switch (clazzName) {
// debug mode only, when core.z.js has not been loaded and prior to start
case "J.shape.Balls":
case "J.shape.Sticks":
case "J.shape.Frank":
return null;
}
//if (vwr.rm.repaintPending)
//return function() {setTimeout(function(){vwr.refresh(2)},10)};
if (vwr && vwr.isScriptExecuting && vwr.isScriptExecuting()) {
if (Jmol._asyncCallbacks[clazzName]) {
System.out.println("...ignored");
return 1;
}
var sc = vwr.getEvalContextAndHoldQueue(vwr.eval);
var pc = sc.pc - 1;
sc.asyncID = clazzName;
Jmol._asyncCallbacks[clazzName] = function(pc) {sc.pc=pc; System.out.println("sc.asyncID="+sc.asyncID+" sc.pc = " + sc.pc);vwr.eval.resumeEval(sc)};
vwr.eval.pc = vwr.eval.pcEnd;
System.out.println("setting resume for pc=" + sc.pc + " " + clazzName + " to " + Jmol._asyncCallbacks[clazzName] + "//" )
return function() {System.out.println("resuming " + clazzName + " " + Jmol._asyncCallbacks[clazzName]);Jmol._asyncCallbacks[clazzName](pc)};
}
System.out.println(clazzName + "?????????????????????" + state)
return function() {setTimeout(function(){vwr.refresh(2)},10)};
//return null;
}
}
proto._readyCallback = function(id, fullid, isReady) {
if (!isReady)
return; // ignore -- page is closing
Jmol._setDestroy(this);
this._ready = true;
var script = this._readyScript;
if (this._defaultModel)
Jmol._search(this, this._defaultModel, (script ? ";" + script : ""));
else if (script)
this._script(script);
else if (this._src)
this._script('load "' + this._src + '"');
this._showInfo(true);
this._showInfo(false);
Jmol.Cache.setDragDrop(this);
this._readyFunction && this._readyFunction(this);
Jmol._setReady(this);
var app = this._2dapplet;
if (app && app._isEmbedded && app._ready && app.__Info.visible) {
var me = this;
// for some reason, JSME doesn't get the width/height correctly the first time
me._show2d(true);me._show2d(false);me._show2d(true);
}
Jmol._hideLoadingSpinner(this);
}
proto._showInfo = function(tf) {
if(tf && this._2dapplet)
this._2dapplet._show(false);
Jmol.$html(Jmol.$(this, "infoheaderspan"), this._infoHeader);
if (this._info)
Jmol.$html(Jmol.$(this, "infodiv"), this._info);
if ((!this._isInfoVisible) == (!tf))
return;
this._isInfoVisible = tf;
// 1px does not work for MSIE
if (this._isJava) {
var x = (tf ? 2 : "100%");
Jmol.$setSize(Jmol.$(this, "appletdiv"), x, x);
}
Jmol.$setVisible(Jmol.$(this, "infotablediv"), tf);
Jmol.$setVisible(Jmol.$(this, "infoheaderdiv"), tf);
this._show(!tf);
}
proto._show2d = function(tf) {
this._2dapplet._show2d(tf);
if (this._2dapplet._isEmbedded) {
this._showInfo(false);
this._show(!tf);
// for whatever reason this must be here
this._2dapplet.__showContainer(true, true);
}
}
proto._getSpinner = function() {
return (this.__Info.appletLoadingImage || this._j2sPath + "/img/JSmol_spinner.gif");
}
proto._getAtomCorrelation = function(molData) {
// get the first atom mapping available by loading the model structure into model 2,
this._loadMolData(molData, "atommap = compare({1.1} {2.1} 'MAP' 'H'); zap 2.1", true);
var map = this._evaluate("atommap");
var n = this._evaluate("{*}.count");
var A = [];
var B = [];
// these are Jmol atom indexes. The second number will be >= n, and all must be incremented by 1.
for (var i = 0; i < map.length; i++) {
var c = map[i];
A[c[0] + 1] = c[1] - n + 1;
B[c[1] - n + 1] = c[0] + 1;
}
return {fromJmol:A, toJmol:B}; // forward and rev.
}
proto._show = function(tf) {
var x = (!tf ? 2 : "100%");
Jmol.$setSize(Jmol.$(this, "object"), x, x);
if (!this._isJava)
Jmol.$setVisible(Jmol.$(this, "appletdiv"), tf);
}
proto._clearConsole = function () {
if (this._console == this._id + "_infodiv")
this.info = "";
if (!self.Clazz)return;
Jmol._setConsoleDiv(this._console);
Clazz.Console.clear();
}
proto._addScript = function(script) {
this._readyScript || (this.readyScript = "");
this._readyScript && (this._readyScript += ";");
this._readyScript += script;
return true;
}
proto._script = function(script) {
if (!this._ready)
return this._addScript(script);
Jmol._setConsoleDiv(this._console);
Jmol._hideLocalFileReader(this);
this._applet.script(script);
}
proto._syncScript = function(script) {
this._applet.syncScript(script);
}
proto._scriptCheck = function(script) {
return this._ready && this._applet.scriptCheck(script);
}
proto._scriptWait = function(script, noReturn) {
var Ret = this._scriptWaitAsArray(script);
var s = "";
if (!noReturn)
for(var i = Ret.length; --i >= 0; )
for(var j = 0, jj = Ret[i].length; j < jj; j++)
s += Ret[i][j] + "\n";
return s;
}
proto._scriptEcho = function(script) {
// returns a newline-separated list of all echos from a script
var Ret = this._scriptWaitAsArray(script);
var s = "";
for(var i = Ret.length; --i >= 0; )
for(var j = Ret[i].length; --j >= 0; )
if(Ret[i][j][1] == "scriptEcho")
s += Ret[i][j][3] + "\n";
return s.replace(/ \| /g, "\n");
}
proto._scriptMessage = function(script) {
// returns a newline-separated list of all messages from a script, ending with "script completed\n"
var Ret = this._scriptWaitAsArray(script);
var s = "";
for(var i = Ret.length; --i >= 0; )
for(var j = Ret[i].length; --j >= 0; )
if(Ret[i][j][1] == "scriptStatus")
s += Ret[i][j][3] + "\n";
return s.replace(/ \| /g, "\n");
}
proto._scriptWaitOutput = function(script) {
var ret = "";
try {
if(script) {
ret += this._applet.scriptWaitOutput(script);
}
} catch(e) {
}
return ret;
}
proto._scriptWaitAsArray = function(script) {
var ret = "";
try {
this._getStatus("scriptEcho,scriptMessage,scriptStatus,scriptError");
if(script) {
ret += this._applet.scriptWait(script);
ret = Jmol._evalJSON(ret, "jmolStatus");
if( typeof ret == "object")
return ret;
}
} catch(e) {
}
return [[ret]];
}
proto._getStatus = function(strStatus) {
return Jmol._sortMessages(this._getPropertyAsArray("jmolStatus",strStatus));
}
proto._getPropertyAsArray = function(sKey,sValue) {
return Jmol._evalJSON(this._getPropertyAsJSON(sKey,sValue),sKey);
}
proto._getPropertyAsString = function(sKey,sValue) {
sValue == undefined && ( sValue = "");
return this._applet.getPropertyAsString(sKey, sValue) + "";
}
proto._getPropertyAsJSON = function(sKey,sValue) {
sValue == undefined && ( sValue = "");
try {
return (this._applet.getPropertyAsJSON(sKey, sValue) + "");
} catch(e) {
return "";
}
}
proto._getPropertyAsJavaObject = function(sKey,sValue) {
sValue == undefined && ( sValue = "");
return this._applet.getProperty(sKey,sValue);
}
proto._evaluate = function(expr) {
expr != null || (expr = "");
return this._getPropertyAsArray("variableInfo", expr);
}
proto._evaluateDEPRECATED = function(molecularMath) { // DEPRECATED!!!
// DEPRECATED!!!
//carries out molecular math on a model
var result = "" + this._getPropertyAsJavaObject("evaluate", molecularMath);
var s = result.replace(/\-*\d+/, "");
if(s == "" && !isNaN(parseInt(result)))
return parseInt(result);
var s = result.replace(/\-*\d*\.\d*/, "")
if(s == "" && !isNaN(parseFloat(result)))
return parseFloat(result);
return result;
// DEPRECATED!!!
}
proto._saveOrientation = function(id) {
return this._savedOrientations[id] = this._getPropertyAsArray("orientationInfo","info").moveTo;
}
proto._restoreOrientation = function(id) {
var s = this._savedOrientations[id];
if(!s || s == "")
return s = s.replace(/1\.0/, "0");
return this._scriptWait(s);
}
proto._restoreOrientationDelayed = function(id,delay) {
arguments.length < 1 && ( delay = 1);
var s = this._savedOrientations[id];
if(!s || s == "")
return s = s.replace(/1\.0/, delay);
return this._scriptWait(s);
}
proto._resizeApplet = function(size) {
// See _jmolGetAppletSize() for the formats accepted as size [same used by jmolApplet()]
// Special case: an empty value for width or height is accepted, meaning no change in that dimension.
/*
* private functions
*/
function _getAppletSize(size, units) {
/* Accepts single number, 2-value array, or object with width and height as mroperties, each one can be one of:
percent (text string ending %), decimal 0 to 1 (percent/100), number, or text string (interpreted as nr.)
[width, height] array of strings is returned, with units added if specified.
Percent is relative to container div or element (which should have explicitly set size).
*/
var width, height;
if(( typeof size) == "object" && size != null) {
width = size[0]||size.width;
height = size[1]||size.height;
} else {
width = height = size;
}
return [_fixDim(width, units), _fixDim(height, units)];
}
function _fixDim(x, units) {
var sx = "" + x;
return (sx.length == 0 ? (units ? "" : Jmol._allowedJmolSize[2])
: sx.indexOf("%") == sx.length - 1 ? sx
: (x = parseFloat(x)) <= 1 && x > 0 ? x * 100 + "%"
: (isNaN(x = Math.floor(x)) ? Jmol._allowedJmolSize[2]
: x < Jmol._allowedJmolSize[0] ? Jmol._allowedJmolSize[0]
: x > Jmol._allowedJmolSize[1] ? Jmol._allowedJmolSize[1]
: x)
+ (units ? units : "")
);
}
var sz = _getAppletSize(size, "px");
var d = Jmol._getElement(this, "appletinfotablediv");
d.style.width = sz[0];
d.style.height = sz[1];
this._containerWidth = sz[0];
this._containerHeight = sz[1];
if (this._is2D)
Jmol._repaint(this, true);
}
proto._search = function(query, script){
Jmol._search(this, query, script);
}
proto._searchDatabase = function(query, database, script, _jmol_searchDatabase){
if (this._2dapplet && this._2dapplet._isEmbedded && !Jmol.$(this, "appletdiv:visible")[0])
return this._2dapplet._searchDatabase(query, database, script);
this._showInfo(false);
if (query.indexOf("?") >= 0) {
Jmol._getInfoFromDatabase(this, database, query.split("?")[0]);
return;
}
script || (script = Jmol._getScriptForDatabase(database));
var dm = database + query;
this._currentView = null;
this._searchQuery = dm;
this._loadFile(dm, script, dm);
}
proto._loadFile = function(fileName, script, chemID, _jmol_loadFile){
this._showInfo(false);
script || (script = "");
this._thisJmolModel = "" + Math.random();
this._fileName = fileName;
if (!this._scriptLoad(fileName, script)) {
// we load the data here instead of in Jmol in the case of
// JSmol/Java/Sandboxed or when part of a view set
var me = this;
Jmol._loadFileData(this, fileName,
function(data){me.__loadModel(data, script, chemID)},
function() {me.__loadModel(null)}
);
}
}
proto._scriptLoad = function(file, script, _jmol_scriptLoad) {
script || (script = "");
var doscript = (this._isJava || !this._noscript);
if (doscript)
this._script("zap;set echo middle center;echo Retrieving data...");
if (!this._isSigned || this._viewSet != null)
return false;
if (doscript)
this._script("load async \"" + file + "\";" + script);
else
this._applet.openFile(file);
this._checkDeferred("");
return true;
}
proto.__loadModel = function(mol, script, chemID, _jmol__loadModel) {
if (mol == null)
return;
if (this._viewSet != null) {
script || (script = "");
// first component only
script += ";if ({*}.molecule.max > 1 || {*}.modelindex.max > 0){ delete molecule > 1 or modelindex > 0;x = getProperty('extractModel',{*});load inline @x};"
}
if (!script && this._noscript) {
this._applet.loadInlineString(mol, "", false);
} else {
this._loadMolData(mol, script, false);
}
if (this._viewSet != null) {
Jmol.View.updateView(this, {chemID:chemID, data:mol});
}
}
proto._loadMolData = function(mol, script, isAppend) {
script || (script = "");
var name = (isAppend ? "append" : "model");
script = 'load DATA "' + name + '"' + mol + '\nEND "'+ name +'" ;' + script;
this._applet.scriptWait(script);
}
proto._loadModelFromView = function(view, _jmol_loadModelFromView) {
// request from Jmol.View to update view with view.JME.data==null or needs changing
this._currentView = view;
var rec = view.Jmol;
if (rec.data != null) {
this.__loadModel(rec.data, null, view.info.chemID);
return;
}
if (view.info.chemID != null) {
Jmol._searchMol(this, view.info.chemID, null, false);
return;
}
rec = view.JME;
if (rec) {
rec.applet._show2d(false, this);
return;
}
}
proto._reset = function(_jmol_resetView) {
this._scriptWait("zap", true);
}
proto._updateView = function(_jmol_updateView) {
if (this._viewSet == null || !this._applet)
return;
// called from model change without chemical identifier, possibly by user action and call to Jmol.updateView(applet)
chemID = "" + this._getPropertyAsJavaObject("variableInfo","script('show chemical inchiKey')");
if (chemID.length() < 36) // InChIKey=RZVAJINKPMORJF-BGGKNDAXNA-N
chemID = null;
else
chemID = chemID.substring(36).split('\n')[0];
Jmol.View.updateView(this, {chemID:chemID, data: "" + this._getPropertyAsJavaObject("evaluate", "extractModel", "{visible}")});
}
proto._atomPickedCallback = function(imodel, iatom, _jmol_atomPickedCallback) {
// direct callback from Jmol HTML5 applet
if (iatom < 0) {
// TODO could be a model change?
} else {
var A = [iatom + 1];
Jmol.View.updateAtomPick(this, A);
this._updateAtomPick(A);
}
}
proto._updateAtomPick = function(A) {
this._script(A.length == 0 ? "select none" : "select on visible and (@" + A.join(",@") + ")");
}
proto._isDeferred = function () {
return !this._canvas && this._cover && this._isCovered && this._deferApplet
}
proto._checkDeferred = function(script) {
if (this._isDeferred()) {
this._coverScript = script;
this._cover(false);
return true;
}
return false;
}
proto._cover = function (doCover) {
if (doCover || !this._deferApplet) {
this._displayCoverImage(doCover);
return;
}
// uncovering UNMADE applet upon clicking image
var s = (this._coverScript ? this._coverScript : "");
this._coverScript = "";
if (this._deferUncover)
s += ";refresh;javascript " + this._id + "._displayCoverImage(false)";
this._script(s, true);
if (this._deferUncover && this._coverTitle == "activate 3D model")
Jmol._getElement(this, "coverimage").title = "3D model is loading...";
if (!this._isJava)
this._newCanvas(false);
if (this._defaultModel)
Jmol._search(this, this._defaultModel);
this._showInfo(false);
if (!this._deferUncover)
this._displayCoverImage(false);
if (this._isJava)
Jmol.$html(Jmol.$(this, "appletdiv"), this._javaCode);
if (this._init)
this._init();
};
proto._displayCoverImage = function(TF) {
if (!this._coverImage || this._isCovered == TF) return;
this._isCovered = TF;
Jmol._getElement(this, "coverdiv").style.display = (TF ? "block" : "none");
};
proto._getSmiles = function() {
return this._evaluate("{visible}.find('SMILES')");
}
proto._getMol = function() {
return this._evaluate("getProperty('ExtractModel',{visible})");
}
proto._getMol2D = function() {
return this._evaluate("script('select visible;show chemical sdf')"); // 2D equivalent no longer!
}
})(Jmol._Applet, Jmol._Applet.prototype);
/* ****************************************
// _Image -- an alternative to _Applet
// commented out here, as it has found no use
Jmol._Image = function(id, Info, checkOnly){
this._jmolType = "image";
if (checkOnly)
return this;
this._create(id, Info);
return this;
}
;(function (Image, proto) {
Jmol._Applet._setCommonMethods(proto);
proto._create = function(id, Info) {
Jmol._setObject(this, id, Info);
thisnfo);
this._src || (this._src = "");
var t = Jmol._getWrapper(this, true)
+ '<img id="'+id+'_image" width="' + Info.width + '" height="' + Info.height + '" src=""/>'
+ Jmol._getWrapper(this, false)
+ (Info.addSelectionOptions ? Jmol._getGrabberOptions(this) : "");
if (Jmol._debugAlert)
alert (t);
this._code = Jmol._documentWrite(t);
this._ready = false;
if (Jmol._document)
this._readyCallback(id, null, this._ready = true, null);
}
proto._canScript = function(script) {
var slc = script.toLowerCase().replace(/[\",\']/g, '');
var ipt = slc.length;
return (script.indexOf("#alt:LOAD") >= 0 || slc.indexOf(";") < 0 && slc.indexOf("\n") < 0
&& (slc.indexOf("script ") == 0 || slc.indexOf("load ") == 0)
&& (slc.indexOf(".png") == ipt - 4 || slc.indexOf(".jpg") == ipt - 4));
}
proto._script = function(script) {
var slc = script.toLowerCase().replace(/[\",\']/g, '');
// single command only
// "script ..." or "load ..." only
// PNG or PNGJ or JPG only
// automatically switches to .all.png(j) from .min.png(j)
var ipt = slc.length;
if (slc.indexOf(";") < 0 && slc.indexOf("\n") < 0
&& (slc.indexOf("script ") == 0 || slc.indexOf("load ") == 0)
&& (slc.indexOf(".png") == ipt - 4 || slc.indexOf(".pngj") == ipt - 5 || slc.indexOf(".jpg") == ipt - 4)) {
var imageFile = script.substring(script.indexOf(" ") + 1);
ipt = imageFile.length;
for (var i = 0; i < ipt; i++) {
switch (imageFile.charAt(i)) {
case " ":
continue;
case '"':
imageFile = imageFile.substring(i + 1, imageFile.indexOf('"', i + 1))
i = ipt;
continue;
case "'":
imageFile = imageFile.substring(i + 1, imageFile.indexOf("'", i + 1))
i = ipt;
continue;
default:
imageFile = imageFile.substring(i)
i = ipt;
continue;
}
}
imageFile = imageFile.replace(/\.min\.png/,".all.png")
document.getElementById(this._id + "_image").src = imageFile
} else if (script.indexOf("#alt:LOAD ") >= 0) {
imageFile = script.split("#alt:LOAD ")[1]
if (imageFile.indexOf("??") >= 0) {
var db = imageFile.split("??")[0];
imageFile = prompt(imageFile.split("??")[1], "");
if (!imageFile)
return;
if (!Jmol.db._DirectDatabaseCalls[imageFile.substring(0,1)])
imageFile = db + imageFile;
}
this._loadFile(imageFile);
}
}
proto._show = function(tf) {
Jmol._getElement(this, "appletdiv").style.display = (tf ? "block" : "none");
}
proto._loadFile = function(fileName, params){
this._showInfo(false);
this._thisJmolModel = "" + Math.random();
params = (params ? params : "");
var database = "";
if (Jmol._isDatabaseCall(fileName)) {
database = fileName.substring(0, 1);
fileName = Jmol._getDirectDatabaseCall(fileName, false);
} else if (fileName.indexOf("://") < 0) {
var ref = document.location.href
var pt = ref.lastIndexOf("/");
fileName = ref.substring(0, pt + 1) + fileName;
}
var src = Jmol._serverUrl
+ "?call=getImageForFileLoad"
+ "&file=" + escape(fileName)
+ "&width=" + this._width
+ "&height=" + this._height
+ "¶ms=" + encodeURIComponent(params + ";frank off;");
Jmol._getElement(this, "image").src = src;
}
proto._searchDatabase = function(query, database, script){
if (query.indexOf("?") == query.length - 1) {
Jmol._getInfoFromDatabase(this, database, query.split("?")[0]);
return;
}
this._showInfo(false);
script || (script = Jmol._getScriptForDatabase(database));
var src = Jmol._serverUrl
+ "?call=getImageFromDatabase"
+ "&database=" + database
+ "&query=" + query
+ "&width=" + this._width
+ "&height=" + this._height
+ "&script=" + encodeURIComponent(script + ";frank off;");
Jmol._getElement(this, "image").src = src;
}
})(Jmol._Image, Jmol._Image.prototype);
************************************ */
Jmol.jmolSmiles = function(jmol, withStereoChemistry) {
return jmol._getSmiles();
}
})(Jmol, document);
// JSmolControls.js
// BH 11/13/2015 7:12:40 PM addded indeterminate checkbox masters
// BH 5/29/2014 8:14:06 AM added default command for command input box
// BH 5/15/2014 -- removed script check prior to execution
// BH 12/3/2013 12:39:48 PM added up/down arrow key-driven command history for commandInput (changed keypress to keydown)
// BH 5/16/2013 8:14:47 AM fix for checkbox groups and default radio names
// BH 8:36 AM 7/27/2012 adds name/id for cmd button
// BH 8/12/2012 6:51:53 AM adds function() {...} option for all controls:
// Jmol.jmolButton(jmol, function(jmol) {...}, "xxxx")
(function(Jmol) {
// private
var c = Jmol.controls = {
_hasResetForms: false,
_scripts: [""],
_checkboxMasters: {},
_checkboxItems: {},
_actions: {},
_buttonCount: 0,
_checkboxCount: 0,
_radioGroupCount: 0,
_radioCount: 0,
_linkCount: 0,
_cmdCount: 0,
_menuCount: 0,
_previousOnloadHandler: null,
_control: null,
_element: null,
_appletCssClass: null,
_appletCssText: "",
_buttonCssClass: null,
_buttonCssText: "",
_checkboxCssClass: null,
_checkboxCssText: "",
_radioCssClass: null,
_radioCssText: "",
_linkCssClass: null,
_linkCssText: "",
_menuCssClass: null,
_menuCssText: ""
};
c._addScript = function(appId,script) {
var index = c._scripts.length;
c._scripts[index] = [appId, script];
return index;
}
c._getIdForControl = function(appletOrId, script) {
//alert(appletOrId + " " + typeof appletOrId + " " + script + appletOrId._canScript)
return (typeof appletOrId == "string" ? appletOrId
: !script || !appletOrId._canScript || appletOrId._canScript(script) ? appletOrId._id
: null);
}
c._radio = function(appletOrId, script, labelHtml, isChecked, separatorHtml, groupName, id, title) {
var appId = c._getIdForControl(appletOrId, script);
if (appId == null)
return null;
++c._radioCount;
groupName != undefined && groupName != null || (groupName = "jmolRadioGroup" + (c._radioGroupCount - 1));
if (!script)
return "";
id != undefined && id != null || (id = "jmolRadio" + (c._radioCount - 1));
labelHtml != undefined && labelHtml != null || (labelHtml = script.substring(0, 32));
separatorHtml || (separatorHtml = "");
var eospan = "</span>";
c._actions[id] = c._addScript(appId, script);
var t = "<span id=\"span_"+id+"\""+(title ? " title=\"" + title + "\"":"")+"><input name='"
+ groupName + "' id='"+id+"' type='radio'"
+ " onclick='Jmol.controls._click(this);return true;'"
+ " onmouseover='Jmol.controls._mouseOver(this);return true;'"
+ " onmouseout='Jmol.controls._mouseOut()' " +
(isChecked ? "checked='true' " : "") + c._radioCssText + " />";
if (labelHtml.toLowerCase().indexOf("<td>")>=0) {
t += eospan;
eospan = "";
}
t += "<label for=\"" + id + "\">" + labelHtml + "</label>" +eospan + separatorHtml;
return t;
}
/////////// events //////////
c._scriptExecute = function(element, scriptInfo) {
var applet = Jmol._applets[scriptInfo[0]];
var script = scriptInfo[1];
if (typeof(script) == "object")
script[0](element, script, applet);
else if (typeof(script) == "function")
script(applet);
else
Jmol.script(applet, script);
}
c.__checkScript = function(applet, d) {
var ok = (d.value.indexOf("JSCONSOLE ") >= 0 || applet._scriptCheck(d.value) === "");
d.style.color = (ok ? "black" : "red");
return ok;
}
c.__getCmd = function(dir, d) {
if (!d._cmds || !d._cmds.length)return
var s = d._cmds[d._cmdpt = (d._cmdpt + d._cmds.length + dir) % d._cmds.length]
setTimeout(function(){d.value = s},10);
d._cmdadd = 1;
d._cmddir = dir;
}
c._commandKeyPress = function(e, id, appId) {
var keycode = (e == 13 ? 13 : window.event ? window.event.keyCode : e ? e.keyCode || e.which : 0);
var d = document.getElementById(id);
var applet = Jmol._applets[appId];
switch (keycode) {
case 13:
var v = d.value;
if ((c._scriptExecute(d, [appId, v]) || 1)) {
if (!d._cmds){
d._cmds = [];
d._cmddir = 0;
d._cmdpt = -1;
d._cmdadd = 0;
}
if (v && d._cmdadd == 0) {
++d._cmdpt;
d._cmds.splice(d._cmdpt, 0, v);
d._cmdadd = 0;
d._cmddir = 0;
} else {
//d._cmdpt -= d._cmddir;
d._cmdadd = 0;
}
d.value = "";
}
return false;
case 27:
setTimeout(function() {d.value = ""}, 20);
return false;
case 38: // up
c.__getCmd(-1, d);
break;
case 40: // dn
c.__getCmd(1, d);
break;
default:
d._cmdadd = 0;
}
setTimeout(function() {c.__checkScript(applet, d)}, 20);
return true;
}
c._click = function(obj, scriptIndex) {
c._element = obj;
if (arguments.length == 1)
scriptIndex = c._actions[obj.id];
c._scriptExecute(obj, c._scripts[scriptIndex]);
}
c._menuSelected = function(menuObject) {
var scriptIndex = menuObject.value;
if (scriptIndex != undefined) {
c._scriptExecute(menuObject, c._scripts[scriptIndex]);
return;
}
var len = menuObject.length;
if (typeof len == "number")
for (var i = 0; i < len; ++i)
if (menuObject[i].selected) {
c._click(menuObject[i], menuObject[i].value);
return;
}
alert("?Que? menu selected bug #8734");
}
c._cbNotifyMaster = function(m){
//called when a group item is checked
var allOn = true;
var allOff = true;
var mixed = false;
var cb;
for (var id in m.chkGroup){ //siblings of m
cb = m.chkGroup[id];
if (cb.checked)
allOff = false;
else
allOn = false;
if (cb.indeterminate)
mixed = true;
}
cb = m.chkMaster;
if (allOn) { cb.checked = true; }
else if (allOff) { cb.checked = false; }
else { mixed = true; }
cb.indeterminate = mixed;
(m = c._checkboxItems[cb.id]) && (cb = m.chkMaster)
&& c._cbNotifyMaster(c._checkboxMasters[cb.id])
}
c._cbNotifyGroup = function(m, isOn){
//called when a master item is checked
for (var chkBox in m.chkGroup){
var item = m.chkGroup[chkBox]
if (item.checked != isOn) {
item.checked = isOn;
c._cbClick(item);
}
if (c._checkboxMasters[item.id])
c._cbNotifyGroup(c._checkboxMasters[item.id], isOn)
}
}
c._cbSetCheckboxGroup = function(chkMaster, chkboxes, args){
var id = chkMaster;
if(typeof(id)=="number")id = "jmolCheckbox" + id;
chkMaster = document.getElementById(id);
if (!chkMaster)alert("jmolSetCheckboxGroup: master checkbox not found: " + id);
var m = c._checkboxMasters[id] = {};
m.chkMaster = chkMaster;
m.chkGroup = {};
var i0;
if (typeof(chkboxes)=="string") {
chkboxes = args;
i0 = 1;
} else {
i0 = 0;
}
for (var i = i0; i < chkboxes.length; i++){
var id = chkboxes[i];
if(typeof(id)=="number")id = "jmolCheckbox" + id;
var checkboxItem = document.getElementById(id);
if (!checkboxItem)alert("jmolSetCheckboxGroup: group checkbox not found: " + id);
m.chkGroup[id] = checkboxItem;
c._checkboxItems[id] = m;
}
}
c._cbClick = function(ckbox) {
c._control = ckbox;
var whenChecked = c._actions[ckbox.id][0];
var whenUnchecked = c._actions[ckbox.id][1];
c._click(ckbox, ckbox.checked ? whenChecked : whenUnchecked);
if(c._checkboxMasters[ckbox.id])
c._cbNotifyGroup(c._checkboxMasters[ckbox.id], ckbox.checked)
if(c._checkboxItems[ckbox.id])
c._cbNotifyMaster(c._checkboxItems[ckbox.id])
}
c._cbOver = function(ckbox) {
var whenChecked = c._actions[ckbox.id][0];
var whenUnchecked = c._actions[ckbox.id][1];
window.status = c._scripts[ckbox.checked ? whenUnchecked : whenChecked];
}
c._mouseOver = function(obj, scriptIndex) {
if (arguments.length == 1)
scriptIndex = c._actions[obj.id];
window.status = c._scripts[scriptIndex];
}
c._mouseOut = function() {
window.status = " ";
return true;
}
// from JmolApplet
c._onloadResetForms = function() {
// must be evaluated ONLY once -- is this compatible with jQuery?
if (c._hasResetForms)
return;
c._hasResetForms = true;
c._previousOnloadHandler = window.onload;
window.onload = function() {
if (c._buttonCount+c._checkboxCount+c._menuCount+c._radioCount+c._radioGroupCount > 0) {
var forms = document.forms;
for (var i = forms.length; --i >= 0; )
forms[i].reset();
}
if (c._previousOnloadHandler)
c._previousOnloadHandler();
}
}
// from JmolApi
c._getButton = function(appletOrId, script, label, id, title) {
var appId = c._getIdForControl(appletOrId, script);
if (appId == null)
return "";
//_jmolInitCheck();
id != undefined && id != null || (id = "jmolButton" + c._buttonCount);
label != undefined && label != null || (label = script.substring(0, 32));
++c._buttonCount;
c._actions[id] = c._addScript(appId, script);
var t = "<span id=\"span_"+id+"\""+(title ? " title=\"" + title + "\"":"")+"><input type='button' name='" + id + "' id='" + id +
"' value='" + label +
"' onclick='Jmol.controls._click(this)' onmouseover='Jmol.controls._mouseOver(this);return true' onmouseout='Jmol.controls._mouseOut()' " +
c._buttonCssText + " /></span>";
if (Jmol._debugAlert)
alert(t);
return Jmol._documentWrite(t);
}
c._getCheckbox = function(appletOrId, scriptWhenChecked, scriptWhenUnchecked,
labelHtml, isChecked, id, title) {
var appId = c._getIdForControl(appletOrId, scriptWhenChecked);
if (appId != null)
appId = c._getIdForControl(appletOrId, scriptWhenUnchecked);
if (appId == null)
return "";
//_jmolInitCheck();
id != undefined && id != null || (id = "jmolCheckbox" + c._checkboxCount);
++c._checkboxCount;
if (scriptWhenChecked == undefined || scriptWhenChecked == null ||
scriptWhenUnchecked == undefined || scriptWhenUnchecked == null) {
alert("jmolCheckbox requires two scripts");
return;
}
if (labelHtml == undefined || labelHtml == null) {
alert("jmolCheckbox requires a label");
return;
}
c._actions[id] = [c._addScript(appId, scriptWhenChecked),c._addScript(appId, scriptWhenUnchecked)];
var eospan = "</span>"
var t = "<span id=\"span_"+id+"\""+(title ? " title=\"" + title + "\"":"")+"><input type='checkbox' name='" + id + "' id='" + id +
"' onclick='Jmol.controls._cbClick(this)" +
"' onmouseover='Jmol.controls._cbOver(this)" +
";return true' onmouseout='Jmol.controls._mouseOut()' " +
(isChecked ? "checked='true' " : "")+ c._checkboxCssText + " />"
if (labelHtml.toLowerCase().indexOf("<td>")>=0) {
t += eospan
eospan = "";
}
t += "<label for=\"" + id + "\">" + labelHtml + "</label>" +eospan;
if (Jmol._debugAlert)
alert(t);
return Jmol._documentWrite(t);
}
c._getCommandInput = function(appletOrId, label, size, id, title, cmd0) {
var appId = c._getIdForControl(appletOrId, "x");
if (appId == null)
return "";
//_jmolInitCheck();
id != undefined && id != null || (id = "jmolCmd" + c._cmdCount);
label != undefined && label != null || (label = "Execute");
size != undefined && !isNaN(size) || (size = 60);
cmd0 != undefined || (cmd0 = "help");
++c._cmdCount;
var t = "<span id=\"span_"+id+"\""+(title ? " title=\"" + title + "\"":"")+"><input name='" + id + "' id='" + id +
"' size='"+size+"' onkeydown='return Jmol.controls._commandKeyPress(event,\""+id+"\",\"" + appId + "\")' value='" + cmd0 + "'/><input " +
" type='button' name='" + id + "Btn' id='" + id + "Btn' value = '"+label+"' onclick='Jmol.controls._commandKeyPress(13,\""+id+"\",\"" + appId + "\")' /></span>";
if (Jmol._debugAlert)
alert(t);
return Jmol._documentWrite(t);
}
c._getLink = function(appletOrId, script, label, id, title) {
var appId = c._getIdForControl(appletOrId, script);
if (appId == null)
return "";
//_jmolInitCheck();
id != undefined && id != null || (id = "jmolLink" + c._linkCount);
label != undefined && label != null || (label = script.substring(0, 32));
++c._linkCount;
var scriptIndex = c._addScript(appId, script);
var t = "<span id=\"span_"+id+"\""+(title ? " title=\"" + title + "\"":"")+"><a name='" + id + "' id='" + id +
"' href='javascript:Jmol.controls._click(null,"+scriptIndex+");' onmouseover='Jmol.controls._mouseOver(null,"+scriptIndex+");return true;' onmouseout='Jmol.controls._mouseOut()' " +
c._linkCssText + ">" + label + "</a></span>";
if (Jmol._debugAlert)
alert(t);
return Jmol._documentWrite(t);
}
c._getMenu = function(appletOrId, arrayOfMenuItems, size, id, title) {
var appId = c._getIdForControl(appletOrId, null);
var optgroup = null;
//_jmolInitCheck();
id != undefined && id != null || (id = "jmolMenu" + c._menuCount);
++c._menuCount;
var type = typeof arrayOfMenuItems;
if (type != null && type == "object" && arrayOfMenuItems.length) {
var len = arrayOfMenuItems.length;
if (typeof size != "number" || size == 1)
size = null;
else if (size < 0)
size = len;
var sizeText = size ? " size='" + size + "' " : "";
var t = "<span id=\"span_"+id+"\""+(title ? " title=\"" + title + "\"":"")+"><select name='" + id + "' id='" + id +
"' onChange='Jmol.controls._menuSelected(this)'" +
sizeText + c._menuCssText + ">";
for (var i = 0; i < len; ++i) {
var menuItem = arrayOfMenuItems[i];
type = typeof menuItem;
var script = null;
var text = null;
var isSelected = null;
if (type == "object" && menuItem != null) {
script = menuItem[0];
text = menuItem[1];
isSelected = menuItem[2];
} else {
script = text = menuItem;
}
appId = c._getIdForControl(appletOrId, script);
if (appId == null)
return "";
text == null && (text = script);
if (script=="#optgroup") {
t += "<optgroup label='" + text + "'>";
} else if (script=="#optgroupEnd") {
t += "</optgroup>";
} else {
var scriptIndex = c._addScript(appId, script);
var selectedText = isSelected ? "' selected='true'>" : "'>";
t += "<option value='" + scriptIndex + selectedText + text + "</option>";
}
}
t += "</select></span>";
if (Jmol._debugAlert)
alert(t);
return Jmol._documentWrite(t);
}
}
c._getRadio = function(appletOrId, script, labelHtml, isChecked, separatorHtml, groupName, id, title) {
//_jmolInitCheck();
if (c._radioGroupCount == 0)
++c._radioGroupCount;
groupName || (groupName = "jmolRadioGroup" + (c._radioGroupCount - 1));
var t = c._radio(appletOrId, script, labelHtml, isChecked, separatorHtml, groupName, (id ? id : groupName + "_" + c._radioCount), title ? title : 0);
if (t == null)
return "";
if (Jmol._debugAlert)
alert(t);
return Jmol._documentWrite(t);
}
c._getRadioGroup = function(appletOrId, arrayOfRadioButtons, separatorHtml, groupName, id, title) {
/*
array: [radio1,radio2,radio3...]
where radioN = ["script","label",isSelected,"id","title"]
*/
//_jmolInitCheck();
var type = typeof arrayOfRadioButtons;
if (type != "object" || type == null || ! arrayOfRadioButtons.length) {
alert("invalid arrayOfRadioButtons");
return;
}
separatorHtml != undefined && separatorHtml != null || (separatorHtml = "  ");
var len = arrayOfRadioButtons.length;
++c._radioGroupCount;
groupName || (groupName = "jmolRadioGroup" + (c._radioGroupCount - 1));
var t = "<span id='"+(id ? id : groupName)+"'>";
for (var i = 0; i < len; ++i) {
if (i == len - 1)
separatorHtml = "";
var radio = arrayOfRadioButtons[i];
type = typeof radio;
var s = null;
if (type == "object") {
t += (s = c._radio(appletOrId, radio[0], radio[1], radio[2], separatorHtml, groupName, (radio.length > 3 ? radio[3]: (id ? id : groupName)+"_"+i), (radio.length > 4 ? radio[4] : 0), title));
} else {
t += (s = c._radio(appletOrId, radio, null, null, separatorHtml, groupName, (id ? id : groupName)+"_"+i, title));
}
if (s == null)
return "";
}
t+="</span>"
if (Jmol._debugAlert)
alert(t);
return Jmol._documentWrite(t);
}
})(Jmol);
// JmolApi.js -- Jmol user functions Bob Hanson hansonr@stolaf.edu
// BH 4/1/2016 12:59:45 PM fix applet_or_identifier reference in Jmol.getChemicalInfo
// BH 5/29/2014 8:14:06 AM added default command for command input box
// BH 3/10/2014 10:35:25 AM adds Jmol.saveImage(applet)
// BH 1/22/2014 7:31:59 AM Jmol._Image removed -- just never found useful to have
// a server-side process with only a client-side image. Response time is too slow.
// BH 12/13/2013 8:39:00 AM Jmol.evaulate is DEPRECATED -- use Jmol.evaluateVar
// BH 11/25/2013 6:55:53 AM adds URL flags _USE=, _JAR=, _J2S=
// BH 9/3/2013 5:48:03 PM simplification of Jmol.getAppletHTML()
// BH 5/16/2013 9:01:41 AM checkbox group fix
// BH 1/15/2013 10:55:06 AM updated to default to HTML5 not JAVA
// This file is part of JSmol.min.js.
// If you do not use that, then along with this file you need several other files. See JSmolCore.js for details.
// default settings are below. Generally you would do something like this:
// jmol = "jmol"
// Info = {.....your settings if not default....}
// Jmol.jmolButton(jmol,....)
// jmol = Jmol.getApplet(jmol, Info)
// Jmol.script(jmol,"....")
// Jmol.jmolLink(jmol,....)
// etc.
// first parameter is always the applet id, either the string "jmol" or the object defined by Jmol.getApplet()
// no need for waiting to start giving script commands. You can also define a callback function as part of Info.
// see JmolCore.js for details
// BH 8/12/2012 5:15:11 PM added Jmol.getAppletHtml()
;(function (Jmol) {
var getField = function(key) {
key = "&" + key + "=";
return decodeURI(("&" + document.location.search.substring(1) + key).split(key)[1].split("&")[0]);
}
Jmol._j2sPath = getField("_J2S");
// allows URL-line setting of Info.j2sPath
Jmol._jarFile = getField("_JAR");
// allows URL-line setting of Info.jarPath and Info.jarFile
Jmol._use = getField("_USE");
// allows URL-line setting of Info.use
// defaults to "HTML5"
// looking for "_USE=xxxx"
// _USE=SIGNED implies JAVA, sets Info.isSigned, and adds "Signed" to applet jar name if necessary
Jmol.getVersion = function(){return Jmol._jmolInfo.version};
Jmol.getApplet = function(id, Info, checkOnly) {
// requires JmolApplet.js and, if JAVA, java/JmolApplet*.jar
// or if HTML5, then j2s/ subdirectory (core, java, JZ, J)
/*
var DefaultInfo = {
color: "#FFFFFF", // applet object background color, as for older jmolSetBackgroundColor(s)
width: 300,
height: 300,
addSelectionOptions: false,
serverURL: "http://your.server.here/jsmol.php",
console: null, // div for where the JavaScript console will be.
defaultModel: "",
script: null,
src: null,
readyFunction: null,
use: "HTML5",//other options include JAVA, WEBGL//, and IMAGE (removed)
jarPath: "java",
jarFile: "JmolApplet0.jar",
isSigned: false,
j2sPath: "j2s",
coverImage: null, // URL for image to display
coverTitle: "", // tip that is displayed before model starts to load
coverCommand: "", // Jmol command executed upon clicking image
deferApplet: false, // true == the model should not be loaded until the image is clicked
deferUncover: false, // true == the image should remain until command execution is complete
disableJ2SLoadMonitor: false,
disableInitialConsole: false,
debug: false
};
*/
return Jmol._Applet._get(id, Info, checkOnly);
}
Jmol.getJMEApplet = function(id, Info, linkedApplet, checkOnly) {
// Java Molecular Editor
// requires JmolJME.js and jme/ subdirectory
/*
var DefaultInfo = {
width: 300,
height: 300,
jarPath: "jme",
jarFile: "JME.jar",
use: "HTML", // or JAVA
options: "autoez"
// see http://www2.chemie.uni-erlangen.de/services/fragment/editor/jme_functions.html
// rbutton, norbutton - show / hide R button
// hydrogens, nohydrogens - display / hide hydrogens
// query, noquery - enable / disable query features
// autoez, noautoez - automatic generation of SMILES with E,Z stereochemistry
// nocanonize - SMILES canonicalization and detection of aromaticity supressed
// nostereo - stereochemistry not considered when creating SMILES
// reaction, noreaction - enable / disable reaction input
// multipart - possibility to enter multipart structures
// number - possibility to number (mark) atoms
// depict - the applet will appear without editing butons,this is used for structure display only
};
*/
return Jmol._JMEApplet._get(id, Info, linkedApplet, checkOnly);
}
Jmol.getJSVApplet = function(id, Info, checkOnly) {
// JSpecView
// requires JmolJSV.js and, if JAVA, either JSpecViewApplet.jar or JSpecViewAppletSigned.jar
// or if HTML5, then j2s/ subdirectory (core, java, JZ, J, JSV)
/*
var DefaultInfo = {
width: 500,
height: 300,
debug: false,
jarPath: ".",
jarFile: "JSpecViewApplet.jar", // or "JSpecViewAppletSigned.jar"
uee: "HTML5", // or JAVA
isSigned: false,
initParams: null,
readyFunction: null,
script: null
};
*/
return Jmol._JSVApplet._get(id, Info, checkOnly);
}
////////////////// scripting ///////////////////
Jmol.loadFile = function(applet, fileName, params){
applet._loadFile(fileName, params);
}
Jmol.script = function(applet, script) {
if (applet._checkDeferred(script))
return;
applet._script(script);
}
/**
* returns false if cannot check, empty string if OK, or error message if not OK
*/
Jmol.scriptCheck = function(applet, script) {
return applet && applet._scriptCheck && applet._ready && applet._scriptCheck(script);
}
Jmol.scriptWait = function(applet, script) {
return applet._scriptWait(script);
}
Jmol.scriptEcho = function(applet, script) {
return applet._scriptEcho(script);
}
Jmol.scriptMessage = function(applet, script) {
return applet._scriptMessage(script);
}
Jmol.scriptWaitOutput = function(applet, script) {
return applet._scriptWait(script);
}
Jmol.scriptWaitAsArray = function(applet, script) {
return applet._scriptWaitAsArray(script);
}
Jmol.search = function(applet, query, script) {
applet._search(query, script);
}
////////////////// "get" methods ///////////////////
Jmol.evaluateVar = function(applet,expr) {
return applet._evaluate(expr);
}
// DEPRECATED -- use Jmol.evaluateVar
Jmol.evaluate = function(applet,molecularMath) {
return applet._evaluateDEPRECATED(molecularMath);
}
// optional Info here
Jmol.getAppletHtml = function(applet, Info) {
if (Info) {
var d = Jmol._document;
Jmol._document = null;
applet = Jmol.getApplet(applet, Info);
Jmol._document = d;
}
return applet._code;
}
Jmol.getPropertyAsArray = function(applet,sKey,sValue) {
return applet._getPropertyAsArray(sKey,sValue);
}
Jmol.getPropertyAsJavaObject = function(applet,sKey,sValue) {
return applet._getPropertyAsJavaObject(sKey,sValue);
}
Jmol.getPropertyAsJSON = function(applet,sKey,sValue) {
return applet._getPropertyAsJSON(sKey,sValue);
}
Jmol.getPropertyAsString = function(applet,sKey,sValue) {
return applet._getPropertyAsString(sKey,sValue);
}
Jmol.getStatus = function(applet,strStatus) {
return applet._getStatus(strStatus);
}
////////////////// general methods ///////////////////
Jmol.resizeApplet = function(applet,size) {
return applet._resizeApplet(size);
}
Jmol.restoreOrientation = function(applet,id) {
return applet._restoreOrientation(id);
}
Jmol.restoreOrientationDelayed = function(applet,id,delay) {
return applet._restoreOrientationDelayed(id,delay);
}
Jmol.saveOrientation = function(applet,id) {
return applet._saveOrientation(id);
}
Jmol.say = function(msg) {
alert(msg);
}
//////////// console functions /////////////
Jmol.clearConsole = function(applet) {
applet._clearConsole();
}
Jmol.getInfo = function(applet) {
return applet._info;
}
Jmol.setInfo = function(applet, info, isShown) {
applet._info = info;
if (arguments.length > 2)
applet._showInfo(isShown);
}
Jmol.showInfo = function(applet, tf) {
applet._showInfo(tf);
}
Jmol.show2d = function(applet, tf) {
// only when JME or JSME is synced with Jmol
applet._show2d(tf);
}
//////////// controls and HTML /////////////
Jmol.jmolBr = function() {
return Jmol._documentWrite("<br />");
}
Jmol.jmolButton = function(appletOrId, script, label, id, title) {
return Jmol.controls._getButton(appletOrId, script, label, id, title);
}
Jmol.jmolCheckbox = function(appletOrId, scriptWhenChecked, scriptWhenUnchecked,
labelHtml, isChecked, id, title) {
return Jmol.controls._getCheckbox(appletOrId, scriptWhenChecked, scriptWhenUnchecked,
labelHtml, isChecked, id, title);
}
Jmol.jmolCommandInput = function(appletOrId, label, size, id, title, cmd0) {
return Jmol.controls._getCommandInput(appletOrId, label, size, id, title, cmd0);
}
Jmol.jmolHtml = function(html) {
return Jmol._documentWrite(html);
}
Jmol.jmolLink = function(appletOrId, script, label, id, title) {
return Jmol.controls._getLink(appletOrId, script, label, id, title);
}
Jmol.jmolMenu = function(appletOrId, arrayOfMenuItems, size, id, title) {
return Jmol.controls._getMenu(appletOrId, arrayOfMenuItems, size, id, title);
}
Jmol.jmolRadio = function(appletOrId, script, labelHtml, isChecked, separatorHtml, groupName, id, title) {
return Jmol.controls._getRadio(appletOrId, script, labelHtml, isChecked, separatorHtml, groupName, id, title);
}
Jmol.jmolRadioGroup = function (appletOrId, arrayOfRadioButtons, separatorHtml, groupName, id, title) {
return Jmol.controls._getRadioGroup(appletOrId, arrayOfRadioButtons, separatorHtml, groupName, id, title);
}
Jmol.setCheckboxGroup = function(chkMaster, chkBoxes) {
// chkBoxes can be an array or any number of additional string arguments
Jmol.controls._cbSetCheckboxGroup(chkMaster, chkBoxes, arguments);
}
Jmol.setDocument = function(doc) {
// If doc is null or 0, Jmol.getApplet() will still return an Object, but the HTML will
// put in applet._code and not written to the page. This can be nice, because then you
// can still refer to the applet, but place it on the page after the controls are made.
//
// This really isn't necessary, though, because there is a simpler way: Just define the
// applet variable like this:
//
// jmolApplet0 = "jmolApplet0"
//
// and then, in the getApplet command, use
//
// jmolapplet0 = Jmol.getApplet(jmolApplet0,....)
//
// prior to this, "jmolApplet0" will suffice, and after it, the Object will work as well
// in any button creation
//
// Bob Hanson 25.04.2012
Jmol._document = doc;
}
Jmol.setXHTML = function(id) {
Jmol._isXHTML = true;
Jmol._XhtmlElement = null;
Jmol._XhtmlAppendChild = false;
if (id){
Jmol._XhtmlElement = document.getElementById(id);
Jmol._XhtmlAppendChild = true;
}
}
////////////////////////////////////////////////////////////////
// Cascading Style Sheet Class support
////////////////////////////////////////////////////////////////
// BH 4/25 -- added text option. setAppletCss(null, "style=\"xxxx\"")
// note that since you must add the style keyword, this can be used to add any attribute to these tags, not just css.
Jmol.setAppletCss = function(cssClass, text) {
cssClass != null && (Jmol._appletCssClass = cssClass);
Jmol._appletCssText = text ? text + " " : cssClass ? "class=\"" + cssClass + "\" " : "";
}
Jmol.setButtonCss = function(cssClass, text) {
cssClass != null && (Jmol.controls._buttonCssClass = cssClass);
Jmol.controls._buttonCssText = text ? text + " " : cssClass ? "class=\"" + cssClass + "\" " : "";
}
Jmol.setCheckboxCss = function(cssClass, text) {
cssClass != null && (Jmol.controls._checkboxCssClass = cssClass);
Jmol.controls._checkboxCssText = text ? text + " " : cssClass ? "class=\"" + cssClass + "\" " : "";
}
Jmol.setRadioCss = function(cssClass, text) {
cssClass != null && (Jmol.controls._radioCssClass = cssClass);
Jmol.controls._radioCssText = text ? text + " " : cssClass ? "class=\"" + cssClass + "\" " : "";
}
Jmol.setLinkCss = function(cssClass, text) {
cssClass != null && (Jmol.controls._linkCssClass = cssClass);
Jmol.controls._linkCssText = text ? text + " " : cssClass ? "class=\"" + cssClass + "\" " : "";
}
Jmol.setMenuCss = function(cssClass, text) {
cssClass != null && (Jmol.controls._menuCssClass = cssClass);
Jmol.controls._menuCssText = text ? text + " ": cssClass ? "class=\"" + cssClass + "\" " : "";
}
Jmol.setAppletSync = function(applets, commands, isJmolJSV) {
Jmol._syncedApplets = applets; // an array of appletIDs
Jmol._syncedCommands = commands; // an array of commands; one or more may be null
Jmol._syncedReady = {};
Jmol._isJmolJSVSync = isJmolJSV;
}
/*
Jmol._grabberOptions = [
["$", "NCI(small molecules)"],
[":", "PubChem(small molecules)"],
["=", "RCSB(macromolecules)"]
];
*/
Jmol.setGrabberOptions = function(options) {
Jmol._grabberOptions = options;
}
Jmol.setAppletHtml = function (applet, divid) {
if (!applet._code)
return;
Jmol.$html(divid, applet._code);
if (applet._init && !applet._deferApplet)
applet._init();
}
Jmol.coverApplet = function(applet, doCover) {
if (applet._cover)
applet._cover(doCover);
}
Jmol.setFileCaching = function(applet, doCache) {
if (applet) {
applet._cacheFiles = doCache;
} else {
Jmol.fileCache = (doCache ? {} : null);
}
}
Jmol.resetView = function(applet, appletNot) {
Jmol.View.resetView(applet, appletNot);
}
Jmol.updateView = function(applet, param1, param2) {
applet._updateView(param1, param2);
}
Jmol.getChemicalInfo = function(appletOrIdentifier, what, fCallback) {
what || (what = "name");
if (typeof appletOrIdentifier != "string")
appletOrIdentifier = appletOrIdentifier._getSmiles();
return Jmol._getNCIInfo(appletOrIdentifier, what, fCallback);
}
Jmol.saveImage = function(app) {
// see: https://svgopen.org/2010/papers/62-From_SVG_to_Canvas_and_Back/index.html
// From SVG to Canvas and Back
// Samuli Kaipiainen University of Helsinki, Department of Computer Science samuli.kaipiainen@cs.helsinki.fi
// Matti Paksula University of Helsinki, Department of Computer Science matti.paksula@cs.helsinki.fi
switch (app._viewType) {
case "Jmol":
app._script("write PNGJ \"" + app._id + ".png\"");
break;
case "JSV":
app._script("write PDF");
break;
case "JME":
app._script("print");
break;
}
}
})(Jmol);
// j2sjmol.js
// NOTE: updates to this file should be copies to j2sSwingJS.js
// latest author: Bob Hanson, St. Olaf College, hansonr@stolaf.edu
// Requires JSmolCore.js and (for now; probably) JSmol.js
// This version of j2slib requires jQuery and works in both Chrome and MSIE locally,
// though Chrome cannot read local data files, and MSIE cannot read local binary data files.
// Java programming notes by Bob Hanson:
//
// There are a few motifs to avoid when optimizing Java code to work smoothly
// with the J2S compiler:
//
// arrays:
//
// 1. an array with null elements cannot be typed and must be avoided.
// 2. instances of Java "instance of" involving arrays must be found and convered to calls to Clazz.isA...
// 3. new int[n][] must not be used. Use instead JU.AU.newInt2(n);
// 4. new int[] { 1, 2, 3 } has problems because it creates simply [ ] and not IntArray32
//
// numbers:
//
// 1. Remember that EVERY number in JavaScript is a double -- doesn't matter if it is in IntArray32 or not.
// 2. You cannot reliably use Java long, because doubles consume bits for the exponent which cannot be tested.
// 3. Bit 31 of an integer is unreliable, since (int) -1 is now , not just 0zFFFFFFFF, and
// FFFFFFFF + 1 = 100000000, not 0. In JavaScript, 0xFFFFFFFF is 4294967295, not -1.
// This means that writeInt(b) will fail if b is negative. What you need is instead
// writeInt((int)(b & 0xFFFFFFFFl) so that JavaScript knocks off the high bits explicitly.
//
// general:
//
// 1. j2sRequireImport xxxx is needed if xxxx is a method used in a static function
// 2. URL.getContent() is not supported. Use other means based on URL.toString()
// 3. It is critical for performance to avoid any significant amount of function overloading.
// In particular, methods such as xxx(int a, int b) and xxx(float a, int b) MUST be renamed,
// because JavaScript only has Number, and there is absolutely no way to tell these apart.
// It's probably bad Java programming, anyway.
// 4. Calls to super(...) can almost always be avoided. These trigger the SAEM
// (searchAndExecuteMethod) call, and it is very destructive to performance.
// Just find another way to do it.
// NOTES by Bob Hanson:
// J2S class changes:
// BH 1/8/2016 6:21:38 PM adjustments to prevent multiple load of corejmol.js
// BH 12/30/2015 9:13:40 PM Clazz.floatToInt should return 0 for NaN
// BH 12/23/2015 9:23:06 AM allowing browser to display stack for TypeError in exceptionOf
// BH 12/21/2015 6:14:59 PM adding typeArray.buffer.slice to be compatible with Safari
// BH 12/20/2015 6:13:52 AM adding Int8Array; streamlining array checking
// BH 12/18/2015 5:02:52 PM adding .slice and also better array copy
// BH 7/24/2015 6:48:50 AM adding optional ?j2sdebug flag on page URL
// -- switches to using j2s/core/corexxx.js, not j2s/core/corexxx.z.js
// -- adds ";//# sourceURL="+file in eval(js)
// -- enables DebugJS.$(msg) call to debugger;
// see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger
// see https://developer.mozilla.org/en-US/docs/Tools/Debugger/How_to/Debug_eval_sources
// BH 7/23/2015 6:45:55 PM added sourceURL in each js class eval(), allowing full
// breakpoint debugging and code checking in Firefox and Chrome
// BH 7/19/2015 6:18:17 PM added os.name, line.separator, etc. to System.getProperty()
// BH 7/19/2015 5:39:10 PM added java.lang.System = System
// BH 7/19/2015 10:33:10 AM fix for SAEM equating "null" with number or boolean
// BH 7/18/2015 6:08:05 PM for Jmol I was able to remove the $private/$fx business, but now
// I see that in general that cannot be done. Thinking about a strategy...
// BH 7/18/2015 4:43:38 PM better handling of TypeError and InternalError for e.getMessage() and e.getStackTrace()
// BH 7/17/2015 11:51:15 AM adds class.getResource(name) and class.getResourceAsStream(name)
// BH 7/16/2015 7:56:49 PM general instantiation using any constructor (in Java here):
// BH x = class.forName("my.class.name").newInstance()
// BH or
// BH x = class.forName("my.class.name").getConstructor(String.class,String.class).newInstance(new Object[] {"test", "now"})
// BH 7/15/2015 11:34:58 PM adding System.lineSeparator()
// BH 7/15/2015 7:32:41 AM adding class.getCanonicalName == getName
// BH 5/31/2015 5:38:14 PM NPEExceptionPredicate fix
// BH 4/25/2015 9:16:12 AM SAEM misrepresnting Number as Object in parameters and Integer as Number
// BH 4/24/2015 7:32:54 AM Object.hashCode() and System.getIdentityHashCode() fail. changed to: return this._$hashcode || (this._$hashcode = ++Clazz._hashCode)
// BH 4/23/2015 9:08:59 AM Clazz.instanceOf(a, b) needs to check for a == b.
// BH 4/23/2015 9:08:59 AM xx.getContentType() is nonfunctional. Array.newInstance now defines a wrapper for .getClass().getComponentType() that works
// BH 4/12/2015 11:48:03 AM added Clazz.getStackTrace(-n) -- reports actual parameter values for n levels
// BH 4/10/2015 8:23:05 AM adding Int32Array.prototype.clone and Float64.prototype.clone
// BH 4/5/2015 8:12:57 AM refactoring j2slib (this file) to make private functions really private using var
// BH 4/3/2015 6:14:34 AM adding anonymous local "ClazzLoader" (Clazz._Loader) --> "_Loader"
// BH 4/3/2015 6:14:34 AM adding Clazz._Loader._classPending, Clazz._Loader._classCount
// BH 4/3/2015 6:14:34 AM adding Clazz._Loader._checkLoad
// -- forces asynchronous class loading
// -- builds Clazz._Loader._classPending and Clazz._classCount
// -- allows reporting
// BH 3/24/2015 4:11:26 AM better file load failure message in _Loader.evaluate
// BH 2/28/2015 7:30:25 AM corrects newIntArray32() and newArray() for pre-defined arrays
// int[] a = new int[] {1,2,3,343};
// int[][] b = new int[][] {new int[]{4,5},new int[]{5,6}};
// BH 9/29/2014 11:34:19 PM removing support for getClass().isArray()
// BH 8/29/2014 9:15:57 AM total reworking of Java2Script in preparation for all-asynchronous loading
// (currently sync loading is only for
// LOAD command and load() function without ASYNC
// getInterface()
// see JSmol.js and Jmol._isAsync flag
// BH 5/11/2015 5:58:42 AM adding __signatures for debugging SAEM issues
// BH 3/29/2015 8:12:44 PM System.getProperty(x, "") does not return ""
// BH 8/23/2014 10:04:19 AM cleaning up a few general methods; Clazz.removeArrayItem
// BH 6/1/2014 10:58:46 AM fix for Clazz.isAP() not working
// BH 5/26/2014 5:19:29 PM removing superConstructor call in creating Enum constants
// BH 4/1/2014 7:55:54 PM removing all $fz references and instances where sub/super classes have same private function names
// BH 4/1/2014 4:47:30 PM all $_X removed; this is taken care of by Google Closure Compiler
// BH 4/1/2014 6:40:08 AM removing ClassLoader -- equals Clazz._Loader
// BH 4/1/2014 6:40:08 AM removing ClassLoaderProgressMonitor -- equals _LoaderProgressMonitor
// BH 4/1/2014 6:17:21 AM removing Class -- only used for "Class.forName" in Jmol, which ANT will now change to "Clazz._4Name"
// BH 3/7/2014 9:05:06 AM Array.prototype.toString should not be aliased. -- http://sourceforge.net/p/jmol/bugs/560/ with Google Visualization
// BH 1/30/2014 12:54:22 PM gave all field variables prefix underscore. This allows Google Closure Compiler to skip them.
// BH 12/3/2013 3:39:57 PM window["j2s.lib"].base implemented
// BH 12/1/2013 5:34:21 AM removed _LoaderProgressMonitor.initialize and all Clazz.event business; handled by Jmol.clearVars()
// BH 11/30/2013 12:43:58 PM adding Clazz.arrayIs() -- avoids Number.constructor.toString() infinite recursion
// BH 11/29/2013 6:33:51 AM adding Clazz._profiler -- reports use of SAEM
// BH 11/10/2013 9:02:20 AM fixing fading in MSIE
// BH 11/3/2013 7:21:39 AM additional wrapping functions for better compressibility
// BH 10/30/2013 8:10:58 AM added getClass().getResource() -- returning a relative string, not a URL
// BH 10/30/2013 6:43:00 AM removed second System def and added System.$props and default System.property "line.separator"
// BH 6/15/2013 8:02:07 AM corrections to Class.isAS to return true if first element is null
// BH 6/14/2013 4:41:09 PM corrections to Clazz.isAI and related methods to include check for null object
// BH 3/17/2013 11:54:28 AM adds stackTrace for ERROR
// BH 3/13/2013 6:58:26 PM adds Clazz.clone(me) for BS clone
// BH 3/12/2013 6:30:53 AM fixes Clazz.exceptionOf for ERROR condition trapping
// BH 3/2/2013 9:09:53 AM delete globals c$ and $fz
// BH 3/2/2013 9:10:45 AM optimizing defineMethod using "look no further" "@" parameter designation (see "\\@" below -- removed 3/23/13)
// BH 2/27/2013 optimizing Clazz.getParamsType for common cases () and (Number)
// BH 2/27/2013 optimizing SAEM delegation for hashCode and equals -- disallows overloading of equals(Object)
// BH 2/23/2013 found String.replaceAll does not work -- solution was to never call it.
// BH 2/9/2013 9:18:03 PM Int32Array/Float64Array fixed for MSIE9
// BH 1/25/2013 1:55:31 AM moved package.js from j2s/java to j2s/core
// BH 1/17/2013 4:37:17 PM String.compareTo() added
// BH 1/17/2013 4:52:22 PM Int32Array and Float64Array may not have .prototype.sort method
// BH 1/16/2013 6:20:34 PM Float64Array not available in Safari 5.1
// BH 1/14/2013 11:28:58 PM Going to all doubles in JavaScript (Float64Array, not Float32Array)
// so that (new float[] {13.48f})[0] == 13.48f, effectively
// BH 1/14/2013 12:53:41 AM Fix for Opera 10 not loading any files
// BH 1/13/2013 11:50:11 PM Fix for MSIE not loading (nonbinary) files locally
// BH 12/1/2012 9:52:26 AM Compiler note: Thread.start() cannot be executed within the constructor;
// BH 11/24/2012 11:08:39 AM removed unneeded sections
// BH 11/24/2012 10:23:22 AM all XHR uses sync loading (_Loader.setLoadingMode)
// BH 11/21/2012 7:30:06 PM if (base) map["@" + pkg] = base; critical for multiple applets
// BH 10/8/2012 3:27:41 PM if (clazzName.indexOf("Array") >= 0) return "Array"; in Clazz.getClassName for function
// BH removed Clazz.ie$plit = "\\2".split (/\\/).length == 1; unnecessary; using RegEx slows process significantly in all browsers
// BH 10/6/12 added Int32Array, Float32Array, newArrayBH, upgraded java.lang and java.io
// BH added Integer.bitCount in core.z.js
// BH changed alert to Clazz.alert in java.lang.Class.js *.ClassLoader.js, java.lang.thread.js
// BH removed toString from innerFunctionNames due to infinite recursion
// BH note: Logger.error(null, e) does not work -- get no constructor for (String) (TypeError)
// BH added j2s.lib.console
// BH allowed for alias="."
// BH removed alert def --> Clazz.alert
// BH added wrapper at line 2856
// BH newArray fix at line 2205
// BH System.getProperty fix at line 6693
// BH added Enum .value() method at line 2183
// BH added System.getSecurityManager() at end
// BH added String.contains() at end
// BH added System.gc() at end
// BH added Clazz.exceptionOf = updated
// BH added String.getBytes() at end
LoadClazz = function() {
// BH This is the ONLY global used in J2S now. I do not think it is necessary,
// but it is created by the compiler, and I have not found a work-around.
// it is used as a local variable in class definitions to point to the
// current method. See Clazz.p0p and Clazz.pu$h
c$ = null;
if (!window["j2s.clazzloaded"])
window["j2s.clazzloaded"] = false;
if (window["j2s.clazzloaded"])return;
window["j2s.clazzloaded"] = true;
window["j2s.object.native"] = true;
// Clazz changes:
/* http://j2s.sf.net/ *//******************************************************************************
* Copyright (c) 2007 java2script.org and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Zhou Renjian - initial API and implementation
*****************************************************************************/
/*******
* @author zhou renjian
* @create Nov 5, 2005
*******/
/**
* Class Clazz. All the methods are static in this class.
*/
/* static */
/*Class = */ Clazz = {
_isQuiet: false,
_debugging: false
};
;(function(Clazz, Jmol) {
try {
Clazz._debugging = (document.location.href.indexOf("j2sdebug") >= 0);
} catch (e) {
}
var __debuggingBH = false;
var _globals = ["j2s.clazzloaded", "j2s.object.native"];
Clazz.setGlobal = function(a, v) {
_globals.push(a);
window[a] = v;
}
Clazz.getGlobals = function() {
return _globals.sort().join("\n");
}
Clazz.setConsoleDiv = function(d) {
window["j2s.lib"] && (window["j2s.lib"].console = d);
};
// BH Clazz.getProfile monitors exactly what is being delegated with SAEM,
// which could be a bottle-neck for function calling.
// This is critical for performance optimization.
// Jmol.getProfile()
var _profile = null;
Clazz._startProfiling = function(doProfile) {
_profile = (doProfile && self.JSON ? {} : null);
}
NullObject = function () {};
/* protected */
Clazz._supportsNativeObject = window["j2s.object.native"];
if (Clazz._supportsNativeObject) {
Clazz._O = function () {};
Clazz._O.__CLASS_NAME__ = "Object";
Clazz._O["getClass"] = function () { return Clazz._O; };
} else {
Clazz._O = Object;
}
Clazz.Console = {};
Clazz.dateToString = Date.prototype.toString;
Clazz._hashCode = 0;
var addProto = function(proto, name, func) {
return proto[name] = func;
};
;(function(proto) {
addProto(proto, "equals", function (obj) {
return this == obj;
});
addProto(proto, "hashCode", function () {
return this._$hashcode || (this._$hashcode = ++Clazz._hashCode)
/*
try {
return this.toString ().hashCode ();
} catch (e) {
var str = ":";
for (var s in this) {
str += s + ":"
}
return str.hashCode ();
}
*/
});
addProto(proto, "getClass", function () { return Clazz.getClass (this); });
addProto(proto, "clone", function () { return Clazz.clone(this); });
Clazz.clone = function(me) {
// BH allows @j2sNative access without super constructor
var o = new me.constructor();
for (var i in me) {
o[i] = me[i];
}
return o;
}
/*
* Methods for thread in Object
*/
addProto(proto, "finalize", function () {});
addProto(proto, "notify", function () {});
addProto(proto, "notifyAll", function () {});
addProto(proto, "wait", function () {});
addProto(proto, "to$tring", Object.prototype.toString);
addProto(proto, "toString", function () { return (this.__CLASS_NAME__ ? "[" + this.__CLASS_NAME__ + " object]" : this.to$tring.apply(this, arguments)); });
Clazz._extendedObjectMethods = [ "equals", "hashCode", "getClass", "clone", "finalize", "notify", "notifyAll", "wait", "to$tring", "toString" ];
})(Clazz._O.prototype);
Clazz.extendJO = function(c, name) {
if (name)
c.__CLASS_NAME__ = c.prototype.__CLASS_NAME__ = name;
if (Clazz._supportsNativeObject) {
for (var i = 0; i < Clazz._extendedObjectMethods.length; i++) {
var p = Clazz._extendedObjectMethods[i];
addProto(c.prototype, p, Clazz._O.prototype[p]);
}
}
};
/**
* Try to fix bug on Safari
*/
//InternalFunction = Object;
Clazz.extractClassName = function(clazzStr) {
// [object Int32Array]
var clazzName = clazzStr.substring (1, clazzStr.length - 1);
return (clazzName.indexOf("Array") >= 0 ? "Array" // BH -- for Float64Array and Int32Array
: clazzName.indexOf ("object ") >= 0 ? clazzName.substring (7) // IE
: clazzName);
}
/**
* Return the class name of the given class or object.
*
* @param clazzHost given class or object
* @return class name
*/
/* public */
Clazz.getClassName = function (obj) {
if (obj == null)
return "NullObject";
if (obj instanceof Clazz.CastedNull)
return obj.clazzName;
switch(typeof obj) {
case "number":
return "n";
case "boolean":
return "b";
case "string":
// Always treat the constant string as String object.
// This will be compatiable with Java String instance.
return "String";
case "function":
if (obj.__CLASS_NAME__)
return (arguments[1] ? obj.__CLASS_NAME__ : "Class"); /* user defined class name */
var s = obj.toString();
var idx0 = s.indexOf("function");
if (idx0 < 0)
return (s.charAt(0) == '[' ? Clazz.extractClassName(s) : s.replace(/[^a-zA-Z0-9]/g, ''));
var idx1 = idx0 + 8;
var idx2 = s.indexOf ("(", idx1);
if (idx2 < 0)
return "Object";
s = s.substring (idx1, idx2);
if (s.indexOf("Array") >= 0)
return "Array";
s = s.replace (/^\s+/, "").replace (/\s+$/, "");
return (s == "anonymous" || s == "" ? "Function" : s);
case "object":
if (obj.__CLASS_NAME__) // user defined class name
return obj.__CLASS_NAME__;
if (!obj.constructor)
return "Object"; // For HTML Element in IE
if (!obj.constructor.__CLASS_NAME__) {
if (obj instanceof Number)
return "Number";
if (obj instanceof Boolean)
return "Boolean";
if (obj instanceof Array || obj.BYTES_PER_ELEMENT)
return "Array";
var s = obj.toString();
// "[object Int32Array]"
if (s.charAt(0) == '[')
return Clazz.extractClassName(s);
}
return Clazz.getClassName (obj.constructor, true);
}
// some new, unidentified class
return "Object";
};
/**
* Return the class of the given class or object.
*
* @param clazzHost given class or object
* @return class name
*/
/* public */
Clazz.getClass = function (clazzHost) {
if (!clazzHost)
return Clazz._O; // null/undefined is always treated as Object
if (typeof clazzHost == "function")
return clazzHost;
var clazzName;
if (clazzHost instanceof Clazz.CastedNull) {
clazzName = clazzHost.clazzName;
} else {
switch (typeof clazzHost) {
case "string":
return String;
case "object":
if (!clazzHost.__CLASS_NAME__)
return (clazzHost.constructor || Clazz._O);
clazzName = clazzHost.__CLASS_NAME__;
break;
default:
return clazzHost.constructor;
}
}
return Clazz.evalType(clazzName, true);
};
/* private */
var checkInnerFunction = function (hostSuper, funName) {
for (var k = 0; k < Clazz.innerFunctionNames.length; k++)
if (funName == Clazz.innerFunctionNames[k] &&
Clazz._innerFunctions[funName] === hostSuper[funName])
return true;
return false;
};
var args4InheritClass = function () {};
Clazz.inheritArgs = new args4InheritClass ();
/**
* Inherit class with "extends" keyword and also copy those static members.
* Example, as in Java, if NAME is a static member of ClassA, and ClassB
* extends ClassA then ClassB.NAME can be accessed in some ways.
*
* @param clazzThis child class to be extended
* @param clazzSuper super class which is inherited from
* @param objSuper super class instance
*/
/* protected */
Clazz.inheritClass = function (clazzThis, clazzSuper, objSuper) {
//var thisClassName = Clazz.getClassName (clazzThis);
for (var o in clazzSuper) {
if (o != "b$" && o != "prototype" && o != "superClazz"
&& o != "__CLASS_NAME__" && o != "implementz"
&& !checkInnerFunction (clazzSuper, o)) {
clazzThis[o] = clazzSuper[o];
}
}
if (Clazz.unloadedClasses[Clazz.getClassName(clazzThis, true)]) {
// Don't change clazzThis.protoype! Keep it!
} else if (objSuper) {
// ! Unsafe reference prototype to an instance!
// Feb 19, 2006 --josson
// OK for this reference to an instance, as this is anonymous instance,
// which is not referenced elsewhere.
// March 13, 2006
clazzThis.prototype = objSuper;
} else if (clazzSuper !== Number) {
clazzThis.prototype = new clazzSuper (Clazz.inheritArgs);
} else { // Number
clazzThis.prototype = new Number ();
}
clazzThis.superClazz = clazzSuper;
/*
* Is it necessary to reassign the class name?
* Mar 10, 2006 --josson
*/
//clazzThis.__CLASS_NAME__ = thisClassName;
clazzThis.prototype.__CLASS_NAME__ = clazzThis.__CLASS_NAME__;
};
/**
* Implementation of Java's keyword "implements".
* As in JavaScript there are on "implements" keyword implemented, a property
* of "implementz" is added to the class to record the interfaces the class
* is implemented.
*
* @param clazzThis the class to implement
* @param interfacez Array of interfaces
*/
/* public */
Clazz.implementOf = function (clazzThis, interfacez) {
if (arguments.length >= 2) {
if (!clazzThis.implementz)
clazzThis.implementz = [];
var impls = clazzThis.implementz;
if (arguments.length == 2) {
if (typeof interfacez == "function") {
impls.push(interfacez);
copyProperties(clazzThis, interfacez);
} else if (interfacez instanceof Array) {
for (var i = 0; i < interfacez.length; i++) {
impls.push(interfacez[i]);
copyProperties(clazzThis, interfacez[i]);
}
}
} else {
for (var i = 1; i < arguments.length; i++) {
impls.push(arguments[i]);
copyProperties(clazzThis, arguments[i]);
}
}
}
};
/*
* Copy members of interface
*/
/* private */
var copyProperties = function(clazzThis, clazzSuper) {
for (var o in clazzSuper)
if (o != "b$"
&& o != "prototype" && o != "superClazz"
&& o != "__CLASS_NAME__" && o != "implementz"
&& (typeof clazzSuper[o] != "function" || !checkInnerFunction(clazzSuper, o)))
clazzThis[o] = clazzThis.prototype[o] = clazzSuper[o];
};
/**
* TODO: More should be done for interface's inheritance
*/
/* public */
Clazz.extendInterface = Clazz.implementOf;
/* protected */
Clazz.equalsOrExtendsLevel = function (clazzThis, clazzAncestor) {
if (clazzThis === clazzAncestor)
return 0;
if (clazzThis.implementz) {
var impls = clazzThis.implementz;
for (var i = 0; i < impls.length; i++) {
var level = Clazz.equalsOrExtendsLevel (impls[i], clazzAncestor);
if (level >= 0)
return level + 1;
}
}
return -1;
};
/* protected */
Clazz.getInheritedLevel = function (clazzTarget, clazzBase) {
if (clazzTarget === clazzBase)
return 0;
var isTgtStr = (typeof clazzTarget == "string");
if (isTgtStr && ("void" == clazzTarget || "unknown" == clazzTarget))
return -1;
var isBaseStr = (typeof clazzBase == "string");
if (isBaseStr && ("void" == clazzBase || "unknown" == clazzBase))
return -1;
if (clazzTarget === (isTgtStr ? "NullObject" : NullObject)) {
switch (clazzBase) {
case "n":
case "b":
return -1;
case Number:
case Boolean:
case NullObject:
break;
default:
return 0;
}
}
if (isTgtStr)
clazzTarget = Clazz.evalType(clazzTarget);
if (isBaseStr)
clazzBase = Clazz.evalType(clazzBase);
if (!clazzBase || !clazzTarget)
return -1;
var level = 0;
var zzalc = clazzTarget; // zzalc <--> clazz
while (zzalc !== clazzBase && level < 10) {
/* maybe clazzBase is interface */
if (zzalc.implementz) {
var impls = zzalc.implementz;
for (var i = 0; i < impls.length; i++) {
var implsLevel = Clazz.equalsOrExtendsLevel (impls[i], clazzBase);
if (implsLevel >= 0)
return level + implsLevel + 1;
}
}
zzalc = zzalc.superClazz;
if (!zzalc)
return (clazzBase === Object || clazzBase === Clazz._O ?
// getInheritedLevel(String, CharSequence) == 1
// getInheritedLevel(String, Object) == 1.5
// So if both #test(CharSequence) and #test(Object) existed,
// #test("hello") will correctly call #test(CharSequence)
// instead of #test(Object).
level + 1.5 // 1.5! Special!
: -1);
level++;
}
return level;
};
/**
* Implements Java's keyword "instanceof" in JavaScript's way.
* As in JavaScript part of the object inheritance is implemented in only-
* JavaScript way.
*
* @param obj the object to be tested
* @param clazz the class to be checked
* @return whether the object is an instance of the class
*/
/* public */
Clazz.instanceOf = function (obj, clazz) {
// allows obj to be a class already, from arrayX.getClass().isInstance(y)
return (obj != null && clazz && (obj == clazz || obj instanceof clazz || Clazz.getInheritedLevel(Clazz.getClassName(obj), clazz) >= 0));
};
/**
* Call super method of the class.
* The same effect as Java's expression:
* <code> super.* () </code>
*
* @param objThis host object
* @param clazzThis class of declaring method scope. It's hard to determine
* which super class is right class for "super.*()" call when it's in runtime
* environment. For example,
* 1. ClasssA has method #run()
* 2. ClassB extends ClassA overriding method #run() with "super.run()" call
* 3. ClassC extends ClassB
* 4. objC is an instance of ClassC
* Now we have to decide which super #run() method is to be invoked. Without
* explicit clazzThis parameter, we only know that objC.getClass() is ClassC
* and current method scope is #run(). We do not known we are in scope
* ClassA#run() or scope of ClassB#run(). if ClassB is given, Clazz can search
* all super methods that are before ClassB and get the correct super method.
* This is the reason why there must be an extra clazzThis parameter.
* @param funName method name to be called
* @param funParams Array of method parameters
*/
/* public */
Clazz.superCall = function (objThis, clazzThis, funName, funParams) {
var fx = null;
var i = -1;
var clazzFun = objThis[funName];
if (clazzFun) {
if (clazzFun.claxxOwner) {
// claxxOwner is a mark for methods that is single.
if (clazzFun.claxxOwner !== clazzThis) {
// This is a single method, call directly!
fx = clazzFun;
}
} else if (!clazzFun.stacks && !(clazzFun.lastClaxxRef
&& clazzFun.lastClaxxRef.prototype[funName]
&& clazzFun.lastClaxxRef.prototype[funName].stacks)) { // super.toString
fx = clazzFun;
} else { // normal wrapped method
var stacks = clazzFun.stacks;
if (!stacks)
stacks = clazzFun.lastClaxxRef.prototype[funName].stacks;
for (i = stacks.length; --i >= 0;) {
/*
* Once super call is computed precisely, there are no need
* to calculate the inherited level but just an equals
* comparision
*/
//var level = Clazz.getInheritedLevel (clazzThis, stacks[i]);
if (clazzThis === stacks[i]) { // level == 0
if (i > 0) {
fx = stacks[--i].prototype[funName];
} else {
/*
* Will this case be reachable?
* March 4, 2006
* Should never reach here if all things are converted
* by Java2Script
*/
fx = stacks[0].prototype[funName]["\\unknown"];
}
break;
} else if (Clazz.getInheritedLevel (clazzThis, stacks[i]) > 0) {
fx = stacks[i].prototype[funName];
break;
}
} // end of for loop
} // end of normal wrapped method
} // end of clazzFun
if (!fx) {
if (funName != "construct") {
Clazz.alert (["j2slib","no class found",(funParams).typeString])
newMethodNotFoundException(objThis, clazzThis, funName,
Clazz.getParamsType(funParams).typeString);
}
/* there are members which are initialized out of the constructor */
/* No super constructor! */
return;
}
/* there are members which are initialized out of the constructor */
if (i == 0 && funName == "construct") {
var ss = clazzFun.stacks;
if (ss && !ss[0].superClazz && ss[0].con$truct)
ss[0].con$truct.apply (objThis, []);
}
/*# {$no.debug.support} >>x #*/
/* not used in Jmol
if (Clazz.tracingCalling) {
var caller = arguments.callee.caller;
if (caller === Clazz.superConstructor) {
caller = caller.arguments.callee.caller;
}
Clazz._callingStackTraces.push(new Clazz.callingStack (caller, clazzThis));
var ret = fx.apply (objThis, (funParams == null) ? [] : funParams);
Clazz._callingStackTraces.pop();
return ret;
}
*/
/*# x<< #*/
return fx.apply (objThis, funParams || []);
};
/**
* Call super constructor of the class.
* The same effect as Java's expression:
* <code> super () </code>
*/
/* public */
Clazz.superConstructor = function (objThis, clazzThis, funParams) {
Clazz.superCall (objThis, clazzThis, "construct", funParams);
/* If there are members which are initialized out of the constructor */
if (clazzThis.con$truct) {
clazzThis.con$truct.apply (objThis, []);
}
};
/**
* Class for null with a given class as to be casted.
* This class will be used as an implementation of Java's casting way.
* For example,
* <code> this.call ((String) null); </code>
*/
/* public */
Clazz.CastedNull = function (asClazz) {
if (asClazz) {
if (asClazz instanceof String) {
this.clazzName = asClazz;
} else if (asClazz instanceof Function) {
this.clazzName = Clazz.getClassName (asClazz, true);
} else {
this.clazzName = "" + asClazz;
}
} else {
this.clazzName = "Object";
}
this.toString = function () {
return null;
};
this.valueOf = function () {
return null;
};
};
/**
* API for Java's casting null.
* @see Clazz.CastedNull
*
* @param asClazz given class
* @return an instance of class Clazz.CastedNull
*/
/* public */
Clazz.castNullAs = function (asClazz) {
return new Clazz.CastedNull (asClazz);
};
/////////////////////////// Exception handling ////////////////////////////
/*
* Use to mark that the Throwable instance is created or not.
*
* Called from java.lang.Throwable, as defined in JSmolJavaExt.js
*
* The underscore is important - it tells the JSmol ANT task to NOT
* turn this into Clazz_initializingException, because coreBottom2.js does
* not include that call, and so Google Closure Compiler does not minify it.
*
*/
/* public */
Clazz._initializingException = false;
/**
* BH: used in Throwable
*
*/
/* public */
Clazz._callingStackTraces = [];
/**
* MethodException will be used as a signal to notify that the method is
* not found in the current clazz hierarchy.
*/
/* private */
var MethodException = function () {
this.toString = function () {
return "J2S MethodException";
};
};
/* private */
//var MethodNotFoundException = function () {
// this.toString = function () {
// return "J2S MethodNotFoundException";
// };
//};
var _isNPEExceptionPredicate;
/* super private */
;(function() {
/* sgurin: native exception detection mechanism. Only NullPointerException detected and wrapped to java excepions */
/** private utility method for creating a general regexp that can be used later
* for detecting a certain kind of native exceptions. use with error messages like "blabla IDENTIFIER blabla"
* @param msg String - the error message
* @param spliterName String, must be contained once in msg
* spliterRegex String, a string with the regexp literal for identifying the spitter in exception further error messages.
*/
// reproduce NullPointerException for knowing how to detect them, and create detector function Clazz._isNPEExceptionPredicate
var $$o$$ = null;
try {
$$o$$.hello();
} catch (e) {
var _ex_reg = function(msg, spliterName, spliterRegex) {
if(!spliterRegex)
spliterRegex="[^\\s]+";
var idx = msg.indexOf (spliterName),
str = msg.substring (0, idx) + spliterRegex + msg.substring(idx + spliterName.length),
regexp = new RegExp("^"+str+"$");
return regexp;
};
if(/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent)) {// opera throws an exception with fixed messages like "Statement on line 23: Cannot convert undefined or null to Object Backtrace: Line....long text... "
var idx1 = e.message.indexOf(":"), idx2 = e.message.indexOf(":", idx1+2);
var _NPEMsgFragment = e.message.substr(idx1+1, idx2-idx1-20);
_isNPEExceptionPredicate = function(e) { return e.message.indexOf(_NPEMsgFragment)!=-1; };
} else if(navigator.userAgent.toLowerCase().indexOf("webkit")!=-1) { //webkit, google chrome prints the property name accessed.
var _exceptionNPERegExp = _ex_reg(e.message, "hello");
_isNPEExceptionPredicate = function(e) { return _exceptionNPERegExp.test(e.message); };
} else {// ie, firefox and others print the name of the object accessed:
var _exceptionNPERegExp = _ex_reg(e.message, "$$o$$");
_isNPEExceptionPredicate = function(e) { return _exceptionNPERegExp.test(e.message); };
}
};
})();
/**sgurin
* Implements Java's keyword "instanceof" in JavaScript's way **for exception objects**.
*
* calls Clazz.instanceOf if e is a Java exception. If not, try to detect known native
* exceptions, like native NullPointerExceptions and wrap it into a Java exception and
* call Clazz.instanceOf again. if the native exception can't be wrapped, false is returned.
*
* @param obj the object to be tested
* @param clazz the class to be checked
* @return whether the object is an instance of the class
* @author: sgurin
*/
Clazz.exceptionOf = function(e, clazz) {
if(e.__CLASS_NAME__)
return Clazz.instanceOf(e, clazz);
if (!e.getMessage) {
// Firefox at least now has a nice stack report
e.getMessage = function() {return "" + e + (e.stack ? "\n" + e.stack : "")};
}
if (!e.printStackTrace) {
e.printStackTrace = function(){};
}
if(clazz == Error) {
if (("" + e).indexOf("Error") < 0)
return false;
System.out.println (Clazz.getStackTrace());
return true;
// everything here is a Java Exception, not a Java Error
}
return (clazz == Exception || clazz == Throwable
|| clazz == NullPointerException && _isNPEExceptionPredicate(e));
};
/**
* BH need to limit this, as JavaScript call stack may be recursive
*/
Clazz.getStackTrace = function(n) {
n || (n = 25);
// updateNode and updateParents cause infinite loop here
var s = "\n";
var c = arguments.callee;
var showParams = (n < 0);
if (showParams)
n = -n;
for (var i = 0; i < n; i++) {
if (!(c = c.caller))
break;
var sig = (c.toString ? c.toString().substring(0, c.toString().indexOf("{")) : "<native method>");
s += i + " " + (c.exName ? (c.claxxOwner ? c.claxxOwner.__CLASS_NAME__ + "." : "") + c.exName + sig.replace(/function /,""): sig) + "\n";
if (c == c.caller) {
s += "<recursing>\n";
break;
}
if (showParams) {
var args = c.arguments;
for (var j = 0; j < args.length; j++) {
var sa = "" + args[j];
if (sa.length > 60)
sa = sa.substring(0, 60) + "...";
s += " args[" + j + "]=" + sa.replace(/\s+/g," ") + "\n";
}
}
}
return s;
}
///////////////////// method creation ////////////////////////////////
/**
* Make constructor for the class with the given function body and parameters
* signature.
*
* @param clazzThis host class
* @param funBody constructor body
* @param funParams constructor parameters signature
*/
/* public */
Clazz.makeConstructor = function (clazzThis, funBody, funParams) {
Clazz.defineMethod (clazzThis, "construct", funBody, funParams);
if (clazzThis.con$truct) {
clazzThis.con$truct.index = clazzThis.con$truct.stacks.length;
}
//clazzThis.con$truct = clazzThis.prototype.con$truct = null;
};
/**
* Override constructor for the class with the given function body and
* parameters signature.
*
* @param clazzThis host class
* @param funBody constructor body
* @param funParams constructor parameters signature
*/
/* public */
Clazz.overrideConstructor = function (clazzThis, funBody, funParams) {
Clazz.overrideMethod (clazzThis, "construct", funBody, funParams);
if (clazzThis.con$truct) {
clazzThis.con$truct.index = clazzThis.con$truct.stacks.length;
}
//clazzThis.con$truct = clazzThis.prototype.con$truct = null;
};
/*
* Define method for the class with the given method name and method
* body and method parameter signature.
*
* @param clazzThis host class in which the method to be defined
* @param funName method name
* @param funBody function object, e.g function () { ... }
* @param funParams paramether signature, e.g ["string", "number"]
* @return method of the given name. The method may be funBody or a wrapper
* of the given funBody.
*/
/* public */
Clazz.defineMethod = function (clazzThis, funName, funBody, funParams) {
//if (Clazz.assureInnerClass)
//Clazz.assureInnerClass(clazzThis, funBody);
funBody.exName = funName;
var fpName = formatParameters(funParams);
var proto = clazzThis.prototype;
var f$ = proto[funName];
if (Clazz._Loader._checkLoad)
checkDuplicate(clazzThis, funName, fpName);
if (!f$ || (f$.claxxOwner === clazzThis && f$.funParams == fpName)) {
// property "funParams" will be used as a mark of only-one method
funBody.funParams = fpName;
funBody.claxxOwner = clazzThis;
funBody.exClazz = clazzThis; // make it traceable
return addProto(proto, funName, funBody);
}
// we have found a duplicate
var oldFun = null;
var oldStacks = f$.stacks;
if (!oldStacks) {
/* method is not defined by Clazz.defineMethod () */
oldStacks = [];
oldFun = f$;
if (f$.claxxOwner) {
oldStacks[0] = oldFun.claxxOwner;
}
}
/*
* Method that is already defined in super class will be overridden
* with a new proxy method with class hierarchy stored in a stack.
* That is to say, the super methods are lost in this class' proxy
* method.
* When method are being called, methods defined in the new proxy
* method will be searched through first. And if no method fitted,
* it will then try to search method in the super class stacks.
*/
if (!f$.stacks || f$.claxxReference !== clazzThis) {
//Generate a new delegating method for the class
var id = ++SAEMid;
var delegate = function () {
return searchAndExecuteMethod(id, this, arguments.callee.claxxReference, arguments.callee.methodName, arguments);
};
delegate.methodName = funName;
delegate.claxxReference = clazzThis;
f$ = addProto(proto, funName, delegate);
// Keep the class inheritance stacks
var arr = [];
for (var i = 0; i < oldStacks.length; i++)
arr[i] = oldStacks[i];
f$.stacks = arr;
}
var ss = f$.stacks;
if (findArrayItem(ss, clazzThis) < 0) ss.push(clazzThis);
if (oldFun) {
if (oldFun.claxxOwner === clazzThis) {
f$[oldFun.funParams] = oldFun;
oldFun.claxxOwner = null;
// property "funParams" will be used as a mark of only-one method
oldFun.funParams = null; // null ? safe ? // safe for != null
} else if (!oldFun.claxxOwner) {
/*
* The function is not defined Clazz.defineMethod ().
* Try to fixup the method ...
* As a matter of lost method information, I just suppose
* the method to be fixed is with void parameter!
*/
f$["\\unknown"] = oldFun;
}
}
funBody.exClazz = clazzThis; // make it traceable
f$[fpName] = funBody;
return f$;
};
duplicatedMethods = {};
var checkDuplicate = function(clazzThis, funName, fpName) {
var proto = clazzThis.prototype;
var f$ = proto[funName];
if (f$ && (f$.claxxOwner || f$.claxxReference) === clazzThis) {
key = clazzThis.__CLASS_NAME__ + "." + funName + fpName;
var m = duplicatedMethods[key];
if (m) {
var s = "Warning! Duplicate method found for " + key;
System.out.println(s);
Clazz.alert(s);
duplicatedMethods[key] = m + 1;
} else {
duplicatedMethods[key] = 1;
}
}
}
Clazz.showDuplicates = function(quiet) {
var s = "";
var a = duplicatedMethods;
var n = 0;
for (var key in a)
if (a[key] > 1) {
s += a[key] + "\t" + key + "\n";
n++;
}
s = "Duplicates: " + n + "\n\n" + s;
System.out.println(s);
if (!quiet)
alert(s);
}
var findArrayItem = function(arr, item) {
if (arr && item)
for (var i = arr.length; --i >= 0;)
if (arr[i] === item)
return i;
return -1;
}
var removeArrayItem = function(arr, item) {
var i = findArrayItem(arr, item);
if (i >= 0) {
var n = arr.length - 1;
for (; i < n; i++)
arr[i] = arr[i + 1];
arr.length--;
return true;
}
}
/*
* Other developers may need to extend this formatParameters method
* to deal complicated situation.
*/
/* protected */
var formatParameters = function (funParams) {
return (funParams ? funParams.replace (/~([NABSO])/g,
function ($0, $1) {
switch ($1) {
case 'N':
return "n";
case 'B':
return "b";
case 'S':
return "String";
case 'O':
return "Object";
case 'A':
return "Array";
}
return "Unknown";
}).replace (/\s+/g, "").replace (/^|,/g, "\\").replace (/\$/g, "org.eclipse.s") : "\\void");
};
/*
* Override the existed methods which are in the same name.
* Overriding methods is provided for the purpose that the JavaScript
* does not need to search the whole hierarchied methods to find the
* correct method to execute.
* Be cautious about this method. Incorrectly using this method may
* break the inheritance system.
*
* @param clazzThis host class in which the method to be defined
* @param funName method name
* @param funBody function object, e.g function () { ... }
* @param funParams paramether signature, e.g ["string", "number"]
*/
/* public */
Clazz.overrideMethod = function(clazzThis, funName, funBody, funParams) {
//if (Clazz.assureInnerClass) Clazz.assureInnerClass (clazzThis, funBody);
funBody.exName = funName;
var fpName = formatParameters(funParams);
if (Clazz._Loader._checkLoad)
checkDuplicate(clazzThis, funName, fpName);
/*
* Replace old methods with new method. No super methods are kept.
*/
funBody.funParams = fpName;
funBody.claxxOwner = clazzThis;
return addProto(clazzThis.prototype, funName, funBody);
};
////////////// Overridden and Overloaded Java Method Handling //////////////////
// SAEM (SearchAndExecuteMethod)
// adapted by BH
//
/*
* BH Clazz.getProfile monitors exactly what is being delegated with SAEM,
* which could be a bottle-neck for function calling.
* This is critical for performance optimization.
*/
var __signatures = "";
Clazz.getProfile = function() {
var s = "";
if (_profile) {
var l = [];
for (var i in _profile) {
var n = "" + _profile[i];
l.push(" ".substring(n.length) + n + "\t" + i);
}
s = l.sort().reverse().join("\r\n");
_profile = {};
}
return s; //+ __signatures;
}
var addProfile = function(c, f, p, id) {
var s = c.__CLASS_NAME__ + " " + f + " ";// + JSON.stringify(p);
if (__signatures.indexOf(s) < 0)
__signatures += s + "\n";
_profile[s] || (_profile[s] = 0);
_profile[s]++;
}
/**
* Called also by Throwable
*
/* public */
Clazz.getParamsType = function (funParams) {
// bh: optimization here for very common cases
var n = funParams.length;
switch (n) {
case 0:
var params = ["void"];
params.typeString = "\\void";
return params;
case 1:
// BH just so common
switch (typeof obj) {
case "number":
var params = ["n"];
params.typeString = "\\n";
return params;
case "boolean":
var params = ["b"];
params.typeString = "\\b";
return params;
}
}
var params = [];
params.hasCastedNull = false;
if (funParams) {
for (var i = 0; i < n; i++) {
params[i] = Clazz.getClassName (funParams[i]);
if (funParams[i] instanceof Clazz.CastedNull) {
params.hasCastedNull = true;
}
}
}
params.typeString = "\\" + params.join ('\\');
return params;
};
var SAEMid = 0;
//xxxSAEMlist = "";
//var SAEMarray = [];
/**
* BH: OK, this was an idea that doesn't work. The idea was to tag SAEM calls
* and then refer back to an array. But the id number cannot be put in the right place.
*
* Say we have this:
*
* StringBuffer sb = new StringBuffer();
* sb.append("").append(1);
*
* Here we have two different append methods to call. They are saved under two
* names: StringBuffer.prototype.append["\\String"]
* and StringBuffer.prototype.append["\\Number"]
*
* The job of generateDelegatingMethod is to discriminate between those two. We can do
* that, but the real issue is that we have to do that EVERY time a call is made.
* This is a problem that must be handled at compile time. There is no way to
* make .append("") to go one way the first time and another way the second time.
* What we need at run time is something like this:
*
* Clazz.delegate(sb.append,1,[""]) and Clazz.delegate(sb.append,2,[1])
* The we would be able to log those numbers at run time and refer to them.
*
* The only real way to avoid SAEM is:
*
* 1) to never call super() -- always call a differently named function in a superclass.
* 2) don't overload functions
*
*/
/**
* Search the given class prototype, find the method with the same
* method name and the same parameter signatures by the given
* parameters, and then run the method with the given parameters.
*
* @param objThis the current host object
* @param claxxRef the current host object's class
* @param fxName the method name
* @param funParams the given arguments
* @return the result of the specified method of the host object,
* the return maybe void.
* @throws MethodNotFoundException if no matched method is found
*/
/* protected */
var searchAndExecuteMethod = function (id, objThis, claxxRef, fxName, args, _saem) {
// var fx = SAEMarray[id];
// if (fx) {
// return fx.apply(objThis, args);
// }
fx = objThis[fxName];
var params = Clazz.getParamsType(args);
//var s = "SAEM " + claxxRef.__CLASS_NAME__ + "." + fxName + "(" + params+ ")\n";
//if (xxxSAEMlist.length > 300)xxxSAEMlist = "";
//xxxSAEMlist += s;
if (!fx)
try {System.out.println(Clazz.getStackTrace(5))} catch (e){}
_profile && addProfile(claxxRef, fxName, params, id);
// Cache last matched method
if (fx.lastParams == params.typeString && fx.lastClaxxRef === claxxRef) {
var methodParams;
if (params.hasCastedNull) {
methodParams = [];
// For Clazz.CastedNull instances, the type name is
// already used to indentified the method in searchMethod.
for (var k = 0; k < args.length; k++)
methodParams[k] = (args[k] instanceof Clazz.CastedNull ? null : args[k]);
} else {
// if (fx.lastMethod) SAEMarray[id] = fx.lastMethod;
methodParams = args;
}
return (fx.lastMethod ? fx.lastMethod.apply(objThis, methodParams) : null);
}
fx.lastParams = params.typeString;
fx.lastClaxxRef = claxxRef;
var stacks = fx.stacks;
if (!stacks)
stacks = claxxRef.prototype[fxName].stacks;
var length = stacks.length;
/*
* Search the inheritance stacks to get the given class' function
*/
var began = false; // began to search its super classes
for (var i = length; --i >= 0;) {
if (began || stacks[i] === claxxRef) {
/*
* First try to search method within the same class scope
* with stacks[i] === claxxRef
*/
var clazzFun = stacks[i].prototype[fxName];
var ret = tryToSearchAndExecute(id, fxName, objThis, clazzFun, params,
args, fx);
if (!(ret instanceof MethodException)) {
return ret;
}
/*
* As there are no such methods in current class, Clazz will try
* to search its super class stacks. Here variable began indicates
* that super searchi is began, and there is no need checking
* <code>stacks[i] === claxxRef</code>
*/
began = true;
} // end of if
} // end of for
if ("construct" == fxName) {
/*
* For non existed constructors, just return without throwing
* exceptions. In Java codes, extending Object can call super
* default Object#constructor, which is not defined in JS.
*/
return;
}
newMethodNotFoundException(objThis, claxxRef,
fxName, params.typeString);
};
/* private */
var tryToSearchAndExecute = function(id, fxName, objThis, clazzFun, params, args, fx, _ttsaem) {
var method = [];
var generic = true;
for (var fn in clazzFun) {
if (fn.charCodeAt(0) == 92) { // 92 == '\\'.charCodeAt (0)
var ps = fn.substring(1).split("\\");
(ps.length == params.length) && method.push(ps);
generic = false;
continue;
}
/*
* When there is only one method in the class, use the args
* to identify the parameter type.
*
* AbstractCollection.remove (Object)
* AbstractList.remove (int)
* ArrayList.remove (int)
*
* Then calling #remove (Object) method on ArrayList instance will
* need to search up to the AbstractCollection.remove (Object),
* which contains only one method.
*/
/*
* See Clazz#defineMethod --Mar 10, 2006, josson
*/
if (generic && fn == "funParams" && clazzFun.funParams) {
fn = clazzFun.funParams;
var ps = fn.substring(1).split ("\\");
(ps.length == params.length) && (method[0] = ps);
break;
}
}
var debug = false;//(method.length > 1 && method.join().indexOf("Listen")< 0 && params.join().indexOf("Null") >= 0)
if (debug)alert(fxName + " -- " + method.join("|") + " -- searching for method with " + params)
if (method.length == 0 || !(method = searchMethod(method, params, debug)))
return new MethodException();
if (debug) alert("OK: \\" + method)
var f = (generic ? clazzFun : clazzFun["\\" + method]);
//if (generic)
//{ /* Use the generic method */
/*
* Will this case be reachable?
* March 4, 2006 josson
*
* Reachable for calling #remove (Object) method on
* ArrayList instance
* May 5, 2006 josson
*/
var methodParams = null;
if (params.hasCastedNull) {
methodParams = [];
for (var k = 0; k < args.length; k++) {
if (args[k] instanceof Clazz.CastedNull) {
/*
* For Clazz.CastedNull instances, the type name is
* already used to indentify the method in searchMethod.
*/
methodParams[k] = null;
} else {
methodParams[k] = args[k];
}
}
} else {
methodParams = args;
}
fx.lastMethod = f;
//if (!params.hasCastedNull) SAEMarray[id] = f;
return f.apply(objThis, methodParams);
};
/**
* Search the existed polymorphic methods to get the matched method with
* the given parameter types.
*
* @param existedMethods Array of string which contains method parameters
* @param paramTypes Array of string that is parameter type.
* @return string of method parameters seperated by "\\"
*/
/* private */
var searchMethod = function(roundOne, paramTypes, debug) {
// Filter out all the fitted methods for the given parameters
var roundTwo = [];
var len = roundOne.length;
for (var i = 0; i < len; i++) {
var fittedLevel = [];
var isFitted = true;
var len2 = roundOne[i].length;
for (var j = 0; j < len2; j++) {
fittedLevel[j] = Clazz.getInheritedLevel (paramTypes[j],
roundOne[i][j]);
//if (debug)alert([paramTypes[j],fittedLevel[j],roundOne[i][j]])
if (fittedLevel[j] < 0) {
isFitted = false;
break;
}
}
if (isFitted) {
fittedLevel[paramTypes.length] = i; // Keep index for later use
roundTwo.push(fittedLevel);
}
}
if (roundTwo.length == 0)
return null;
// Find out the best method according to the inheritance.
var resultTwo = roundTwo;
var min = resultTwo[0];
for (var i = 1; i < resultTwo.length; i++) {
var isVectorLesser = true;
for (var j = 0; j < paramTypes.length; j++) {
if (min[j] < resultTwo[i][j]) {
isVectorLesser = false;;
break;
}
}
if (isVectorLesser)
min = resultTwo[i];
}
var index = min[paramTypes.length]; // Get the previously stored index
/*
* Return the method parameters' type string as indentifier of the
* choosen method.
*/
return roundOne[index].join ('\\');
};
////////////////////////////////// package loading ///////////////////////
/*
* all root packages. e.g. java.*, org.*, com.*
*/
/* protected */
Clazz.allPackage = {};
/**
* Will be used to keep value of whether the class is defined or not.
*/
/* protected */
Clazz.allClasses = {};
Clazz.lastPackageName = null;
Clazz.lastPackage = null;
/* protected */
Clazz.unloadedClasses = [];
/* public */
Clazz.declarePackage = function (pkgName) {
if (Clazz.lastPackageName == pkgName)
return Clazz.lastPackage;
if (pkgName && pkgName.length) {
var pkgFrags = pkgName.split (/\./);
var pkg = Clazz.allPackage;
for (var i = 0; i < pkgFrags.length; i++) {
if (!pkg[pkgFrags[i]]) {
pkg[pkgFrags[i]] = {
__PKG_NAME__ : (pkg.__PKG_NAME__ ?
pkg.__PKG_NAME__ + "." + pkgFrags[i] : pkgFrags[i])
};
// pkg[pkgFrags[i]] = {};
if (i == 0) {
// eval ...
Clazz.setGlobal(pkgFrags[i], pkg[pkgFrags[i]]);
}
}
pkg = pkg[pkgFrags[i]]
}
Clazz.lastPackageName = pkgName;
Clazz.lastPackage = pkg;
return pkg;
}
};
/* protected */
Clazz.evalType = function (typeStr, isQualified) {
var idx = typeStr.lastIndexOf(".");
if (idx != -1) {
var pkgName = typeStr.substring (0, idx);
var pkg = Clazz.declarePackage (pkgName);
var clazzName = typeStr.substring (idx + 1);
return pkg[clazzName];
}
if (isQualified)
return window[typeStr];
switch (typeStr) {
case "string":
return String;
case "number":
return Number;
case "object":
return Clazz._O;
case "boolean":
return Boolean;
case "function":
return Function;
case "void":
case "undefined":
case "unknown":
return typeStr;
case "NullObject":
return NullObject;
default:
return window[typeStr];
}
};
/**
* Define a class or interface.
*
* @param qClazzName String presents the qualified name of the class
* @param clazzFun Function of the body
* @param clazzParent Clazz to inherit from, may be null
* @param interfacez Clazz may implement one or many interfaces
* interfacez can be Clazz object or Array of Clazz objects.
* @return Ruturn the modified Clazz object
*/
/* public */
Clazz.defineType = function (qClazzName, clazzFun, clazzParent, interfacez) {
var cf = Clazz.unloadedClasses[qClazzName];
if (cf) {
clazzFun = cf;
}
var idx = qClazzName.lastIndexOf (".");
if (idx != -1) {
var pkgName = qClazzName.substring (0, idx);
var pkg = Clazz.declarePackage (pkgName);
var clazzName = qClazzName.substring (idx + 1);
if (pkg[clazzName]) {
// already defined! Should throw exception!
return pkg[clazzName];
}
pkg[clazzName] = clazzFun;
} else {
if (window[qClazzName]) {
// already defined! Should throw exception!
return window[qClazzName];
}
Clazz.setGlobal(qClazzName, clazzFun);
}
Clazz.decorateAsType(clazzFun, qClazzName, clazzParent, interfacez);
/*# {$no.javascript.support} >>x #*/
var iFun = Clazz._innerFunctions;
clazzFun.defineMethod = iFun.defineMethod;
clazzFun.defineStaticMethod = iFun.defineStaticMethod;
clazzFun.makeConstructor = iFun.makeConstructor;
/*# x<< #*/
return clazzFun;
};
var isSafari = (navigator.userAgent.indexOf ("Safari") != -1);
var isSafari4Plus = false;
if (isSafari) {
var ua = navigator.userAgent;
var verIdx = ua.indexOf("Version/");
if (verIdx != -1) {
var verStr = ua.substring(verIdx + 8);
var verNumber = parseFloat(verStr);
isSafari4Plus = verNumber >= 4.0;
}
}
/* public */
Clazz.instantialize = function (objThis, args) {
if (args && args.length == 1 && args[0]
&& args[0] instanceof args4InheritClass) {
return;
}
if (objThis instanceof Number) {
objThis.valueOf = function () {
return this;
};
}
if (isSafari4Plus) { // Fix bug of Safari 4.0+'s over-optimization
var argsClone = [];
for (var k = 0; k < args.length; k++) {
argsClone[k] = args[k];
}
args = argsClone;
}
var c = objThis.construct;
if (c) {
if (!objThis.con$truct) { // no need to init fields
c.apply (objThis, args);
} else if (!objThis.getClass ().superClazz) { // the base class
objThis.con$truct.apply (objThis, []);
c.apply (objThis, args);
} else if ((c.claxxOwner
&& c.claxxOwner === objThis.getClass ())
|| (c.stacks
&& c.stacks[c.stacks.length - 1] == objThis.getClass ())) {
/*
* This #construct is defined by this class itself.
* #construct will call Clazz.superConstructor, which will
* call #con$truct back
*/
c.apply (objThis, args);
} else { // constructor is a super constructor
if (c.claxxOwner && !c.claxxOwner.superClazz
&& c.claxxOwner.con$truct) {
c.claxxOwner.con$truct.apply (objThis, []);
} else if (c.stacks && c.stacks.length == 1
&& !c.stacks[0].superClazz) {
c.stacks[0].con$truct.apply (objThis, []);
}
c.apply (objThis, args);
objThis.con$truct.apply (objThis, []);
}
} else if (objThis.con$truct) {
objThis.con$truct.apply (objThis, []);
}
};
/**
* Once there are other methods registered to the Function.prototype,
* those method names should be add to the following Array.
*/
/*
* static final member of interface may be a class, which may
* be function.
*/
/* protected */
Clazz.innerFunctionNames = [
"isInstance", "equals", "hashCode", /*"toString",*/ "getName", "getCanonicalName", "getClassLoader", "getResource", "getResourceAsStream" /*# {$no.javascript.support} >>x #*/, "defineMethod", "defineStaticMethod",
"makeConstructor" /*# x<< #*/
];
/*
* Static methods
*/
Clazz._innerFunctions = {
/*
* Similar to Object#equals
*/
isInstance: function(c) {
return Clazz.instanceOf(c, this);
},
equals : function (aFun) {
return this === aFun;
},
hashCode : function () {
return this.getName ().hashCode ();
},
toString : function () {
return "class " + this.getName ();
},
/*
* Similar to Class#getName
*/
getName : function () {
return Clazz.getClassName (this, true);
},
getCanonicalName : function () {
return this.__CLASS_NAME__;
},
getClassLoader : function () {
var clazzName = this.__CLASS_NAME__;
var baseFolder = Clazz._Loader.getClasspathFor(clazzName);
var x = baseFolder.lastIndexOf (clazzName.replace (/\./g, "/"));
if (x != -1) {
baseFolder = baseFolder.substring (0, x);
} else {
baseFolder = Clazz._Loader.getClasspathFor(clazzName, true);
}
var loader = Clazz._Loader.requireLoaderByBase(baseFolder);
loader.getResourceAsStream = Clazz._innerFunctions.getResourceAsStream;
loader.getResource = Clazz._innerFunctions.getResource; // BH
return loader;
},
getResource : function(name) {
var stream = this.getResourceAsStream(name);
return (stream ? stream.url : null);
},
getResourceAsStream : function (name) {
if (!name)
return null;
name = name.replace (/\\/g, '/');
var baseFolder = null;
var fname = name;
var clazzName = this.__CLASS_NAME__;
if (arguments.length == 2 && name.indexOf ('/') != 0) { // additional argument
name = "/" + name;
}
if (name.indexOf ('/') == 0) {
//is.url = name.substring (1);
if (arguments.length == 2) { // additional argument
baseFolder = arguments[1];
if (!baseFolder)
baseFolder = Clazz.binaryFolders[0];
} else if (Clazz._Loader) {
baseFolder = Clazz._Loader.getClasspathFor(clazzName, true);
}
if (!baseFolder) {
fname = name.substring (1);
} else {
baseFolder = baseFolder.replace (/\\/g, '/');
var length = baseFolder.length;
var lastChar = baseFolder.charAt (length - 1);
if (lastChar != '/') {
baseFolder += "/";
}
fname = baseFolder + name.substring (1);
}
} else {
if (this.base) {
baseFolder = this.base;
} else if (Clazz._Loader) {
baseFolder = Clazz._Loader.getClasspathFor(clazzName);
var x = baseFolder.lastIndexOf (clazzName.replace (/\./g, "/"));
if (x != -1) {
baseFolder = baseFolder.substring (0, x);
} else {
//baseFolder = null;
var y = -1;
if (baseFolder.indexOf (".z.js") == baseFolder.length - 5
&& (y = baseFolder.lastIndexOf ("/")) != -1) {
baseFolder = baseFolder.substring (0, y + 1);
var pkgs = clazzName.split (/\./);
for (var k = 1; k < pkgs.length; k++) {
var pkgURL = "/";
for (var j = 0; j < k; j++) {
pkgURL += pkgs[j] + "/";
}
if (pkgURL.length > baseFolder.length) {
break;
}
if (baseFolder.indexOf (pkgURL) == baseFolder.length - pkgURL.length) {
baseFolder = baseFolder.substring (0, baseFolder.length - pkgURL.length + 1);
break;
}
}
} else {
baseFolder = Clazz._Loader.getClasspathFor(clazzName, true);
}
}
} else {
var bins = Clazz.binaryFolders;
if (bins && bins.length) {
baseFolder = bins[0];
}
}
if (!baseFolder)
baseFolder = "j2s/";
baseFolder = baseFolder.replace (/\\/g, '/');
var length = baseFolder.length;
var lastChar = baseFolder.charAt (length - 1);
if (lastChar != '/') {
baseFolder += "/";
}
if (this.base) {
fname = baseFolder + name;
} else {
var idx = clazzName.lastIndexOf ('.');
if (idx == -1 || this.base) {
fname = baseFolder + name;
} else {
fname = baseFolder + clazzName.substring (0, idx)
.replace (/\./g, '/') + "/" + name;
}
}
}
var url = null;
try {
if (fname.indexOf(":/") < 0) {
var d = document.location.href.split("?")[0].split("/");
d[d.length - 1] = fname;
fname = d.join("/");
}
url = new java.net.URL(fname);
} catch (e) {
}
var data = (url == null ? null : Jmol._getFileData(fname.toString()));
if (!data || data == "error" || data.indexOf("[Exception") == 0)
return null;
var bytes = new java.lang.String(data).getBytes();
var is = new java.io.BufferedInputStream ( new java.io.ByteArrayInputStream (bytes));
is.url = url;
return is;
}/*# {$no.javascript.support} >>x #*/,
/*
* For JavaScript programmers
*/
defineMethod : function (methodName, funBody, paramTypes) {
Clazz.defineMethod (this, methodName, funBody, paramTypes);
},
/*
* For JavaScript programmers
*/
defineStaticMethod : function (methodName, funBody, paramTypes) {
Clazz.defineMethod (this, methodName, funBody, paramTypes);
this[methodName] = this.prototype[methodName];
},
/*
* For JavaScript programmers
*/
makeConstructor : function (funBody, paramTypes) {
Clazz.makeConstructor (this, funBody, paramTypes);
}
/*# x<< #*/
};
var cStack = [];
/**
* BH: I would like to be able to remove "self.c$" here, but that is tricky.
*/
Clazz.pu$h = function (c) {
c || (c = self.c$); // old style
c && cStack.push(c);
};
Clazz.p0p = function () {
return cStack.pop();
};
/* protected */
Clazz.decorateAsClass = function (clazzFun, prefix, name, clazzParent,
interfacez, parentClazzInstance, _decorateAsClass) {
var prefixName = null;
if (prefix) {
prefixName = prefix.__PKG_NAME__;
if (!prefixName)
prefixName = prefix.__CLASS_NAME__;
}
var qName = (prefixName ? prefixName + "." : "") + name;
if (Clazz._Loader._classPending[qName]) {
delete Clazz._Loader._classPending[qName];
Clazz._Loader._classCountOK++;
Clazz._Loader._classCountPending--;
}
if (Clazz._Loader && Clazz._Loader._checkLoad) {
System.out.println("decorating class " + prefixName + "." + name);
}
var cf = Clazz.unloadedClasses[qName];
if (cf) {
clazzFun = cf;
}
var qName = null;
decorateFunction(clazzFun, prefix, name);
if (parentClazzInstance) {
Clazz.inheritClass (clazzFun, clazzParent, parentClazzInstance);
} else if (clazzParent) {
Clazz.inheritClass (clazzFun, clazzParent);
}
if (interfacez) {
Clazz.implementOf (clazzFun, interfacez);
}
return clazzFun;
};
/* private */
var decorateFunction = function (clazzFun, prefix, name, _decorateFunction) {
var qName;
if (!prefix) {
// e.g. Clazz.declareInterface (null, "ICorePlugin", org.eclipse.ui.IPlugin);
qName = name;
Clazz.setGlobal(name, clazzFun);
} else if (prefix.__PKG_NAME__) {
// e.g. Clazz.declareInterface (org.eclipse.ui, "ICorePlugin", org.eclipse.ui.IPlugin);
qName = prefix.__PKG_NAME__ + "." + name;
prefix[name] = clazzFun;
if (prefix === java.lang)
Clazz.setGlobal(name, clazzFun);
} else {
// e.g. Clazz.declareInterface (org.eclipse.ui.Plugin, "ICorePlugin", org.eclipse.ui.IPlugin);
qName = prefix.__CLASS_NAME__ + "." + name;
prefix[name] = clazzFun;
}
Clazz.extendJO(clazzFun, qName);
var inF = Clazz.innerFunctionNames;
for (var i = 0; i < inF.length; i++) {
clazzFun[inF[i]] = Clazz._innerFunctions[inF[i]];
}
if (Clazz._Loader)
Clazz._Loader.updateNodeForFunctionDecoration(qName);
};
/* protected */
Clazz.declareInterface = function (prefix, name, interfacez, _declareInterface) {
var clazzFun = function () {};
decorateFunction(clazzFun, prefix, name);
if (interfacez) {
Clazz.implementOf (clazzFun, interfacez);
}
return clazzFun;
};
/* public */
Clazz.declareType = function (prefix, name, clazzParent, interfacez,
parentClazzInstance, _declareType) {
var f = function () {
Clazz.instantialize (this, arguments);
};
return Clazz.decorateAsClass (f, prefix, name, clazzParent, interfacez,
parentClazzInstance);
};
/* public */
Clazz.declareAnonymous = function (prefix, name, clazzParent, interfacez,
parentClazzInstance, _declareAnonymous) {
var f = function () {
Clazz.prepareCallback(this, arguments);
Clazz.instantialize (this, arguments);
};
return Clazz.decorateAsClass (f, prefix, name, clazzParent, interfacez,
parentClazzInstance);
};
/* public */
Clazz.decorateAsType = function (clazzFun, qClazzName, clazzParent,
interfacez, parentClazzInstance, inheritClazzFuns, _decorateAsType) {
Clazz.extendJO(clazzFun, qClazzName);
clazzFun.equals = Clazz._innerFunctions.equals;
clazzFun.getName = Clazz._innerFunctions.getName;
if (inheritClazzFuns) {
for (var i = 0; i < Clazz.innerFunctionNames.length; i++) {
var methodName = Clazz.innerFunctionNames[i];
clazzFun[methodName] = Clazz._innerFunctions[methodName];
}
}
if (parentClazzInstance) {
Clazz.inheritClass (clazzFun, clazzParent, parentClazzInstance);
} else if (clazzParent) {
Clazz.inheritClass (clazzFun, clazzParent);
}
if (interfacez) {
Clazz.implementOf (clazzFun, interfacez);
}
return clazzFun;
};
////////////////////////// default package declarations ////////////////////////
/* sgurin: preserve Number.prototype.toString */
Number.prototype._numberToString=Number.prototype.toString;
Clazz.declarePackage ("java.io");
//Clazz.declarePackage ("java.lang");
Clazz.declarePackage ("java.lang.annotation"); // java.lang
Clazz.declarePackage ("java.lang.instrument"); // java.lang
Clazz.declarePackage ("java.lang.management"); // java.lang
Clazz.declarePackage ("java.lang.reflect"); // java.lang
Clazz.declarePackage ("java.lang.ref"); // java.lang.ref
java.lang.ref.reflect = java.lang.reflect;
Clazz.declarePackage ("java.util");
//var reflect = Clazz.declarePackage ("java.lang.reflect");
Clazz.declarePackage ("java.security");
/*
* Consider these interfaces are basic!
*/
Clazz.declareInterface (java.io,"Closeable");
Clazz.declareInterface (java.io,"DataInput");
Clazz.declareInterface (java.io,"DataOutput");
Clazz.declareInterface (java.io,"Externalizable");
Clazz.declareInterface (java.io,"Flushable");
Clazz.declareInterface (java.io,"Serializable");
Clazz.declareInterface (java.lang,"Iterable");
Clazz.declareInterface (java.lang,"CharSequence");
Clazz.declareInterface (java.lang,"Cloneable");
Clazz.declareInterface (java.lang,"Appendable");
Clazz.declareInterface (java.lang,"Comparable");
Clazz.declareInterface (java.lang,"Runnable");
Clazz.declareInterface (java.util,"Comparator");
java.lang.ClassLoader = {
__CLASS_NAME__ : "ClassLoader"
};
/******************************************************************************
* Copyright (c) 2007 java2script.org and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Zhou Renjian - initial API and implementation
*****************************************************************************/
/*******
* @author zhou renjian
* @create March 10, 2006
*******/
/**
* Once ClassExt.js is part of Class.js.
* In order to make the Class.js as small as possible, part of its content
* is moved into this ClassExt.js.
*
* See also http://j2s.sourceforge.net/j2sclazz/
*/
/**
* Clazz.MethodNotFoundException is used to notify the developer about calling
* methods with incorrect parameters.
*/
/* protected */
// Override the Clazz.MethodNotFoundException in Class.js to give details
var newMethodNotFoundException = function (obj, clazz, method, params) {
var paramStr = "";
if (params) {
paramStr = params.substring (1).replace (/\\/g, ",");
}
var leadingStr = "";
if (method && method != "construct") {
leadingStr = "Method";
} else {
leadingStr = "Constructor";
}
var message = leadingStr + " " + Clazz.getClassName (clazz, true) + "."
+ method + "(" + paramStr + ") is not found!";
throw new java.lang.NoSuchMethodException(message);
};
/**
* Prepare "callback" for instance of anonymous Class.
* For example for the callback:
* this.callbacks.MyEditor.sayHello();
*
* This is specifically for inner classes that are referring to
* outer class methods and fields.
*
* @param objThis the host object for callback
* @param args arguments object. args[0] will be classThisObj -- the "this"
* object to be hooked
*
* Attention: parameters should not be null!
*/
/* protected */
Clazz.prepareCallback = function (innerObj, args) {
var outerObj = args[0];
var cbName = "b$"; // "callbacks";
if (innerObj && outerObj && outerObj !== window) {
var className = Clazz.getClassName(outerObj, true);
var obs = {};
if (innerObj[cbName]) // must make a copy!
for (var s in innerObj[cbName])
obs[s] = innerObj[cbName][s];
innerObj[cbName] = obs;
/*
* TODO: the following line is SWT-specific! Try to move it out!
*/
// obs[className.replace (/org\.eclipse\.swt\./, "$wt.")] = outerObj;
// all references to outer class and its superclass objects must be here as well
obs[className] = outerObj;
var clazz = Clazz.getClass(outerObj);
while (clazz.superClazz) {
clazz = clazz.superClazz;
/*
* TODO: the following line is SWT-specific! Try to move it out!
*/
// obs[Clazz.getClassName (clazz, true)
// .replace (/org\.eclipse\.swt\./, "$wt.")] = outerObj;
obs[Clazz.getClassName(clazz, true)] = outerObj;
}
var cbs = outerObj[cbName];
if (cbs)
for (var s in cbs)
obs[s] = cbs[s];
}
// remove "this" argument
// note that args is an instance of arguments -- NOT an array; does not have the .shift() method!
for (var i = 0; i < args.length - 1; i++)
args[i] = args[i + 1];
args.length--;
};
/**
* Construct instance of the given inner class.
*
* @param classInner given inner class, alway with name like "*$*"
* @param innerObj this instance which can be used to call back.
* @param finalVars final variables which the inner class may use
* @return the constructed object
*
* @see Clazz#cloneFinals
*/
/* public */
Clazz.innerTypeInstance = function (clazzInner, innerObj, finalVars) {
if (!clazzInner)
clazzInner = arguments.callee.caller;
var obj;
if (finalVars || innerObj.$finals) {
obj = new clazzInner(innerObj, Clazz.inheritArgs);
// f$ is short for the once choosen "$finals"
if (finalVars) {
if (innerObj.f$) {
var o = {};
for (var attr in innerObj.f$)
o[attr] = innerObj.f$[attr];
for (var attr in finalVars)
o[attr] = finalVars[attr];
obj.f$ = o;
} else {
obj.f$ = finalVars;
}
} else if (innerObj.f$) {
obj.f$ = innerObj.f$;
}
} else {
switch (arguments.length) {
case 3:
return new clazzInner(innerObj);
case 4:
return (innerObj.__CLASS_NAME__ == clazzInner.__CLASS_NAME__
&& arguments[3] === Clazz.inheritArgs ? innerObj : new clazzInner(innerObj, arguments[3]));
case 5:
return new clazzInner(innerObj, arguments[3], arguments[4]);
case 6:
return new clazzInner(innerObj, arguments[3], arguments[4],
arguments[5]);
case 7:
return new clazzInner(innerObj, arguments[3], arguments[4],
arguments[5], arguments[6]);
case 8:
return new clazzInner(innerObj, arguments[3], arguments[4],
arguments[5], arguments[6], arguments[7]);
case 9:
return new clazzInner(innerObj, arguments[3], arguments[4],
arguments[5], arguments[6], arguments[7], arguments[8]);
case 10:
return new clazzInner(innerObj, arguments[3], arguments[4],
arguments[5], arguments[6], arguments[7], arguments[8],
arguments[9]);
default:
//Should construct instance manually.
obj = new clazzInner(innerObj, Clazz.inheritArgs);
break;
}
}
var n = arguments.length - 3;
var args = new Array(n);
for (var i = n; --i >= 0;)
args[i] = arguments[i + 3];
Clazz.instantialize(obj, args);
return obj;
};
/**
* Clone variables whose modifier is "final".
* Usage: var o = Clazz.cloneFinals ("name", name, "age", age);
*
* @return Object with all final variables
*/
/* public */
Clazz.cloneFinals = function () {
var o = {};
var len = arguments.length / 2;
for (var i = len; --i >= 0;)
o[arguments[i + i]] = arguments[i + i + 1];
return o;
};
/* public */
Clazz.isClassDefined = Clazz.isDefinedClass = function(clazzName) {
if (!clazzName)
return false; /* consider null or empty name as non-defined class */
if (Clazz.allClasses[clazzName])
return true;
var pkgFrags = clazzName.split (/\./);
var pkg = null;
for (var i = 0; i < pkgFrags.length; i++)
if (!(pkg = (pkg ? pkg[pkgFrags[i]] : Clazz.allPackage[pkgFrags[0]]))) {
return false;
}
return (pkg && (Clazz.allClasses[clazzName] = true));
};
/**
* Define the enum constant.
* @param classEnum enum type
* @param enumName enum constant
* @param enumOrdinal enum ordinal
* @param initialParams enum constant constructor parameters
* @return return defined enum constant
*/
/* public */
Clazz.defineEnumConstant = function (clazzEnum, enumName, enumOrdinal, initialParams, clazzEnumExt) {
var o = (clazzEnumExt ? new clazzEnumExt() : new clazzEnum());
// BH avoids unnecessary calls to SAEM
o.$name = enumName;
o.$ordinal = enumOrdinal;
//Clazz.superConstructor (o, clazzEnum, [enumName, enumOrdinal]);
if (initialParams && initialParams.length)
o.construct.apply (o, initialParams);
clazzEnum[enumName] = o;
clazzEnum.prototype[enumName] = o;
if (!clazzEnum["$ values"]) { // BH added
clazzEnum["$ values"] = [] // BH added
clazzEnum.values = function() { // BH added
return this["$ values"]; // BH added
}; // BH added
}
clazzEnum["$ values"].push(o);
return o;
};
//////// (int) conversions //////////
Clazz.floatToInt = function (x) {
return isNaN(x) ? 0 : x < 0 ? Math.ceil(x) : Math.floor(x);
};
Clazz.floatToByte = Clazz.floatToShort = Clazz.floatToLong = Clazz.floatToInt;
Clazz.doubleToByte = Clazz.doubleToShort = Clazz.doubleToLong = Clazz.doubleToInt = Clazz.floatToInt;
Clazz.floatToChar = function (x) {
return String.fromCharCode (x < 0 ? Math.ceil(x) : Math.floor(x));
};
Clazz.doubleToChar = Clazz.floatToChar;
///////////////////////////////// Array additions //////////////////////////////
//
// BH: these are necessary for integer processing, especially
//
//
var getArrayType = function(n, nbits) {
if (!n) n = 0;
if (typeof n == "object") {
var b = n;
} else {
var b = new Array(n);
for (var i = 0; i < n; i++)b[i] = 0
}
b.BYTES_PER_ELEMENT = nbits >> 3;
b._fake = true;
return b;
}
var arraySlice = function(istart, iend) {
// could be Safari or could be fake
istart || (istart = 0);
iend || (iend = this.length);
if (this._fake) {
var b = new this.constructor(iend - istart);
System.arraycopy(this, istart, b, 0, iend - istart);
return b;
}
return new this.constructor(this.buffer.slice(istart * this.BYTES_PER_ELEMENT, iend * this.BYTES_PER_ELEMENT));
};
if ((Clazz.haveInt32 = !!(self.Int32Array && self.Int32Array != Array)) == true) {
if (!Int32Array.prototype.sort)
Int32Array.prototype.sort = Array.prototype.sort
} else {
Int32Array = function(n) { return getArrayType(n, 32); };
Int32Array.prototype.sort = Array.prototype.sort
Int32Array.prototype.toString = function(){return "[object Int32Array]"};
}
if (!Int32Array.prototype.slice)
Int32Array.prototype.slice = function() {return arraySlice.apply(this, arguments)};
Int32Array.prototype.clone = function() { var a = this.slice(); a.BYTES_PER_ELEMENT = 4; return a; };
if ((Clazz.haveFloat64 = !!(self.Float64Array && self.Float64Array != Array)) == true) {
if (!Float64Array.prototype.sort)
Float64Array.prototype.sort = Array.prototype.sort
} else {
Float64Array = function(n) { return getArrayType(n, 64); };
Float64Array.prototype.sort = Array.prototype.sort
Float64Array.prototype.toString = function() {return "[object Float64Array]"};
// Darn! Mozilla makes this a double, not a float. It's 64-bit.
// and Safari 5.1 doesn't have Float64Array
}
if (!Float64Array.prototype.slice)
Float64Array.prototype.slice = function() {return arraySlice.apply(this, arguments)};
Float64Array.prototype.clone = function() { return this.slice(); };
/**
* Make arrays.
*
* @return the created Array object
*/
/* public */
Clazz.newArray = function (a, b, c, d) {
if (a != -1 || arguments.length == 2) {
// Clazz.newArray(36,null)
// Clazz.newArray(3, 0)
// Clazz.newArray(-1, ["A","B"])
// Clazz.newArray(3, 5, null)
return newTypedArray(arguments, 0);
}
// truncate array using slice
// Clazz.newArray(-1, array, ifirst, ilast+1)
// from JU.AU; slice, ensuring BYTES_PER_ELEMENT is set correctly
a = b.slice(c, d);
a.BYTES_PER_ELEMENT = b.BYTES_PER_ELEMENT;
return a;
};
var newTypedArray = function(args, nBits) {
var dim = args[0];
if (typeof dim == "string")
dim = dim.charCodeAt(0); // char
var last = args.length - 1;
var val = args[last];
if (last > 1) {
// array of arrays
// Clazz.newArray(3, 5, null)
var xargs = new Array(last); // 2 in this case
for (var i = 0; i < last; i++)
xargs[i] = args[i + 1];
var arr = new Array(dim);
for (var i = 0; i < dim; i++)
arr[i] = newTypedArray(xargs, nBits); // Call recursively
return arr;
}
// Clazz.newArray(36,null)
// Clazz.newArray(3, 0)
// Clazz.newArray(-1, ["A","B"])
if (nBits > 0 && dim < 0)
dim = val; // because we can initialize an array using new Int32Array([...])
switch (nBits) {
case 8:
var arr = new Int8Array(dim);
arr.BYTES_PER_ELEMENT = 1;
return arr;
case 32:
var arr = new Int32Array(dim);
arr.BYTES_PER_ELEMENT = 4;
return arr;
case 64:
var arr = new Float64Array(dim);
arr.BYTES_PER_ELEMENT = 8;
return arr;
default:
var arr = (dim < 0 ? val : new Array(dim));
arr.BYTES_PER_ELEMENT = 0;
if (dim > 0 && val != null)
for (var i = dim; --i >= 0;)
arr[i] = val;
return arr;
}
}
/**
* Make arrays.
*
* @return the created Array object
*/
/* public */
Clazz.newByteArray = function () {
return newTypedArray(arguments, 8);
}
/**
* Make arrays.
*
* @return the created Array object
*/
/* public */
Clazz.newIntArray = function () {
return newTypedArray(arguments, 32);
}
/**
* Make arrays.
*
* @return the created Array object
*/
/* public */
Clazz.newFloatArray = function () {
return newTypedArray(arguments, 64);
}
Clazz.newDoubleArray = Clazz.newFloatArray;
Clazz.newLongArray = Clazz.newShortArray = Clazz.newIntArray;
Clazz.newCharArray = Clazz.newBooleanArray = Clazz.newArray;
if ((Clazz.haveInt8 = !!self.Int8Array) == true) {
if (!Int8Array.prototype.sort)
Int8Array.prototype.sort = Array.prototype.sort
if (!Int8Array.prototype.slice)
Int8Array.prototype.slice = function() {return arraySlice.apply(this, arguments)};
} else {
Clazz.newByteArray = Clazz.newIntArray;
}
Int8Array.prototype.clone = function() { var a = this.slice(); a.BYTES_PER_ELEMENT = 1;return a; };
Clazz.isAB = function(a) {
return (a && typeof a == "object" && a.BYTES_PER_ELEMENT == 1);
}
Clazz.isAI = function(a) {
return (a && typeof a == "object" && a.BYTES_PER_ELEMENT == 4);
}
Clazz.isAF = function(a) {
return (a && typeof a == "object" && a.BYTES_PER_ELEMENT == 8);
}
Clazz.isAS = function(a) { // just checking first parameter
return (a && typeof a == "object" && a.constructor == Array && (typeof a[0] == "string" || typeof a[0] == "undefined"));
}
Clazz.isAII = function(a) { // assumes non-null a[0]
return (a && typeof a == "object" && Clazz.isAI(a[0]));
}
Clazz.isAFF = function(a) { // assumes non-null a[0]
return (a && typeof a == "object" && Clazz.isAF(a[0]));
}
Clazz.isAFFF = function(a) { // assumes non-null a[0]
return (a && typeof a == "object" && Clazz.isAFF(a[0]));
}
Clazz.isASS = function(a) {
return (a && typeof a == "object" && Clazz.isAS(a[0]));
}
Clazz.isAFloat = function(a) { // just checking first parameter
return (a && typeof a == "object" && a.constructor == Array && Clazz.instanceOf(a[0], Float));
}
Clazz.isAP = function(a) {
return (a && Clazz.getClassName(a[0]) == "JU.P3");
}
/**
* Make the RunnableCompatiability instance as a JavaScript function.
*
* @param jsr Instance of RunnableCompatiability
* @return JavaScript function instance represents the method run of jsr.
*/
/* public */
/*
Clazz.makeFunction = function (jsr) {
// never used in Jmol -- called by Enum, but not accessible to it -- part of SWT
return function(e) {
if (!e)
e = window.event;
if (jsr.setEvent)
jsr.setEvent(e);
jsr.run();
switch (jsr.returnSet) {
case 1:
return jsr.returnNumber;
case 2:
return jsr.returnBoolean;
case 3:
return jsr.returnObject;
}
};
};
*/
/* protected */
Clazz.defineStatics = function (clazz) {
for (var j = arguments.length, i = (j - 1) / 2; --i >= 0;) {
var val = arguments[--j]
var name = arguments[--j];
clazz[name] = clazz.prototype[name] = val;
}
};
/* public */
Clazz.prepareFields = function (clazz, fieldsFun) {
var stacks = [];
if (clazz.con$truct) {
var ss = clazz.con$truct.stacks;
var idx = 0;//clazz.con$truct.index;
for (var i = idx; i < ss.length; i++) {
stacks[i] = ss[i];
}
}
addProto(clazz.prototype, "con$truct", clazz.con$truct = function () {
var stacks = arguments.callee.stacks;
if (stacks) {
for (var i = 0; i < stacks.length; i++) {
stacks[i].apply (this, []);
}
}
});
stacks.push(fieldsFun);
clazz.con$truct.stacks = stacks;
clazz.con$truct.index = 0;
};
/*
* Serialize those public or protected fields in class
* net.sf.j2s.ajax.SimpleSerializable.
*/
/* protected */
/*
Clazz.registerSerializableFields = function (clazz) {
var args = arguments;
var length = args.length;
var newArr = [];
if (clazz.declared$Fields) {
for (var i = 0; i < clazz.declared$Fields.length; i++) {
newArr[i] = clazz.declared$Fields[i];
}
}
clazz.declared$Fields = newArr;
if (length > 0 && length % 2 == 1) {
var fs = clazz.declared$Fields;
var n = (length - 1) / 2;
for (var i = 1; i <= n; i++) {
var o = { name : args[i + i - 1], type : args[i + i] };
var existed = false;
for (var j = 0; j < fs.length; j++) {
if (fs[j].name == o.name) { // reloaded classes
fs[j].type = o.type; // update type
existed = true;
break;
}
}
if (!existed)
fs.push(o);
}
}
};
*/
/*
* Get the caller method for those methods that are wrapped by
* Clazz.searchAndExecuteMethod.
*
* @param args caller method's arguments
* @return caller method, null if there is not wrapped by
* Clazz.searchAndExecuteMethod or is called directly.
*/
/* protected */
/*
Clazz.getMixedCallerMethod = function (args) {
var o = {};
var argc = args.callee.caller; // tryToSearchAndExecute
if (argc && argc !== tryToSearchAndExecute) // inherited method's apply
argc = argc.arguments.callee.caller;
if (argc !== tryToSearchAndExecute
|| (argc = argc.arguments.callee.caller) !== Clazz.searchAndExecuteMethod)
return null;
o.claxxRef = argc.arguments[1];
o.fxName = argc.arguments[2];
o.paramTypes = Clazz.getParamsType(argc.arguments[3]);
argc = argc.arguments.callee.caller // Clazz.generateDelegatingMethod
&& argc.arguments.callee.caller; // the private method's caller
if (!argc)
return null;
o.caller = argc;
return o;
};
*/
/* BH -- The issue here is a subclass calling its private method FOO when
* there is also a private method of the same name in its super class.
* This can ALWAYS be avoided and, one could argue, is bad
* program design anyway. In Jmol, the presence of this possibility
* creates over 8000 references to the global $fx, which was only
* checked in a few rare cases. We can then also remove $fz references.
*
*/
/*
* Check and return super private method.
* In order make private methods be executed correctly, some extra javascript
* must be inserted into the beggining of the method body of the non-private
* methods that with the same method signature as following:
* <code>
* var $private = Clazz.checkPrivateMethod (arguments);
* if ($private) {
* return $private.apply (this, arguments);
* }
* </code>
* Be cautious about this. The above codes should be insert by Java2Script
* compiler or with double checks to make sure things work correctly.
*
* @param args caller method's arguments
* @return private method if there are private method fitted for the current
* calling environment
*/
/* public */
Clazz.checkPrivateMethod = function () {
// get both this one and the one calling it
me = arguments.callee.caller;
caller = arguments.callee.caller.caller;
var stack = me.stacks;
// if their classes are the same, no issue
var mySig = "\\" + Clazz.getParamsType(arguments[0]).join("\\")
if (!me.privateNote) {
me.privateNote = "You are seeing this note because the method "
+ me.exName + mySig + " in class "
+ me.exClazz.__CLASS_NAME__
+ " has a superclass method by the same name (possibly with the same parameters) that is private and "
+ " therefore might be called improperly from this class. If your "
+ " code does not run properly, or you want to make it run faster, change the name of this method to something else."
System.out.println(me.privateNote);
alert(me.privateNote);
}
/*
alert([me.exClazz.__CLASS_NAME__, me.exName,
caller.exClazz.__CLASS_NAME__, caller.exName,stack,mySig])
if (stack == null || caller.exClazz == me.exClazz)
return null;
// I am being called by a different class...
for (var i = stack.length; --i >= 0;) {
if (stacks[i] != caller.claxxRef)
continue;
// and it is on MY class stack
// if (
}
*/
/* var m = Clazz.getMixedCallerMethod (args);
if (m == null) return null;
var callerFx = m.claxxRef.prototype[m.caller.exName];
if (callerFx == null) return null; // may not be in the class hierarchies
var ppFun = null;
if (callerFx.claxxOwner ) {
ppFun = callerFx.claxxOwner.prototype[m.fxName];
} else {
var stacks = callerFx.stacks;
for (var i = stacks.length - 1; i >= 0; i--) {
var fx = stacks[i].prototype[m.caller.exName];
if (fx === m.caller) {
ppFun = stacks[i].prototype[m.fxName];
} else if (fx ) {
for (var fn in fx) {
if (fn.indexOf ('\\') == 0 && fx[fn] === m.caller) {
ppFun = stacks[i].prototype[m.fxName];
break;
}
}
}
if (ppFun) {
break;
}
}
}
if (ppFun && ppFun.claxxOwner == null) {
ppFun = ppFun["\\" + m.paramTypes];
}
if (ppFun && ppFun.isPrivate && ppFun !== args.callee) {
return ppFun;
}
*/
return null;
};
//$fz = null; // for private method declaration
// /*# {$no.debug.support} >>x #*/
// /*
// * Option to switch on/off of stack traces.
// */
// /* protect */
//Clazz.tracingCalling = false;
// /* private */
// Clazz.callingStack = function (caller, owner) {
// this.caller = caller;
// this.owner = owner;
// };
/*# x<< #*/
/**
* The first folder is considered as the primary folder.
* And try to be compatiable with _Loader system.
*/
/* private */
/*** not used in Jmol
* *
if (window["_Loader"] && _Loader.binaryFolders) {
Clazz.binaryFolders = _Loader.binaryFolders;
} else {
Clazz.binaryFolders = ["j2s/", "", "j2slib/"];
}
Clazz.addBinaryFolder = function (bin) {
if (bin) {
var bins = Clazz.binaryFolders;
for (var i = 0; i < bins.length; i++) {
if (bins[i] == bin) {
return ;
}
}
bins[bins.length] = bin;
}
};
Clazz.removeBinaryFolder = function (bin) {
if (bin) {
var bins = Clazz.binaryFolders;
for (var i = 0; i < bins.length; i++) {
if (bins[i] == bin) {
for (var j = i; j < bins.length - 1; j++) {
bins[j] = bins[j + 1];
}
bins.length--;
return bin;
}
}
}
return null;
};
Clazz.setPrimaryFolder = function (bin) {
if (bin) {
Clazz.removeBinaryFolder (bin);
var bins = Clazz.binaryFolders;
for (var i = bins.length - 1; i >= 0; i--) {
bins[i + 1] = bins[i];
}
bins[0] = bin;
}
};
***/
///////////////// special definitions of standard Java class methods ///////////
/**
* This is a simple implementation for Clazz#load. It just ignore dependencies
* of the class. This will be fine for jar *.z.js file.
* It will be overriden by _Loader#load.
* For more details, see _Loader.js
*/
/* protected */
/*
Clazz.load = function (musts, clazz, optionals, declaration) {
// not used in Jmol
if (declaration)
declaration ();
};
*/
/*
* Invade the Object prototype!
* TODO: make sure that invading Object prototype does not affect other
* existed library, such as Dojo, YUI, Prototype, ...
*/
java.lang.Object = Clazz._O;
Clazz._O.getName = Clazz._innerFunctions.getName;
java.lang.System = System = {
props : null, //new java.util.Properties (),
$props : {},
arraycopy : function (src, srcPos, dest, destPos, length) {
if (src !== dest || srcPos > destPos) {
for (var i = length; --i >= 0;)
dest[destPos++] = src[srcPos++];
} else {
destPos += length;
srcPos += length;
for (var i = length; --i >= 0;)
src[--destPos] = src[--srcPos];
}
},
currentTimeMillis : function () {
return new Date ().getTime ();
},
gc : function() {}, // bh
getProperties : function () {
return System.props;
},
getProperty : function (key, def) {
if (System.props)
return System.props.getProperty (key, def);
var v = System.$props[key];
if (typeof v != "undefined")
return v;
if (key.indexOf(".") > 0) {
v = null;
switch (key) {
case "java.version":
v = "1.6";
case "file.separator":
case "path.separator":
v = "/";
break;
case "line.separator":
v = (navigator.userAgent.indexOf("Windows") >= 0 ? "\r\n" : "\n");
break;
case "os.name":
case "os.version":
v = navigator.userAgent;
break;
}
if (v)
return System.$props[key] = v;
}
return (arguments.length == 1 ? null : def == null ? key : def); // BH
},
getSecurityManager : function() { return null }, // bh
setProperties : function (props) {
System.props = props;
},
lineSeparator : function() { return '\n' }, // bh
setProperty : function (key, val) {
if (!System.props)
return System.$props[key] = val; // BH
System.props.setProperty (key, val);
}
};
System.identityHashCode=function(obj){
if(obj==null)
return 0;
return obj._$hashcode || (obj._$hashcode = ++Clazz._hashCode)
/*
try{
return obj.toString().hashCode();
}catch(e){
var str=":";
for(var s in obj){
str+=s+":"
}
return str.hashCode();
}
*/
}
System.out = new Clazz._O ();
System.out.__CLASS_NAME__ = "java.io.PrintStream";
System.out.print = function () {};
System.out.printf = function () {};
System.out.println = function () {};
System.out.write = function () {};
System.err = new Clazz._O ();
System.err.__CLASS_NAME__ = "java.io.PrintStream";
System.err.print = function () {};
System.err.printf = function () {};
System.err.println = function () {};
System.err.write = function () {};
Clazz.popup = Clazz.assert = Clazz.log = Clazz.error = window.alert;
Thread = function () {};
Thread.J2S_THREAD = Thread.prototype.J2S_THREAD = new Thread ();
Thread.currentThread = Thread.prototype.currentThread = function () {
return this.J2S_THREAD;
};
/* not used in Jmol
Clazz.intCast = function (n) { // 32bit
var b1 = (n & 0xff000000) >> 24;
var b2 = (n & 0xff0000) >> 16;
var b3 = (n & 0xff00) >> 8;
var b4 = n & 0xff;
if ((b1 & 0x80) != 0) {
return -(((b1 & 0x7f) << 24) + (b2 << 16) + (b3 << 8) + b4 + 1);
} else {
return (b1 << 24) + (b2 << 16) + (b3 << 8) + b4;
}
};
Clazz.shortCast = function (s) { // 16bit
var b1 = (n & 0xff00) >> 8;
var b2 = n & 0xff;
if ((b1 & 0x80) != 0) {
return -(((b1 & 0x7f) << 8) + b2 + 1);
} else {
return (b1 << 8) + b4;
}
};
Clazz.byteCast = function (b) { // 8bit
if ((b & 0x80) != 0) {
return -((b & 0x7f) + 1);
} else {
return b & 0xff;
}
};
Clazz.charCast = function (c) { // 8bit
return String.fromCharCode (c & 0xff).charAt (0);
};
Clazz.floatCast = function (f) { // 32bit
return f;
};
*/
/*
* Try to fix JavaScript's shift operator defects on long type numbers.
*/
/* not used in Jmol
Clazz.longMasks = [];
Clazz.longReverseMasks = [];
Clazz.longBits = [];
;(function () {
var arr = [1];
for (var i = 1; i < 53; i++) {
arr[i] = arr[i - 1] + arr[i - 1]; // * 2 or << 1
}
Clazz.longBits = arr;
Clazz.longMasks[52] = arr[52];
for (var i = 51; i >= 0; i--) {
Clazz.longMasks[i] = Clazz.longMasks[i + 1] + arr[i];
}
Clazz.longReverseMasks[0] = arr[0];
for (var i = 1; i < 52; i++) {
Clazz.longReverseMasks[i] = Clazz.longReverseMasks[i - 1] + arr[i];
}
}) ();
Clazz.longLeftShift = function (l, o) { // 64bit
if (o == 0) return l;
if (o >= 64) return 0;
if (o > 52) {
error ("[Java2Script] Error : JavaScript does not support long shift!");
return l;
}
if ((l & Clazz.longMasks[o - 1]) != 0) {
error ("[Java2Script] Error : Such shift operator results in wrong calculation!");
return l;
}
var high = l & Clazz.longMasks[52 - 32 + o];
if (high != 0) {
return high * Clazz.longBits[o] + (l & Clazz.longReverseMasks[32 - o]) << 0;
} else {
return l << o;
}
};
Clazz.intLeftShift = function (n, o) { // 32bit
return (n << o) & 0xffffffff;
};
Clazz.longRightShift = function (l, o) { // 64bit
if ((l & Clazz.longMasks[52 - 32]) != 0) {
return Math.round((l & Clazz.longMasks[52 - 32]) / Clazz.longBits[32 - o]) + (l & Clazz.longReverseMasks[o]) >> o;
} else {
return l >> o;
}
};
Clazz.intRightShift = function (n, o) { // 32bit
return n >> o; // no needs for this shifting wrapper
};
Clazz.long0RightShift = function (l, o) { // 64bit
return l >>> o;
};
Clazz.int0RightShift = function (n, o) { // 64bit
return n >>> o; // no needs for this shifting wrapper
};
*/
// Compress the common public API method in shorter name
//$_L=Clazz.load;
//$_W=Clazz.declareAnonymous;$_T=Clazz.declareType;
//$_J=Clazz.declarePackage;$_C=Clazz.decorateAsClass;
//$_Z=Clazz.instantialize;$_I=Clazz.declareInterface;$_D=Clazz.isClassDefined;
//$_H=Clazz.pu$h;$_P=Clazz.p0p;$_B=Clazz.prepareCallback;
//$_N=Clazz.innerTypeInstance;$_K=Clazz.makeConstructor;$_U=Clazz.superCall;$_R=Clazz.superConstructor;
//$_M=Clazz.defineMethod;$_V=Clazz.overrideMethod;$_S=Clazz.defineStatics;
//$_E=Clazz.defineEnumConstant;
//$_F=Clazz.cloneFinals;
//$_Y=Clazz.prepareFields;$_A=Clazz.newArray;$_O=Clazz.instanceOf;
//$_G=Clazz.inheritArgs;$_X=Clazz.checkPrivateMethod;$_Q=Clazz.makeFunction;
//$_s=Clazz.registerSerializableFields;
//$_k=Clazz.overrideConstructor;
/////////////////////// inner function support /////////////////////////////////
/* public */
Clazz.innerFunctionNames = Clazz.innerFunctionNames.concat ([
"getSuperclass", "isAssignableFrom",
"getConstructor",
"getDeclaredMethod", "getDeclaredMethods",
"getMethod", "getMethods",
"getModifiers", /*"isArray",*/ "newInstance"]);
/* public */
Clazz._innerFunctions.getSuperclass = function () {
return this.superClazz;
};
/* public */
Clazz._innerFunctions.isAssignableFrom = function (clazz) {
return Clazz.getInheritedLevel (clazz, this) >= 0;
};
/* public */
Clazz._innerFunctions.getConstructor = function () {
return new java.lang.reflect.Constructor (this, [], [],
java.lang.reflect.Modifier.PUBLIC);
};
/**
* TODO: fix bug for polymorphic methods!
*/
/* public */
Clazz._innerFunctions.getDeclaredMethods = Clazz._innerFunctions.getMethods = function () {
var ms = [];
var p = this.prototype;
for (var attr in p) {
if (typeof p[attr] == "function" && !p[attr].__CLASS_NAME__) {
/* there are polynormical methods. */
ms.push(new java.lang.reflect.Method (this, attr,
[], java.lang.Void, [], java.lang.reflect.Modifier.PUBLIC));
}
}
p = this;
for (var attr in p) {
if (typeof p[attr] == "function" && !p[attr].__CLASS_NAME__) {
ms.push(new java.lang.reflect.Method (this, attr,
[], java.lang.Void, [], java.lang.reflect.Modifier.PUBLIC
| java.lang.reflect.Modifier.STATIC));
}
}
return ms;
};
/* public */
Clazz._innerFunctions.getDeclaredMethod = Clazz._innerFunctions.getMethod = function (name, clazzes) {
var p = this.prototype;
for (var attr in p) {
if (name == attr && typeof p[attr] == "function"
&& !p[attr].__CLASS_NAME__) {
/* there are polynormical methods. */
return new java.lang.reflect.Method (this, attr,
[], java.lang.Void, [], java.lang.reflect.Modifier.PUBLIC);
}
}
p = this;
for (var attr in p) {
if (name == attr && typeof p[attr] == "function"
&& !p[attr].__CLASS_NAME__) {
return new java.lang.reflect.Method (this, attr,
[], java.lang.Void, [], java.lang.reflect.Modifier.PUBLIC
| java.lang.reflect.Modifier.STATIC);
}
}
return null;
};
/* public */
Clazz._innerFunctions.getModifiers = function () {
return java.lang.reflect.Modifier.PUBLIC;
};
Clazz._innerFunctions.newInstance = function (a) {
var clz = this;
switch(a == null ? 0 : a.length) {
case 0:
return new clz();
case 1:
return new clz(a[0]);
case 2:
return new clz(a[0], a[1]);
case 3:
return new clz(a[0], a[1], a[2]);
case 4:
return new clz(a[0], a[1], a[2], a[3]);
default:
var x = "new " + clz.__CLASS_NAME__ + "(";
for (var i = 0; i < a.length; i++)
x += (i == 0 ? "" : ",") + "a[" + i + "]";
x += ")";
return eval(x);
}
};
//Object.newInstance = Clazz._innerFunctions.newInstance;
;(function(){ // BH added wrapper here
var inF = Clazz.innerFunctionNames;
for (var i = 0; i < inF.length; i++) {
Clazz._O[inF[i]] = Clazz._innerFunctions[inF[i]];
Array[inF[i]] = Clazz._innerFunctions[inF[i]];
}
//Array["isArray"] = function () {
// return true;
//};
})();
//////////////////////////// hotspot and unloading /////////////////////////////
/* For hotspot and unloading */
// not used in Jmol
/*
if (window["Clazz"] && !window["Clazz"].unloadClass) {
/ * public * /
Clazz.unloadClass = function (qClazzName) {
var cc = Clazz.evalType (qClazzName);
if (cc) {
Clazz.unloadedClasses[qClazzName] = cc;
var clazzName = qClazzName;
var pkgFrags = clazzName.split (/\./);
var pkg = null;
for (var i = 0; i < pkgFrags.length - 1; i++)
pkg = (pkg ? pkg[pkgFrags[i]] : Clazz.allPackage[pkgFrags[0]]);
if (!pkg) {
Clazz.allPackage[pkgFrags[0]] = null;
window[pkgFrags[0]] = null;
// also try to unload inner or anonymous classes
for (var c in window) {
if (c.indexOf (qClazzName + "$") == 0) {
Clazz.unloadClass (c);
window[c] = null;
}
}
} else {
pkg[pkgFrags[pkgFrags.length - 1]] = null;
// also try to unload inner or anonymous classes
for (var c in pkg) {
if (c.indexOf (pkgFrags[pkgFrags.length - 1] + "$") == 0) {
Clazz.unloadClass (pkg.__PKG_NAME__ + "." + c);
pkg[c] = null;
}
}
}
if (Clazz.allClasses[qClazzName]) {
Clazz.allClasses[qClazzName] = false;
// also try to unload inner or anonymous classes
for (var c in Clazz.allClasses) {
if (c.indexOf (qClazzName + "$") == 0) {
Clazz.allClasses[c] = false;
}
}
}
for (var m in cc) {
cleanDelegateMethod (cc[m]);
}
for (var m in cc.prototype) {
cleanDelegateMethod (cc.prototype[m]);
}
if (Clazz._Loader) {
Clazz._Loader.unloadClassExt(qClazzName);
}
return true;
}
return false;
};
/ * private * /
var cleanDelegateMethod = function (m) {
if (!m)
return;
if (typeof m == "function" && m.lastMethod
&& m.lastParams && m.lastClaxxRef) {
m.lastMethod = null;
m.lastParams = null;
m.lastClaxxRef = null;
}
};
} // if (window["Clazz"] && !window["Clazz"].unloadClass)
*/
/******************************************************************************
* Copyright (c) 2007 java2script.org and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Zhou Renjian - initial API and implementation
*****************************************************************************/
/*******
* @author zhou renjian
* @create July 10, 2006
*******/
//if (window["ClazzNode"] == null) {
/**
* TODO:
* Make optimization over class dependency tree.
*/
/*
* ClassLoader Summary
*
* ClassLoader creates SCRIPT elements and setup class path and onload
* callback to continue class loading.
*
* In the onload callbacks, _Loader will try to calculate the next-to-be-
* load *.js and load it. In *.js, it will contains some codes like
* Clazz.load (..., "$wt.widgets.Control", ...);
* to provide information to build up the class dependency tree.
*
* Some known problems of different browsers:
* 1. In IE, loading *.js through SCRIPT will first triggers onreadstatechange
* event, and then executes inner *.js source.
* 2. In Firefox, loading *.js will first executes *.js source and then
* triggers onload event.
* 3. In Opera, similar to IE, but trigger onload event. (TODO: More details
* should be studied. Currently, Opera supports no multiple-thread-loading)
*
* For class dependency tree, actually, it is not a tree. It is a reference
* net with nodes have n parents and n children. There is a root, which
* ClassLoader knows where to start searching and loading classes, for such
* a net. Each node is a class. Each class may require a set of must-classes,
* which must be loaded before itself getting initialized, and also need a set
* of optional classes, which also be loaded before being called.
*
* The class loading status will be in 6 stages.
* 1. Unknown, the class is newly introduced by other class.
* 2. Known, the class is already mentioned by other class.
* 3. Loaded, *.js source is in memory, but may not be initialized yet. It
* requires all its must-classes be intiailized, which is in the next stage.
* 4. Musts loaded, all must classes is already loaded and declared.
* 5. Delcared, the class is already declared (_Loader#isClassDefined).
* 6. Optionals loaded, all optional classes is loaded and declared.
*
* The ClassLoader tries to load all necessary classes in order, and intialize
* them in order. For such job, it will traverse the dependency tree, and try
* to next class to-be-loaded. Sometime, the class dependencies may be in one
* or more cycles, which must be broken down so classes is loaded in correct
* order.
*
* Loading order and intializing order is very important for the ClassLoader.
* The following technical options are considered:
* 1. SCRIPT is loading asynchronously, which means controling order must use
* callback methods to continue.
* 2. Multiple loading threads are later introduced, which requires the
* ClassLoader should use variables to record the class status.
* 3. Different browsers have different loading orders, which means extra tests
* should be tested to make sure loading order won't be broken.
* 4. Java2Script simulator itself have some loading orders that must be
* honored, which means it should be integrated seamlessly to Clazz system.
* 5. Packed *.z.js is introduced to avoid lots of small *.js which requires
* lots of HTTP connections, which means that packed *.z.js should be treated
* specially (There will be mappings for such packed classes).
* 6. *.js or *.css loading may fail according to network status, which means
* another loading try should be performed, so _Loader is more robust.
* 7. SWT lazy loading is later introduced, which means that class loading
* process may be paused and should be resumed later.
*
* Some known bugs:
* <code>$_L(["$wt.graphics.Drawable","$wt.widgets.Widget"],
* "$wt.widgets.Control", ...</code>
* has errors while must classes in different order such as
* <code>$_L(["$wt.widgets.Widget", "$wt.graphics.Drawable"],
* "$wt.widgets.Control", ...</code>
* has no error.
*
* Other maybe bug scenarios:
* 1. In <code>_Loader.maxLoadingThreads = 1;</code> single loading thread
* mode, there are no errors, but in default multiple thread loading mode,
* there are errors.
* 2. No errors in one browser, but has errors on other browsers (Browser
* script loading order differences).
* 3. First time loading has errors, but reloading it gets no errors (Maybe
* HTTP connections timeout, but should not accur in local file system, or it
* is a loading bug by using JavaScript timeout thread).
*/
/*
* The following comments with "#" are special configurations for a much
* smaller *.js file size.
*
* @see net.sf.j2s.lib/src/net/sf/j2s/lib/build/SmartJSCompressor.java
*/
/**
* Static class loader class
*/
Clazz._Loader = Clazz.ClazzLoader = function () {};
/**
* Class dependency tree node
*/
/* private */
var Node = function () {
this.parents = [];
this.musts = [];
this.optionals = [];
this.declaration = null;
this.name = null; // id
this.path = null;
// this.requires = null;
// this.requiresMap = null;
this.onLoaded = null;
this.status = 0;
this.random = 0.13412;
};
;(function(Clazz, _Loader) {
_Loader._checkLoad = Jmol._checkLoad;
_Loader.updateNodeForFunctionDecoration = function(qName) {
var node = findNode(qName);
if (node && node.status == Node.STATUS_KNOWN) {
window.setTimeout((function(nnn) {
return function() {
updateNode(nnn);
};
})(node), 1);
}
}
Node.prototype.toString = function() {
return this.name || this.path || "ClazzNode";
}
Node.STATUS_UNKNOWN = 0;
Node.STATUS_KNOWN = 1;
Node.STATUS_CONTENT_LOADED = 2;
Node.STATUS_MUSTS_LOADED = 3;
Node.STATUS_DECLARED = 4;
Node.STATUS_LOAD_COMPLETE = 5;
var loaders = [];
/* public */
_Loader.requireLoaderByBase = function (base) {
for (var i = 0; i < loaders.length; i++) {
if (loaders[i].base == base) {
return loaders[i];
}
}
var loader = new _Loader ();
loader.base = base;
loaders.push(loader);
return loader;
};
/**
* Class dependency tree
*/
var clazzTreeRoot = new Node();
/**
* Used to keep the status whether a given *.js path is loaded or not.
*/
/* private */
var loadedScripts = {};
/**
* Multiple threads are used to speed up *.js loading.
*/
/* private */
var inLoadingThreads = 0;
/**
* Maximum of loading threads
*/
/* private */
var maxLoadingThreads = 6;
var userAgent = navigator.userAgent.toLowerCase ();
var isOpera = (userAgent.indexOf ("opera") != -1);
var isIE = (userAgent.indexOf ("msie") != -1) && !isOpera;
var isGecko = (userAgent.indexOf ("gecko") != -1);
/*
* Opera has different loading order which will result in performance degrade!
* So just return to single thread loading in Opera!
*
* FIXME: This different loading order also causes bugs in single thread!
*/
if (isOpera) {
maxLoadingThreads = 1;
var index = userAgent.indexOf ("opera/");
if (index != -1) {
var verNumber = 9.0;
try {
verNumber = parseFloat(userAgent.subString (index + 6));
} catch (e) {}
if (verNumber >= 9.6) {
maxLoadingThreads = 6;
}
}
}
/**
* Try to be compatiable with Clazz system.
* In original design _Loader and Clazz are independent!
* -- zhourenjian @ December 23, 2006
*/
var isClassdefined;
var definedClasses;
if (self.Clazz && Clazz.isClassDefined) {
isClassDefined = Clazz.isClassDefined;
} else {
definedClasses = {};
isClassDefined = function (clazzName) {
return definedClasses[clazzName] == true;
};
}
/**
* Expand the shortened list of class names.
* For example:
* JU.Log, $.Display, $.Decorations
* will be expanded to
* JU.Log, JU.Display, JU.Decorations
* where "$." stands for the previous class name's package.
*
* This method will be used to unwrap the required/optional classes list and
* the ignored classes list.
*/
/* private */
var unwrapArray = function (arr) {
if (!arr || arr.length == 0)
return [];
var last = null;
for (var i = 0; i < arr.length; i++) {
if (!arr[i])
continue;
if (arr[i].charAt (0) == '$') {
if (arr[i].charAt (1) == '.') {
if (!last)
continue;
var idx = last.lastIndexOf (".");
if (idx != -1) {
var prefix = last.substring (0, idx);
arr[i] = prefix + arr[i].substring (1);
}
} else {
arr[i] = "org.eclipse.s" + arr[i].substring (1);
}
}
last = arr[i];
}
return arr;
};
/**
* Used to keep to-be-loaded classes.
*/
/* private */
var classQueue = [];
/* private */
var classpathMap = {};
/* private */
var pkgRefCount = 0;
/* public */
_Loader.loadPackageClasspath = function (pkg, base, isIndex, fSuccess, mode, pt) {
var map = classpathMap;
mode || (mode = 0);
fSuccess || (fSuccess = null);
pt || (pt = 0);
/*
* In some situation, maybe,
* _Loader.packageClasspath ("java", ..., true);
* is called after other _Loader#packageClasspath, e.g.
* <code>
* _Loader.packageClasspath ("org.eclipse.swt", "...", true);
* _Loader.packageClasspath ("java", "...", true);
* </code>
* which is not recommended. But _Loader should try to adjust orders
* which requires "java" to be declared before normal _Loader
* #packageClasspath call before that line! And later that line
* should never initialize "java/package.js" again!
*/
var isPkgDeclared = (isIndex && map["@" + pkg]);
if (mode == 0 && isIndex && !map["@java"] && pkg.indexOf ("java") != 0 && needPackage("java")) {
_Loader.loadPackage("java", fSuccess ? function(_package){_Loader.loadPackageClasspath(pkg, base, isIndex, fSuccess, 1)} : null);
if (fSuccess)
return;
}
if (pkg instanceof Array) {
unwrapArray(pkg);
if (fSuccess) {
if (pt < pkg.length)
_Loader.loadPackageClasspath(pkg[pt], base, isIndex, function(_loadPackageClassPath){_Loader.loadPackageClasspath(pkg, base, isIndex, fSuccess, 1, pt + 1)}, 1);
else
fSuccess();
} else {
for (var i = 0; i < pkg.length; i++)
_Loader.loadPackageClasspath(pkg[i], base, isIndex, null);
}
return;
}
switch (pkg) {
case "java.*":
pkg = "java";
// fall through
case "java":
if (base) {
// support ajax for default
var key = "@net.sf.j2s.ajax";
if (!map[key])
map[key] = base;
key = "@net.sf.j2s";
if (!map[key])
map[key] = base;
}
break;
case "swt":
pkg = "org.eclipse.swt";
break;
case "ajax":
pkg = "net.sf.j2s.ajax";
break;
case "j2s":
pkg = "net.sf.j2s";
break;
default:
if (pkg.lastIndexOf(".*") == pkg.length - 2)
pkg = pkg.substring(0, pkg.length - 2);
break;
}
if (base) // critical for multiple applets
map["@" + pkg] = base;
if (isIndex && !isPkgDeclared && !window[pkg + ".registered"]) {
pkgRefCount++;
if (pkg == "java")
pkg = "core" // JSmol -- moves java/package.js to core/package.js
_Loader.loadClass(pkg + ".package", function () {
if (--pkgRefCount == 0)
runtimeLoaded();
//fSuccess && fSuccess();
}, true, true, 1);
return;
}
fSuccess && fSuccess();
};
/**
* BH: allows user/developer to load classes even though wrapping and Google
* Closure Compiler has not been run on the class.
*
*/
Clazz.loadClass = function (name, onLoaded, async) {
if (!self.Class) {
Class = Clazz;
Class.forName = Clazz._4Name;
JavaObject = Clazz._O;
// maybe more here
}
return (name && _Loader.loadClass(name, onLoaded, true, async, 1));
}
/**
* Load the given class ant its related classes.
*/
/* public */
_Loader.loadClass = function (name, onLoaded, forced, async, mode) {
//System.out.println("loadClass " + name)
mode || (mode = 0); // BH: not implemented
(async == null) && (async = false);
if (typeof onLoaded == "boolean")
return Clazz.evalType(name);
// Make sure that packageClasspath ("java", base, true);
// is called before any _Loader#loadClass is called.
if (needPackage("java")) {
_Loader.loadPackage("java");
}
// BH unnecessary
// if (needPackage("core")) {
// _Loader.loadPackage("core");
// }
// var swtPkg = "org.eclipse.swt";
// if (name.indexOf (swtPkg) == 0 || name.indexOf ("$wt") == 0) {
// _Loader.assurePackageClasspath (swtPkg);
// }
// if (name.indexOf ("junit") == 0) {
// _Loader.assurePackageClasspath ("junit");
// }
// Any _Loader#loadClass calls will be queued until java.* core classes are loaded.
_Loader.keepOnLoading = true;
if (!forced && (pkgRefCount && name.lastIndexOf(".package") != name.length - 8
|| name.indexOf("java.") != 0 && !isClassDefined(runtimeKeyClass)
)) {
queueBe4KeyClazz.push([name, onLoaded]);
System.out.println("loadclass-queuing" + name+ runtimeKeyClass + " "+ isClassDefined(runtimeKeyClass))
return;
}
var b;
if ((b = isClassDefined(name)) || isClassExcluded(name)) {
if (b && onLoaded) {
var nn = findNode(name);
if (!nn || nn.status >= Node.STATUS_LOAD_COMPLETE) {
if (async) {
window.setTimeout(onLoaded, 25);
} else {
onLoaded();
}
}
}
return;
}
var path = _Loader.getClasspathFor(name);
var existed = loadedScripts[path];
var qq = classQueue;
if (!existed)
for (var i = qq.length; --i >= 0;)
if (qq[i].path == path || qq[i].name == name) {
existed = true;
break;
}
if (existed) {
if (onLoaded) {
var n = findNode(name);
if (n) {
if (!n.onLoaded) {
n.onLoaded = onLoaded;
} else if (onLoaded != n.onLoaded) {
n.onLoaded = (function (nF, oF) { return function () { nF(); oF() }; }) (n.onLoaded, onLoaded);
}
}
}
return;
}
var n = (Clazz.unloadedClasses[name] && findNode(name) || new Node());
n.name = name;
n.path = path;
n.isPackage = (path.lastIndexOf("package.js") == path.length - 10);
mappingPathNameNode(path, name, n);
n.onLoaded = onLoaded;
n.status = Node.STATUS_KNOWN;
var needBeingQueued = false;
for (var i = qq.length; --i >= 0;) {
if (qq[i].status != Node.STATUS_LOAD_COMPLETE) {
needBeingQueued = true;
break;
}
}
if (n.isPackage) {//forced
// push class to queue
var pt = qq.length;
for (; --pt >= 0;) {
if (qq[pt].isPackage)
break;
qq[pt + 1] = qq[pt];
}
qq[++pt] = n;
} else if (needBeingQueued) {
qq.push(n);
}
if (!needBeingQueued) { // can be loaded directly
var bSave = false;
if (onLoaded) {
bSave = isLoadingEntryClass;
isLoadingEntryClass = true;
}
if (forced)onLoaded = null;
addChildClassNode(clazzTreeRoot, n, true);
loadScript(n, n.path, n.requiredBy, false, onLoaded ? function(_loadClass){ isLoadingEntryClass = bSave; onLoaded()}: null);
}
};
/*
* Check whether given package's classpath is setup or not.
* Only "java" and "org.eclipse.swt" are accepted in argument.
*/
/* private */
var needPackage = function(pkg) {
// note that false != null and true != null
return (window[pkg + ".registered"] != null && !classpathMap["@" + pkg]);
}
/* private */
_Loader.loadPackage = function(pkg, fSuccess) {
fSuccess || (fSuccess = null);
window[pkg + ".registered"] = false;
_Loader.loadPackageClasspath(pkg,
(_Loader.J2SLibBase || (_Loader.J2SLibBase = (_Loader.getJ2SLibBase() || "j2s/"))),
true, fSuccess);
};
/**
* Register classes to a given *.z.js path, so only a single *.z.js is loaded
* for all those classes.
*/
/* public */
_Loader.jarClasspath = function (jar, clazzes) {
if (!(clazzes instanceof Array))
clazzes = [clazzes];
unwrapArray(clazzes);
for (var i = clazzes.length; --i >= 0;)
classpathMap["#" + clazzes[i]] = jar;
classpathMap["$" + jar] = clazzes;
};
/**
* Usually be used in .../package.js. All given packages will be registered
* to the same classpath of given prefix package.
*/
/* public */
_Loader.registerPackages = function (prefix, pkgs) {
//_Loader.checkInteractive ();
var base = _Loader.getClasspathFor (prefix + ".*", true);
for (var i = 0; i < pkgs.length; i++) {
if (window["Clazz"]) {
Clazz.declarePackage (prefix + "." + pkgs[i]);
}
_Loader.loadPackageClasspath (prefix + "." + pkgs[i], base);
}
};
/**
* Using multiple sites to load *.js in multiple threads. Using multiple
* sites may avoid 2 HTTP 1.1 connections recommendation limit.
* Here is a default implementation for http://archive.java2script.org.
* In site archive.java2script.org, there are 6 sites:
* 1. http://archive.java2script.org or http://a.java2script.org
* 2. http://erchive.java2script.org or http://e.java2script.org
* 3. http://irchive.java2script.org or http://i.java2script.org
* 4. http://orchive.java2script.org or http://o.java2script.org
* 5. http://urchive.java2script.org or http://u.java2script.org
* 6. http://yrchive.java2script.org or http://y.java2script.org
*/
/* protected */
/*
_Loader.multipleSites = function (path) {
var deltas = window["j2s.update.delta"];
if (deltas && deltas instanceof Array && deltas.length >= 3) {
var lastOldVersion = null;
var lastNewVersion = null;
for (var i = 0; i < deltas.length / 3; i++) {
var oldVersion = deltas[i + i + i];
if (oldVersion != "$") {
lastOldVersion = oldVersion;
}
var newVersion = deltas[i + i + i + 1];
if (newVersion != "$") {
lastNewVersion = newVersion;
}
var relativePath = deltas[i + i + i + 2];
var key = lastOldVersion + "/" + relativePath;
var idx = path.indexOf (key);
if (idx != -1 && idx == path.length - key.length) {
path = path.substring (0, idx) + lastNewVersion + "/" + relativePath;
break;
}
}
}
var length = path.length;
if (maxLoadingThreads > 1
&& ((length > 15 && path.substring (0, 15) == "http://archive.")
|| (length > 9 && path.substring (0, 9) == "http://a."))) {
var index = path.lastIndexOf("/");
if (index < length - 3) {
var arr = ['a', 'e', 'i', 'o', 'u', 'y'];
var c1 = path.charCodeAt (index + 1);
var c2 = path.charCodeAt (index + 2);
var idx = (length - index) * 3 + c1 * 5 + c2 * 7; // Hash
return path.substring (0, 7) + arr[idx % 6] + path.substring (8);
}
}
return path;
};
*/
/**
* Return the *.js path of the given class. Maybe the class is contained
* in a *.z.js jar file.
* @param clazz Given class that the path is to be calculated for. May
* be java.package, or java.lang.String
* @param forRoot Optional argument, if true, the return path will be root
* of the given classs' package root path.
* @param ext Optional argument, if given, it will replace the default ".js"
* extension.
*/
/* public */
_Loader.getClasspathFor = function (clazz, forRoot, ext) {
var path = classpathMap["#" + clazz];
if (!path || forRoot || ext) {
var base;
var idx;
if (path) {
clazz = clazz.replace(/\./g, "/");
if ((idx = path.lastIndexOf(clazz)) >= 0
|| (idx = clazz.lastIndexOf("/")) >= 0
&& (idx = path.lastIndexOf(clazz.substring(0, idx))) >= 0)
base = path.substring(0, idx);
} else {
idx = clazz.length + 2;
while ((idx = clazz.lastIndexOf(".", idx - 2)) >= 0)
if ((base = classpathMap["@" + clazz.substring(0, idx)]))
break;
if (!forRoot)
clazz = clazz.replace (/\./g, "/");
}
if (base == null) {
var bins = "binaryFolders";
base = (window["Clazz"] && Clazz[bins] && Clazz[bins].length ? Clazz[bins][0]
: _Loader[bins] && _Loader[bins].length ? _Loader[bins][0]
: "j2s");
}
path = (base.lastIndexOf("/") == base.length - 1 ? base : base + "/") + (forRoot ? ""
: clazz.lastIndexOf("/*") == clazz.length - 2 ? clazz.substring(0, idx + 1)
: clazz + (!ext ? ".js" : ext.charAt(0) != '.' ? "." + ext : ext));
}
return path;//_Loader.multipleSites(path);
};
/**
* To ignore some classes.
*/
/* public */
_Loader.ignore = function () {
var clazzes = (arguments.length == 1 && arguments[0] instanceof Array ?
clazzes = arguments[0] : null);
var n = (clazzes ? clazzes.length : arguments.length);
if (!clazzes) {
clazzes = new Array(n);
for (var i = 0; i < n; i++)
clazzes[i] = arguments[i];
}
unwrapArray(clazzes);
for (var i = 0; i < n; i++)
excludeClassMap["@" + clazzes[i]] = 1;
};
/**
* The following *.script* can be overriden to indicate the
* status of classes loading.
*
* TODO: There should be a Java interface with name like INativeLoaderStatus
*/
/* public */
_Loader.onScriptLoading = function (file){};
/* public */
_Loader.onScriptLoaded = function (file, isError){};
/* public */
_Loader.onScriptInitialized = function (file){};
/* public */
_Loader.onScriptCompleted = function (file){};
/* public */
_Loader.onClassUnloaded = function (clazz){};
/**
* After all the classes are loaded, this method will be called.
* Should be overriden to run *.main([]).
*/
/* public */
_Loader.onGlobalLoaded = function () {};
/* public */
_Loader.keepOnLoading = true; // never set false in this code
/* private */
var mapPath2ClassNode = {};
/* private */
var isClassExcluded = function (clazz) {
return excludeClassMap["@" + clazz];
};
/* Used to keep ignored classes */
/* private */
var excludeClassMap = {};
/* private */
var evaluate = function(file, file0, js, isLoaded) {
if (!isLoaded)
try {
eval(js + ";//# sourceURL="+file);
} catch (e) {
if (Clazz._isQuiet)
return;
var s = "[Java2Script] The required class file \n\n" + file + (js.indexOf("[Exception") == 0 && js.indexOf("data: no") ?
"\nwas not found.\n"
: "\ncould not be loaded. Script error: " + e.message + " \n\ndata:\n\n" + js) + "\n\n" + Clazz.getStackTrace();
alert(s)
Clazz.alert(s);
throw e;
}
_Loader.onScriptLoaded(file, false);
tryToLoadNext(file0);
}
/* private */
var failedHandles = {};
/* private */
var generateRemovingFunction = function (node) {
return function () {
if (node.readyState != "interactive") {
try {
if (node.parentNode)
node.parentNode.removeChild (node);
} catch (e) { }
node = null;
}
};
};
/* private */
var removeScriptNode = function (n) {
if (window["j2s.script.debugging"]) {
return;
}
// lazily remove script nodes.
window.setTimeout (generateRemovingFunction (n), 1);
};
/* public */
Clazz._4Name = function(clazzName, applet, state) {
if (Clazz.isClassDefined(clazzName))
return Clazz.evalType(clazzName);
var f = (Jmol._isAsync && applet ? applet._restoreState(clazzName, state) : null);
if (f == 1)
return null; // must be already being created
if (_Loader.setLoadingMode(f ? _Loader.MODE_SCRIPT : "xhr.sync")) {
_Loader.loadClass(clazzName, f, false, true, 1);
return null; // this will surely throw an error, but that is OK
}
//alert ("Using Java reflection: " + clazzName + " for " + applet._id + " \n"+ Clazz.getStackTrace());
_Loader.loadClass(clazzName);
return Clazz.evalType(clazzName);
};
/**
* BH: possibly useful for debugging
*/
Clazz.currentPath= "";
/**
* Load *.js by adding script elements into head. Hook the onload event to
* load the next class in dependency tree.
*/
/* private */
var loadScript = function (node, file, why, ignoreOnload, fSuccess, _loadScript) {
Clazz.currentPath = file;
if (ignoreOnload)alert("WHY>>")
//BH removed // maybe some scripts are to be loaded without needs to know onload event.
// if (!ignoreOnload && loadedScripts[file]) {
// _Loader.tryToLoadNext(file);
// return;
// }
var isLoaded = loadedScripts[file];
loadedScripts[file] = true;
// also remove from queue
removeArrayItem(classQueue, file);
// forces not-found message
// at least for now, force synchronous transfer of all class files
isUsingXMLHttpRequest = true;
isAsynchronousLoading = false;
if (_Loader._checkLoad) {
System.out.println("\t" + file + (why ? "\n -- required by " + why : "") + " ajax=" + isUsingXMLHttpRequest + " async=" + isAsynchronousLoading)
}
var file0 = file;
if (Clazz._debugging) {
file = file.replace(/\.z\.js/,".js");
}
if (!isLoaded)
System.out.println("loadScript " + file)
_Loader.onScriptLoading(file);
if (isUsingXMLHttpRequest && !isAsynchronousLoading) {
// alert("\t" + file + (why ? "\n -- required by " + why : "") + " ajax=" + isUsingXMLHttpRequest + " async=" + isAsynchronousLoading + " " + Clazz.getStackTrace())
// synchronous loading
// works in MSIE locally unless a binary file :)
// from Jmol.api.Interface only
var data = Jmol._getFileData(file);
try{
evaluate(file, file0, data, isLoaded);
}catch(e) {
alert(e + " loading file " + file + " " + node.name + " " + Clazz.getStackTrace());
}
if (fSuccess) {
// System.out.println("firing in loadScript " + file + " " + (fSuccess && fSuccess.toString()))
fSuccess();
}
return;
}
// only when running asynchronously
var info = {
dataType:"script",
async:true,
type:"GET",
url:file,
success:W3CScriptOnCallback(file, false, fSuccess),
error:W3CScriptOnCallback(file, true, fSuccess)
};
inLoadingThreads++;
if (isLoaded)
setTimeout(info.success, 0);
else
Jmol.$ajax(info);
};
/* private */
var W3CScriptOnCallback = function (path, forError, fSuccess) {
var s = Clazz.getStackTrace();
return function () {
if (forError && __debuggingBH)Clazz.alert ("############ forError=" + forError + " path=" + path + " ####" + (forError ? "NOT" : "") + "LOADED###");
if (isGecko && this.timeoutHandle)
window.clearTimeout(this.timeoutHandle), this.timeoutHandle = null;
if (inLoadingThreads > 0)
inLoadingThreads--;
this.onload = null;
this.onerror = null;
if (forError)
alert ("There was a problem loading " + path);
_Loader.onScriptLoaded(path, true);
var node = this;
var f;
if (fSuccess)
f = function(_W3scriptFS){removeScriptNode(node);tryToLoadNext(path, fSuccess); };
else
f = function(_W3script){removeScriptNode(node);tryToLoadNext(path)};
if (loadingTimeLag >= 0)
window.setTimeout(function() { tryToLoadNext(path, f); }, loadingTimeLag);
else
tryToLoadNext(path, f);
};
};
/* private */
var isLoadingEntryClass = true;
/* private */
var besidesJavaPackage = false;
/**
* After class is loaded, this method will be executed to check whether there
* are classes in the dependency tree that need to be loaded.
*/
/* private */
var tryToLoadNext = function (file, fSuccess) {
var node = mapPath2ClassNode["@" + file];
if (!node) // maybe class tree root
return;
var n;
// check for content loaded
var clazzes = classpathMap["$" + file];
if (clazzes) {
for (var i = 0; i < clazzes.length; i++) {
var name = clazzes[i];
if (name != node.name && (n = findNode(name))) {
if (n.status < Node.STATUS_CONTENT_LOADED) {
n.status = Node.STATUS_CONTENT_LOADED;
updateNode(n);
}
} else {
n = new Node();
n.name = name;
var pp = classpathMap["#" + name];
if (!pp) {
alert (name + " J2S error in tryToLoadNext");
error("Java2Script implementation error! Please report this bug!");
}
n.path = pp;
mappingPathNameNode (n.path, name, n);
n.status = Node.STATUS_CONTENT_LOADED;
addChildClassNode(clazzTreeRoot, n, false);
updateNode(n);
}
}
}
if (node instanceof Array) {
for (var i = 0; i < node.length; i++) {
if (node[i].status < Node.STATUS_CONTENT_LOADED) {
node[i].status = Node.STATUS_CONTENT_LOADED;
updateNode(node[i]);
}
}
} else if (node.status < Node.STATUS_CONTENT_LOADED) {
var stillLoading = false;
var ss = document.getElementsByTagName ("SCRIPT");
for (var i = 0; i < ss.length; i++) {
if (isIE) {
if (ss[i].onreadystatechange && ss[i].onreadystatechange.path == node.path
&& ss[i].readyState == "interactive") {
stillLoading = true;
break;
}
} else if (ss[i].onload && ss[i].onload.path == node.path) {
stillLoading = true;
break;
}
}
if (!stillLoading) {
node.status = Node.STATUS_CONTENT_LOADED;
updateNode(node);
}
}
/*
* Maybe in #optinalLoaded inside above _Loader#updateNode calls,
* _Loader.keepOnLoading is set false (Already loaded the wanted
* classes), so here check to stop.
*/
if (!_Loader.keepOnLoading) // set externally
return;
// check for a "must" class that has content and load it
var cq;
var working = true;
if ((n = findNextMustClass(Node.STATUS_KNOWN))) {
loadClassNode(n);
while (inLoadingThreads < maxLoadingThreads) {
if (!(n = findNextMustClass(Node.STATUS_KNOWN)))
break;
loadClassNode(n); // will increase inLoadingThreads!
}
} else if ((cq = classQueue).length != 0) {
/* queue must be loaded in order! */
n = cq.shift();
if (!loadedScripts[n.path]
|| cq.length != 0
|| !isLoadingEntryClass
|| n.musts.length
|| n.optionals.length) {
addChildClassNode(clazzTreeRoot, n, true);
loadScript(n, n.path, n.requiredBy, false);
} else if (isLoadingEntryClass) {
/*
* The first time reaching here is the time when ClassLoader
* is trying to load entry class. Class with #main method and
* is to be executed is called Entry Class.
*
* Here when loading entry class, ClassLoader should not call
* the next following loading script. This is because, those
* scripts will try to mark the class as loaded directly and
* then continue to call #onLoaded callback method,
* which results in an script error!
*/
isLoadingEntryClass = false;
}
} else if ((n = findNextRequiredClass(Node.STATUS_KNOWN))) {
loadClassNode(n);
while (inLoadingThreads < maxLoadingThreads) {
if (!(n = findNextRequiredClass(Node.STATUS_KNOWN)))
break;
loadClassNode(n); // will increase inLoadingThreads!
}
} else {
working = false;
}
if (working || inLoadingThreads > 0)
return;
//
// now check all classes that MUST be loaded prior to initialization
// of some other class (static calls, extends, implements)
// and all classes REQUIRED somewhere in that class, possibly by the constructor
// (that is, "new xxxx()" called somewhere in code) and update them
// that have content but are not declared already
var f = [findNextMustClass,findNextRequiredClass];
var lastNode = null;
for (var i = 0; i < 2; i++)
while ((n = f[i](Node.STATUS_CONTENT_LOADED))) {
if (i == 1 && lastNode === n) // Already existed cycle ?
n.status = Node.STATUS_LOAD_COMPLETE;
updateNode(n);
lastNode = n;
}
// check for load cycles
while (true) {
tracks = [];
if (!checkCycle(clazzTreeRoot, file))
break;
}
// and update all MUST and REQUIRED classes that are declared already
for (var i = 0; i < 2; i++) {
lastNode = null;
while ((n = f[i](Node.STATUS_DECLARED))) {
if (lastNode === n)
break;
updateNode(lastNode = n);
}
}
var done = [];
for (var i = 0; i < 2; i++)
while ((n = f[i](Node.STATUS_DECLARED)))
done.push(n), n.status = Node.STATUS_LOAD_COMPLETE;
if (done.length) {
for (var i = 0; i < done.length; i++)
destroyClassNode(done[i]);
for (var i = 0; i < done.length; i++)
if ((f = done[i].onLoaded))
done[i].onLoaded = null, f();
}
//System.out.println(node.name + " loaded completely" + _Loader.onGlobalLoaded + "\n\n")
if (fSuccess) {
//System.out.println("tryToLoadNext firing " + _Loader._classCountOK + "/" + _Loader._classCountPending + " " + fSuccess.toString() + " " + Clazz.getStackTrace())
fSuccess();
} else if (_Loader._classCountPending) {
for (var name in _Loader._classPending) {
var n = findNode(name);
System.out.println("class left pending " + name + " " + n);
if (n) {
updateNode(n);
break;
}
}
} else {
// System.out.println("I think I'm done "
// + _Loader._classCountOK + "/" + _Loader._classCountPending + " "
//+ _Loader.onGlobalLoaded.toString() + " " + Clazz.getStackTrace()
// )
if (_Loader._checkLoad) {
System.out.println("I think I'm done: SAEM call count: " + SAEMid);
Clazz.showDuplicates(true);
}
}
_Loader.onGlobalLoaded();
};
var tracks = [];
/*
* There are classes reference cycles. Try to detect and break those cycles.
*/
/* private */
var checkCycle = function (node, file) {
var ts = tracks;
var len = ts.length;
// add this node to tracks
ts.push(node);
var i = len;
for (; --i >= 0;)
if (ts[i] === node && ts[i].status >= Node.STATUS_DECLARED)
break;
if (i >= 0) {
// this node is already in tracks, and it has been declared already
// for each node in tracks, set its status to "LOAD_COMPLETE"
// update all parents, remove all parents, and fire its onLoaded function
// then clear tracks and return true (keep checking)
if (_Loader._checkLoad) {
var msg = "cycle found loading " + file + " for " + node;
System.out.println(msg)
}
for (; i < len; i++) {
var n = ts[i];
n.status = Node.STATUS_LOAD_COMPLETE;
destroyClassNode(n); // Same as above
for (var k = 0; k < n.parents.length; k++)
updateNode(n.parents[k]);
n.parents = [];
var f = n.onLoaded;
if (_Loader._checkLoad) {
var msg = "cycle setting status to LOAD_COMPLETE for " + n.name + (f ? " firing " + f.toString() : "");
System.out.println(msg)
}
if (f)
n.onLoaded = null, f();
}
ts.length = 0;
return true;
}
var a = [node.musts, node.optionals];
for (var j = 0; j < 2; j++)
for (var r = a[j], i = r.length; --i >= 0;)
if (r[i].status == Node.STATUS_DECLARED && checkCycle(r[i], file))
return true;
// reset _tracks to its original length
ts.length = len;
return false; // done
};
_Loader._classCountPending = 0;
_Loader._classCountOK = 0;
_Loader._classPending = {};
_Loader.showPending = function() {
var a = [];
for (var name in _Loader._classPending) {
var n = findNode(name);
if (!n) {
alert("No node for " + name);
continue;
}
a.push(n);
System.out.println(showNode("", "", n, "", 0));
}
return a;
}
var showNode = function(s, names, node, inset, level) {
names += "--" + node.name;
s += names + "\n";
if (level > 5) {
s += inset + " ...\n";
return s;
}
inset += "\t";
s += inset + "status: " + node.status + "\n";
if (node.parents && node.parents.length && node.parents[0] && node.parents[0].name) {
s += inset + "parents: " + node.parents.length + "\n";
for (var i = 0; i < node.parents.length; i++) {
s = showNode(s, names, node.parents[i], inset + "\t", level+1);
}
s += "\n";
}
// if (node.requiredBy) {
// s += inset + "requiredBy:\n";
// s = showNode(s, names, node.requiredBy, inset + "\t", level+1);
// s += "\n";
// }
return s;
}
/**
* Update the dependency tree nodes recursively.
*/
/* private */
updateNode = function(node, _updateNode) {
if (!node.name || node.status >= Node.STATUS_LOAD_COMPLETE) {
destroyClassNode(node);
return;
}
var ready = true;
// check for declared and also having MUSTS
if (node.musts.length && node.declaration) {
for (var mustLength = node.musts.length, i = mustLength; --i >= 0;) {
var n = node.musts[i];
n.requiredBy = node;
if (n.status < Node.STATUS_DECLARED && isClassDefined (n.name)) {
var nns = []; // a stack for onLoaded events
n.status = Node.STATUS_LOAD_COMPLETE;
destroyClassNode(n); // Same as above
if (n.declaration && n.declaration.clazzList) {
// For those classes within one *.js file, update them synchronously.
for (var j = 0, list = n.declaration.clazzList, l = list.length; j < l; j++) {
var nn = findNode (list[j]);
if (nn && nn.status != Node.STATUS_LOAD_COMPLETE
&& nn !== n) {
nn.status = n.status;
nn.declaration = null;
destroyClassNode(nn);
nn.onLoaded && nns.push(nn);
}
}
n.declaration = null;
}
// fire all onLoaded events
if (n.onLoaded)
nns.push(n);
for (var j = 0; j < nns.length; j++) {
var onLoaded = nns[j].onLoaded;
if (onLoaded) {
nns[j].onLoaded = null;
onLoaded();
}
}
} else {
(n.status == Node.STATUS_CONTENT_LOADED) && updateNode(n); // musts may be changed
if (n.status < Node.STATUS_DECLARED)
ready = false;
}
if (node.musts.length != mustLength) {
// length changed -- restart!
i = mustLength = node.musts.length;
ready = true;
}
}
}
if (!ready)
return;
if (node.status < Node.STATUS_DECLARED) {
var decl = node.declaration;
if (decl)
decl(), decl.executed = true;
if(_Loader._checkLoad) {
if (_Loader._classPending[node.name]) {
delete _Loader._classPending[node.name];
_Loader._classCountOK;
_Loader._classCountPending--;
// System.out.println("OK " + (_Loader._classCountOK) + " FOR " + node.name)
}
}
node.status = Node.STATUS_DECLARED;
if (definedClasses)
definedClasses[node.name] = true;
_Loader.onScriptInitialized(node.path);
if (node.declaration && node.declaration.clazzList) {
// For those classes within one *.js file, update them synchronously.
for (var j = 0, list = node.declaration.clazzList, l = list.length; j < l; j++) {
var nn = findNode(list[j]);
if (nn && nn.status != Node.STATUS_DECLARED
&& nn !== node) {
nn.status = Node.STATUS_DECLARED;
if (definedClasses)
definedClasses[nn.name] = true;
_Loader.onScriptInitialized(nn.path);
}
}
}
}
var level = Node.STATUS_DECLARED;
if (node.optionals.length == 0 && node.musts.length == 0
|| node.status > Node.STATUS_KNOWN && !node.declaration
|| checkStatusIs(node.musts, Node.STATUS_LOAD_COMPLETE)
&& checkStatusIs(node.optionals, Node.STATUS_LOAD_COMPLETE)) {
level = Node.STATUS_LOAD_COMPLETE;
if (!doneLoading(node, level))
return false;
// For those classes within one *.js file, update them synchronously.
if (node.declaration && node.declaration.clazzList) {
for (var j = 0, list = node.declaration.clazzList, l = list.length; j < l; j++) {
var nn = findNode(list[j]);
if (nn && nn.status != level && nn !== node) {
nn.declaration = null;
if (!doneLoading(nn, level))
return false;
}
}
}
}
// _Loader.updateParents = function (node, level, _updateParents)
if (node.parents && node.parents.length) {
for (var i = 0; i < node.parents.length; i++) {
var p = node.parents[i];
if (p.status < level)
updateNode(p, p.name);
}
if (level == Node.STATUS_LOAD_COMPLETE)
node.parents = [];
}
};
/* private */
var checkStatusIs = function(arr, status){
for (var i = arr.length; --i >= 0;)
if (arr[i].status < status)
return false;
return true;
}
/* private */
var doneLoading = function(node, level, _doneLoading) {
node.status = level;
_Loader.onScriptCompleted(node.path);
var onLoaded = node.onLoaded;
if (onLoaded) {
node.onLoaded = null;
onLoaded();
if (!_Loader.keepOnLoading)
return false;
}
destroyClassNode(node);
return true;
}
/*
* Be used to record already used random numbers. And next new random
* number should not be in the property set.
*/
/* private */
var usedRandoms = {
"r0.13412" : 1
};
/* private */
var getRnd = function() {
while (true) { // get a unique random number
var rnd = Math.random();
var s = "r" + rnd;
if (!usedRandoms[s])
return (usedRandoms[s] = 1, clazzTreeRoot.random = rnd);
}
}
/* protected */
var findNode = function(clazzName) {
getRnd();
return findNodeUnderNode(clazzName, clazzTreeRoot);
};
/* private */
var findNextRequiredClass = function(status) {
getRnd();
return findNextRequiredNode(clazzTreeRoot, status);
};
/* private */
var findNextMustClass = function(status) {
return findNextMustNode(clazzTreeRoot, status);
};
/* private */
var findNodeUnderNode = function(clazzName, node) {
var n;
// node, then musts then optionals
return (node.name == clazzName ? node
: (n = findNodeWithin(clazzName, node.musts))
|| (n = findNodeWithin(clazzName, node.optionals))
? n : null);
};
/* private */
var findNodeWithin = function(name, arr) {
var rnd = clazzTreeRoot.random;
for (var i = arr.length; --i >= 0;) {
var n = arr[i];
if (n.name == name)
return n;
if (n.random != rnd) {
n.random = rnd;
if ((n = findNodeUnderNode(name, n)))
return n;
}
}
return null;
}
/* private */
var checkStatus = function(n, status) {
return (n.status == status
&& (status != Node.STATUS_KNOWN || !loadedScripts[n.path])
&& (status == Node.STATUS_DECLARED || !isClassDefined (n.name)));
}
/* private */
var findNextMustNode = function(node, status) {
for (var i = node.musts.length; --i >= 0;) {
var n = node.musts[i];
if (checkStatus(n, status) || (n = findNextMustNode(n, status)))
return n;
}
return (checkStatus(node, status) ? node : null);
};
/* private */
var findNextRequiredNode = function (node, status) {
// search musts first
// search optionals second
// search itself last
var n;
return ((n = searchClassArray(node.musts, status))
|| (n = searchClassArray(node.optionals, status))
|| checkStatus(n = node, status) ? n : null);
};
/* private */
var searchClassArray = function (arr, status) {
if (arr) {
var rnd = clazzTreeRoot.random;
for (var i = 0; i < arr.length; i++) {
var n = arr[i];
if (checkStatus(n, status))
return n;
if (n.random != rnd) {
n.random = rnd; // mark as visited!
if ((n = findNextRequiredNode(n, status)))
return n;
}
}
}
return null;
};
/**
* This map variable is used to mark that *.js is correctly loaded.
* In IE, _Loader has defects to detect whether a *.js is correctly
* loaded or not, so inner loading mark is used for detecting.
*/
/* private */
var innerLoadedScripts = {};
/**
* This method will be called in almost every *.js generated by Java2Script
* compiler.
*/
/* public */
var load = function (musts, name, optionals, declaration) {
// called as name.load in Jmol
if (name instanceof Array) {
unwrapArray(name);
for (var i = 0; i < name.length; i++)
load(musts, name[i], optionals, declaration, name);
return;
}
if (_Loader._checkLoad) {
if (_Loader._classPending[name]) {
//alert("duplicate load for " + name)
} else {
_Loader._classPending[name] = 1;
if (_Loader._classCountPending++ == 0)
_Loader._classCountOK = 0;
System.out.println("Loading class " + name);
}
}
// if (clazz.charAt (0) == '$')
// clazz = "org.eclipse.s" + clazz.substring (1);
var node = mapPath2ClassNode["#" + name];
if (!node) { // load called inside *.z.js?
var n = findNode(name);
node = (n ? n : new Node());
node.name = name;
node.path = classpathMap["#" + name] || "unknown";
mappingPathNameNode(node.path, name, node);
node.status = Node.STATUS_KNOWN;
addChildClassNode(clazzTreeRoot, node, false);
}
processRequired(node, musts, true);
if (arguments.length == 5 && declaration) {
declaration.status = node.status;
declaration.clazzList = arguments[4];
}
node.declaration = declaration;
if (declaration)
node.status = Node.STATUS_CONTENT_LOADED;
processRequired(node, optionals, false);
};
/* private */
var processRequired = function(node, arr, isMust) {
if (arr && arr.length) {
unwrapArray(arr);
for (var i = 0; i < arr.length; i++) {
var name = arr[i];
if (!name)
continue;
if (isClassDefined(name)
|| isClassExcluded(name))
continue;
var n = findNode(name);
if (!n) {
n = new Node();
n.name = name;
n.status = Node.STATUS_KNOWN;
}
n.requiredBy = node;
addChildClassNode(node, n, isMust);
}
}
}
/*
* Try to be compatiable of Clazz
*/
if (window["Clazz"]) {
Clazz.load = load;
} else {
_Loader.load = load;
}
/**
* Map different class to the same path! Many classes may be packed into
* a *.z.js already.
*
* @path *.js path
* @name class name
* @node Node object
*/
/* private */
var mappingPathNameNode = function (path, name, node) {
var map = mapPath2ClassNode;
var keyPath = "@" + path;
var v = map[keyPath];
if (v) {
if (v instanceof Array) {
var existed = false;
for (var i = 0; i < v.length; i++) {
if (v[i].name == name) {
existed = true;
break;
}
}
if (!existed)
v.push(node);
} else {
map[keyPath] = [v, node];
}
} else {
map[keyPath] = node;
}
map["#" + name] = node;
};
/* protected */
var loadClassNode = function (node) {
var name = node.name;
if (!isClassDefined (name)
&& !isClassExcluded (name)) {
var path = _Loader.getClasspathFor (name/*, true*/);
node.path = path;
mappingPathNameNode (path, name, node);
if (!loadedScripts[path]) {
loadScript(node, path, node.requiredBy, false);
return true;
}
}
return false;
};
/**
* Used in package
/* public */
var runtimeKeyClass = _Loader.runtimeKeyClass = "java.lang.String";
/**
* Queue used to store classes before key class is loaded.
*/
/* private */
var queueBe4KeyClazz = [];
/* private */
var J2sLibBase;
/**
* Return J2SLib base path from existed SCRIPT src attribute.
*/
/* public */
_Loader.getJ2SLibBase = function () {
var o = window["j2s.lib"];
return (o ? o.base + (o.alias == "." ? "" : (o.alias ? o.alias : (o.version ? o.version : "1.0.0")) + "/") : null);
};
/**
* Indicate whether _Loader is loading script synchronously or
* asynchronously.
*/
/* private */
var isAsynchronousLoading = true;
/* private */
var isUsingXMLHttpRequest = false;
/* private */
var loadingTimeLag = -1;
_Loader.MODE_SCRIPT = 4;
_Loader.MODE_XHR = 2;
_Loader.MODE_SYNC = 1;
/**
* String mode:
* asynchronous modes:
* async(...).script, async(...).xhr, async(...).xmlhttprequest,
* script.async(...), xhr.async(...), xmlhttprequest.async(...),
* script
*
* synchronous modes:
* sync(...).xhr, sync(...).xmlhttprequest,
* xhr.sync(...), xmlhttprequest.sync(...),
* xmlhttprequest, xhr
*
* Integer mode:
* Script 4; XHR 2; SYNC bit 1;
*/
/* public */
_Loader.setLoadingMode = function (mode, timeLag) {
var async = true;
var ajax = true;
if (typeof mode == "string") {
mode = mode.toLowerCase();
if (mode.indexOf("script") >= 0)
ajax = false;
else
async = (mode.indexOf("async") >=0);
async = false; // BH
} else {
if (mode & _Loader.MODE_SCRIPT)
ajax = false;
else
async = !(mode & _Loader.MODE_SYNC);
}
isUsingXMLHttpRequest = ajax;
isAsynchronousLoading = async;
loadingTimeLag = (async && timeLag >= 0 ? timeLag: -1);
return async;
};
/* private */
var runtimeLoaded = function () {
if (pkgRefCount || !isClassDefined(runtimeKeyClass))
return;
var qbs = queueBe4KeyClazz;
for (var i = 0; i < qbs.length; i++)
_Loader.loadClass(qbs[i][0], qbs[i][1]);
queueBe4KeyClazz = [];
};
/*
* Load those key *.z.js. This *.z.js will be surely loaded before other
* queued *.js.
*/
/* public */
_Loader.loadZJar = function (zjarPath, keyClass) {
// used only by package.js for core.z.js
var f = null;
var isArr = (keyClass instanceof Array);
if (isArr)
keyClass = keyClass[keyClass.length - 1];
else
f = (keyClass == runtimeKeyClass ? runtimeLoaded : null);
_Loader.jarClasspath(zjarPath, isArr ? keyClass : [keyClass]);
// BH note: runtimeKeyClass is java.lang.String
_Loader.loadClass(keyClass, f, true);
};
var NodeMap = {};
var _allNodes = [];
/**
* The method help constructing the multiple-binary class dependency tree.
*/
/* private */
var addChildClassNode = function (parent, child, isMust) {
var existed = false;
var arr;
if (isMust) {
arr = parent.musts;
if (!child.requiredBy)
child.requiredBy = parent;
// if (!parent.requiresMap){
// parent.requires = [];
// parent.requiresMap = {};
// }
// if (!parent.requiresMap[child.name]) {
// parent.requiresMap[child.name] = 1;
// parent.requires.push[child];
// }
} else {
arr = parent.optionals;
}
if (!NodeMap[child.name]) {
_allNodes.push(child)
NodeMap[child.name]=child
}
for (var i = 0; i < arr.length; i++) {
if (arr[i].name == child.name) {
existed = true;
break;
}
}
if (!existed) {
arr.push(child);
if (isLoadingEntryClass
&& child.name.indexOf("java") != 0
&& child.name.indexOf("net.sf.j2s.ajax") != 0) {
if (besidesJavaPackage)
isLoadingEntryClass = false;
besidesJavaPackage = true;
// } else if (child.name.indexOf("org.eclipse.swt") == 0
// || child.name.indexOf("$wt") == 0) {
// window["swt.lazy.loading.callback"] = swtLazyLoading;
// if (needPackage("org.eclipse.swt"))
// return _Loader.loadPackage("org.eclipse.swt", function() {addParentClassNode(child, parent)});
}
}
addParentClassNode(child, parent);
};
/* private */
var addParentClassNode = function(child, parent) {
if (parent.name && parent != clazzTreeRoot && parent != child)
for (var i = 0; i < child.parents.length; i++)
if (child.parents[i].name == parent.name)
return;
child.parents.push(parent);
}
/* private */
var destroyClassNode = function (node) {
var parents = node.parents;
if (parents)
for (var k = parents.length; --k >= 0;)
removeArrayItem(parents[k].musts, node) || removeArrayItem(parents[k].optionals, node);
};
/*
/ * public * /
_Loader.unloadClassExt = function (qClazzName) {
if (definedClasses)
definedClasses[qClazzName] = false;
if (classpathMap["#" + qClazzName]) {
var pp = classpathMap["#" + qClazzName];
classpathMap["#" + qClazzName] = null;
var arr = classpathMap["$" + pp];
removeArrayItem(arr, qClazzName) && (classpathMap["$" + pp] = arr);
}
var n = findNode(qClazzName);
if (n) {
n.status = Node.STATUS_KNOWN;
loadedScripts[n.path] = false;
}
var path = _Loader.getClasspathFor (qClazzName);
loadedScripts[path] = false;
innerLoadedScripts[path] && (innerLoadedScripts[path] = false);
_Loader.onClassUnloaded(qClazzName);
};
/ * private * /
var assureInnerClass = function (clzz, fun) {
clzz = clzz.__CLASS_NAME__;
if (Clazz.unloadedClasses[clzz]) {
if (clzz.indexOf("$") >= 0)
return;
var list = [];
var key = clzz + "$";
for (var s in Clazz.unloadedClasses)
if (Clazz.unloadedClasses[s] && s.indexOf(key) == 0)
list.push(s);
if (!list.length)
return;
fun = "" + fun;
var idx1, idx2;
if ((idx1 = fun.indexOf(key)) < 0 || (idx2 = fun.indexOf("\"", idx1 + key.length)) < 0)
return;
clzz = fun.substring(idx1, idx2);
if (!Clazz.unloadedClasses[clzz] || (idx1 = fun.indexOf("{", idx2) + 1) == 0)
return;
if ((idx2 = fun.indexOf("(" + clzz + ",", idx1 + 3)) < 0
|| (idx2 = fun.lastIndexOf("}", idx2 - 1)) < 0)
return;
eval(fun.substring(idx1, idx2));
Clazz.unloadedClasses[clzz] = null;
}
};
*/
Clazz.binaryFolders = _Loader.binaryFolders = [ _Loader.getJ2SLibBase() ];
})(Clazz, Clazz._Loader);
//}
/******************************************************************************
* Copyright (c) 2007 java2script.org and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Zhou Renjian - initial API and implementation
*****************************************************************************/
/*******
* @author zhou renjian
* @create Jan 11, 2007
*******/
Clazz._LoaderProgressMonitor = {};
;(function(CLPM, Jmol) {
var fadeOutTimer = null;
var fadeAlpha = 0;
var monitorEl = null;
var lastScrollTop = 0;
var bindingParent = null;
CLPM.DEFAULT_OPACITY = (Jmol && Jmol._j2sLoadMonitorOpacity ? Jmol._j2sLoadMonitorOpacity : 55);
/* public */
/*CLPM.initialize = function (parent) {
bindingParent = parent;
if (parent && !attached) {
attached = true;
//Clazz.addEvent (window, "unload", cleanup);
// window.attachEvent ("onunload", cleanup);
}
};
*/
/* public */
CLPM.hideMonitor = function () {
monitorEl.style.display = "none";
}
/* public */
CLPM.showStatus = function (msg, fading) {
if (!monitorEl) {
createHandle ();
if (!attached) {
attached = true;
//Clazz.addEvent (window, "unload", cleanup);
// window.attachEvent ("onunload", cleanup);
}
}
clearChildren(monitorEl);
if (msg == null) {
if (fading) {
fadeOut();
} else {
CLPM.hideMonitor();
}
return;
}
monitorEl.appendChild(document.createTextNode ("" + msg));
if (monitorEl.style.display == "none") {
monitorEl.style.display = "";
}
setAlpha(CLPM.DEFAULT_OPACITY);
var offTop = getFixedOffsetTop();
if (lastScrollTop != offTop) {
lastScrollTop = offTop;
monitorEl.style.bottom = (lastScrollTop + 4) + "px";
}
if (fading) {
fadeOut();
}
};
/* private static */
var clearChildren = function (el) {
if (!el)
return;
for (var i = el.childNodes.length; --i >= 0;) {
var child = el.childNodes[i];
if (!child)
continue;
if (child.childNodes && child.childNodes.length)
clearChildren (child);
try {
el.removeChild (child);
} catch (e) {};
}
};
/* private */
var setAlpha = function (alpha) {
if (fadeOutTimer && alpha == CLPM.DEFAULT_OPACITY) {
window.clearTimeout (fadeOutTimer);
fadeOutTimer = null;
}
fadeAlpha = alpha;
var ua = navigator.userAgent.toLowerCase();
monitorEl.style.filter = "Alpha(Opacity=" + alpha + ")";
monitorEl.style.opacity = alpha / 100.0;
};
/* private */
var hidingOnMouseOver = function () {
CLPM.hideMonitor();
};
/* private */
var attached = false;
/* private */
var cleanup = function () {
//if (monitorEl) {
// monitorEl.onmouseover = null;
//}
monitorEl = null;
bindingParent = null;
//Clazz.removeEvent (window, "unload", cleanup);
//window.detachEvent ("onunload", cleanup);
attached = false;
};
/* private */
var createHandle = function () {
var div = document.createElement ("DIV");
div.id = "_Loader-status";
div.style.cssText = "position:absolute;bottom:4px;left:4px;padding:2px 8px;"
+ "z-index:" + (window["j2s.lib"].monitorZIndex || 10000) + ";background-color:#8e0000;color:yellow;"
+ "font-family:Arial, sans-serif;font-size:10pt;white-space:nowrap;";
div.onmouseover = hidingOnMouseOver;
monitorEl = div;
if (bindingParent) {
bindingParent.appendChild(div);
} else {
document.body.appendChild(div);
}
return div;
};
/* private */
var fadeOut = function () {
if (monitorEl.style.display == "none") return;
if (fadeAlpha == CLPM.DEFAULT_OPACITY) {
fadeOutTimer = window.setTimeout(function () {
fadeOut();
}, 750);
fadeAlpha -= 5;
} else if (fadeAlpha - 10 >= 0) {
setAlpha(fadeAlpha - 10);
fadeOutTimer = window.setTimeout(function () {
fadeOut();
}, 40);
} else {
monitorEl.style.display = "none";
}
};
/* private */
var getFixedOffsetTop = function (){
if (bindingParent) {
var b = bindingParent;
return b.scrollTop;
}
var dua = navigator.userAgent;
var b = document.body;
var p = b.parentNode;
var pcHeight = p.clientHeight;
var bcScrollTop = b.scrollTop + b.offsetTop;
var pcScrollTop = p.scrollTop + p.offsetTop;
return (dua.indexOf("Opera") < 0 && document.all ? (pcHeight == 0 ? bcScrollTop : pcScrollTop)
: dua.indexOf("Gecko") < 0 ? (pcHeight == p.offsetHeight
&& pcHeight == p.scrollHeight ? bcScrollTop : pcScrollTop) : bcScrollTop);
};
/* not used in Jmol
if (window["ClazzLoader"]) {
_Loader.onScriptLoading = function(file) {
CLPM.showStatus("Loading " + file + "...");
};
_Loader.onScriptLoaded = function(file, isError) {
CLPM.showStatus(file + (isError ? " loading failed." : " loaded."), true);
};
_Loader.onGlobalLoaded = function(file) {
CLPM.showStatus("Application loaded.", true);
};
_Loader.onClassUnloaded = function(clazz) {
CLPM.showStatus("Class " + clazz + " is unloaded.", true);
};
}
*/
})(Clazz._LoaderProgressMonitor, Jmol);
//}
/******************************************************************************
* Copyright (c) 2007 java2script.org and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Zhou Renjian - initial API and implementation
*****************************************************************************/
/*******
* @author zhou renjian
* @create Nov 5, 2005
*******/
;(function(Con, Sys) {
/**
* Setting maxTotalLines to -1 will not limit the console result
*/
/* protected */
Con.maxTotalLines = 10000;
/* protected */
Con.setMaxTotalLines = function (lines) {
Con.maxTotalLines = (lines > 0 ? lines : 999999);
}
/* protected */
Con.maxLatency = 40;
/* protected */
Con.setMaxLatency = function (latency) {
Con.maxLatency = (latency > 0 ? latency : 40);
};
/* protected */
Con.pinning = false;
/* protected */
Con.enablePinning = function (enabled) {
Con.pinning = enabled;
};
/* private */
Con.linesCount = 0;
/* private */
Con.metLineBreak = false;
/*
* Give an extension point so external script can create and bind the console
* themself.
*
* TODO: provide more template of binding console window to browser.
*/
/* protected */
Con.createConsoleWindow = function (parentEl) {
var console = document.createElement ("DIV");
console.style.cssText = "font-family:monospace, Arial, sans-serif;";
document.body.appendChild (console);
return console;
};
var c160 = String.fromCharCode(160); //nbsp;
c160 += c160+c160+c160;
/* protected */
Con.consoleOutput = function (s, color) {
var o = window["j2s.lib"];
var console = (o && o.console);
if (console && typeof console == "string")
console = document.getElementById(console)
if (!console)
return false; // BH this just means we have turned off all console action
if (Con.linesCount > Con.maxTotalLines) {
for (var i = 0; i < Con.linesCount - Con.maxTotalLines; i++) {
if (console && console.childNodes.length > 0) {
console.removeChild (console.childNodes[0]);
}
}
Con.linesCount = Con.maxTotalLines;
}
var willMeetLineBreak = false;
s = (typeof s == "undefined" ? "" : s == null ? "null" : "" + s);
s = s.replace (/\t/g, c160);
if (s.length > 0)
switch (s.charAt(s.length - 1)) {
case '\n':
case '\r':
s = (s.length > 1 ? s.substring (0, s.length - (s.charAt (s.length - 2) == '\r' ? 2 : 1)) : "");
willMeetLineBreak = true;
break;
}
var lines = null;
s = s.replace (/\t/g, c160);
lines = s.split(/\r\n|\r|\n/g);
for (var i = 0, last = lines.length - 1; i <= last; i++) {
var lastLineEl = null;
if (Con.metLineBreak || Con.linesCount == 0
|| console.childNodes.length < 1) {
lastLineEl = document.createElement ("DIV");
console.appendChild (lastLineEl);
lastLineEl.style.whiteSpace = "nowrap";
Con.linesCount++;
} else {
try {
lastLineEl = console.childNodes[console.childNodes.length - 1];
} catch (e) {
lastLineEl = document.createElement ("DIV");
console.appendChild (lastLineEl);
lastLineEl.style.whiteSpace = "nowrap";
Con.linesCount++;
}
}
var el = document.createElement ("SPAN");
lastLineEl.appendChild (el);
el.style.whiteSpace = "nowrap";
if (color)
el.style.color = color;
var l = lines[i]
if (l.length == 0)
l = c160;
el.appendChild(document.createTextNode(l));
if (!Con.pinning)
console.scrollTop += 100;
Con.metLineBreak = (i != last || willMeetLineBreak);
}
var cssClazzName = console.parentNode.className;
if (!Con.pinning && cssClazzName
&& cssClazzName.indexOf ("composite") != -1) {
console.parentNode.scrollTop = console.parentNode.scrollHeight;
}
Con.lastOutputTime = new Date ().getTime ();
};
/*
* Clear all contents inside the console.
*/
/* public */
Con.clear = function () {
try {
Con.metLineBreak = true;
var o = window["j2s.lib"];
var console = o && o.console;
if (!console || !(console = document.getElementById (console)))
return;
var childNodes = console.childNodes;
for (var i = childNodes.length; --i >= 0;)
console.removeChild (childNodes[i]);
Con.linesCount = 0;
} catch(e){};
};
/* public */
Clazz.alert = function (s) {
Con.consoleOutput (s + "\r\n");
};
/* public */
Sys.out.print = function (s) {
Con.consoleOutput (s);
};
/* public */
Sys.out.println = function(s) {
Con.consoleOutput(typeof s == "undefined" ? "\r\n" : s == null ? s = "null\r\n" : s + "\r\n");
};
Sys.out.write = function (buf, offset, len) {
Sys.out.print(String.instantialize(buf).substring(offset, offset+len));
};
/* public */
Sys.err.__CLASS_NAME__ = "java.io.PrintStream";
/* public */
Sys.err.print = function (s) {
Con.consoleOutput (s, "red");
};
/* public */
Sys.err.println = function (s) {
Con.consoleOutput (typeof s == "undefined" ? "\r\n" : s == null ? s = "null\r\n" : s + "\r\n", "red");
};
Sys.err.write = function (buf, offset, len) {
Sys.err.print(String.instantialize(buf).substring(offset, offset+len));
};
})(Clazz.Console, System);
})(Clazz, Jmol); // requires JSmolCore.js
}; // called by external application
Jmol.___JmolDate="$Date: 2016-12-02 07:03:48 -0600 (Fri, 02 Dec 2016) $"
Jmol.___fullJmolProperties="src/org/jmol/viewer/Jmol.properties"
Jmol.___JmolVersion="14.7.5_2016.12.02"
|
angular
.module("portfolio")
.component("portfolioView", {
templateUrl: "padifolio/app/components/portfolio/portfolio-view-frame.html",
controller: PortfolioViewController,
bindings: {
portfolioList: "<"
}
});
PortfolioViewController.$inject = ["$state", "$stateParams", "appService"];
function PortfolioViewController($state, $stateParams, appService) {
var vm = this;
vm.selectPortfolio = function(portfolio) {
if (portfolio.id) {
$state.go("home.portfolio", { portfolioId: portfolio.id });
} else {
$state.go("home");
}
}
}
|
import Footers from './footer/Footers'
import Headers from './header/Headers'
import HeaderSelect from './header/HeaderSelect'
import LeftMenus from './leftMenu/LeftMenus'
import LeftOrderMenu from './leftMenu/LeftOrderMenu'
import Cascaders from './cascader'
import NoData from './noData'
import Page from './pagination'
import SearchBox from './searchBox/SearchBox'
import BrandList from './searchBox/BrandList'
import BuyerAttrList from './searchBox/BuyerAttrList'
import Table from './table'
import Percent from './table/Percent'
import TableArrows from './table/TableArrows'
import TimeSelect from './timeSelect'
import LoadingInfo from './LoadingInfo'
import Counter from './counter'
module.exports = {
Footers,
Counter,
LeftMenus,
Headers,
LeftOrderMenu,
Cascaders,
NoData,
Page,
SearchBox,
BrandList,
BuyerAttrList,
Table,
Percent,
TableArrows,
TimeSelect,
HeaderSelect,
LoadingInfo
}
|
var DbEditor = require('./DbManipulator');
var Schema = require('./Schema');
var getArticle = function(id, callback){
var q = 'SELECT ' + Schema.Article.column.id + ', ' + Schema.User.column.username + ' as author ,' + Schema.Article.column.content + ', ' + Schema.Article.column.time + ', ' + Schema.Article.column.title + ', ' + Schema.ArticleImage.column.url + ' ' +
'FROM ' + Schema.Article.table + ', ' + Schema.User.table + ' ' +
'WHERE ' + Schema.Article.column.id + '=' + id + ' AND ' + Schema.Article.column.authorId + '=' + Schema.User.column.commentId + ';';
console.log(q);
DbEditor.rawQuery(q, callback);
// DbEditor.query(Schema.Article.table, ['*'], [Schema.Article.column.id+'='], [id], callback);
};
var getLatestArticles = function(callback){
var q = 'SELECT articleId, username as author, content, createTime, title, authorId' + ' ' +
'FROM ' + Schema.Article.table + ', ' + Schema.User.table + ' ' +
'WHERE ' + Schema.Article.table + '.' + Schema.Article.column.authorId + '=' + Schema.User.table + '.' + Schema.User.column.id + ' ' +
'ORDER BY ' + Schema.Article.column.time + ' DESC;';
console.log(q);
DbEditor.rawQuery(q, callback);
};
var getLove = function(articleId, callback){
var q = 'SELECT ' + Schema.Love.table + '.' + Schema.Love.column.uid + ', '+ Schema.User.column.fname + ', ' + Schema.User.column.lname + ' ' +
'FROM ' + Schema.User.table + ', ' + Schema.Love.table + ' ' +
'WHERE ' + Schema.Love.table + '.' + Schema.Love.column.aid + '=' + articleId + ' AND ' + Schema.Love.table + '.' + Schema.Love.column.uid + '=' + Schema.User.table +'.' + Schema.User.column.id +';';
console.log(q);
DbEditor.rawQuery(q, callback);
// DbEditor.query(Schema.Love.table, [Schema.Love.column.uid, 'count(' + Schema.Love.column.aid +') as number'], [Schema.Love.column.aid+'='], [articleId], callback);
};
var postLove = function(userId, articleId, callback){
var q = 'INSERT INTO ' + Schema.Love.table + ' VALUES (' + articleId + ', ' + userId + ');';
console.log(q);
DbEditor.rawQuery(q, callback);
};
var deleteLove = function(userId, articleId, callback){
var q = 'DELETE FROM ' + Schema.Love.table +
' WHERE ' + Schema.Love.column.uid + '=' + userId + ' AND ' + Schema.Love.column.aid + '=' + articleId + ';';
console.log(q);
DbEditor.rawQuery(q, callback);
};
var postArticle = function(newArticleId ,userId, title, content, callback){
var q = 'INSERT INTO ' + Schema.Article.table +
' VALUES ('+ newArticleId + ', ' + userId + ', ' + title + ', ' + content + ', NOW() );';
console.log(q);
DbEditor.rawQuery(q, callback);
};
var getComments = function(articleId, callback){
var q = 'SELECT ' + Schema.Comment.column.commentId + ', ' + Schema.User.column.fname + ', ' + Schema.User.column.lname + ', ' + Schema.Comment.column.comment + ', ' + Schema.Comment.column.time + ' ' +
'FROM ' + Schema.Comment.table + ', ' + Schema.User.table + ' ' +
'WHERE ' + Schema.Comment.column.aid + '=' + articleId + ' AND ' + Schema.Comment.column.commentorId + '=' + Schema.User.column.id + ';';
console.log(q);
DbEditor.rawQuery(q, callback);
// DbEditor.query(Schema.Comment.table, [Schema.Comment.column.commentId, Schema.Comment.column.commentorId, Schema.Comment.column.comment, 'date_format(' + Schema.Comment.column.time + ', \'%e-%c-%Y %T\') as createTime'], [Schema.Comment.column.aid+'='], [articleId], callback);
};
var postComment = function(newCommentId, articleId, commentorId, comment, callback){
var q = 'INSERT INTO ' + Schema.Comment.table + ' ' +
'VALUES (' + newCommentId + ', ' + articleId + ', ' + commentorId + ', ' + toString(comment) + ', NOW());';
console.log(q);
DbEditor.rawQuery(q, callback);
};
var getUserInfo = function(username, callback){
var q = 'SELECT ' + Schema.User.column.id + ', ' + Schema.User.column.username + ', ' + Schema.User.column.fname + ', ' + Schema.User.column.lname + ' ' +
'FROM ' + Schema.User.table + ' '+
'WHERE ' + Schema.User.column.username + '=' + toString(username) + ';';
console.log(q);
DbEditor.rawQuery(q, callback);
};
var postArticleImage = function(articleId, imageURL, callback){
var q = 'INSERT INTO ' + Schema.ArticleImage.table + ' ' +
'VAULES (' + articleId + ', ' + toString(imageURL) + ');';
console.log(q);
DbEditor.rawQuery(q, callback);
};
var postTagFromArticle = function(articleId, tags, callback){
var q = 'INSERT INTO ' + Schema.Tag.table + ' ' +
'VALUES ';
for(var i = 0; i < tags.length; i++) {
q += '( ' + toString(tags[i]) + ', ' + articleId + ')';
if(i < tags.length - 1) q += ',';
else q += ';';
}
console.log(q);
DbEditor.rawQuery(q, callback);
};
var getFollowingsArticle = function(userId, callback){
var q = 'SELECT tbl_articles.articleId, tbl_users.username as author, tbl_users.firstName, tbl_users.lastName, tbl_articles.content, tbl_articles.title, tbl_articles.createTime, tbl_articles.authorId ' +
'FROM tbl_articles, tbl_users, tbl_follows ' +
'WHERE tbl_follows.uid=' + userId + ' AND tbl_follows.following=tbl_articles.authorId AND tbl_follows.following=tbl_users.uid';
console.log(q);
DbEditor.rawQuery(q, callback);
};
var getFollowings = function(userId, callback){
var q = 'SELECT tbl_users.uid, tbl_users.username, tbl_users.firstName, tbl_users.lastName ' +
'FROM tbl_users, tbl_follows ' +
'WHERE tbl_follows.uid=' + userId + ' AND tbl_follows.following=tbl_users.uid;';
console.log(q);
DbEditor.rawQuery(q, callback);
};
var postFollowing = function(userId, followingId, callback){
var q = 'INSERT INTO tbl_follows ' +
'VALUES(' + userId + ', ' + followingId + ');';
console.log(q);
DbEditor.rawQuery(q, callback);
};
function toString(s){
return '\''+s+'\'';
}
module.exports = {
getArticle: getArticle,
getLatestArticle: getLatestArticles,
getLovesInArticle: getLove,
postLoveToArticle: postLove,
removeLoveFromArticle: deleteLove,
postArticle: postArticle,
getCommentsOfArticle: getComments,
postCommentsToArticle: postComment,
getUserInfo: getUserInfo,
getFollowingsArticle: getFollowingsArticle,
getFollowings: getFollowings,
postFollowing: postFollowing
};
|
let test = require('test'),
asserts = test.asserts,
Context = require('../lib/juice/context').Context,
qmock = require('./lib/juice-test'),
Mock = qmock.Mock;
function mock_view( app, opts ) {
var tmpl = new Mock( {
render : {
calls: 1,
interface : [
{ accepts : [
opts.input || "raw-template",
opts.stash || { key: "value" }
],
returns : opts.returns || "rendered-template"
}
]
}
} );
tmpl.accepts( Object );
app.expects(1)
.method("loadRelativeComponent")
.interface({
accepts: [ "./view/" + opts.name ],
returns: { View: tmpl }
});
return tmpl;
}
exports.test_RenderTemplateDefault = qmock.mockForTest(
function mock() {
qmock.mockModule( 'fs-base',
require( './lib/fs-mock' ).mock( {
"templates/index.tt": "raw-template"
} )
);
},
function test() {
var rawTemplate = "raw-template",
stash = { key : "value" },
renderedTemplate = "rendered-template";
var app = qmock.mock_app( module );
app.docRoot = "";
app.config = { }
app.templatePath = [ 'templates/' ];
var tt = mock_view( app, { name: "tt" } );
asserts.same(
Context.prototype.renderTemplate.call( app, "index", stash ),
"rendered-template",
"Should default to .tt when there's no conf"
);
qmock.verifyOk( app );
qmock.verifyOk( tt );
} );
exports.test_RenderTemplateNotFound = qmock.mockForTest(
function mock() {
// Mock empty fs
qmock.mockModule( 'fs-base',
require( './lib/fs-mock' ).mock( { } )
);
},
function test() {
var rawTemplate = "raw-template",
stash = { key : "value" },
renderedTemplate = "rendered-template";
var app = qmock.mock_app( module );
app.docRoot = "";
app.config = {};
app.templatePath = [ app.docRoot + 'templates/' ];
asserts.throwsOk(
function() { Context.prototype.renderTemplate.call( app, "index", stash ); },
"Should throw an error if no template file exists"
);
qmock.verifyOk( app );
} );
exports.test_RenderTemplateEngineNotFound = qmock.mockForTest(
function mock() {
qmock.mockModule( 'fs-base',
require( './lib/fs-mock' ).mock( {
"templates/index.made-up": "raw-template"
} )
);
},
function test() {
var rawTemplate = "raw-template",
stash = { key : "value" },
renderedTemplate = "rendered-template";
var app = qmock.mock_app( module );
app.docRoot = "";
app.config = { templates: { "made-up": "made-up" } };
app.templatePath = [ 'templates/' ];
asserts.throwsOk(
function() { Context.prototype.renderTemplate.call( app, "index", stash ) },
"Should throw an error if the rendering engine doesn't exist"
);
} );
exports.test_RenderTemplateOrder = qmock.mockForTest(
function mock() {
qmock.mockModule( 'fs-base',
require( './lib/fs-mock' ).mock( {
"templates/index.haml": "raw-template"
} )
);
},
function test() {
var stash = { key : "value" },
renderedTemplate = "rendered-template";
var app = qmock.mock_app( module );
app.docRoot = "";
app.config = { templates: { tt: "tt", haml: "haml" } };
app.templatePath = [ app.docRoot + 'templates/' ];
var haml = mock_view( app, { name: "haml" } );
asserts.same(
Context.prototype.renderTemplate.call( app, "index", stash ),
renderedTemplate,
"Should try the next option if the first doesn't exist"
);
qmock.verifyOk( app, "template adaptor loaded correctly" );
qmock.verifyOk( haml, "template adaptor called correctly" );
} );
if (require.main == module)
test.runner(exports);
|
const html = require('bel')
module.exports = (props) => {
const handleSubmit = (e) => {
e.preventDefault()
props.onSubmit && props.type === 'radio' ? props.onSubmit(e.target.querySelector('input:checked').value) : props.onSubmit(e.target.querySelector('input').value)
}
if (!props.readOnly && props.editMode) {
return html`
<form onsubmit=${handleSubmit} class="media">
<div class="media-left">${props.label}</div>
<div class="media-content">
<p class="control">
${props.type === 'radio'
? props.options.map(opt => html`<label class="radio"><input type="radio" name=${props.name} value="${opt.value}" checked=${props.value === opt.value}/> ${opt.label}</label>`)
: html`<input class="input" type="${props.type || 'text'}" value="${props.value || ''}">`
}
</p>
</div>
<div class="media-right">
<button type="submit" class="button is-icon-button is-primary is-inverted">
<i class="material-icons">save</i>
</button>
</div>
</form>
`
} else {
return html`
<div class="media">
<div class="media-left">${props.label}</div>
<div class="media-content">
${props.linkto ? html`<a href="${props.linkto}" target="${props.linktarget ? props.linktarget : html`_self`}">${props.value}</a>` : props.value}
${props.type === 'password' ? '●●●●●●●●' : ''}
</div>
${!props.readOnly ? html`
<div class="media-right">
<button class="button is-icon-button is-info is-inverted" onclick=${props.onEditClick}>
<i class="material-icons">edit</i>
</button>
</div>
` : ''}
</div>
`
}
}
|
const _ = require('lodash');
const hooks = require('hooks-fixed');
import _privateKey from './privatekey'
import { Model } from './model'
import { Schema } from './schema'
/**
* Compiles a schema into a Model
* @param descriptor
* @param options
* @param name
* @returns {ModelInstance}
* @private
*/
export function compile(descriptor, options = {}, name = undefined) {
var schema = descriptor;
if (!(schema instanceof Schema)) {
schema = new Schema(schema, options);
}
// Some of the options require the reflection.
if (typeof(Proxy) === 'undefined') {
// If strict mode is off but the --harmony flag is not, fail.
if (!options.strict) {
throw new Error('Turning strict mode off requires --harmony flag.');
}
// If dot notation is on but the --harmony flag is not, fail.
if (options.dotNotation) {
throw new Error('Dot notation support requires --harmony flag.');
}
}
/**
* ModelInstance class is the compiled class from a schema definition. It extends <code>Model</code>.
* All models generated are an instance of ModelInstance. It also inherits <code>hooks-fixed</code>
* See {@link https://www.npmjs.com/package/hooks-fixed hooks-fixed} for pre and post hooks.
* @class
* @augments Model
*
*/
class ModelInstance extends Model {
/**
* This would be the constructor for the generated models.
* @param {Object} data - the model instance data
* @param {Object} options - optional creation options
* @param {Boolean} options.clone - Whether to deep clone the incoming data. Default: <code>false</code>.
* Make sure you wish to do this as it has performance implications. This is
* useful if you are creating multiple instances from same base data and then
* wish to modify each instance.
*
*/
constructor(data, options = {}) {
super(data, options, schema, name);
}
}
var k;
for (k in hooks) {
ModelInstance.prototype[k] = ModelInstance[k] = hooks[k];
}
/**
* @name schema
* @static {Schema}
* @memberof ModelInstance
* @description Schema the schema of this model.
*/
ModelInstance.schema = schema;
/**
* @name modelName
* @static {String}
* @memberof ModelInstance
* @description The name of the model.
*/
ModelInstance.modelName = name;
// Add custom methods to generated class.
_.each(schema.methods, (method, key) => {
if (ModelInstance.prototype[key]) {
throw new Error(`Cannot overwrite existing ${key} method with custom method.`);
}
ModelInstance.prototype[key] = method;
});
// Add custom static methods to generated class.
_.each(schema.statics, (method, key) => {
if (ModelInstance[key]) {
throw new Error(`Cannot overwrite existing ${key} static with custom method.`);
}
ModelInstance[key] = method;
});
setupHooks(ModelInstance);
// if the user wants to allow modifications
if (options.freeze !== false) Object.freeze(ModelInstance);
return ModelInstance;
}
/*!
* Sets up hooks for the new Model
* @param InstanceModel
*/
function setupHooks(InstanceModel) {
// set up hooks
var ourHookedFnNames = ['save', 'remove'];
ourHookedFnNames.forEach(function (fnName) {
InstanceModel.hook(fnName, InstanceModel.prototype[fnName]);
});
var q = InstanceModel.schema && InstanceModel.schema.callQueue;
if (q) {
for (var i = 0, l = q.length; i < l; i++) {
var hookFn = q[i].hook;
var args = q[i].args;
var hookedFnName = args[0];
if (ourHookedFnNames.indexOf(hookedFnName) === -1) {
InstanceModel.hook(hookedFnName, InstanceModel.prototype[hookedFnName]);
}
function wrapPostHook(fnArgs, index) {
var mwfn = fnArgs[index];
function hookCb(next) {
mwfn.apply(this);
next(undefined, this);
}
fnArgs[index] = hookCb;
}
// wrap post
if (hookFn === 'post' && ourHookedFnNames.indexOf(hookedFnName) >= 0) {
if (args.length === 2 && typeof args[1] === 'function') {
wrapPostHook(args, 1);
}
else if (args.length === 3 && typeof args[2] === 'function') {
wrapPostHook(args, 2);
}
}
InstanceModel[hookFn].apply(InstanceModel, args);
}
}
} |
'use trict'
const Hapi = require( 'hapi');
const config = require( './app/config');
var mongoose = require('mongoose');
console.log( config.db.getUrl());
mongoose.connect( config.db.getUrl());
const server = new Hapi.Server();
server.connection( config.api_server);
require( './app/route')(server);
module.exports = server; |
L.SVG.include({
_updateShape: function _updateShape(layer) {
var p = layer._point;
var s = layer._radius;
var shape = layer.options.shape;
if(shape === "diamond"){
var d = "M"+ (p.x-(Math.sqrt(2)*s))+ " "+ (p.y)+ " L " + (p.x) +" "+ (p.y-(Math.sqrt(2)*s))+ " L" + (p.x+(Math.sqrt(2)*s)) + " " + (p.y)+ " L" + (p.x) + " " + (p.y+(Math.sqrt(2)*s)) +" L" + (p.x-(Math.sqrt(2)*s)) + " " + (p.y);
this._setPath(layer, d);
}
if(shape === "square"){
var d = "M"+ (p.x-s)+ " "+ (p.y-s)+ " L " + (p.x+s) +" "+ (p.y-s)+ " L" + (p.x+s) + " " + (p.y+s)+ " L" + (p.x-s) + " " + (p.y+s) +" L" + (p.x-s) + " " + (p.y-s);
this._setPath(layer, d);
}
if (shape === "triangle" || shape === "triangle-up") {
var d = "M" + (p.x - (13/10*s)) + " " + (p.y + (0.75*s)) + " L" + (p.x) + " " + (p.y - (1.5*s)) + " L" + (p.x + (13/10*s)) + " " + (p.y + (0.75*s)) + " Z";
this._setPath(layer, d);
}
if (shape === "triangle-down") {
var d = "M" + (p.x - (13/10*s)) + " " + (p.y - (0.75*s)) + " L" + (p.x) + " " + (p.y + (1.5*s)) + " L" + (p.x + (13/10*s)) + " " + (p.y - (0.75*s)) + " Z";
this._setPath(layer, d);
}
if (shape === "arrowhead" || shape === "arrowhead-up") {
var d = "M " + (p.x + (1.3*s)) + " " + (p.y + (1.3*s)) + " L " + (p.x) + " " + (p.y - (1.3*s)) + " L " + (p.x - (1.3*s)) + " " + (p.y + (1.3*s)) + " L " + (p.x) + " " + (p.y + (0.5 * s)) + " L " + (p.x + (1.3*s)) + " " + (p.y + (1.3*s)) + " Z";
this._setPath(layer, d);
}
if (shape === "arrowhead-down") {
var d = "M " + (p.x - (1.3*s)) + " " + (p.y - (1.3*s)) + " L " + (p.x) + " " + (p.y + (1.3*s)) + " L " + (p.x + (1.3*s)) + " " + (p.y - (1.3*s)) + " L " + (p.x) + " " + (p.y - (0.5 * s)) + " L " + (p.x - (1.3*s)) + " " + (p.y - (1.3*s)) + " Z";
this._setPath(layer, d);
}
if (shape === "circle") {
this._updateCircle(layer)
}
if (shape === "x") {
s = s / 2;
var d = 'M' + (p.x + s) + ',' + (p.y + s) +
'L' + (p.x - s) + ',' + (p.y - s) +
'M' + (p.x - s) + ',' + (p.y + s) +
'L' + (p.x + s) + ',' + (p.y - s);
this._setPath(layer, d);
}
}
});
;L.ShapeMarker = L.Path.extend({
options: {
fill: true,
shape: 'triangle',
radius: 10
},
initialize: function (latlng, options) {
L.setOptions(this, options);
this._latlng = L.latLng(latlng);
this._radius = this.options.radius;
},
setLatLng: function (latlng) {
this._latlng = L.latLng(latlng);
this.redraw();
return this.fire('move', {latlng: this._latlng});
},
getLatLng: function () {
return this._latlng;
},
setRadius: function (radius) {
this.options.radius = this._radius = radius;
return this.redraw();
},
getRadius: function () {
return this._radius;
},
setStyle : function (options) {
var radius = options && options.radius || this._radius;
L.Path.prototype.setStyle.call(this, options);
this.setRadius(radius);
return this;
},
_project: function () {
this._point = this._map.latLngToLayerPoint(this._latlng);
this._updateBounds();
},
_updateBounds: function () {
var r = this._radius,
r2 = this._radiusY || r,
w = this._clickTolerance(),
p = [r + w, r2 + w];
this._pxBounds = new L.Bounds(this._point.subtract(p), this._point.add(p));
},
_update: function () {
if (this._map) {
this._updatePath();
}
},
_updatePath: function () {
this._renderer._updateShape(this);
},
_empty: function () {
return this._size && !this._renderer._bounds.intersects(this._pxBounds);
},
toGeoJSON: function () {
return L.GeoJSON.getFeature(this, {
type: 'Point',
coordinates: L.GeoJSON.latLngToCoords(this.getLatLng())
});
}
});
// @factory L.shapeMarker(latlng: LatLng, options? ShapeMarker options)
//
L.shapeMarker = function shapeMarker(latlng, options) {
return new L.ShapeMarker(latlng, options);
};
|
var searchData=
[
['alloc',['alloc',['../structcstring.html#a5d0c6d93ac71cc14384bcf732ea07092',1,'cstring::alloc()'],['../structvector.html#a84d51c347934dd8fdd066e288c2eef08',1,'vector::alloc()']]]
];
|
'use strict';
import gulp from 'gulp';
import paths from '../config';
gulp.task('build:images', () => gulp.src(paths.source.images).pipe(gulp.dest(paths.build.images)));
|
/*
* economy.js by CreaturePhil
* Shop Code Credits - Lord Haji, HoeenCoder
* Dice Game Credits - Lord Haji, SilverTactic (Silveee)
*/
'use strict';
let color = require('../config/color');
let fs = require('fs');
let path = require('path');
let writeJSON = true;
let Shop = {};
const INACTIVE_END_TIME = 1 * 60 * 1000; // 1 minute
/**
* Gets an amount and returns the amount with the name of the currency.
*
* @examples
* currencyName(0); // 0 bucks
* currencyName(1); // 1 buck
* currencyName(5); // 5 bucks
*
* @param {Number} amount
* @returns {String}
*/
function currencyName(amount) {
let name = " buck";
return amount === 1 ? name : name + "s";
}
/**
* Checks if the money input is actually money.
*
* @param {String} money
* @return {String|Number}
*/
function isMoney(money) {
let numMoney = Number(money);
if (isNaN(money)) return "Must be a number.";
if (String(money).includes('.')) return "Cannot contain a decimal.";
if (numMoney < 1) return "Cannot be less than one buck.";
return numMoney;
}
/**
* Log money to logs/money.txt file.
*
* @param {String} message
*/
function logMoney(message) {
if (!message) return;
let file = path.join(__dirname, '../logs/money.txt');
let date = "[" + new Date().toUTCString() + "] ";
let msg = message + "\n";
fs.appendFile(file, date + msg);
}
/*
* Shop start
*/
function NewItem(name, desc, price) {
this.name = name;
this.id = toId(name);
this.desc = Chat.escapeHTML(desc);
this.price = Number(price);
}
function writeShop() {
if (!writeJSON) return false; //Prevent corruptions
fs.writeFile('config/Shop.json', JSON.stringify(Shop));
}
function shopDisplay() {
let output = '<div style="max-height:300px; width: 100%; overflow: scroll"><table style="border:2px solid #000000; border-radius: 5px; width: 100%;"><tr><th colspan="3" style="border: 2px solid #000000; border-radius: 5px">Server Shop</th></tr>';
for (let i in Shop) {
if (!Shop[i]) continue;
output += '<tr><td style="border: 2px solid #000000; width: 20%; text-align: center"><button class="button" name="send" value="/Shop buy ' + Shop[i].id + '">' + Shop[i].name + '</button></td><td style="border: 2px solid #000000; width: 70%; text-align: center">' + Shop[i].desc + '</td><td style="border: 2px solid #000000; width: 10%; text-align: center">' + Shop[i].price + '</td></tr>';
}
output += '</table></div>';
return output;
}
try {
fs.accessSync('config/Shop.json', fs.F_OK);
let raw = JSON.parse(fs.readFileSync('config/Shop.json', 'utf8'));
Shop = raw;
} catch (e) {
fs.writeFile('config/Shop.json', "{}", function (err) {
if (err) {
console.error('Error while loading Shop: ' + err);
Shop = {
closed: true,
};
writeJSON = false;
} else {
console.log("config/Shop.json not found, creating a new one...");
}
});
}
/*
* Shop end
*/
/*
* Dice start
*/
function diceImg(num) {
switch (num) {
case 0:
return "http://i.imgur.com/nUbpLTD.png";
case 1:
return "http://i.imgur.com/BSt9nfV.png";
case 2:
return "http://i.imgur.com/eTQMVhY.png";
case 3:
return "http://i.imgur.com/3Y2hCAJ.png";
case 4:
return "http://i.imgur.com/KP3Za7O.png";
case 5:
return "http://i.imgur.com/lvi2ZZe.png";
}
}
class Dice {
constructor(room, amount, starter) {
this.room = room;
if (!this.room.diceCount) this.room.diceCount = 0;
this.bet = amount;
this.players = [];
this.timer = setTimeout(() => {
this.room.add('|uhtmlchange|' + this.room.diceCount + '|<div class = "infobox">(This game of dice has been ended due to inactivity.)</div>').update();
delete this.room.dice;
}, INACTIVE_END_TIME);
this.startMessage = '<div class="infobox"><b style="font-size: 14pt; color: #24678d"><center><span style="color: ' + color(starter) + '">' + Chat.escapeHTML(starter) + '</span> has started a game of dice for <span style = "color: green">' + amount + '</span> ' + currencyName(amount) + '!</center></b><br>' +
'<center><img style="margin-right: 30px;" src = "http://i.imgur.com/eywnpqX.png" width="80" height="80">' +
'<img style="transform:rotateY(180deg); margin-left: 30px;" src="http://i.imgur.com/eywnpqX.png" width="80" height="80"><br>' +
'<button name="send" value="/joindice">Click to join!</button></center>';
this.room.add('|uhtml|' + (++this.room.diceCount) + '|' + this.startMessage + '</div>').update();
}
join(user, self) {
if (this.players.length === 2) return self.errorReply("Two users have already joined this game of dice.");
if (Db.money.get(user.userid, 0) < this.bet) return self.errorReply('You don\'t have enough money for this game of dice.');
if (this.players.includes(user)) return self.sendReply('You have already joined this game of dice.');
//if (this.players.length && this.players[0].latestIp === user.latestIp) return self.errorReply("You have already joined this game of dice under the alt '" + this.players[0].name + "'.");
this.players.push(user);
this.room.add('|uhtmlchange|' + this.room.diceCount + '|' + this.startMessage + '<center><b><font color ="' + color(user.name) + '">' + Chat.escapeHTML(user.name) + '</font></b> has joined the game!</center></div>').update();
if (this.players.length === 2) this.play();
}
leave(user, self) {
if (!this.players.includes(user)) return self.sendReply('You haven\'t joined the game of dice yet.');
this.players.remove(user);
this.room.add('|uhtmlchange|' + this.room.diceCount + '|' + this.startMessage + '</div>');
}
play() {
let p1 = this.players[0], p2 = this.players[1];
let money1 = Db.money.get(p1.userid, 0);
let money2 = Db.money.get(p2.userid, 0);
if (money1 < this.bet || money2 < this.bet) {
let user = (money1 < this.bet ? p1 : p2);
let other = (user === p1 ? p2 : p1);
user.sendTo(this.room, 'You have been removed from this game of dice, as you do not have enough money.');
other.sendTo(this.room, user.name + ' has been removed from this game of dice, as they do not have enough money. Wait for another user to join.');
this.players.remove(user);
this.room.add('|uhtmlchange|' + this.room.diceCount + '|' + this.startMessage + '<center>' + this.players.map(user => "<b><font color='" + color(user.name) + "'>" + Chat.escapeHTML(user.name) + "</font></b>") + ' has joined the game!</center>').update();
return;
}
let players = this.players.map(user => "<b><font color='" + color(user.name) + "'>" + Chat.escapeHTML(user.name) + "</font></b>").join(' and ');
this.room.add('|uhtmlchange|' + this.room.diceCount + '|' + this.startMessage + '<center>' + players + ' have joined the game!</center></div>').update();
let roll1, roll2;
do {
roll1 = Math.floor(Math.random() * 6);
roll2 = Math.floor(Math.random() * 6);
} while (roll1 === roll2);
if (roll2 > roll1) this.players.reverse();
let winner = this.players[0], loser = this.players[1];
setTimeout(() => {
this.room.add('|uhtmlchange|' + this.room.diceCount + '|<div class="infobox"><center>' + players + ' have joined the game!<br /><br />' +
'The game has been started! Rolling the dice...<br />' +
'<img src = "' + diceImg(roll1) + '" align = "left" title = "' + Chat.escapeHTML(p1.name) + '\'s roll"><img src = "' + diceImg(roll2) + '" align = "right" title = "' + p2.name + '\'s roll"><br />' +
'<b><font color="' + color(p1.name) + '">' + Chat.escapeHTML(p1.name) + '</font></b> rolled ' + (roll1 + 1) + '!<br />' +
'<b><font color="' + color(p2.name) + '">' + Chat.escapeHTML(p2.name) + '</font></b> rolled ' + (roll2 + 1) + '!<br />' +
'<b><font color="' + color(winner.name) + '">' + Chat.escapeHTML(winner.name) + '</font></b> has won <b style="color:red">' + (this.bet) + '</b> ' + currencyName(this.bet) + '!<br />' +
'Better luck next time, <b><font color="' + color(loser.name) + '">' + Chat.escapeHTML(loser.name) + '</font></b>!'
).update();
Db.money.set(winner.userid, Db.money.get(winner.userid) + this.bet);
Db.money.set(loser.userid, Db.money.get(loser.userid) - this.bet);
this.end();
}, 800);
}
end(user) {
if (user) this.room.add('|uhtmlchange|' + this.room.diceCount + '|<div class = "infobox">(This game of dice has been forcibly ended by ' + Chat.escapeHTML(user.name) + '.)</div>').update();
clearTimeout(this.timer);
delete this.room.dice;
}
}
/*
* Dice end
*/
exports.commands = {
atm: 'wallet',
purse: 'wallet',
wallet: function (target, room, user) {
if (!this.runBroadcast()) return;
target = toId(target);
if (!target) target = user.name;
const amount = Db.money.get(toId(target), 0);
this.sendReplyBox("<font color=" + color(target) + "><b>" + Chat.escapeHTML(target) + "</b></font> has " + amount + currencyName(amount) + ".");
},
wallethelp: ["/wallet [user] - Shows the amount of money a user has."],
givebuck: 'givemoney',
givebucks: 'givemoney',
givemoney: function (target, room, user) {
if (!this.can('forcewin')) return false;
if (!target || target.indexOf(',') < 0) return this.parse('/help givemoney');
let parts = target.split(',');
let username = parts[0];
let amount = isMoney(parts[1]);
if (typeof amount === 'string') return this.errorReply(amount);
Db.money.set(toId(username), Db.money.get(toId(username), 0) + amount);
let total = Db.money.get(toId(username));
amount = amount + currencyName(amount);
total = total + currencyName(total);
this.sendReply(username + " was given " + amount + ". " + username + " now has " + total + ".");
if (Users.get(username)) Users(username).popup(user.name + " has given you " + amount + ". You now have " + total + ".");
logMoney(username + " was given " + amount + " by " + user.name + ". " + username + " now has " + total);
},
givemoneyhelp: ["/givemoney [user], [amount] - Give a user a certain amount of money."],
takebuck: 'takemoney',
takebucks: 'takemoney',
takemoney: function (target, room, user) {
if (!this.can('forcewin')) return false;
if (!target || target.indexOf(',') < 0) return this.parse('/help takemoney');
let parts = target.split(',');
let username = parts[0];
let amount = isMoney(parts[1]);
if (typeof amount === 'string') return this.errorReply(amount);
Db.money.set(toId(username), Db.money.get(toId(username), 0) - amount);
let total = Db.money.get(toId(username));
amount = amount + currencyName(amount);
total = total + currencyName(total);
this.sendReply(username + " losted " + amount + ". " + username + " now has " + total + ".");
if (Users.get(username)) Users(username).popup(user.name + " has taken " + amount + " from you. You now have " + total + ".");
logMoney(username + " had " + amount + " taken away by " + user.name + ". " + username + " now has " + total);
},
takemoneyhelp: ["/takemoney [user], [amount] - Take a certain amount of money from a user."],
resetbuck: 'resetmoney',
resetbucks: 'resetmoney',
resetmoney: function (target, room, user) {
if (!this.can('forcewin')) return false;
Db.money.set(toId(target), 0);
this.sendReply(target + " now has 0 bucks.");
logMoney(user.name + " reset the money of " + target + ".");
},
resetmoneyhelp: ["/resetmoney [user] - Reset user's money to zero."],
transfer: 'transfermoney',
transferbuck: 'transfermoney',
transferbucks: 'transfermoney',
transfermoney: function (target, room, user) {
if (!target || target.indexOf(',') < 0) return this.parse('/help transfermoney');
let parts = target.split(',');
let username = parts[0];
let uid = toId(username);
let amount = isMoney(parts[1]);
if (toId(username) === user.userid) return this.errorReply("You cannot transfer to yourself.");
if (username.length > 19) return this.errorReply("Username cannot be longer than 19 characters.");
if (typeof amount === 'string') return this.errorReply(amount);
if (amount > Db.money.get(user.userid, 0)) return this.errorReply("You cannot transfer more money than what you have.");
Db.money.set(user.userid, Db.money.get(user.userid) - amount);
Db.money.set(uid, Db.money.get(uid, 0) + amount);
let userTotal = Db.money.get(user.userid) + currencyName(Db.money.get(user.userid));
let targetTotal = Db.money.get(uid) + currencyName(Db.money.get(uid));
amount = amount + currencyName(amount);
this.sendReply("You have successfully transferred " + amount + ". You now have " + userTotal + ".");
if (Users.get(username)) Users(username).popup(user.name + " has transferred " + amount + ". You now have " + targetTotal + ".");
logMoney(user.name + " transferred " + amount + " to " + username + ". " + user.name + " now has " + userTotal + " and " + username + " now has " + targetTotal + ".");
},
transfermoneyhelp: ["/transfer [user], [amount] - Transfer a certain amount of money to a user."],
shop: {
add: function (target, room, user, connection, cmd, message) {
if (!this.can('roomowner')) return false;
if (Shop.closed) return this.sendReply('An error closed the shop.');
target = target.split(',');
if (!target[2]) return this.parse('/shop help');
if (Shop[toId(target[0])]) return this.errorReply(target[0] + ' is already in the shop.');
if (isNaN(Number(target[2]))) return this.parse('/shop help');
Shop[toId(target[0])] = new NewItem(target[0], target[1], target[2]);
writeShop();
return this.sendReply('The item ' + target[0] + ' was added.');
},
delete: 'remove',
remove: function (target, room, user, connection, cmd, message) {
if (!this.can('roomowner')) return false;
if (Shop.closed) return this.sendReply('An error closed the shop.');
if (!target) return this.parse('/shop help');
if (!Shop[toId(target)]) return this.errorReply(target + ' is not in the shop.');
delete Shop[toId(target)];
writeShop();
return this.sendReply('The item ' + target + ' was removed.');
},
buy: function (target, room, user, connection, cmd, message) {
if (!target) return this.parse('/shop help buy');
if (Shop.closed) return this.sendReply('The shop is closed, come back later.');
if (!Shop[toId(target)]) return this.errorReply('Item ' + target + ' not found.');
let item = Shop[toId(target)];
if (item.price > Db.money.get(user.userid, 0)) return this.errorReply("You don't have you enough money for this. You need " + (item.price - Db.money.get(user.userid)) + currencyName((item.price - Db.money.get(user.userid))) + " more to buy this.");
Db.money.set(user.userid, Db.money.get(user.userid) - item.price);
logMoney(user.name + " has purchased " + item.name + " from the shop for " + item.price + " and " + user.name + " now has " + Db.money.get(user.userid) + currencyName(Db.money.get(user.userid)) + ".");
if (item.id === 'customsymbol') {
user.canCustomSymbol = true;
}
let msg = '**' + user.name + " has bought " + item.name + ".** for " + item.price + currencyName(item.price) + " and now has " + Db.money.get(user.userid) + currencyName(Db.money.get(user.userid)) + ".";
Rooms.rooms.get("staff").add('|c|~Shop Alert|' + msg);
Rooms.rooms.get("staff").update();
Users.users.forEach(function (user) {
if (user.group === '~' || user.group === '&') {
user.send('|pm|~Shop Alert|' + user.getIdentity() + '|' + msg);
}
});
user.sendTo(room, "|uhtmlchange|shop" + user.userid + "|<div style='max-height:300px'><table style='border:2px solid #000000; border-radius: 5px'><tr><th colspan='3' style='border: 2px solid #000000; border-radius: 5px'>Server Shop</th></tr><tr><td style='colspan: 3; border: 2px solid #000000; border-radius: 5px'><center>You have purchased a " + item.name + ". " + (item.id === 'customsymbol' ? "You may now use /customsymbol [symbol] to change your symbol." : "Upper staff have been notified of your purchase and will contact you shortly.") + "</center></td></tr><tr><td colspan='3' style='text-align:center'><button class='button' name='send' value='/shop reopen'>Return to Shop</button></td></tr></table>");
},
help: function (target, room, user, connection, cmd, message) {
let reply = '<b>Shop commands</b><br/>';
reply += '/shop - Load the shop screen.<br/>';
reply += '/shop buy [item] - Buy an item from the shop.<br/>';
if (user.can('roomowner')) {
reply += '<b>Administrative shop commands:</b><br/>';
reply += '/shop add [item name], [description], [price] - Adds a item to the shop.<br/>';
reply += '/shop remove [item] - removes a item from the shop.<br/>';
}
return this.sendReplyBox(reply);
},
reopen: '',
'': function (target, room, user, connection, cmd, message) {
if (cmd === 'reopen') return user.sendTo(room, '|uhtmlchange|Shop' + user.userid + '|' + shopDisplay());
return user.sendTo(room, '|uhtml|shop' + user.userid + '|' + shopDisplay());
},
},
customsymbol: function (target, room, user) {
let bannedSymbols = ['!', '|', '‽', '\u2030', '\u534D', '\u5350', '\u223C'];
for (let u in Config.groups) if (Config.groups[u].symbol) bannedSymbols.push(Config.groups[u].symbol);
if (!user.canCustomSymbol) return this.errorReply('You need to buy this item from the shop to use.');
if (!target || target.length > 1) return this.sendReply('/customsymbol [symbol] - changes your symbol (usergroup) to the specified symbol. The symbol can only be one character');
if (target.match(/([a-zA-Z ^0-9])/g) || bannedSymbols.indexOf(target) >= 0) {
return this.sendReply('Sorry, but you cannot change your symbol to this for safety/stability reasons.');
}
user.customSymbol = target;
user.updateIdentity();
user.canCustomSymbol = false;
this.sendReply('Your symbol is now ' + target + '. It will be saved until you log off for more than an hour, or the server restarts. You can remove it with /resetsymbol');
},
customsymbolhelp: ["/customsymbol [symbol] - Get a custom symbol."],
removesymbol: 'resetsymbol',
resetsymbol: function (target, room, user) {
if (!user.customSymbol) return this.errorReply("You don't have a custom symbol!");
delete user.customSymbol;
user.updateIdentity();
this.sendReply('Your symbol has been removed.');
},
resetsymbolhelp: ["/resetsymbol - Resets your custom symbol."],
moneylog: function (target, room, user, connection) {
if (!this.can('modlog')) return;
target = toId(target);
let numLines = 15;
let matching = true;
if (target.match(/\d/g) && !isNaN(target)) {
numLines = Number(target);
matching = false;
}
let topMsg = "Displaying the last " + numLines + " lines of transactions:\n";
let file = path.join(__dirname, '../logs/money.txt');
fs.exists(file, function (exists) {
if (!exists) return connection.popup("No transactions.");
fs.readFile(file, 'utf8', function (err, data) {
data = data.split('\n');
if (target && matching) {
data = data.filter(function (line) {
return line.toLowerCase().indexOf(target.toLowerCase()) >= 0;
});
}
connection.popup('|wide|' + topMsg + data.slice(-(numLines + 1)).join('\n'));
});
});
},
moneyladder: 'richestuser',
richladder: 'richestuser',
richestusers: 'richestuser',
richestuser: function (target, room, user) {
if (!this.runBroadcast()) return;
let display = '<center><u><b>Richest Users</b></u></center><br><table border="1" cellspacing="0" cellpadding="5" width="100%"><tbody><tr><th>Rank</th><th>Username</th><th>Money</th></tr>';
let keys = Db.money.keys().map(function (name) {
return {name: name, money: Db.money.get(name)};
});
if (!keys.length) return this.sendReplyBox("Money ladder is empty.");
keys.sort(function (a, b) {
return b.money - a.money;
});
keys.slice(0, 10).forEach(function (user, index) {
display += "<tr><td>" + (index + 1) + "</td><td>" + user.name + "</td><td>" + user.money + "</td></tr>";
});
display += "</tbody></table>";
this.sendReply("|raw|" + display);
},
startdice: 'dicegame',
dicegame: function (target, room, user) {
if (room.id === 'lobby') return this.errorReply("This command cannot be used in the Lobby.");
if (!user.can('broadcast', null, room) && room.id !== 'casino' && room.id !== 'coldfrontcasino') return this.errorReply("You must be ranked + or higher in this room to start a game of dice outside the Casino.");
if ((user.locked || room.isMuted(user)) && !user.can('bypassall')) return this.errorReply("You cannot use this command while unable to talk.");
if (room.dice) return this.errorReply("There is already a game of dice going on in this room.");
let amount = Number(target) || 1;
if (isNaN(target)) return this.errorReply('"' + target + '" isn\'t a valid number.');
if (target.includes('.') || amount < 1 || amount > 5000) return this.sendReply('The number of bucks must be between 1 and 5,000 and cannot contain a decimal.');
if (Db.money.get(user.userid, 0) < amount) return this.sendReply("You don't have " + amount + " " + currencyName(amount) + ".");
room.dice = new Dice(room, amount, user.name);
this.parse("/joindice");
},
startdicehelp: ["/startdice or /dicegame [bet] - Start a dice game to gamble for money."],
dicejoin: 'joindice',
joindice: function (target, room, user) {
if (room.id === 'lobby') return this.errorReply("This command cannot be used in the Lobby.");
if ((user.locked || room.isMuted(user)) && !user.can('bypassall')) return this.sendReply("You cannot use this command while unable to talk.");
if (!room.dice) return this.errorReply('There is no game of dice going on in this room.');
room.dice.join(user, this);
},
joindicehelp: ["/joindice or /dicejoin - Joins ongoing dice game in the room."],
diceleave: 'leavedice',
leavedice: function (target, room, user) {
if (room.id === 'lobby') return this.errorReply("This command cannot be used in the Lobby.");
if (!room.dice) return this.errorReply('There is no game of dice going on in this room.');
room.dice.leave(user, this);
},
leavedicehelp: ["/leavedice or /diceleave - Leaves currently joined dice game in the room."],
diceend: 'enddice',
enddice: function (target, room, user) {
if (room.id === 'lobby') return this.errorReply("This command cannot be used in the Lobby.");
if ((user.locked || room.isMuted(user)) && !user.can('bypassall')) return this.sendReply("You cannot use this command while unable to talk.");
if (!room.dice) return this.errorReply('There is no game of dice going on in this room.');
if (!user.can('broadcast', null, room) && !room.dice.players.includes(user)) return this.errorReply("You must be ranked + or higher in this room to end a game of dice.");
room.dice.end(user);
},
enddicehelp: ["/enddice or /diceend - Ends ongoing dice game in the room."],
bucks: 'economystats',
economystats: function (target, room, user) {
if (!this.runBroadcast()) return;
const users = Db.money.keys();
const total = users.reduce(function (acc, cur) {
return acc + Db.money.get(cur);
}, 0);
let average = Math.floor(total / users.length) || '0';
let output = "There " + (total > 1 ? "are " : "is ") + total + currencyName(total) + " circulating in the economy. ";
output += "The average user has " + average + currencyName(average) + ".";
this.sendReplyBox(output);
},
};
|
var searchData=
[
['iter',['ITER',['../_list-_iterator_8h.html#a9fb89b8cc4bfcf19dd865dcc780f6af4',1,'List-Iterator.h']]]
];
|
// All code points in the `Tai_Tham` script as per Unicode v9.0.0:
[
0x1A20,
0x1A21,
0x1A22,
0x1A23,
0x1A24,
0x1A25,
0x1A26,
0x1A27,
0x1A28,
0x1A29,
0x1A2A,
0x1A2B,
0x1A2C,
0x1A2D,
0x1A2E,
0x1A2F,
0x1A30,
0x1A31,
0x1A32,
0x1A33,
0x1A34,
0x1A35,
0x1A36,
0x1A37,
0x1A38,
0x1A39,
0x1A3A,
0x1A3B,
0x1A3C,
0x1A3D,
0x1A3E,
0x1A3F,
0x1A40,
0x1A41,
0x1A42,
0x1A43,
0x1A44,
0x1A45,
0x1A46,
0x1A47,
0x1A48,
0x1A49,
0x1A4A,
0x1A4B,
0x1A4C,
0x1A4D,
0x1A4E,
0x1A4F,
0x1A50,
0x1A51,
0x1A52,
0x1A53,
0x1A54,
0x1A55,
0x1A56,
0x1A57,
0x1A58,
0x1A59,
0x1A5A,
0x1A5B,
0x1A5C,
0x1A5D,
0x1A5E,
0x1A60,
0x1A61,
0x1A62,
0x1A63,
0x1A64,
0x1A65,
0x1A66,
0x1A67,
0x1A68,
0x1A69,
0x1A6A,
0x1A6B,
0x1A6C,
0x1A6D,
0x1A6E,
0x1A6F,
0x1A70,
0x1A71,
0x1A72,
0x1A73,
0x1A74,
0x1A75,
0x1A76,
0x1A77,
0x1A78,
0x1A79,
0x1A7A,
0x1A7B,
0x1A7C,
0x1A7F,
0x1A80,
0x1A81,
0x1A82,
0x1A83,
0x1A84,
0x1A85,
0x1A86,
0x1A87,
0x1A88,
0x1A89,
0x1A90,
0x1A91,
0x1A92,
0x1A93,
0x1A94,
0x1A95,
0x1A96,
0x1A97,
0x1A98,
0x1A99,
0x1AA0,
0x1AA1,
0x1AA2,
0x1AA3,
0x1AA4,
0x1AA5,
0x1AA6,
0x1AA7,
0x1AA8,
0x1AA9,
0x1AAA,
0x1AAB,
0x1AAC,
0x1AAD
]; |
(function () {
'use strict';
angular
.module('app')
.factory('AuthenticationService', AuthenticationService);
AuthenticationService.$inject = ['$http', '$cookieStore', '$rootScope', '$timeout'];
function AuthenticationService($http, $cookieStore, $rootScope, $timeout) {
var service = {};
service.Login = Login;
service.SetCredentials = SetCredentials;
service.ClearCredentials = ClearCredentials;
return service;
function Login(email, password, callback) {
$http.post('/api/v0.1/login', { email: email, password: password })
.success(function (response) {
callback(response);
});
}
function SetCredentials(email, password) {
var authdata = Base64.encode(email + ':' + password);
$rootScope.globals = {
currentUser: {
email: email,
authdata: authdata
}
};
$http.defaults.headers.common['Authorization'] = 'Basic ' + authdata; // jshint ignore:line
$cookieStore.put('globals', $rootScope.globals);
}
function ClearCredentials() {
$rootScope.globals = {};
$cookieStore.remove('globals');
$http.defaults.headers.common.Authorization = 'Basic ';
}
}
// Base64 encoding service used by AuthenticationService
var Base64 = {
keyStr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
encode: function (input) {
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;
do {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this.keyStr.charAt(enc1) +
this.keyStr.charAt(enc2) +
this.keyStr.charAt(enc3) +
this.keyStr.charAt(enc4);
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return output;
},
decode: function (input) {
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;
// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
var base64test = /[^A-Za-z0-9\+\/\=]/g;
if (base64test.exec(input)) {
window.alert("There were invalid base64 characters in the input text.\n" +
"Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
"Expect errors in decoding.");
}
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
do {
enc1 = this.keyStr.indexOf(input.charAt(i++));
enc2 = this.keyStr.indexOf(input.charAt(i++));
enc3 = this.keyStr.indexOf(input.charAt(i++));
enc4 = this.keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return output;
}
};
})();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.