mirror of
https://github.com/atom/atom.git
synced 2026-04-06 03:02:13 -04:00
663 lines
19 KiB
JavaScript
663 lines
19 KiB
JavaScript
/* ***** BEGIN LICENSE BLOCK *****
|
|
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
|
|
*
|
|
* The contents of this file are subject to the Mozilla Public License Version
|
|
* 1.1 (the "License"); you may not use this file except in compliance with
|
|
* the License. You may obtain a copy of the License at
|
|
* http://www.mozilla.org/MPL/
|
|
*
|
|
* Software distributed under the License is distributed on an "AS IS" basis,
|
|
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
|
|
* for the specific language governing rights and limitations under the
|
|
* License.
|
|
*
|
|
* The Original Code is Mozilla Skywriter.
|
|
*
|
|
* The Initial Developer of the Original Code is
|
|
* Mozilla.
|
|
* Portions created by the Initial Developer are Copyright (C) 2009
|
|
* the Initial Developer. All Rights Reserved.
|
|
*
|
|
* Contributor(s):
|
|
* Joe Walker (jwalker@mozilla.com)
|
|
*
|
|
* Alternatively, the contents of this file may be used under the terms of
|
|
* either the GNU General Public License Version 2 or later (the "GPL"), or
|
|
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
|
|
* in which case the provisions of the GPL or the LGPL are applicable instead
|
|
* of those above. If you wish to allow use of your version of this file only
|
|
* under the terms of either the GPL or the LGPL, and not to allow others to
|
|
* use your version of this file under the terms of the MPL, indicate your
|
|
* decision by deleting the provisions above and replace them with the notice
|
|
* and other provisions required by the GPL or the LGPL. If you do not delete
|
|
* the provisions above, a recipient may use your version of this file under
|
|
* the terms of any one of the MPL, the GPL or the LGPL.
|
|
*
|
|
* ***** END LICENSE BLOCK ***** */
|
|
|
|
define(function(require, exports, module) {
|
|
|
|
var console = require('pilot/console');
|
|
var Trace = require('pilot/stacktrace').Trace;
|
|
var oop = require('pilot/oop');
|
|
var useragent = require('pilot/useragent');
|
|
var keyUtil = require('pilot/keys');
|
|
var EventEmitter = require('pilot/event_emitter').EventEmitter;
|
|
var typecheck = require('pilot/typecheck');
|
|
var catalog = require('pilot/catalog');
|
|
var Status = require('pilot/types').Status;
|
|
var types = require('pilot/types');
|
|
var lang = require('pilot/lang');
|
|
|
|
/*
|
|
// TODO: this doesn't belong here - or maybe anywhere?
|
|
var dimensionsChangedExtensionSpec = {
|
|
name: 'dimensionsChanged',
|
|
description: 'A dimensionsChanged is a way to be notified of ' +
|
|
'changes to the dimension of Skywriter'
|
|
};
|
|
exports.startup = function(data, reason) {
|
|
catalog.addExtensionSpec(commandExtensionSpec);
|
|
};
|
|
exports.shutdown = function(data, reason) {
|
|
catalog.removeExtensionSpec(commandExtensionSpec);
|
|
};
|
|
*/
|
|
|
|
var commandExtensionSpec = {
|
|
name: 'command',
|
|
description: 'A command is a bit of functionality with optional ' +
|
|
'typed arguments which can do something small like moving ' +
|
|
'the cursor around the screen, or large like cloning a ' +
|
|
'project from VCS.',
|
|
indexOn: 'name'
|
|
};
|
|
|
|
exports.startup = function(data, reason) {
|
|
// TODO: this is probably all kinds of evil, but we need something working
|
|
catalog.addExtensionSpec(commandExtensionSpec);
|
|
};
|
|
|
|
exports.shutdown = function(data, reason) {
|
|
catalog.removeExtensionSpec(commandExtensionSpec);
|
|
};
|
|
|
|
/**
|
|
* Manage a list of commands in the current canon
|
|
*/
|
|
|
|
/**
|
|
* A Command is a discrete action optionally with a set of ways to customize
|
|
* how it happens. This is here for documentation purposes.
|
|
* TODO: Document better
|
|
*/
|
|
var thingCommand = {
|
|
name: 'thing',
|
|
description: 'thing is an example command',
|
|
params: [{
|
|
name: 'param1',
|
|
description: 'an example parameter',
|
|
type: 'text',
|
|
defaultValue: null
|
|
}],
|
|
exec: function(env, args, request) {
|
|
thing();
|
|
}
|
|
};
|
|
|
|
/**
|
|
* A lookup hash of our registered commands
|
|
*/
|
|
var commands = {};
|
|
|
|
/**
|
|
* A lookup has for command key bindings that use a string as sender.
|
|
*/
|
|
var commmandKeyBinding = {};
|
|
|
|
/**
|
|
* Array with command key bindings that use a function to determ the sender.
|
|
*/
|
|
var commandKeyBindingFunc = { };
|
|
|
|
function splitSafe(s, separator, limit, bLowerCase) {
|
|
return (bLowerCase && s.toLowerCase() || s)
|
|
.replace(/(?:^\s+|\n|\s+$)/g, "")
|
|
.split(new RegExp("[\\s ]*" + separator + "[\\s ]*", "g"), limit || 999);
|
|
}
|
|
|
|
function parseKeys(keys, val, ret) {
|
|
var key,
|
|
hashId = 0,
|
|
parts = splitSafe(keys, "\\-", null, true),
|
|
i = 0,
|
|
l = parts.length;
|
|
|
|
for (; i < l; ++i) {
|
|
if (keyUtil.KEY_MODS[parts[i]])
|
|
hashId = hashId | keyUtil.KEY_MODS[parts[i]];
|
|
else
|
|
key = parts[i] || "-"; //when empty, the splitSafe removed a '-'
|
|
}
|
|
|
|
if (ret == null) {
|
|
return {
|
|
key: key,
|
|
hashId: hashId
|
|
}
|
|
} else {
|
|
(ret[hashId] || (ret[hashId] = {}))[key] = val;
|
|
}
|
|
}
|
|
|
|
var platform = useragent.isMac ? "mac" : "win";
|
|
function buildKeyHash(command) {
|
|
var binding = command.bindKey,
|
|
key = binding[platform],
|
|
ckb = commmandKeyBinding,
|
|
ckbf = commandKeyBindingFunc
|
|
|
|
if (!binding.sender) {
|
|
throw new Error('All key bindings must have a sender');
|
|
}
|
|
if (!binding.mac && binding.mac !== null) {
|
|
throw new Error('All key bindings must have a mac key binding');
|
|
}
|
|
if (!binding.win && binding.win !== null) {
|
|
throw new Error('All key bindings must have a windows key binding');
|
|
}
|
|
if(!binding[platform]) {
|
|
// No keymapping for this platform.
|
|
return;
|
|
}
|
|
if (typeof binding.sender == 'string') {
|
|
var targets = splitSafe(binding.sender, "\\|", null, true);
|
|
targets.forEach(function(target) {
|
|
if (!ckb[target]) {
|
|
ckb[target] = { };
|
|
}
|
|
key.split("|").forEach(function(keyPart) {
|
|
parseKeys(keyPart, command, ckb[target]);
|
|
});
|
|
});
|
|
} else if (typecheck.isFunction(binding.sender)) {
|
|
var val = {
|
|
command: command,
|
|
sender: binding.sender
|
|
};
|
|
|
|
keyData = parseKeys(key);
|
|
if (!ckbf[keyData.hashId]) {
|
|
ckbf[keyData.hashId] = { };
|
|
}
|
|
if (!ckbf[keyData.hashId][keyData.key]) {
|
|
ckbf[keyData.hashId][keyData.key] = [ val ];
|
|
} else {
|
|
ckbf[keyData.hashId][keyData.key].push(val);
|
|
}
|
|
} else {
|
|
throw new Error('Key binding must have a sender that is a string or function');
|
|
}
|
|
}
|
|
|
|
function findKeyCommand(env, sender, hashId, textOrKey) {
|
|
// Convert keyCode to the string representation.
|
|
if (typecheck.isNumber(textOrKey)) {
|
|
textOrKey = keyUtil.keyCodeToString(textOrKey);
|
|
}
|
|
|
|
// Check bindings with functions as sender first.
|
|
var bindFuncs = (commandKeyBindingFunc[hashId] || {})[textOrKey] || [];
|
|
for (var i = 0; i < bindFuncs.length; i++) {
|
|
if (bindFuncs[i].sender(env, sender, hashId, textOrKey)) {
|
|
return bindFuncs[i].command;
|
|
}
|
|
}
|
|
|
|
var ckbr = commmandKeyBinding[sender];
|
|
return ckbr && ckbr[hashId] && ckbr[hashId][textOrKey];
|
|
}
|
|
|
|
function execKeyCommand(env, sender, hashId, textOrKey) {
|
|
var command = findKeyCommand(env, sender, hashId, textOrKey);
|
|
if (command) {
|
|
return exec(command, env, sender, { });
|
|
} else {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* A sorted list of command names, we regularly want them in order, so pre-sort
|
|
*/
|
|
var commandNames = [];
|
|
|
|
/**
|
|
* This registration method isn't like other Ace registration methods because
|
|
* it doesn't return a decorated command because there is no functional
|
|
* decoration to be done.
|
|
* TODO: Are we sure that in the future there will be no such decoration?
|
|
*/
|
|
function addCommand(command) {
|
|
if (!command.name) {
|
|
throw new Error('All registered commands must have a name');
|
|
}
|
|
if (command.params == null) {
|
|
command.params = [];
|
|
}
|
|
if (!Array.isArray(command.params)) {
|
|
throw new Error('command.params must be an array in ' + command.name);
|
|
}
|
|
// Replace the type
|
|
command.params.forEach(function(param) {
|
|
if (!param.name) {
|
|
throw new Error('In ' + command.name + ': all params must have a name');
|
|
}
|
|
upgradeType(command.name, param);
|
|
}, this);
|
|
commands[command.name] = command;
|
|
|
|
if (command.bindKey) {
|
|
buildKeyHash(command);
|
|
}
|
|
|
|
commandNames.push(command.name);
|
|
commandNames.sort();
|
|
};
|
|
|
|
function upgradeType(name, param) {
|
|
var lookup = param.type;
|
|
param.type = types.getType(lookup);
|
|
if (param.type == null) {
|
|
throw new Error('In ' + name + '/' + param.name +
|
|
': can\'t find type for: ' + JSON.stringify(lookup));
|
|
}
|
|
}
|
|
|
|
function removeCommand(command) {
|
|
var name = (typeof command === 'string' ? command : command.name);
|
|
command = commands[name];
|
|
delete commands[name];
|
|
lang.arrayRemove(commandNames, name);
|
|
|
|
// exaustive search is a little bit brute force but since removeCommand is
|
|
// not a performance critical operation this should be OK
|
|
var ckb = commmandKeyBinding;
|
|
for (var k1 in ckb) {
|
|
for (var k2 in ckb[k1]) {
|
|
for (var k3 in ckb[k1][k2]) {
|
|
if (ckb[k1][k2][k3] == command)
|
|
delete ckb[k1][k2][k3];
|
|
}
|
|
}
|
|
}
|
|
|
|
var ckbf = commandKeyBindingFunc;
|
|
for (var k1 in ckbf) {
|
|
for (var k2 in ckbf[k1]) {
|
|
ckbf[k1][k2].forEach(function(cmd, i) {
|
|
if (cmd.command == command) {
|
|
ckbf[k1][k2].splice(i, 1);
|
|
}
|
|
})
|
|
}
|
|
}
|
|
};
|
|
|
|
function getCommand(name) {
|
|
return commands[name];
|
|
};
|
|
|
|
function getCommandNames() {
|
|
return commandNames;
|
|
};
|
|
|
|
/**
|
|
* Default ArgumentProvider that is used if no ArgumentProvider is provided
|
|
* by the command's sender.
|
|
*/
|
|
function defaultArgsProvider(request, callback) {
|
|
var args = request.args,
|
|
params = request.command.params;
|
|
|
|
for (var i = 0; i < params.length; i++) {
|
|
var param = params[i];
|
|
|
|
// If the parameter is already valid, then don't ask for it anymore.
|
|
if (request.getParamStatus(param) != Status.VALID ||
|
|
// Ask for optional parameters as well.
|
|
param.defaultValue === null)
|
|
{
|
|
var paramPrompt = param.description;
|
|
if (param.defaultValue === null) {
|
|
paramPrompt += " (optional)";
|
|
}
|
|
var value = prompt(paramPrompt, param.defaultValue || "");
|
|
// No value but required -> nope.
|
|
if (!value) {
|
|
callback();
|
|
return;
|
|
} else {
|
|
args[param.name] = value;
|
|
}
|
|
}
|
|
}
|
|
callback();
|
|
}
|
|
|
|
/**
|
|
* Entry point for keyboard accelerators or anything else that wants to execute
|
|
* a command. A new request object is created and a check performed, if the
|
|
* passed in arguments are VALID/INVALID or INCOMPLETE. If they are INCOMPLETE
|
|
* the ArgumentProvider on the sender is called or otherwise the default
|
|
* ArgumentProvider to get the still required arguments.
|
|
* If they are valid (or valid after the ArgumentProvider is done), the command
|
|
* is executed.
|
|
*
|
|
* @param command Either a command, or the name of one
|
|
* @param env Current environment to execute the command in
|
|
* @param sender String that should be the same as the senderObject stored on
|
|
* the environment in env[sender]
|
|
* @param args Arguments for the command
|
|
* @param typed (Optional)
|
|
*/
|
|
function exec(command, env, sender, args, typed) {
|
|
if (typeof command === 'string') {
|
|
command = commands[command];
|
|
}
|
|
if (!command) {
|
|
// TODO: Should we complain more than returning false?
|
|
return false;
|
|
}
|
|
|
|
var request = new Request({
|
|
sender: sender,
|
|
command: command,
|
|
args: args || {},
|
|
typed: typed
|
|
});
|
|
|
|
/**
|
|
* Executes the command and ensures request.done is called on the request in
|
|
* case it's not marked to be done already or async.
|
|
*/
|
|
function execute() {
|
|
command.exec(env, request.args, request);
|
|
|
|
// If the request isn't asnync and isn't done, then make it done.
|
|
if (!request.isAsync && !request.isDone) {
|
|
request.done();
|
|
}
|
|
}
|
|
|
|
|
|
if (request.getStatus() == Status.INVALID) {
|
|
console.error("Canon.exec: Invalid parameter(s) passed to " +
|
|
command.name);
|
|
return false;
|
|
}
|
|
// If the request isn't complete yet, try to complete it.
|
|
else if (request.getStatus() == Status.INCOMPLETE) {
|
|
// Check if the sender has a ArgsProvider, otherwise use the default
|
|
// build in one.
|
|
var argsProvider;
|
|
var senderObj = env[sender];
|
|
if (!senderObj || !senderObj.getArgsProvider ||
|
|
!(argsProvider = senderObj.getArgsProvider()))
|
|
{
|
|
argsProvider = defaultArgsProvider;
|
|
}
|
|
|
|
// Ask the paramProvider to complete the request.
|
|
argsProvider(request, function() {
|
|
if (request.getStatus() == Status.VALID) {
|
|
execute();
|
|
}
|
|
});
|
|
return true;
|
|
} else {
|
|
execute();
|
|
return true;
|
|
}
|
|
};
|
|
|
|
exports.removeCommand = removeCommand;
|
|
exports.addCommand = addCommand;
|
|
exports.getCommand = getCommand;
|
|
exports.getCommandNames = getCommandNames;
|
|
exports.findKeyCommand = findKeyCommand;
|
|
exports.exec = exec;
|
|
exports.execKeyCommand = execKeyCommand;
|
|
exports.upgradeType = upgradeType;
|
|
|
|
|
|
/**
|
|
* We publish a 'output' event whenever new command begins output
|
|
* TODO: make this more obvious
|
|
*/
|
|
oop.implement(exports, EventEmitter);
|
|
|
|
|
|
/**
|
|
* Current requirements are around displaying the command line, and provision
|
|
* of a 'history' command and cursor up|down navigation of history.
|
|
* <p>Future requirements could include:
|
|
* <ul>
|
|
* <li>Multiple command lines
|
|
* <li>The ability to recall key presses (i.e. requests with no output) which
|
|
* will likely be needed for macro recording or similar
|
|
* <li>The ability to store the command history either on the server or in the
|
|
* browser local storage.
|
|
* </ul>
|
|
* <p>The execute() command doesn't really live here, except as part of that
|
|
* last future requirement, and because it doesn't really have anywhere else to
|
|
* live.
|
|
*/
|
|
|
|
/**
|
|
* The array of requests that wish to announce their presence
|
|
*/
|
|
var requests = [];
|
|
|
|
/**
|
|
* How many requests do we store?
|
|
*/
|
|
var maxRequestLength = 100;
|
|
|
|
/**
|
|
* To create an invocation, you need to do something like this (all the ctor
|
|
* args are optional):
|
|
* <pre>
|
|
* var request = new Request({
|
|
* command: command,
|
|
* args: args,
|
|
* typed: typed
|
|
* });
|
|
* </pre>
|
|
* @constructor
|
|
*/
|
|
function Request(options) {
|
|
options = options || {};
|
|
|
|
// Will be used in the keyboard case and the cli case
|
|
this.command = options.command;
|
|
|
|
// Will be used only in the cli case
|
|
this.args = options.args;
|
|
this.typed = options.typed;
|
|
|
|
// Have we been initialized?
|
|
this._begunOutput = false;
|
|
|
|
this.start = new Date();
|
|
this.end = null;
|
|
this.completed = false;
|
|
this.error = false;
|
|
};
|
|
|
|
oop.implement(Request.prototype, EventEmitter);
|
|
|
|
/**
|
|
* Return the status of a parameter on the request object.
|
|
*/
|
|
Request.prototype.getParamStatus = function(param) {
|
|
var args = this.args || {};
|
|
|
|
// Check if there is already a value for this parameter.
|
|
if (param.name in args) {
|
|
// If there is no value set and then the value is VALID if it's not
|
|
// required or INCOMPLETE if not set yet.
|
|
if (args[param.name] == null) {
|
|
if (param.defaultValue === null) {
|
|
return Status.VALID;
|
|
} else {
|
|
return Status.INCOMPLETE;
|
|
}
|
|
}
|
|
|
|
// Check if the parameter value is valid.
|
|
var reply,
|
|
// The passed in value when parsing a type is a string.
|
|
argsValue = args[param.name].toString();
|
|
|
|
// Type.parse can throw errors.
|
|
try {
|
|
reply = param.type.parse(argsValue);
|
|
} catch (e) {
|
|
return Status.INVALID;
|
|
}
|
|
|
|
if (reply.status != Status.VALID) {
|
|
return reply.status;
|
|
}
|
|
}
|
|
// Check if the param is marked as required.
|
|
else if (param.defaultValue === undefined) {
|
|
// The parameter is not set on the args object but it's required,
|
|
// which means, things are invalid.
|
|
return Status.INCOMPLETE;
|
|
}
|
|
|
|
return Status.VALID;
|
|
}
|
|
|
|
/**
|
|
* Return the status of a parameter name on the request object.
|
|
*/
|
|
Request.prototype.getParamNameStatus = function(paramName) {
|
|
var params = this.command.params || [];
|
|
|
|
for (var i = 0; i < params.length; i++) {
|
|
if (params[i].name == paramName) {
|
|
return this.getParamStatus(params[i]);
|
|
}
|
|
}
|
|
|
|
throw "Parameter '" + paramName +
|
|
"' not defined on command '" + this.command.name + "'";
|
|
}
|
|
|
|
/**
|
|
* Checks if all required arguments are set on the request such that it can
|
|
* get executed.
|
|
*/
|
|
Request.prototype.getStatus = function() {
|
|
var args = this.args || {},
|
|
params = this.command.params;
|
|
|
|
// If there are not parameters, then it's valid.
|
|
if (!params || params.length == 0) {
|
|
return Status.VALID;
|
|
}
|
|
|
|
var status = [];
|
|
for (var i = 0; i < params.length; i++) {
|
|
status.push(this.getParamStatus(params[i]));
|
|
}
|
|
|
|
return Status.combine(status);
|
|
}
|
|
|
|
/**
|
|
* Lazy init to register with the history should only be done on output.
|
|
* init() is expensive, and won't be used in the majority of cases
|
|
*/
|
|
Request.prototype._beginOutput = function() {
|
|
this._begunOutput = true;
|
|
this.outputs = [];
|
|
|
|
requests.push(this);
|
|
// This could probably be optimized with some maths, but 99.99% of the
|
|
// time we will only be off by one, and I'm feeling lazy.
|
|
while (requests.length > maxRequestLength) {
|
|
requests.shiftObject();
|
|
}
|
|
|
|
exports._dispatchEvent('output', { requests: requests, request: this });
|
|
};
|
|
|
|
/**
|
|
* Sugar for:
|
|
* <pre>request.error = true; request.done(output);</pre>
|
|
*/
|
|
Request.prototype.doneWithError = function(content) {
|
|
this.error = true;
|
|
this.done(content);
|
|
};
|
|
|
|
/**
|
|
* Declares that this function will not be automatically done when
|
|
* the command exits
|
|
*/
|
|
Request.prototype.async = function() {
|
|
this.isAsync = true;
|
|
if (!this._begunOutput) {
|
|
this._beginOutput();
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Complete the currently executing command with successful output.
|
|
* @param output Either DOM node, an SproutCore element or something that
|
|
* can be used in the content of a DIV to create a DOM node.
|
|
*/
|
|
Request.prototype.output = function(content) {
|
|
if (!this._begunOutput) {
|
|
this._beginOutput();
|
|
}
|
|
|
|
if (typeof content !== 'string' && !(content instanceof Node)) {
|
|
content = content.toString();
|
|
}
|
|
|
|
this.outputs.push(content);
|
|
this.isDone = true;
|
|
this._dispatchEvent('output', {});
|
|
|
|
return this;
|
|
};
|
|
|
|
/**
|
|
* All commands that do output must call this to indicate that the command
|
|
* has finished execution.
|
|
*/
|
|
Request.prototype.done = function(content) {
|
|
this.completed = true;
|
|
this.end = new Date();
|
|
this.duration = this.end.getTime() - this.start.getTime();
|
|
|
|
if (content) {
|
|
this.output(content);
|
|
}
|
|
|
|
// Ensure to finish the request only once.
|
|
if (!this.isDone) {
|
|
this.isDone = true;
|
|
this._dispatchEvent('output', {});
|
|
}
|
|
};
|
|
exports.Request = Request;
|
|
|
|
|
|
});
|