<commit_before>'use strict';

var swig = require('swig'),
    mongoose = require('mongoose'),
    container = require('dependable').container(),
    fs = require('fs'),
    path = require('path'),
    util = require('./util'),
    EventEmitter = require('events').EventEmitter;

var events = new EventEmitter(),
    Mean, modules = [],
    menus, config,
    allMenus = [],
    middleware = {
        before: {},
        after: {}
    },
    aggregated = {
        js: '',
        css: ''
    };

function Meanio() {
    if (this.active) return;
    Mean = this;
    this.events = events;
    this.version = require('../package').version;
}

Meanio.prototype.serve = function(options, callback) {

    if (this.active) return this;

    // Initializing system variables
    var defaultConfig = util.loadConfig();

    var database = mongoose.connect(defaultConfig.db || '', function(err) {
        if (err) {
            console.error('Error:', err.message);
            return console.error('**Could not connect to MongoDB. Please ensure mongod is running and restart MEAN app.**');
        }

        // Register database dependency
        Mean.register('database', {
            connection: database
        });

        Mean.config = new Config(function(err, config) {
            // Bootstrap Models, Dependencies, Routes and the app as an express app
            var app = require('./bootstrap')(options, database);

            // Start the app by listening on <port>, optional hostname
            app.listen(config.port, config.hostname);
            console.log('Mean app started on port ' + config.port + ' (' + process.env.NODE_ENV + ')');

            findModules(function() {
                enableModules();
            });
            aggregate('js', null);

            Mean.name = config.app.name;
            Mean.app = app;

            menus = new Mean.Menus();
            Mean.menus = menus;

            callback(app, config);
        });

        Mean.active = true;
        Mean.options = options;
    });
};

Meanio.prototype.loadConfig = util.loadConfig;

function Config(callback) {

    if (this.config) return this.config;

    loadSettings(this, callback);

    function update(settings, callback) {

        var Package = loadPackageModel();

        if (!Package) return callback(new Error('failed to load data model'));

        Package.findOneAndUpdate({
            name: 'config'
        }, {
            $set: {
                settings: settings,
                updated: new Date()
            }
        }, {
            upsert: true,
            multi: false
        }, function(err, doc) {
            if (err) {
                console.log(err);
                return callback(new Error('Failed to update settings'));
            }

            loadSettings(Mean.config);

            return callback(null, doc.settings);
        });
    }

    function loadSettings(Config, callback) {

        var Package = loadPackageModel();

        var defaultConfig = util.loadConfig();

        if (!Package) return defaultConfig;

        Package.findOne({
            name: 'config'
        }, function(err, doc) {

            var original = JSON.flatten(defaultConfig, {
                default: true
            });

            var saved = JSON.flatten(doc ? doc.settings : defaultConfig, {});

            var merged = mergeConfig(original, saved);

            var clean = JSON.unflatten(merged.clean, {});

            var diff = JSON.unflatten(merged.diff, {});

            Config.verbose = {
                clean: clean,
                diff: diff,
                flat: merged
            };

            Config.clean = clean;
            Config.diff = diff;
            Config.flat = merged;
            if (callback) callback(err, clean);
        });
    }

    function mergeConfig(original, saved) {

        var clean = {};

        for (var index in saved) {
            clean[index] = saved[index].value;
            if (original[index]) {
                original[index].value = saved[index].value;
            } else {
                original[index] = {
                    value: saved[index].value,
                };
            }

            original[index]['default'] = original[index]['default'] || saved[index]['default'];
        }

        return {
            diff: original,
            clean: clean
        };
    }

    function loadPackageModel() {

        var database = container.get('database');
        if (!database || !database.connection) {
            return null;
        }

        if (!database.connection.models.Package) {
            require('../modules/package')(database);
        }

        return database.connection.model('Package');
    }

    this.update = update;

}

Meanio.prototype.status = function() {
    return {
        active: this.active,
        name: this.name
    };
};

Meanio.prototype.register = container.register;

Meanio.prototype.resolve = container.resolve;

//confusing names, need to be refactored asap
Meanio.prototype.load = container.get;

Meanio.prototype.moduleEnabled = function(name) {
    return !!modules[name];
};

Meanio.prototype.modules = (function() {
    return modules;
})();

Meanio.prototype.aggregated = aggregated;

Meanio.prototype.Menus = function() {
    this.add = function(options) {
        if (!Array.isArray(options)) options = [options];

        options.forEach(function(opt) {
            opt.menu = opt.menu || 'main';
            opt.roles = opt.roles || ['anonymous'];
            allMenus[opt.menu] = allMenus[opt.menu] || [];
            allMenus[opt.menu].push(opt);
        });
        return menus;
    };

    this.get = function(options) {
        var allowed = [];
        options.menu = options.menu || 'main';
        options.roles = options.roles || ['anonymous'];

        if (!allMenus[options.menu] && !options.defaultMenu) return [];

        var items = options.defaultMenu.concat(allMenus[options.menu] || []);

        items.forEach(function(item) {

            var hasRole = false;
            options.roles.forEach(function(role) {
                if (role === 'admin' || item.roles.indexOf('anonymous') !== -1 || item.roles.indexOf(role) !== -1) {
                    hasRole = true;
                }
            });

            if (hasRole) {
                allowed.push(item);
            }
        });
        return allowed;
    };
};

Meanio.prototype.Module = function(name) {
    this.name = name;
    this.menus = menus;
    this.config = config;

    var nameCap = capitaliseFirstLetter(name);
    if (nameCap !== name) {
        modules[name] = modules[nameCap];
        delete modules[nameCap];
    }

    // bootstrap models
    util.walk(modulePath(this.name, 'server'), 'model', null, function(model) {
        require(model);
    });

    this.render = function(view, options, callback) {
        swig.renderFile(modulePath(this.name, '/server/views/' + view + '.html'), options, callback);
    };

    // bootstrap routes
    this.routes = function() {
        var args = Array.prototype.slice.call(arguments);
        var that = this;
        util.walk(modulePath(this.name, 'server'), 'route', 'middlewares', function(route) {
            require(route).apply(that, [that].concat(args));
        });
    };

    this.aggregateAsset = function(type, asset, options) {
        aggregate(type, (options && options.absolute ? asset : path.join(modules[this.name].source, this.name, 'public/assets', type, asset)), options);
    };

    this.register = function(callback) {
        container.register(name, callback);
    };

    this.angularDependencies = function(dependencies) {
        this.angularDependencies = dependencies;
        modules[this.name].angularDependencies = dependencies;
    };

    this.settings = function() {

        if (!arguments.length) return;

        var database = container.get('database');
        if (!database || !database.connection) {
            return {
                err: true,
                message: 'No database connection'
            };
        }

        if (!database.connection.models.Package) {
            require('../modules/package')(database);
        }

        var Package = database.connection.model('Package');
        if (arguments.length === 2) return updateSettings(this.name, arguments[0], arguments[1]);
        if (arguments.length === 1 && typeof arguments[0] === 'object') return updateSettings(this.name, arguments[0], function() {});
        if (arguments.length === 1 && typeof arguments[0] === 'function') return getSettings(this.name, arguments[0]);

        function updateSettings(name, settings, callback) {
            Package.findOneAndUpdate({
                name: name
            }, {
                $set: {
                    settings: settings,
                    updated: new Date()
                }
            }, {
                upsert: true,
                multi: false
            }, function(err, doc) {
                if (err) {
                    console.log(err);
                    return callback(new Error('Failed to update settings'));
                }
                return callback(null, doc);
            });
        }

        function getSettings(name, callback) {
            Package.findOne({
                name: name
            }, function(err, doc) {
                if (err) {
                    console.log(err);
                    return callback(new Error('Failed to retrieve settings'));
                }
                return callback(null, doc);
            });
        }
    };
};

function capitaliseFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

function modulePath(name, plus) {
    return path.join(process.cwd(), modules[name].source, name.toLowerCase(), plus);
}

function findModules(callback) {

    function searchSource(source, callback) {
        fs.readdir(path.join(process.cwd(), source), function(err, files) {
            if (err || !files || !files.length) {
                if (err && err.code !== 'ENOENT') console.log(err);
                return callback();
            }
            files.forEach(function(file, index) {
                fs.readFile(path.join(process.cwd(), source, file, 'package.json'), function(fileErr, data) {
                    if (err) throw fileErr;
                    if (data) {
                        try {
                            var json = JSON.parse(data.toString());
                            if (json.mean) {
                                modules[capitaliseFirstLetter(json.name)] = {
                                    version: json.version,
                                    source: source
                                };
                            }
                        } catch (err) {
                            return callback();
                        }
                    }
                    if (files.length - 1 === index) return callback();
                });
            });
        });
    }

    var sources = 2;

    function searchDone() {
        sources--;
        if (!sources) {
            events.emit('modulesFound');
            callback();
        }
    }
    searchSource('node_modules', searchDone);
    searchSource('packages', searchDone);
}

function enableModules(callback) {
    var name, remaining = 0;

    for (name in modules) {
        remaining++;
        require(modulePath(name, 'app.js'));
    }

    for (name in modules) {
        name = name;
        container.resolve.apply(container, [name]);
        container.get(name);
        remaining--;
        if (!remaining) {
            events.emit('modulesEnabled');
            if (callback) callback(modules);
        }
    }
}

//will do compression and mingify/uglify soon
function aggregate(ext, aggPath, options) {
    options = options || {};

    //Allow libs
    var libs = true;
    if (aggPath) return readFile(ext, path.join(process.cwd(), aggPath));

    //this redoes all the aggregation for the extention type
    aggregated[ext] = '';

    //Deny Libs
    libs = false;
    events.on('modulesFound', function() {
        for (var name in modules) {
            readFiles(ext, path.join(process.cwd(), modules[name].source, name.toLowerCase(), 'public'));
        }
    });

    function readFiles(ext, filepath) {
        fs.readdir(filepath, function(err, files) {
            if (err) return;
            files.forEach(function(file) {
                if (!libs && file !== 'assets') {
                    readFile(ext, path.join(filepath, file));
                }
            });
        });
    }

    function readFile(ext, filepath) {
        fs.readdir(filepath, function(err, files) {
            if (files) return readFiles(ext, filepath);
            if (path.extname(filepath) !== '.' + ext) return;
            fs.readFile(filepath, function(fileErr, data) {
                //add some exists and refactor
                //if (fileErr) console.log(fileErr)

                if (!data) {
                    readFiles(ext, filepath);
                } else {
                    aggregated[ext] += (ext === 'js' && !options.global) ? ('(function(){' + data.toString() + '})();') : data.toString() + '\n';
                }
            });
        });
    }
}

Meanio.prototype.chainware = {

    add: function(event, weight, func) {
        middleware[event].splice(weight, 0, {
            weight: weight,
            func: func
        });
        middleware[event].join();
        middleware[event].sort(function(a, b) {
            if (a.weight < b.weight) {
                a.next = b.func;
            } else {
                b.next = a.func;
            }
            return (a.weight - b.weight);
        });
    },

    before: function(req, res, next) {
        if (!middleware.before.length) return next();
        this.chain('before', 0, req, res, next);
    },

    after: function(req, res, next) {
        if (!middleware.after.length) return next();
        this.chain('after', 0, req, res, next);
    },

    chain: function(operator, index, req, res, next) {
        var args = [req, res,
            function() {
                if (middleware[operator][index + 1]) {
                    this.chain('before', index + 1, req, res, next);
                } else {
                    next();
                }
            }
        ];

        middleware[operator][index].func.apply(this, args);
    }
};

module.exports = exports = new Meanio();
<commit_msg>not aggregate tests<commit_after>'use strict';

var swig = require('swig'),
    mongoose = require('mongoose'),
    container = require('dependable').container(),
    fs = require('fs'),
    path = require('path'),
    util = require('./util'),
    EventEmitter = require('events').EventEmitter;

var events = new EventEmitter(),
    Mean, modules = [],
    menus, config,
    allMenus = [],
    middleware = {
        before: {},
        after: {}
    },
    aggregated = {
        js: '',
        css: ''
    };

function Meanio() {
    if (this.active) return;
    Mean = this;
    this.events = events;
    this.version = require('../package').version;
}

Meanio.prototype.serve = function(options, callback) {

    if (this.active) return this;

    // Initializing system variables
    var defaultConfig = util.loadConfig();

    var database = mongoose.connect(defaultConfig.db || '', function(err) {
        if (err) {
            console.error('Error:', err.message);
            return console.error('**Could not connect to MongoDB. Please ensure mongod is running and restart MEAN app.**');
        }

        // Register database dependency
        Mean.register('database', {
            connection: database
        });

        Mean.config = new Config(function(err, config) {
            // Bootstrap Models, Dependencies, Routes and the app as an express app
            var app = require('./bootstrap')(options, database);

            // Start the app by listening on <port>, optional hostname
            app.listen(config.port, config.hostname);
            console.log('Mean app started on port ' + config.port + ' (' + process.env.NODE_ENV + ')');

            findModules(function() {
                enableModules();
            });
            aggregate('js', null);

            Mean.name = config.app.name;
            Mean.app = app;

            menus = new Mean.Menus();
            Mean.menus = menus;

            callback(app, config);
        });

        Mean.active = true;
        Mean.options = options;
    });
};

Meanio.prototype.loadConfig = util.loadConfig;

function Config(callback) {

    if (this.config) return this.config;

    loadSettings(this, callback);

    function update(settings, callback) {

        var Package = loadPackageModel();

        if (!Package) return callback(new Error('failed to load data model'));

        Package.findOneAndUpdate({
            name: 'config'
        }, {
            $set: {
                settings: settings,
                updated: new Date()
            }
        }, {
            upsert: true,
            multi: false
        }, function(err, doc) {
            if (err) {
                console.log(err);
                return callback(new Error('Failed to update settings'));
            }

            loadSettings(Mean.config);

            return callback(null, doc.settings);
        });
    }

    function loadSettings(Config, callback) {

        var Package = loadPackageModel();

        var defaultConfig = util.loadConfig();

        if (!Package) return defaultConfig;

        Package.findOne({
            name: 'config'
        }, function(err, doc) {

            var original = JSON.flatten(defaultConfig, {
                default: true
            });

            var saved = JSON.flatten(doc ? doc.settings : defaultConfig, {});

            var merged = mergeConfig(original, saved);

            var clean = JSON.unflatten(merged.clean, {});

            var diff = JSON.unflatten(merged.diff, {});

            Config.verbose = {
                clean: clean,
                diff: diff,
                flat: merged
            };

            Config.clean = clean;
            Config.diff = diff;
            Config.flat = merged;
            if (callback) callback(err, clean);
        });
    }

    function mergeConfig(original, saved) {

        var clean = {};

        for (var index in saved) {
            clean[index] = saved[index].value;
            if (original[index]) {
                original[index].value = saved[index].value;
            } else {
                original[index] = {
                    value: saved[index].value,
                };
            }

            original[index]['default'] = original[index]['default'] || saved[index]['default'];
        }

        return {
            diff: original,
            clean: clean
        };
    }

    function loadPackageModel() {

        var database = container.get('database');
        if (!database || !database.connection) {
            return null;
        }

        if (!database.connection.models.Package) {
            require('../modules/package')(database);
        }

        return database.connection.model('Package');
    }

    this.update = update;

}

Meanio.prototype.status = function() {
    return {
        active: this.active,
        name: this.name
    };
};

Meanio.prototype.register = container.register;

Meanio.prototype.resolve = container.resolve;

//confusing names, need to be refactored asap
Meanio.prototype.load = container.get;

Meanio.prototype.moduleEnabled = function(name) {
    return !!modules[name];
};

Meanio.prototype.modules = (function() {
    return modules;
})();

Meanio.prototype.aggregated = aggregated;

Meanio.prototype.Menus = function() {
    this.add = function(options) {
        if (!Array.isArray(options)) options = [options];

        options.forEach(function(opt) {
            opt.menu = opt.menu || 'main';
            opt.roles = opt.roles || ['anonymous'];
            allMenus[opt.menu] = allMenus[opt.menu] || [];
            allMenus[opt.menu].push(opt);
        });
        return menus;
    };

    this.get = function(options) {
        var allowed = [];
        options.menu = options.menu || 'main';
        options.roles = options.roles || ['anonymous'];

        if (!allMenus[options.menu] && !options.defaultMenu) return [];

        var items = options.defaultMenu.concat(allMenus[options.menu] || []);

        items.forEach(function(item) {

            var hasRole = false;
            options.roles.forEach(function(role) {
                if (role === 'admin' || item.roles.indexOf('anonymous') !== -1 || item.roles.indexOf(role) !== -1) {
                    hasRole = true;
                }
            });

            if (hasRole) {
                allowed.push(item);
            }
        });
        return allowed;
    };
};

Meanio.prototype.Module = function(name) {
    this.name = name;
    this.menus = menus;
    this.config = config;

    var nameCap = capitaliseFirstLetter(name);
    if (nameCap !== name) {
        modules[name] = modules[nameCap];
        delete modules[nameCap];
    }

    // bootstrap models
    util.walk(modulePath(this.name, 'server'), 'model', null, function(model) {
        require(model);
    });

    this.render = function(view, options, callback) {
        swig.renderFile(modulePath(this.name, '/server/views/' + view + '.html'), options, callback);
    };

    // bootstrap routes
    this.routes = function() {
        var args = Array.prototype.slice.call(arguments);
        var that = this;
        util.walk(modulePath(this.name, 'server'), 'route', 'middlewares', function(route) {
            require(route).apply(that, [that].concat(args));
        });
    };

    this.aggregateAsset = function(type, asset, options) {
        aggregate(type, (options && options.absolute ? asset : path.join(modules[this.name].source, this.name, 'public/assets', type, asset)), options);
    };

    this.register = function(callback) {
        container.register(name, callback);
    };

    this.angularDependencies = function(dependencies) {
        this.angularDependencies = dependencies;
        modules[this.name].angularDependencies = dependencies;
    };

    this.settings = function() {

        if (!arguments.length) return;

        var database = container.get('database');
        if (!database || !database.connection) {
            return {
                err: true,
                message: 'No database connection'
            };
        }

        if (!database.connection.models.Package) {
            require('../modules/package')(database);
        }

        var Package = database.connection.model('Package');
        if (arguments.length === 2) return updateSettings(this.name, arguments[0], arguments[1]);
        if (arguments.length === 1 && typeof arguments[0] === 'object') return updateSettings(this.name, arguments[0], function() {});
        if (arguments.length === 1 && typeof arguments[0] === 'function') return getSettings(this.name, arguments[0]);

        function updateSettings(name, settings, callback) {
            Package.findOneAndUpdate({
                name: name
            }, {
                $set: {
                    settings: settings,
                    updated: new Date()
                }
            }, {
                upsert: true,
                multi: false
            }, function(err, doc) {
                if (err) {
                    console.log(err);
                    return callback(new Error('Failed to update settings'));
                }
                return callback(null, doc);
            });
        }

        function getSettings(name, callback) {
            Package.findOne({
                name: name
            }, function(err, doc) {
                if (err) {
                    console.log(err);
                    return callback(new Error('Failed to retrieve settings'));
                }
                return callback(null, doc);
            });
        }
    };
};

function capitaliseFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

function modulePath(name, plus) {
    return path.join(process.cwd(), modules[name].source, name.toLowerCase(), plus);
}

function findModules(callback) {

    function searchSource(source, callback) {
        fs.readdir(path.join(process.cwd(), source), function(err, files) {
            if (err || !files || !files.length) {
                if (err && err.code !== 'ENOENT') console.log(err);
                return callback();
            }
            files.forEach(function(file, index) {
                fs.readFile(path.join(process.cwd(), source, file, 'package.json'), function(fileErr, data) {
                    if (err) throw fileErr;
                    if (data) {
                        try {
                            var json = JSON.parse(data.toString());
                            if (json.mean) {
                                modules[capitaliseFirstLetter(json.name)] = {
                                    version: json.version,
                                    source: source
                                };
                            }
                        } catch (err) {
                            return callback();
                        }
                    }
                    if (files.length - 1 === index) return callback();
                });
            });
        });
    }

    var sources = 2;

    function searchDone() {
        sources--;
        if (!sources) {
            events.emit('modulesFound');
            callback();
        }
    }
    searchSource('node_modules', searchDone);
    searchSource('packages', searchDone);
}

function enableModules(callback) {
    var name, remaining = 0;

    for (name in modules) {
        remaining++;
        require(modulePath(name, 'app.js'));
    }

    for (name in modules) {
        name = name;
        container.resolve.apply(container, [name]);
        container.get(name);
        remaining--;
        if (!remaining) {
            events.emit('modulesEnabled');
            if (callback) callback(modules);
        }
    }
}

//will do compression and mingify/uglify soon
function aggregate(ext, aggPath, options) {
    options = options || {};

    //Allow libs
    var libs = true;
    if (aggPath) return readFile(ext, path.join(process.cwd(), aggPath));

    //this redoes all the aggregation for the extention type
    aggregated[ext] = '';

    //Deny Libs
    libs = false;
    events.on('modulesFound', function() {
        for (var name in modules) {
            readFiles(ext, path.join(process.cwd(), modules[name].source, name.toLowerCase(), 'public'));
        }
    });

    function readFiles(ext, filepath) {
        fs.readdir(filepath, function(err, files) {
            if (err) return;
            files.forEach(function(file) {
                if (!libs && (file !== 'assets' && file !== 'tests')) {
                    readFile(ext, path.join(filepath, file));
                }
            });
        });
    }

    function readFile(ext, filepath) {
        fs.readdir(filepath, function(err, files) {
            if (files) return readFiles(ext, filepath);
            if (path.extname(filepath) !== '.' + ext) return;
            fs.readFile(filepath, function(fileErr, data) {
                //add some exists and refactor
                //if (fileErr) console.log(fileErr)

                if (!data) {
                    readFiles(ext, filepath);
                } else {
                    aggregated[ext] += (ext === 'js' && !options.global) ? ('(function(){' + data.toString() + '})();') : data.toString() + '\n';
                }
            });
        });
    }
}

Meanio.prototype.chainware = {

    add: function(event, weight, func) {
        middleware[event].splice(weight, 0, {
            weight: weight,
            func: func
        });
        middleware[event].join();
        middleware[event].sort(function(a, b) {
            if (a.weight < b.weight) {
                a.next = b.func;
            } else {
                b.next = a.func;
            }
            return (a.weight - b.weight);
        });
    },

    before: function(req, res, next) {
        if (!middleware.before.length) return next();
        this.chain('before', 0, req, res, next);
    },

    after: function(req, res, next) {
        if (!middleware.after.length) return next();
        this.chain('after', 0, req, res, next);
    },

    chain: function(operator, index, req, res, next) {
        var args = [req, res,
            function() {
                if (middleware[operator][index + 1]) {
                    this.chain('before', index + 1, req, res, next);
                } else {
                    next();
                }
            }
        ];

        middleware[operator][index].func.apply(this, args);
    }
};

module.exports = exports = new Meanio();
<|endoftext|>


<commit_before>import React from 'react';
// import logo from './logo.svg';
import './App.css';

var _ = require('lodash');

var TodoList = React.createClass({
  render: function() {
    var createItem = function(item) {
      return
{item.text}
;
    };
    return
{this.props.experiments.map(createItem)}
;
  }
});

var TodoApp = React.createClass({
  getInitialState: function() {
    return {experiments: [], text: ''};
  },
  onChange: function(e) {
    this.setState({text: e.target.value});
  },
  handleSubmit: function(e) {
    e.preventDefault();
    var nextexperiments = this.state.experiments.concat([{text: this.state.text, id: Date.now()}]);
    var nextText = '';
    this.setState({experiments: nextexperiments, text: nextText});
  },
  render: function() {
    return (

TODO

        <TodoList experiments={this.state.experiments} />
        <form onSubmit={this.handleSubmit}>
          <input onChange={this.onChange} value={this.state.text} />
          <button>{'Add #' + (this.state.experiments.length + 1)}</button>
        </form>

{this.computeStuff()}

    );
  },
  computeStuff: function() {
    var options = ["hi", "yo", "sup"];
    for (var i = 0; i < this.state.experiments.length; i++) {
      var experiment = this.state.experiments[i];
      console.log(experiment);
      options = _.difference(options, [experiment.text]);
    }
    return options;
  }
});

export default TodoApp;
<commit_msg>broken commit<commit_after>import React from 'react';
// import logo from './logo.svg';
import './App.css';

// var _ = require('lodash');

var Fact = React.createClass({
  render: function() {
    return
{this.props.item.text}

  }
})

var TodoList = React.createClass({
  getInitialState: function() {
    return {facts: []}
  },
  addFact: function(fact) {
    this.setState({facts: this.state.facts.concat([fact])});
  },
  render: function() {
    var createItem = function(item) {
      return item;
    };
    return
{this.state.facts}
;
  }
});

var TodoApp = React.createClass({
  getInitialState: function() {
    // var foo = React.createElement(TodoList);
    // console.log(foo);
    // foo.addFact(null);
    return {factlist: React.createElement(TodoList), text: ''};
  },
  onChange: function(e) {
    this.setState({text: e.target.value});
  },
  handleSubmit: function(e) {
    e.preventDefault();
    console.log(this.state.factlist);
    var nextfacts = this.state.factlist.addFact(React.createElement(Fact, {text: this.state.text, id: Date.now()}));
    var nextText = '';
    this.setState({factlist: nextfacts, text: nextText});
  },
  render: function() {
    return (

TODO

        {this.state.factlist}
        <form onSubmit={this.handleSubmit}>
          <input onChange={this.onChange} value={this.state.text} />
          <button>{'Add #' + (100)}</button>
        </form>

{this.computeStuff()}

    );
  },
  computeStuff: function() {
    // var options = ["hi", "yo", "sup"];
    // for (var i = 0; i < this.state.facts.length; i++) {
    //   var fact = this.state.facts[i];
    //   console.log(fact);
    //   options = _.difference(options, [fact.text]);
    // }
    // return options;
    return 3;
  }
});

export default TodoApp;
<|endoftext|>


<commit_before>import React from 'react';
// import logo from './logo.svg';
import './App.css';

// var _ = require('lodash');

var Fact = React.createClass({
  render: function() {
    return

      {this.props.index}: {this.props.item.text}
      <button onClick={this.props.deleteFact} value={this.props.index}>Delete</button>

  }
});

var TodoList = React.createClass({
  render: function() {
    return
{this.props.items.map((fact, factIndex) => <Fact key={factIndex} item={fact} index={factIndex} deleteFact={this.props.deleteFact}/>)}
;
  }
});

var TodoApp = React.createClass({
  getInitialState: function() {
    return {factlist: [], text: ''};
  },
  onChange: function(e) {
    this.setState({text: e.target.value});
  },
  handleSubmit: function(e) {
    e.preventDefault();
    this.setState({factlist: this.state.factlist.concat([{text: this.state.text, id: Date.now()}]), text: ""});
  },
  render: function() {
    return (

TODO

        <TodoList items={this.state.factlist} deleteFact={this.deleteFact}/>
        <form onSubmit={this.handleSubmit}>
          <input onChange={this.onChange} value={this.state.text} />
          <button>{'Add #' + (100)}</button>
        </form>

{this.computeStuff()}

    );
  },
  deleteFact: function(e) {
    this.state.factlist.splice(e.target.value, 1);
    this.setState({factlist: this.state.factlist, text: this.state.text});
  },
  computeStuff: function() {
    // var options = ["hi", "yo", "sup"];
    // for (var i = 0; i < this.state.facts.length; i++) {
    //   var fact = this.state.facts[i];
    //   console.log(fact);
    //   options = _.difference(options, [fact.text]);
    // }
    // return options;
    return 3;
  }
});

export default TodoApp;
<commit_msg>Adds mix(), check(), and unit tests<commit_after>import React from 'react';
// import logo from './logo.svg';
import './App.css';

import _ from 'lodash'

import $ from 'jquery'

var Fact = React.createClass({
  render: function() {
    return

      {this.props.index}: {this.props.item.text}
      <button onClick={this.props.deleteFact} value={this.props.index}>Delete</button>

  }
});

var TodoList = React.createClass({
  render: function() {
    return
{this.props.items.map((fact, factIndex) => <Fact key={factIndex} item={fact} index={factIndex} deleteFact={this.props.deleteFact}/>)}
;
  }
});

var TodoApp = React.createClass({
  getInitialState: function() {
    return {factlist: [], text: ''};
  },
  onChange: function(e) {
    this.setState({text: e.target.value});
  },
  handleSubmit: function(e) {
    e.preventDefault();
    this.setState({factlist: this.state.factlist.concat([{text: this.state.text, id: Date.now()}]), text: ""});
  },
  render: function() {
    return (

TODO

        <TodoList items={this.state.factlist} deleteFact={this.deleteFact}/>
        <form onSubmit={this.handleSubmit}>
          <input onChange={this.onChange} value={this.state.text} />
          <button>{'Add #' + (100)}</button>
        </form>

{this.computeStuff()}

    );
  },
  deleteFact: function(e) {
    this.state.factlist.splice(e.target.value, 1);
    this.setState({factlist: this.state.factlist, text: this.state.text});
  },
  computeStuff: function() {
    // var options = ["hi", "yo", "sup"];
    // for (var i = 0; i < this.state.facts.length; i++) {
    //   var fact = this.state.facts[i];
    //   console.log(fact);
    //   options = _.difference(options, [fact.text]);
    // }
    // return options;
    return 3;
  }
});

var ColorMapping = {
  0: "red",
  1: "green",
  2: "blue",
};

// var SignMapping = {
//   -1: "minus",
//   0: "neutral",
//   1: "plus",
// };

// This is what an Alchemical looks like:
// [1, 1, -1]

// Here are all of the Alchemicals:
var alchemicals = [
  [-1, +1, -1],
  [+1, -1, +1],
  [+1, -1, -1],
  [-1, +1, +1],
  [-1, -1, +1],
  [+1, +1, -1],
  [-1, -1, -1],
  [+1, +1, +1],
]

// Alchemical -> Alchemical -> Potion
function mix(alchemicalA, alchemicalB) {
  var mean = _.zipWith(alchemicalA, alchemicalB, function(a,b){return (a+b)/2})
  for (var index = 0; index < 3; index++) {
    if (mean[(index+1) % 3] !== 0)
      mean[index] = 0
  }

  return mean
}

function check(world, fact) {
  var alchemicalA = world[fact.ingredients[0]]
  var alchemicalB = world[fact.ingredients[1]]
  var result = mix(alchemicalA, alchemicalB)
  console.log(result)
  console.log(fact.possibleResults)
  return fact.possibleResults.find(function(arr) {
    return _.isEqual(arr, result)
  }) != undefined
}

// ===== Unit tests =====

// Here is what a World looks like:
var exampleWorld = [
  [+1, -1, -1],
  [-1, +1, -1],
  [+1, -1, +1],
  [-1, +1, +1],
  [+1, +1, +1],
  [-1, -1, +1],
  [+1, +1, -1],
  [-1, -1, -1],
]

// This is what an Ingredient looks like:
var exampleIngredientA = 4
var exampleIngredientB = 5

// This is what a Potion looks like:
var examplePotionA = [0, 0, 1] // this is a blue+
var examplePotionB = [0, 0, 0] // this is soup

// This is what a Fact looks like:
// {
//   ingredients: [5, 7]
//   possibleResults: [0, 0, 1], [0, 1, 0]]
// }
// combining ingredient 5 and 7 make either a green+ or a blue+
var exampleFact = {
  ingredients: [exampleIngredientA, exampleIngredientB],
  possibleResults: [examplePotionA, examplePotionB]
}

console.log(check(exampleWorld, exampleFact))

export default TodoApp;
<|endoftext|>


<commit_before>/******** Project - Final *********************************
Authors: Eric Wooley, Tandra Felly, Lauryn Loudermilk
Description: Javascript automata engine.
**********************************************************/

function changeCursor(id){
	var elem = document.getElementById("main");
	switch(id)
	{
		case "draw":
			elem.style.cursor = "default";
			touch_layer.show();
			break;
		case "move":
			elem.style.cursor = "move";
			touch_layer.hide();
			break;
		case "remove":
			touch_layer.hide();
			elem.style.cursor = "not-allowed";
			break;
		case "rename":
			touch_layer.hide();
			elem.style.cursor = "text";
			rename();
			break;
		case "clear":
			clearscreen();
			getElementById("draw").
			break;
		default:
			alert("this button has no purpose");
	}
}

function move(){
	console.log("in the move function");
}

function remove(){
	var answer = confirm("Would you like to delete this object?")
    if (answer){
    	node.remove();
    	dfa_layer.draw();
    }
    else{
    	return;
    }
}

function rename(){

}

function clearscreen(){

	var answer = confirm("Are you sure you want to clear the screen?")
	if (answer){
       // This will remove the states and transition lines on the dfa layer
       dfa_layer.destroyChildren();
       // This will remove the labels on the transitions that are put on the tooltip layer
       tooltip_layer.destroyChildren();
<<<<<<< HEAD
       dfa_layer.draw();
       tooltip_layer.draw();
=======
       dfa_layer.draw()
       tooltip_layer.draw()
>>>>>>> 88b6388f7f0170aca15f4726894dbfebc09878fb
	}
	else{
        return;
	}
<<<<<<< HEAD
=======

>>>>>>> 88b6388f7f0170aca15f4726894dbfebc09878fb
}<commit_msg>okay really this time<commit_after>/******** Project - Final *********************************
Authors: Eric Wooley, Tandra Felly, Lauryn Loudermilk
Description: Javascript automata engine.
**********************************************************/

function changeCursor(id){
	var elem = document.getElementById("main");
	switch(id)
	{
		case "draw":
			elem.style.cursor = "default";
			touch_layer.show();
			break;
		case "move":
			elem.style.cursor = "move";
			touch_layer.hide();
			break;
		case "remove":
			touch_layer.hide();
			elem.style.cursor = "not-allowed";
			break;
		case "rename":
			touch_layer.hide();
			elem.style.cursor = "text";
			rename();
			break;
		case "clear":
			clearscreen();
			break;
		default:
			alert("this button has no purpose");
	}
}

function move(){
	console.log("in the move function");
}

function remove(){
	var answer = confirm("Would you like to delete this object?")
    if (answer){
    	node.remove();
    	dfa_layer.draw();
    }
    else{
    	return;
    }
}

function rename(){

}

function clearscreen(){
	var answer = confirm("Are you sure you want to clear the screen?")
	if (answer){
       // This will remove the states and transition lines on the dfa layer
       dfa_layer.destroyChildren();
       // This will remove the labels on the transitions that are put on the tooltip layer
       tooltip_layer.destroyChildren();
       dfa_layer.draw();
       tooltip_layer.draw();
	}
	else{
        return;
	}
}<|endoftext|>


<commit_before>/*jshint laxcomma: true, smarttabs: true, node: true*/
'use strict';
/**
 * Small lib for dealing with negotiation of mime types.
 * @module tastypie/lib/mime
 * @author Eric Satterwhite
 * @since 0.1.0
 * @requires accepts
 * @requires mime
 * @requires mout/array/intersection
 */

var accepts      = require( 'accepts' )
  , mime         = require( 'mime' )
  , intersection = require( 'mout/array/intersection' )
  , types        = require('mime/types')
  ;

const EMPTY_STRING = '';

class Mime extends mime.Mime {

	constructor(){
		super();
		this.default_type = null
		this.define( types )
	}

	lookup( format, fallback ){
		return super( format || EMPTY_STRING, fallback )
	}

	extension( ext ){
		return super( ext || EMPTY_STRING )
	}
	/**
	 * best guess determination of request mime type from Accept header
	 * @param {Request} request
	 * @param {String[]} types
	 * @return {String}
	 **/
	static determine( req, types ){

		types = Array.isArray( types ) && types.length ? types : null;

		var accept = accepts( req )
		  , allowed = types || accept.types()
		  ;

		return intersection( accept.types(), allowed )[0];
	}

	/**
	 * Returns a full mime type given a short hand version
	 * @param {String} type a content type to look up
	 * @return String
	 * @example mime.from( 'json' ) // application/json
	 **/
	static from( type ){
		return  type ? mime.lookup( type ) : null;
	}

/**
 * Shortcut to mime.define. Provides a way to define custom mime types
 **/
	static define( map ){
		return mime.define.call( mime, map );
	}
}

module.exports = new Mime();
module.exports.Mime = Mime;
<commit_msg>fixing super calls in mime class<commit_after>/*jshint laxcomma: true, smarttabs: true, node: true*/
'use strict';
/**
 * Small lib for dealing with negotiation of mime types.
 * @module tastypie/lib/mime
 * @author Eric Satterwhite
 * @since 0.1.0
 * @requires accepts
 * @requires mime
 * @requires mout/array/intersection
 */

var accepts      = require( 'accepts' )
  , mime         = require( 'mime' )
  , intersection = require( 'mout/array/intersection' )
  , types        = require('mime/types')
  ;

const EMPTY_STRING = '';

class Mime extends mime.Mime {

	constructor(){
		super();
		this.default_type = null;
		this.define( types );
	}

	lookup( format, fallback ){
		return super.lookup( format || EMPTY_STRING, fallback );
	}

	extension( ext ){
		return super.extension( ext || EMPTY_STRING );
	}
	/**
	 * best guess determination of request mime type from Accept header
	 * @param {Request} request
	 * @param {String[]} types
	 * @return {String}
	 **/
	static determine( req, types ){

		types = Array.isArray( types ) && types.length ? types : null;

		var accept = accepts( req )
		  , allowed = types || accept.types()
		  ;

		return intersection( accept.types(), allowed )[0];
	}

	/**
	 * Returns a full mime type given a short hand version
	 * @param {String} type a content type to look up
	 * @return String
	 * @example mime.from( 'json' ) // application/json
	 **/
	static from( type ){
		return  type ? mime.lookup( type ) : null;
	}

/**
 * Shortcut to mime.define. Provides a way to define custom mime types
 **/
	static define( map ){
		return mime.define.call( mime, map );
	}
}

module.exports = new Mime();
module.exports.Mime = Mime;
<|endoftext|>


<commit_before>/* -*- mode: espresso; espresso-indent-level: 2; indent-tabs-mode: nil -*- */
/* vim: set softtabstop=2 shiftwidth=2 tabstop=2 expandtab: */

/**
 * An action represents a command that may be run from a keyboard
 * shortcut or a button press.  These objects encapsulate:
 *   - The keys that are linked to that action
 *   - The help text associated with the action
 *   - The button IDs that can trigger the action
 *   - The tooltips for those buttons
 *   - The function that should be run to carry out the action
 */

function Action (properties) {

  var helpText = "[No help text set]";
  var buttonIDs = [];
  var keyShortcuts = {};

  /**
     Add a new key shortcut for this action.  'name' should be a
     string representation of the key, and keyCodes should be an
     array of keyCodes that correspond to that key on various
     browsers.  For example, you might call:
        action.addKey( "+", [107, 61, 187] );
  */
  this.addKey = function( name, keyCodes ) {
    if (keyShortcuts.hasOwnProperty(name)) {
      alert("BUG: reaplcing the keyCodes for "+name+" with Action.addKey");
    }
    keyShortcuts[name] = keyCodes;
  }

  this.getKeys = function( ) {
    return keyShortcuts;
  }

  this.getButtonIDs = function( ) {
    return buttonIDs;
  }

  this.getHelpText = function( ) {
    return helpText;
  }

  /**
     Add an array of button IDs, for example:
       action.addButtonIDs(['trace_button_togglelabels')
  */
  this.addButtonIDs = function( newButtonIDs ) {
    buttonIDs.push( newButtonIDs );
  }

  this.setHelpText = function( newHelpText ) {
    helpText = newHelpText;
  }

  this.setRun = function( newRun ) {
    this.run = newRun;
  }

  // -------------------------------------------------------------------

  for (key in properties) {
    if (properties.hasOwnProperty(key)) {
      if (key === 'helpText') {
	this.setHelpText(properties.helpText);
      }
      if (key === 'buttonIDs') {
	this.addButtonIDs(properties.buttonIDs);
      }
      if (key === 'keyShortcuts') {
	for (name in properties.keyShortcuts) {
	  if (properties.keyShortcuts.hasOwnProperty(name)) {
	    this.addKey(name, properties.keyShortcuts[name]);
	  }
	}
      }
      if (key === 'run') {
	this.setRun(properties.run);
      }
    }
  }
}

var getKeyCodeToActionMap = function( actionArray ) {
  var i, j, keyCodeToKeyAction = {}, action;
  var keyShortcuts, keyCodes, keyCode;
  for (i = 0; i < actionArray.length; ++i) {
    action = actionArray[i];
    keyShortcuts = action.getKeys();
    for (name in keyShortcuts) {
      if (keyShortcuts.hasOwnProperty(name)) {
	keyCodes = keyShortcuts[name];
	for( j = 0; j < keyCodes.length; ++j ) {
	  keyCode = keyCodes[j];
	  if (keyCodeToKeyAction[keyCode]) {
	    alert("BUG: overwriting action for keyCode " + keyCode + " (via '" + name + "')");
	  }
	  keyCodeToKeyAction[keyCode] = action;
	}
      }
    }
  }
  return keyCodeToKeyAction;
}

/** Updates the 'alt' and 'title' attributes on the toolbar
    icons that are documented with help text and key presses.
    Also bind the onClick action for the link that contains
    those icons to the corresponding function */

function setButtonClicksFromActions(actions) {
  var i, j, buttonIDs, buttonID;
  for (i = 0; i < actions.length; ++i) {
    action = actions[i];
    buttonIDs = action.getButtonIDs();
    for(j = 0; j < buttonIDs.length; ++j ) {
      buttonID = buttonIDs[j];
      var link = $('#' + buttonID);
      link.attr('href', 'foo');
      link.click(action.run);
      var img = link.find('img');
      img.attr('alt', action.getHelpText());
      var title = i + ': ' + action.getHelpText();
      img.attr('title', title);
    }
  }
}
<commit_msg>Correct a typo<commit_after>/* -*- mode: espresso; espresso-indent-level: 2; indent-tabs-mode: nil -*- */
/* vim: set softtabstop=2 shiftwidth=2 tabstop=2 expandtab: */

/**
 * An action represents a command that may be run from a keyboard
 * shortcut or a button press.  These objects encapsulate:
 *   - The keys that are linked to that action
 *   - The help text associated with the action
 *   - The button IDs that can trigger the action
 *   - The tooltips for those buttons
 *   - The function that should be run to carry out the action
 */

function Action (properties) {

  var helpText = "[No help text set]";
  var buttonIDs = [];
  var keyShortcuts = {};

  /**
     Add a new key shortcut for this action.  'name' should be a
     string representation of the key, and keyCodes should be an
     array of keyCodes that correspond to that key on various
     browsers.  For example, you might call:
        action.addKey( "+", [107, 61, 187] );
  */
  this.addKey = function( name, keyCodes ) {
    if (keyShortcuts.hasOwnProperty(name)) {
      alert("BUG: replacing the keyCodes for "+name+" with Action.addKey");
    }
    keyShortcuts[name] = keyCodes;
  }

  this.getKeys = function( ) {
    return keyShortcuts;
  }

  this.getButtonIDs = function( ) {
    return buttonIDs;
  }

  this.getHelpText = function( ) {
    return helpText;
  }

  /**
     Add an array of button IDs, for example:
       action.addButtonIDs(['trace_button_togglelabels')
  */
  this.addButtonIDs = function( newButtonIDs ) {
    buttonIDs.push( newButtonIDs );
  }

  this.setHelpText = function( newHelpText ) {
    helpText = newHelpText;
  }

  this.setRun = function( newRun ) {
    this.run = newRun;
  }

  // -------------------------------------------------------------------

  for (key in properties) {
    if (properties.hasOwnProperty(key)) {
      if (key === 'helpText') {
	this.setHelpText(properties.helpText);
      }
      if (key === 'buttonIDs') {
	this.addButtonIDs(properties.buttonIDs);
      }
      if (key === 'keyShortcuts') {
	for (name in properties.keyShortcuts) {
	  if (properties.keyShortcuts.hasOwnProperty(name)) {
	    this.addKey(name, properties.keyShortcuts[name]);
	  }
	}
      }
      if (key === 'run') {
	this.setRun(properties.run);
      }
    }
  }
}

var getKeyCodeToActionMap = function( actionArray ) {
  var i, j, keyCodeToKeyAction = {}, action;
  var keyShortcuts, keyCodes, keyCode;
  for (i = 0; i < actionArray.length; ++i) {
    action = actionArray[i];
    keyShortcuts = action.getKeys();
    for (name in keyShortcuts) {
      if (keyShortcuts.hasOwnProperty(name)) {
	keyCodes = keyShortcuts[name];
	for( j = 0; j < keyCodes.length; ++j ) {
	  keyCode = keyCodes[j];
	  if (keyCodeToKeyAction[keyCode]) {
	    alert("BUG: overwriting action for keyCode " + keyCode + " (via '" + name + "')");
	  }
	  keyCodeToKeyAction[keyCode] = action;
	}
      }
    }
  }
  return keyCodeToKeyAction;
}

/** Updates the 'alt' and 'title' attributes on the toolbar
    icons that are documented with help text and key presses.
    Also bind the onClick action for the link that contains
    those icons to the corresponding function */

function setButtonClicksFromActions(actions) {
  var i, j, buttonIDs, buttonID;
  for (i = 0; i < actions.length; ++i) {
    action = actions[i];
    buttonIDs = action.getButtonIDs();
    for(j = 0; j < buttonIDs.length; ++j ) {
      buttonID = buttonIDs[j];
      var link = $('#' + buttonID);
      link.attr('href', 'foo');
      link.click(action.run);
      var img = link.find('img');
      img.attr('alt', action.getHelpText());
      var title = i + ': ' + action.getHelpText();
      img.attr('title', title);
    }
  }
}
<|endoftext|>


<commit_before>
/*!
 * superagent
 * Copyright (c) 2010 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var EventEmitter = require('events').EventEmitter
  , parse = require('url').parse
  , http = require('http')
  , qs = require('qs');

/**
 * Expose the request function.
 */

exports = module.exports = request;

/**
 * Library version.
 */

exports.version = '0.0.1';

/**
 * Noop.
 */

var noop = function(){};

/**
 * Check if `obj` is an object.
 *
 * @param {Object} obj
 * @return {Boolean}
 * @api private
 */

function isObject(obj) {
  return '[object Object]' == toString.call(obj);
}

/**
 * Default MIME type map.
 *
 *     superagent.types.xml = 'application/xml';
 *
 */

exports.types = {
    html: 'text/html'
  , json: 'application/json'
  , urlencoded: 'application/x-www-form-urlencoded'
};

/**
 * Default serialization map.
 *
 *     superagent.serialize['application/xml'] = function(obj){
 *       return 'generated xml here';
 *     };
 *
 */

exports.serialize = {
    'application/x-www-form-urlencoded': qs.stringify
  , 'application/json': JSON.stringify
};

/**
 * Default parsers.
 *
 *     superagent.parse['application/xml'] = function(str){
 *       return { object parsed from str };
 *     };
 *
 */

exports.parse = {
    'application/x-www-form-urlencoded': qs.parse
  , 'application/json': JSON.parse
};

/**
 * Initialize a new `Response` with the given `xhr`.
 *
 *  - set flags (.ok, .error, etc)
 *  - parse header
 *
 * Examples:
 *
 *  Aliasing `superagent` as `request` is nice:
 *
 *      request = superagent;
 *
 *  We can use the promise-like API, or pass callbacks:
 *
 *      request.get('/').end(function(res){});
 *      request.get('/', function(res){});
 *
 *  Sending data can be chained:
 *
 *      request
 *        .post('/user')
 *        .data({ name: 'tj' })
 *        .end(function(res){});
 *
 *  Or passed to `.send()`:
 *
 *      request
 *        .post('/user')
 *        .send({ name: 'tj' }, function(res){});
 *
 *  Or passed to `.post()`:
 *
 *      request
 *        .post('/user', { name: 'tj' })
 *        .end(function(res){});
 *
 * Or further reduced to a single call for simple cases:
 *
 *      request
 *        .post('/user', { name: 'tj' }, function(res){});
 *
 * @param {ClientRequest} req
 * @param {IncomingMessage} res
 * @param {Object} options
 * @api private
 */

function Response(req, res, options) {
  options = options || {};
  this.req = req;
  this.res = res;
  this.text = res.text
  this.header = res.headers;
  this.setStatusProperties(res.statusCode);
  this.setHeaderProperties(this.header);
  this.body = this.parseBody(this.text);
}

/**
 * Set header related properties:
 *
 *   - `.contentType` the content type without params
 *
 * A response of "Content-Type: text/plain; charset=utf-8"
 * will provide you with a `.contentType` of "text/plain".
 *
 * @param {Object} header
 * @api private
 */

Response.prototype.setHeaderProperties = function(header){
  // TODO: moar!
  var params = (this.header['content-type'] || '').split(/ *; */);
  this.contentType = params.shift();
  this.setParams(params);
};

/**
 * Create properties from `params`.
 *
 * For example "Content-Type: text/plain; charset=utf-8"
 * would provide `.charset` "utf-8".
 *
 * @param {Array} params
 * @api private
 */

Response.prototype.setParams = function(params){
  var param;
  for (var i = 0, len = params.length; i < len; ++i) {
    param = params[i].split(/ *= */);
    this[param[0]] = param[1];
  }
};

/**
 * Parse the given body `str`.
 *
 * Used for auto-parsing of bodies. Parsers
 * are defined on the `superagent.parse` object.
 *
 * @param {String} str
 * @return {Mixed}
 * @api private
 */

Response.prototype.parseBody = function(str){
  var parse = exports.parse[this.contentType];
  return parse
    ? parse(str)
    : null;
};

/**
 * Set flags such as `.ok` based on `status`.
 *
 * For example a 2xx response will give you a `.ok` of __true__
 * whereas 5xx will be __false__ and `.error` will be __true__. The
 * `.clientError` and `.serverError` are also available to be more
 * specific, and `.statusType` is the class of error ranging from 1..5
 * sometimes useful for mapping respond colors etc.
 *
 * "sugar" properties are also defined for common cases. Currently providing:
 *
 *   - .noContent
 *   - .badRequest
 *   - .unauthorized
 *   - .notAcceptable
 *   - .notFound
 *
 * @param {Number} status
 * @api private
 */

Response.prototype.setStatusProperties = function(status){
  var type = status / 100 | 0;

  // status / class
  this.status = status;
  this.statusType = type;

  // basics
  this.info = 1 == type;
  this.ok = 2 == type;
  this.clientError = 4 == type;
  this.serverError = 5 == type;
  this.error = 4 == type || 5 == type;

  // sugar
  this.noContent = 204 == status;
  this.badRequest = 400 == status;
  this.unauthorized = 401 == status;
  this.notAcceptable = 406 == status;
  this.notFound = 404 == status;
};

/**
 * Expose `Response`.
 */

exports.Response = Response;

/**
 * Initialize a new `Request` with the given `method` and `url`.
 *
 * @param {String} method
 * @param {String} url
 * @api public
 */

function Request(method, url) {
  var self = this;
  EventEmitter.call(this);
  this.method = method;
  this.url = url;
  this.header = {};
  this.on('end', function(){
    self.callback(new Response(self.req, self.res));
  });
}

/**
 * Inherit from `EventEmitter.prototype`.
 */

Request.prototype = new EventEmitter;
Request.prototype.constructor = Request;

/**
 * Set header `field` to `val`.
 *
 * Examples:
 *
 *      req.get('/')
 *        .set('Accept', 'application/json')
 *        .set('X-API-Key', 'foobar')
 *        .end(callback);
 *
 * @param {String} field
 * @param {String} val
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.set = function(field, val){
  this.header[field.toLowerCase()] = val;
  return this;
};

/**
 * Set Content-Type to `type`, mapping values from `exports.types`.
 *
 * Examples:
 *
 *      superagent.types.xml = 'application/xml';
 *
 *      request.post('/')
 *        .type('xml')
 *        .data(xmlstring)
 *        .end(callback);
 *
 *      request.post('/')
 *        .type('application/xml')
 *        .data(xmlstring)
 *        .end(callback);
 *
 * @param {String} type
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.type = function(type){
  this.set('Content-Type', exports.types[type] || type);
  return this;
};

/**
 * Send `data`, defaulting the `.type()` to "json" when
 * an object is given.
 *
 * Examples:
 *
 *       // manual json
 *       request.post('/user')
 *         .type('json')
 *         .data('{"name":"tj"})
 *         .end(callback)
 *
 *       // auto json
 *       request.post('/user')
 *         .data({ name: 'tj' })
 *         .end(callback)
 *
 *       // manual x-www-form-urlencoded
 *       request.post('/user')
 *         .type('urlencoded')
 *         .data('name=tj')
 *         .end(callback)
 *
 *       // auto x-www-form-urlencoded
 *       request.post('/user')
 *         .type('urlencoded')
 *         .data({ name: 'tj' })
 *         .end(callback)
 *
 * @param {String|Object} data
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.data = function(data){
  var obj = isObject(data);

  // merge
  if (obj && isObject(this._data)) {
    for (var key in data) {
      this._data[key] = data[key];
    }
  } else {
    this._data = data;
  }

  if ('GET' == this.method) return this;
  if (!obj) return this;
  if (this.header['content-type']) return this;
  this.type('json');
  return this;
};

/**
 * Send `.data()` and `.end()` with optional callback `fn`.
 *
 * Examples:
 *
 *       // equivalent to .end()
 *       request.post('/user').send();
 *
 *       // equivalent to .data(user).end()
 *       request.post('/user').send(user);
 *
 *       // equivalent to .data(user).end(callback)
 *       request.post('/user').send(user, callback);
 *
 *       // equivalent to ..end(callback)
 *       request.post('/user').send(callback);
 *
 * @param {Object|String} data
 * @param {Function} fn
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.send = function(data, fn){
  if ('function' == typeof data) {
    this.end(data);
  } else if (data) {
    this.data(data).end(fn);
  } else {
    this.end();
  }
  return this;
};

/**
 * Initiate request, invoking callback `fn(res)`
 * with an instanceof `Response`.
 *
 * @param {Function} fn
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.end = function(fn){
  var self = this
    , options = {}
    , url = parse(this.url)
    , data = this._data || null
    , req;

  // store callback
  this.callback = fn || noop;

  // options
  options.method = this.method;
  options.port = url.port;
  options.path = url.pathname;
  options.host = url.hostname;

  // querystring
  if ('GET' == this.method && null != data) {
    options.path += '?' + qs.stringify(data);
    data = null;
  }

  // initiate request
  req = this.req = http.request(options);

  // body
  if ('GET' != this.method && 'HEAD' != this.method) {
    // serialize stuff
    var serialize = exports.serialize[this.header['content-type']];
    if (serialize) data = serialize(data);

    // content-length
    if (null != data && !this.header['content-length']) {
      this.set('Content-Length', data.length);
    }
  }

  // set header fields
  for (var field in this.header) {
    req.setHeader(field, this.header[field]);
  }

  // response
  req.on('response', function(res){
    self.res = res;
    res.text = '';
    res.on('data', function(chunk){ res.text += chunk; });
    res.on('end', function(){
      self.emit('end');
    });
  });

  req.end(data);
  return this;
};

/**
 * Expose `Request`.
 */

exports.Request = Request;

/**
 * Shortcut for `new Request(method, url)`.
 *
 * @param {String} method
 * @param {String} url
 * @return {Request}
 * @api public
 */

function request(method, url) {
  return new Request(method, url);
}

/**
 * GET `url` with optional callback `fn(res)`.
 *
 * @param {String} url
 * @param {Function} fn
 * @return {Request}
 * @api public
 */

request.get = function(url, fn){
  var req = request('GET', url);
  if (fn) req.end(fn);
  return req;
};

/**
 * DELETE `url` with optional callback `fn(res)`.
 *
 * @param {String} url
 * @param {Function} fn
 * @return {Request}
 * @api public
 */

request.del = function(url, fn){
  var req = request('DELETE', url);
  if (fn) req.end(fn);
  return req;
};

/**
 * POST `url` with optional `data` and callback `fn(res)`.
 *
 * @param {String} url
 * @param {Mixed} data
 * @param {Function} fn
 * @return {Request}
 * @api public
 */

request.post = function(url, data, fn){
  var req = request('POST', url);
  if (data) req.data(data);
  if (fn) req.end(fn);
  return req;
};

/**
 * PUT `url` with optional `data` and callback `fn(res)`.
 *
 * @param {String} url
 * @param {Mixed} data
 * @param {Function} fn
 * @return {Request}
 * @api public
 */

request.put = function(url, data, fn){
  var req = request('PUT', url);
  if (data) req.data(data);
  if (fn) req.end(fn);
  return req;
};
<commit_msg>ported previous change to node<commit_after>
/*!
 * superagent
 * Copyright (c) 2010 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var EventEmitter = require('events').EventEmitter
  , parse = require('url').parse
  , http = require('http')
  , qs = require('qs');

/**
 * Expose the request function.
 */

exports = module.exports = request;

/**
 * Library version.
 */

exports.version = '0.0.1';

/**
 * Noop.
 */

var noop = function(){};

/**
 * Check if `obj` is an object.
 *
 * @param {Object} obj
 * @return {Boolean}
 * @api private
 */

function isObject(obj) {
  return '[object Object]' == toString.call(obj);
}

/**
 * Default MIME type map.
 *
 *     superagent.types.xml = 'application/xml';
 *
 */

exports.types = {
    html: 'text/html'
  , json: 'application/json'
  , urlencoded: 'application/x-www-form-urlencoded'
};

/**
 * Default serialization map.
 *
 *     superagent.serialize['application/xml'] = function(obj){
 *       return 'generated xml here';
 *     };
 *
 */

exports.serialize = {
    'application/x-www-form-urlencoded': qs.stringify
  , 'application/json': JSON.stringify
};

/**
 * Default parsers.
 *
 *     superagent.parse['application/xml'] = function(str){
 *       return { object parsed from str };
 *     };
 *
 */

exports.parse = {
    'application/x-www-form-urlencoded': qs.parse
  , 'application/json': JSON.parse
};

/**
 * Initialize a new `Response` with the given `xhr`.
 *
 *  - set flags (.ok, .error, etc)
 *  - parse header
 *
 * Examples:
 *
 *  Aliasing `superagent` as `request` is nice:
 *
 *      request = superagent;
 *
 *  We can use the promise-like API, or pass callbacks:
 *
 *      request.get('/').end(function(res){});
 *      request.get('/', function(res){});
 *
 *  Sending data can be chained:
 *
 *      request
 *        .post('/user')
 *        .data({ name: 'tj' })
 *        .end(function(res){});
 *
 *  Or passed to `.send()`:
 *
 *      request
 *        .post('/user')
 *        .send({ name: 'tj' }, function(res){});
 *
 *  Or passed to `.post()`:
 *
 *      request
 *        .post('/user', { name: 'tj' })
 *        .end(function(res){});
 *
 * Or further reduced to a single call for simple cases:
 *
 *      request
 *        .post('/user', { name: 'tj' }, function(res){});
 *
 * @param {ClientRequest} req
 * @param {IncomingMessage} res
 * @param {Object} options
 * @api private
 */

function Response(req, res, options) {
  options = options || {};
  this.req = req;
  this.res = res;
  this.text = res.text
  this.header = res.headers;
  this.setStatusProperties(res.statusCode);
  this.setHeaderProperties(this.header);
  this.body = this.parseBody(this.text);
}

/**
 * Set header related properties:
 *
 *   - `.contentType` the content type without params
 *
 * A response of "Content-Type: text/plain; charset=utf-8"
 * will provide you with a `.contentType` of "text/plain".
 *
 * @param {Object} header
 * @api private
 */

Response.prototype.setHeaderProperties = function(header){
  // TODO: moar!
  var params = (this.header['content-type'] || '').split(/ *; */);
  this.contentType = params.shift();
  this.setParams(params);
};

/**
 * Create properties from `params`.
 *
 * For example "Content-Type: text/plain; charset=utf-8"
 * would provide `.charset` "utf-8".
 *
 * @param {Array} params
 * @api private
 */

Response.prototype.setParams = function(params){
  var param;
  for (var i = 0, len = params.length; i < len; ++i) {
    param = params[i].split(/ *= */);
    this[param[0]] = param[1];
  }
};

/**
 * Parse the given body `str`.
 *
 * Used for auto-parsing of bodies. Parsers
 * are defined on the `superagent.parse` object.
 *
 * @param {String} str
 * @return {Mixed}
 * @api private
 */

Response.prototype.parseBody = function(str){
  var parse = exports.parse[this.contentType];
  return parse
    ? parse(str)
    : null;
};

/**
 * Set flags such as `.ok` based on `status`.
 *
 * For example a 2xx response will give you a `.ok` of __true__
 * whereas 5xx will be __false__ and `.error` will be __true__. The
 * `.clientError` and `.serverError` are also available to be more
 * specific, and `.statusType` is the class of error ranging from 1..5
 * sometimes useful for mapping respond colors etc.
 *
 * "sugar" properties are also defined for common cases. Currently providing:
 *
 *   - .noContent
 *   - .badRequest
 *   - .unauthorized
 *   - .notAcceptable
 *   - .notFound
 *
 * @param {Number} status
 * @api private
 */

Response.prototype.setStatusProperties = function(status){
  var type = status / 100 | 0;

  // status / class
  this.status = status;
  this.statusType = type;

  // basics
  this.info = 1 == type;
  this.ok = 2 == type;
  this.clientError = 4 == type;
  this.serverError = 5 == type;
  this.error = 4 == type || 5 == type;

  // sugar
  this.noContent = 204 == status;
  this.badRequest = 400 == status;
  this.unauthorized = 401 == status;
  this.notAcceptable = 406 == status;
  this.notFound = 404 == status;
};

/**
 * Expose `Response`.
 */

exports.Response = Response;

/**
 * Initialize a new `Request` with the given `method` and `url`.
 *
 * @param {String} method
 * @param {String} url
 * @api public
 */

function Request(method, url) {
  var self = this;
  EventEmitter.call(this);
  this.method = method;
  this.url = url;
  this.header = {};
  this.on('end', function(){
    self.callback(new Response(self.req, self.res));
  });
}

/**
 * Inherit from `EventEmitter.prototype`.
 */

Request.prototype = new EventEmitter;
Request.prototype.constructor = Request;

/**
 * Set header `field` to `val`, or multiple fields with one object.
 *
 * Examples:
 *
 *      req.get('/')
 *        .set('Accept', 'application/json')
 *        .set('X-API-Key', 'foobar')
 *        .end(callback);
 *
 *      req.get('/')
 *        .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })
 *        .end(callback);
 *
 * @param {String|Object} field
 * @param {String} val
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.set = function(field, val){
  if (isObject(field)) {
    for (var key in field) {
      this.set(key, field[key]);
    }
    return this;
  }
  this.header[field.toLowerCase()] = val;
  return this;
};

/**
 * Set Content-Type to `type`, mapping values from `exports.types`.
 *
 * Examples:
 *
 *      superagent.types.xml = 'application/xml';
 *
 *      request.post('/')
 *        .type('xml')
 *        .data(xmlstring)
 *        .end(callback);
 *
 *      request.post('/')
 *        .type('application/xml')
 *        .data(xmlstring)
 *        .end(callback);
 *
 * @param {String} type
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.type = function(type){
  this.set('Content-Type', exports.types[type] || type);
  return this;
};

/**
 * Send `data`, defaulting the `.type()` to "json" when
 * an object is given.
 *
 * Examples:
 *
 *       // manual json
 *       request.post('/user')
 *         .type('json')
 *         .data('{"name":"tj"})
 *         .end(callback)
 *
 *       // auto json
 *       request.post('/user')
 *         .data({ name: 'tj' })
 *         .end(callback)
 *
 *       // manual x-www-form-urlencoded
 *       request.post('/user')
 *         .type('urlencoded')
 *         .data('name=tj')
 *         .end(callback)
 *
 *       // auto x-www-form-urlencoded
 *       request.post('/user')
 *         .type('urlencoded')
 *         .data({ name: 'tj' })
 *         .end(callback)
 *
 * @param {String|Object} data
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.data = function(data){
  var obj = isObject(data);

  // merge
  if (obj && isObject(this._data)) {
    for (var key in data) {
      this._data[key] = data[key];
    }
  } else {
    this._data = data;
  }

  if ('GET' == this.method) return this;
  if (!obj) return this;
  if (this.header['content-type']) return this;
  this.type('json');
  return this;
};

/**
 * Send `.data()` and `.end()` with optional callback `fn`.
 *
 * Examples:
 *
 *       // equivalent to .end()
 *       request.post('/user').send();
 *
 *       // equivalent to .data(user).end()
 *       request.post('/user').send(user);
 *
 *       // equivalent to .data(user).end(callback)
 *       request.post('/user').send(user, callback);
 *
 *       // equivalent to ..end(callback)
 *       request.post('/user').send(callback);
 *
 * @param {Object|String} data
 * @param {Function} fn
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.send = function(data, fn){
  if ('function' == typeof data) {
    this.end(data);
  } else if (data) {
    this.data(data).end(fn);
  } else {
    this.end();
  }
  return this;
};

/**
 * Initiate request, invoking callback `fn(res)`
 * with an instanceof `Response`.
 *
 * @param {Function} fn
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.end = function(fn){
  var self = this
    , options = {}
    , url = parse(this.url)
    , data = this._data || null
    , req;

  // store callback
  this.callback = fn || noop;

  // options
  options.method = this.method;
  options.port = url.port;
  options.path = url.pathname;
  options.host = url.hostname;

  // querystring
  if ('GET' == this.method && null != data) {
    options.path += '?' + qs.stringify(data);
    data = null;
  }

  // initiate request
  req = this.req = http.request(options);

  // body
  if ('GET' != this.method && 'HEAD' != this.method) {
    // serialize stuff
    var serialize = exports.serialize[this.header['content-type']];
    if (serialize) data = serialize(data);

    // content-length
    if (null != data && !this.header['content-length']) {
      this.set('Content-Length', data.length);
    }
  }

  // set header fields
  for (var field in this.header) {
    req.setHeader(field, this.header[field]);
  }

  // response
  req.on('response', function(res){
    self.res = res;
    res.text = '';
    res.on('data', function(chunk){ res.text += chunk; });
    res.on('end', function(){
      self.emit('end');
    });
  });

  req.end(data);
  return this;
};

/**
 * Expose `Request`.
 */

exports.Request = Request;

/**
 * Shortcut for `new Request(method, url)`.
 *
 * @param {String} method
 * @param {String} url
 * @return {Request}
 * @api public
 */

function request(method, url) {
  return new Request(method, url);
}

/**
 * GET `url` with optional callback `fn(res)`.
 *
 * @param {String} url
 * @param {Function} fn
 * @return {Request}
 * @api public
 */

request.get = function(url, fn){
  var req = request('GET', url);
  if (fn) req.end(fn);
  return req;
};

/**
 * DELETE `url` with optional callback `fn(res)`.
 *
 * @param {String} url
 * @param {Function} fn
 * @return {Request}
 * @api public
 */

request.del = function(url, fn){
  var req = request('DELETE', url);
  if (fn) req.end(fn);
  return req;
};

/**
 * POST `url` with optional `data` and callback `fn(res)`.
 *
 * @param {String} url
 * @param {Mixed} data
 * @param {Function} fn
 * @return {Request}
 * @api public
 */

request.post = function(url, data, fn){
  var req = request('POST', url);
  if (data) req.data(data);
  if (fn) req.end(fn);
  return req;
};

/**
 * PUT `url` with optional `data` and callback `fn(res)`.
 *
 * @param {String} url
 * @param {Mixed} data
 * @param {Function} fn
 * @return {Request}
 * @api public
 */

request.put = function(url, data, fn){
  var req = request('PUT', url);
  if (data) req.data(data);
  if (fn) req.end(fn);
  return req;
};
<|endoftext|>


<commit_before>/* -*- mode: espresso; espresso-indent-level: 2; indent-tabs-mode: nil -*- */
/* vim: set softtabstop=2 shiftwidth=2 tabstop=2 expandtab: */

/**
 * An action represents a command that may be run from a keyboard
 * shortcut or a button press.  These objects encapsulate:
 *   - The keys that are linked to that action
 *   - The help text associated with the action
 *   - The button IDs that can trigger the action
 *   - The tooltips for those buttons
 *   - The function that should be run to carry out the action
 */

function Action (properties) {

  var helpText = "[No help text set]";
  var buttonID = null;
  var buttonName = null;
  var keyShortcuts = {};

  /**
     Add a new key shortcut for this action.  'name' should be a
     string representation of the key, and keyCodes should be an
     array of keyCodes that correspond to that key on various
     browsers.  For example, you might call:
        action.addKey( "+", [107, 61, 187] );
  */
  this.addKey = function( name, keyCodes ) {
    if (keyShortcuts.hasOwnProperty(name)) {
      alert("BUG: replacing the keyCodes for "+name+" with Action.addKey");
    }
    keyShortcuts[name] = keyCodes;
  }

  this.hasButton = function( ) {
    return buttonID !== null;
  }

  this.getKeys = function( ) {
    return keyShortcuts;
  }

  this.getKeyShortcutsString = function( ) {
    result = [];
    for (var name in keyShortcuts) {
      if (keyShortcuts.hasOwnProperty(name)) {
        result.push(name);
      }
    }
    return result.join(', ');
  }

  this.getButtonID = function( ) {
    return buttonID;
  }

  this.getButtonName = function( ) {
    return buttonName;
  }

  this.getHelpText = function( ) {
    return helpText;
  }

  this.setButtonID = function( newButtonID ) {
    buttonID = newButtonID;
  }

  this.setButtonName = function( newButtonName ) {
    buttonName = newButtonName;
  }

  this.setHelpText = function( newHelpText ) {
    helpText = newHelpText;
  }

  this.setRun = function( newRun ) {
    this.run = newRun;
  }

  // -------------------------------------------------------------------

  for (key in properties) {
    if (properties.hasOwnProperty(key)) {
      if (key === 'helpText') {
	this.setHelpText(properties.helpText);
      }
      if (key === 'buttonID') {
	this.setButtonID(properties.buttonID);
      }
      if (key === 'buttonName') {
	this.setButtonName(properties.buttonName);
      }
      if (key === 'keyShortcuts') {
	for (name in properties.keyShortcuts) {
	  if (properties.keyShortcuts.hasOwnProperty(name)) {
	    this.addKey(name, properties.keyShortcuts[name]);
	  }
	}
      }
      if (key === 'run') {
	this.setRun(properties.run);
      }
    }
  }
}

var getKeyCodeToActionMap = function( actionArray ) {
  var i, j, keyCodeToKeyAction = {}, action;
  var keyShortcuts, keyCodes, keyCode;
  for (i = 0; i < actionArray.length; ++i) {
    action = actionArray[i];
    keyShortcuts = action.getKeys();
    for (name in keyShortcuts) {
      if (keyShortcuts.hasOwnProperty(name)) {
	keyCodes = keyShortcuts[name];
	for( j = 0; j < keyCodes.length; ++j ) {
	  keyCode = keyCodes[j];
	  if (keyCodeToKeyAction[keyCode]) {
	    alert("BUG: overwriting action for keyCode " + keyCode + " (via '" + name + "')");
	  }
	  keyCodeToKeyAction[keyCode] = action;
	}
      }
    }
  }
  return keyCodeToKeyAction;
}

/** Updates the 'alt' and 'title' attributes on the toolbar
    icons that are documented with help text and key presses.
    Also bind the onClick action for the link that contains
    those icons to the corresponding function */

function createButtonsFromActions(actions, boxID, iconPrefix) {
  var box, action, a, img, buttonID, title, shorcuts;
  box = $( '

' );
  for (i = 0; i < actions.length; ++i) {
    action = actions[i];
    if (action.hasButton()) {
      buttonID = action.getButtonID();
      a = document.createElement('a');
      a.setAttribute('class', 'button');
      a.setAttribute('id', action.getButtonID());
      a.onclick = action.run;
      img = document.createElement('img');
      img.setAttribute('src', 'widgets/themes/kde/' + iconPrefix + action.getButtonName() + '.png');
      img.setAttribute('alt', action.getHelpText());
      shortcuts = action.getKeyShortcutsString();
      if (shortcuts.length === 0) {
        title = action.getHelpText();
      } else {
        title = shortcuts + ': ' + action.getHelpText();
      }
      img.setAttribute('title', title);
      a.appendChild(img);
      box.append(a);
    }
  }
  return box;
}

// ---------------------------------------------------------------------

/* These actions are kept in separate arrays, since they need to be
 * added to different DIVs in the toolbar. */

var toolActions = [

	new Action({
		helpText: "Switch to the selector tool",
		buttonID: 'edit_button_select',
		buttonName: "select",
		run: function (e) {
			project.setTool( new Selector() );
			return true;
		}
	}),

	new Action({
		helpText: "Switch to the move tool",
		buttonID: 'edit_button_move',
		buttonName: "move",
		run: function (e) {
			project.setTool( new Navigator() );
			return true;
		}
	}),

	new Action({
		helpText: "Show keyboard shortcut help",
		buttonID: 'key_help_button',
		buttonName: "help",
		keyShortcuts: {
			'F1': [ 112 ]
		},
		run: function (e) {
			WindowMaker.show('keyboard-shortcuts');
			return true;
		}
	}),

  new Action({
    helpText: "Disclaimer",
    buttonID: "disclaimer_button",
    buttonName: 'disclaimer',
    run: function (e) {
      WindowMaker.show('disclaimer');
      return true;
    }
  })

];

var editToolActions = [

	new Action({
		helpText: "Text label tool",
		buttonID: 'edit_button_text',
		buttonName: 'text',
		run: function (e) {
			project.setTool( new TextlabelTool() );
			return true;
		}
	}),

	new Action({
		helpText: "Tagging tool",
		buttonID: 'edit_button_tags',
		buttonName: 'tags',
		run: function (e) {
			project.setTool( new TaggingTool() );
			return true;
		}
	}),

	new Action({
		helpText: "Crop tool",
		buttonID: 'edit_button_crop',
		buttonName: 'crop',
		run: function (e) {
			project.setTool( new CroppingTool() );
			return true;
		}
	}),

    new Action({
       helpText: "Canvas Tool",
       buttonID: 'edit_button_canvas',
       buttonName: 'canvas',
       keyShortcuts: {

       },
       run: function (e) {
         // check if zoom level 0 active
          if( project.focusedStack.s !== 0 ) {
            alert('Segmentation Tool only works on zoom-level 0!');
            return;
          }
          project.setTool( new CanvasTool() );
       }
    }),

  new Action({
     helpText: "Segmentation Tool",
     buttonID: 'edit_button_segmentation',
     buttonName: 'canvas',
     keyShortcuts: {

     },
     run: function (e) {
        // TODO: change to set zoom level for segmentation
        // check if zoom level 0 active
        if( project.focusedStack.s !== 0 ) {
          alert('Segmentation Tool only works on zoom-level 0!');
          return;
        }
        project.setTool( new SegmentationTool() );
     }
  }),

	new Action({
		helpText: "Tracing tool",
		buttonID: 'edit_button_trace',
		buttonName: 'trace',
		run: function (e) {
			project.setTool( new TracingTool() );
			return true;
		}
	})

/*
	new Action({
		helpText: "Profile tool",
		keyShortcuts: {
			'F': [ 70 ]
		},
		run: function (e) {
			project.setMode( 'profile' );
			return true;
		}
	})
*/
];

var segmentationWindowActions = [

  new Action({
    helpText: "Show segments table",
    buttonID: "segmentation_button_segments_table",
    buttonName: 'table_segments',
    run: function (e) {
      WindowMaker.show('segmentstable-widget');
      return true;
    }
  }),

  new Action({
    helpText: "Show 3D WebGL view",
    buttonID: "view_3d_webgl_button",
    buttonName: '3d-view-webgl',
    run: function (e) {
      WindowMaker.show('3d-webgl-view');
    }
  }),

  new Action({
    helpText: "Show object tree",
    buttonID: "data_button_tree",
    buttonName: 'tree',
    run: function (e) {
      WindowMaker.show('object-tree');
      return true;
    }
  }),

];

var tracingWindowActions = [

  new Action({
    helpText: "Show treenode table",
    buttonID: "data_button_table_treenode",
    buttonName: 'table',
    run: function (e) {
      WindowMaker.show('node-table');
      return true;
    }
  }),

  new Action({
    helpText: "Show connector table",
    buttonID: "data_button_table_connector",
    buttonName: 'table_connector',
    run: function (e) {
      WindowMaker.show( 'connector-table' );
      return true;
    }
  }),

  new Action({
      helpText: "Show log",
      buttonID: "data_button_table_log",
      buttonName: 'table_log',
      run: function (e) {
          WindowMaker.show( 'log-table' );
          return true;
      }
  }),

  new Action({
      helpText: "Review system",
      buttonID: "data_button_review",
      buttonName: 'table_review',
      run: function (e) {
          WindowMaker.show('review-system');
          return true;
      }
  }),

    new Action({
        helpText: "Connectivity widget",
        buttonID: "data_button_connectivit",
        buttonName: 'table_connectivity',
        run: function (e) {
            WindowMaker.show('connectivity-widget');
            return true;
        }
    }),

    new Action({
        helpText: "Adjacency Matrix widget",
        buttonID: "data_button_connectivity",
        buttonName: 'adj_matrix',
        run: function (e) {
            WindowMaker.show('adjacencymatrix-widget');
            return true;
        }
    }),

  new Action({
      helpText: "Export widget",
      buttonID: "data_button_export_widget",
      buttonName: 'export_widget',
      run: function (e) {
          WindowMaker.show('export-widget');
          return true;
      }
  }),

  new Action({
      helpText: "Graph widget",
      buttonID: "data_button_graph_widget",
      buttonName: 'graph_widget',
      run: function (e) {
          WindowMaker.show('graph-widget');
          return true;
      }
  }),

  new Action({
      helpText: "Segmentation Graph widget",
      buttonID: "data_button_segmentation_graph_widget",
      buttonName: 'graph_widget',
      run: function (e) {
          WindowMaker.show('cytograph-widget');
          return true;
      }
  }),

  new Action({
    helpText: "Show object tree",
    buttonID: "data_button_tree",
    buttonName: 'tree',
    run: function (e) {
      WindowMaker.show('object-tree');
      return true;
    }
  }),

  new Action({
    helpText: "Show search window",
    buttonID: "data_button_search",
    buttonName: 'search',
    keyShortcuts: {
      '/': [ 191, 47 ]
    },
    run: function (e) {
      WindowMaker.show('search');
      return true;
    }
  }),

  new Action({
    helpText: "Show project statistics",
    buttonID: "data_button_stats",
    buttonName: 'stats',
    run: function (e) {
      WindowMaker.show('statistics');
      return true;
    }
  })

/*
  new Action({
    helpText: "Show object tree as graph",
    buttonID: "view_objecttree_graph",
    buttonName: 'objecttree-graph',
    run: function (e) {
      window.open("apps/graph/index.html?project_id="+project.id+"&lower_skeleton_count=10", "Wiring diagram");
      return true;
    }
  })
  */
   ];

if ( !Detector.webgl ) {
  tracingWindowActions[tracingWindowActions.length] = new Action({
    helpText: "Show 3D canvas view",
    buttonID: "view_3d_button",
    buttonName: '3d-view',
    run: function (e) {
      WindowMaker.show('3d-view');
      return true;
    }
  });
} else {
  tracingWindowActions[tracingWindowActions.length] = new Action({
    helpText: "Show 3D WebGL view",
    buttonID: "view_3d_webgl_button",
    buttonName: '3d-view-webgl',
    run: function (e) {
      WindowMaker.show('3d-webgl-view');
    }
  });
}
<commit_msg>disable canvas tool<commit_after>/* -*- mode: espresso; espresso-indent-level: 2; indent-tabs-mode: nil -*- */
/* vim: set softtabstop=2 shiftwidth=2 tabstop=2 expandtab: */

/**
 * An action represents a command that may be run from a keyboard
 * shortcut or a button press.  These objects encapsulate:
 *   - The keys that are linked to that action
 *   - The help text associated with the action
 *   - The button IDs that can trigger the action
 *   - The tooltips for those buttons
 *   - The function that should be run to carry out the action
 */

function Action (properties) {

  var helpText = "[No help text set]";
  var buttonID = null;
  var buttonName = null;
  var keyShortcuts = {};

  /**
     Add a new key shortcut for this action.  'name' should be a
     string representation of the key, and keyCodes should be an
     array of keyCodes that correspond to that key on various
     browsers.  For example, you might call:
        action.addKey( "+", [107, 61, 187] );
  */
  this.addKey = function( name, keyCodes ) {
    if (keyShortcuts.hasOwnProperty(name)) {
      alert("BUG: replacing the keyCodes for "+name+" with Action.addKey");
    }
    keyShortcuts[name] = keyCodes;
  }

  this.hasButton = function( ) {
    return buttonID !== null;
  }

  this.getKeys = function( ) {
    return keyShortcuts;
  }

  this.getKeyShortcutsString = function( ) {
    result = [];
    for (var name in keyShortcuts) {
      if (keyShortcuts.hasOwnProperty(name)) {
        result.push(name);
      }
    }
    return result.join(', ');
  }

  this.getButtonID = function( ) {
    return buttonID;
  }

  this.getButtonName = function( ) {
    return buttonName;
  }

  this.getHelpText = function( ) {
    return helpText;
  }

  this.setButtonID = function( newButtonID ) {
    buttonID = newButtonID;
  }

  this.setButtonName = function( newButtonName ) {
    buttonName = newButtonName;
  }

  this.setHelpText = function( newHelpText ) {
    helpText = newHelpText;
  }

  this.setRun = function( newRun ) {
    this.run = newRun;
  }

  // -------------------------------------------------------------------

  for (key in properties) {
    if (properties.hasOwnProperty(key)) {
      if (key === 'helpText') {
	this.setHelpText(properties.helpText);
      }
      if (key === 'buttonID') {
	this.setButtonID(properties.buttonID);
      }
      if (key === 'buttonName') {
	this.setButtonName(properties.buttonName);
      }
      if (key === 'keyShortcuts') {
	for (name in properties.keyShortcuts) {
	  if (properties.keyShortcuts.hasOwnProperty(name)) {
	    this.addKey(name, properties.keyShortcuts[name]);
	  }
	}
      }
      if (key === 'run') {
	this.setRun(properties.run);
      }
    }
  }
}

var getKeyCodeToActionMap = function( actionArray ) {
  var i, j, keyCodeToKeyAction = {}, action;
  var keyShortcuts, keyCodes, keyCode;
  for (i = 0; i < actionArray.length; ++i) {
    action = actionArray[i];
    keyShortcuts = action.getKeys();
    for (name in keyShortcuts) {
      if (keyShortcuts.hasOwnProperty(name)) {
	keyCodes = keyShortcuts[name];
	for( j = 0; j < keyCodes.length; ++j ) {
	  keyCode = keyCodes[j];
	  if (keyCodeToKeyAction[keyCode]) {
	    alert("BUG: overwriting action for keyCode " + keyCode + " (via '" + name + "')");
	  }
	  keyCodeToKeyAction[keyCode] = action;
	}
      }
    }
  }
  return keyCodeToKeyAction;
}

/** Updates the 'alt' and 'title' attributes on the toolbar
    icons that are documented with help text and key presses.
    Also bind the onClick action for the link that contains
    those icons to the corresponding function */

function createButtonsFromActions(actions, boxID, iconPrefix) {
  var box, action, a, img, buttonID, title, shorcuts;
  box = $( '

' );
  for (i = 0; i < actions.length; ++i) {
    action = actions[i];
    if (action.hasButton()) {
      buttonID = action.getButtonID();
      a = document.createElement('a');
      a.setAttribute('class', 'button');
      a.setAttribute('id', action.getButtonID());
      a.onclick = action.run;
      img = document.createElement('img');
      img.setAttribute('src', 'widgets/themes/kde/' + iconPrefix + action.getButtonName() + '.png');
      img.setAttribute('alt', action.getHelpText());
      shortcuts = action.getKeyShortcutsString();
      if (shortcuts.length === 0) {
        title = action.getHelpText();
      } else {
        title = shortcuts + ': ' + action.getHelpText();
      }
      img.setAttribute('title', title);
      a.appendChild(img);
      box.append(a);
    }
  }
  return box;
}

// ---------------------------------------------------------------------

/* These actions are kept in separate arrays, since they need to be
 * added to different DIVs in the toolbar. */

var toolActions = [

	new Action({
		helpText: "Switch to the selector tool",
		buttonID: 'edit_button_select',
		buttonName: "select",
		run: function (e) {
			project.setTool( new Selector() );
			return true;
		}
	}),

	new Action({
		helpText: "Switch to the move tool",
		buttonID: 'edit_button_move',
		buttonName: "move",
		run: function (e) {
			project.setTool( new Navigator() );
			return true;
		}
	}),

	new Action({
		helpText: "Show keyboard shortcut help",
		buttonID: 'key_help_button',
		buttonName: "help",
		keyShortcuts: {
			'F1': [ 112 ]
		},
		run: function (e) {
			WindowMaker.show('keyboard-shortcuts');
			return true;
		}
	}),

  new Action({
    helpText: "Disclaimer",
    buttonID: "disclaimer_button",
    buttonName: 'disclaimer',
    run: function (e) {
      WindowMaker.show('disclaimer');
      return true;
    }
  })

];

var editToolActions = [

	new Action({
		helpText: "Text label tool",
		buttonID: 'edit_button_text',
		buttonName: 'text',
		run: function (e) {
			project.setTool( new TextlabelTool() );
			return true;
		}
	}),

	new Action({
		helpText: "Tagging tool",
		buttonID: 'edit_button_tags',
		buttonName: 'tags',
		run: function (e) {
			project.setTool( new TaggingTool() );
			return true;
		}
	}),

	new Action({
		helpText: "Crop tool",
		buttonID: 'edit_button_crop',
		buttonName: 'crop',
		run: function (e) {
			project.setTool( new CroppingTool() );
			return true;
		}
	}),

/*    new Action({
       helpText: "Canvas Tool",
       buttonID: 'edit_button_canvas',
       buttonName: 'canvas',
       keyShortcuts: {

       },
       run: function (e) {
         // check if zoom level 0 active
          if( project.focusedStack.s !== 0 ) {
            alert('Segmentation Tool only works on zoom-level 0!');
            return;
          }
          project.setTool( new CanvasTool() );
       }
    }), */

  new Action({
     helpText: "Segmentation Tool",
     buttonID: 'edit_button_segmentation',
     buttonName: 'canvas',
     keyShortcuts: {

     },
     run: function (e) {
        // TODO: change to set zoom level for segmentation
        // check if zoom level 0 active
        if( project.focusedStack.s !== 0 ) {
          alert('Segmentation Tool only works on zoom-level 0!');
          return;
        }
        project.setTool( new SegmentationTool() );
     }
  }),

	new Action({
		helpText: "Tracing tool",
		buttonID: 'edit_button_trace',
		buttonName: 'trace',
		run: function (e) {
			project.setTool( new TracingTool() );
			return true;
		}
	})

/*
	new Action({
		helpText: "Profile tool",
		keyShortcuts: {
			'F': [ 70 ]
		},
		run: function (e) {
			project.setMode( 'profile' );
			return true;
		}
	})
*/
];

var segmentationWindowActions = [

  new Action({
    helpText: "Show segments table",
    buttonID: "segmentation_button_segments_table",
    buttonName: 'table_segments',
    run: function (e) {
      WindowMaker.show('segmentstable-widget');
      return true;
    }
  }),

  new Action({
    helpText: "Show 3D WebGL view",
    buttonID: "view_3d_webgl_button",
    buttonName: '3d-view-webgl',
    run: function (e) {
      WindowMaker.show('3d-webgl-view');
    }
  }),

  new Action({
    helpText: "Show object tree",
    buttonID: "data_button_tree",
    buttonName: 'tree',
    run: function (e) {
      WindowMaker.show('object-tree');
      return true;
    }
  }),

];

var tracingWindowActions = [

  new Action({
    helpText: "Show treenode table",
    buttonID: "data_button_table_treenode",
    buttonName: 'table',
    run: function (e) {
      WindowMaker.show('node-table');
      return true;
    }
  }),

  new Action({
    helpText: "Show connector table",
    buttonID: "data_button_table_connector",
    buttonName: 'table_connector',
    run: function (e) {
      WindowMaker.show( 'connector-table' );
      return true;
    }
  }),

  new Action({
      helpText: "Show log",
      buttonID: "data_button_table_log",
      buttonName: 'table_log',
      run: function (e) {
          WindowMaker.show( 'log-table' );
          return true;
      }
  }),

  new Action({
      helpText: "Review system",
      buttonID: "data_button_review",
      buttonName: 'table_review',
      run: function (e) {
          WindowMaker.show('review-system');
          return true;
      }
  }),

    new Action({
        helpText: "Connectivity widget",
        buttonID: "data_button_connectivit",
        buttonName: 'table_connectivity',
        run: function (e) {
            WindowMaker.show('connectivity-widget');
            return true;
        }
    }),

    new Action({
        helpText: "Adjacency Matrix widget",
        buttonID: "data_button_connectivity",
        buttonName: 'adj_matrix',
        run: function (e) {
            WindowMaker.show('adjacencymatrix-widget');
            return true;
        }
    }),

  new Action({
      helpText: "Export widget",
      buttonID: "data_button_export_widget",
      buttonName: 'export_widget',
      run: function (e) {
          WindowMaker.show('export-widget');
          return true;
      }
  }),

  new Action({
      helpText: "Graph widget",
      buttonID: "data_button_graph_widget",
      buttonName: 'graph_widget',
      run: function (e) {
          WindowMaker.show('graph-widget');
          return true;
      }
  }),

  new Action({
      helpText: "Segmentation Graph widget",
      buttonID: "data_button_segmentation_graph_widget",
      buttonName: 'graph_widget',
      run: function (e) {
          WindowMaker.show('cytograph-widget');
          return true;
      }
  }),

  new Action({
    helpText: "Show object tree",
    buttonID: "data_button_tree",
    buttonName: 'tree',
    run: function (e) {
      WindowMaker.show('object-tree');
      return true;
    }
  }),

  new Action({
    helpText: "Show search window",
    buttonID: "data_button_search",
    buttonName: 'search',
    keyShortcuts: {
      '/': [ 191, 47 ]
    },
    run: function (e) {
      WindowMaker.show('search');
      return true;
    }
  }),

  new Action({
    helpText: "Show project statistics",
    buttonID: "data_button_stats",
    buttonName: 'stats',
    run: function (e) {
      WindowMaker.show('statistics');
      return true;
    }
  })

/*
  new Action({
    helpText: "Show object tree as graph",
    buttonID: "view_objecttree_graph",
    buttonName: 'objecttree-graph',
    run: function (e) {
      window.open("apps/graph/index.html?project_id="+project.id+"&lower_skeleton_count=10", "Wiring diagram");
      return true;
    }
  })
  */
   ];

if ( !Detector.webgl ) {
  tracingWindowActions[tracingWindowActions.length] = new Action({
    helpText: "Show 3D canvas view",
    buttonID: "view_3d_button",
    buttonName: '3d-view',
    run: function (e) {
      WindowMaker.show('3d-view');
      return true;
    }
  });
} else {
  tracingWindowActions[tracingWindowActions.length] = new Action({
    helpText: "Show 3D WebGL view",
    buttonID: "view_3d_webgl_button",
    buttonName: '3d-view-webgl',
    run: function (e) {
      WindowMaker.show('3d-webgl-view');
    }
  });
}
<|endoftext|>