1 // Copyright (c) 2010-2011 by Kris Maglione <maglione.k@gmail.com>
3 // This work is licensed for reuse under an MIT license. Details are
4 // given in the LICENSE.txt file included with this file.
7 Components.utils.import("resource://dactyl/bootstrap.jsm");
8 defineModule("contexts", {
9 exports: ["Contexts", "Group", "contexts"],
10 require: ["services", "util"]
13 this.lazyRequire("overlay", ["overlay"]);
15 var Const = function Const(val) Class.Property({ enumerable: true, value: val });
17 var Group = Class("Group", {
18 init: function init(name, description, filter, persist) {
22 this.description = description;
23 this.filter = filter || this.constructor.defaultFilter;
24 this.persist = persist || false;
29 get contexts() this.modules.contexts,
31 set lastDocument(val) { this._lastDocument = util.weakReference(val); },
32 get lastDocument() this._lastDocument && this._lastDocument.get(),
36 cleanup: function cleanup(reason) {
37 for (let hive in values(this.hives))
38 util.trapErrors("cleanup", hive);
41 for (let hive in keys(this.hiveMap))
44 if (reason != "shutdown")
45 this.children.splice(0).forEach(this.contexts.closure.removeGroup);
47 destroy: function destroy(reason) {
48 for (let hive in values(this.hives))
49 util.trapErrors("destroy", hive);
51 if (reason != "shutdown")
52 this.children.splice(0).forEach(this.contexts.closure.removeGroup);
55 argsExtra: function argsExtra() ({}),
57 makeArgs: function makeArgs(doc, context, args) {
58 let res = update({ doc: doc, context: context }, args);
59 return update(res, this.argsExtra(res), args);
62 get toStringParams() [this.name],
64 get builtin() this.modules.contexts.builtinGroups.indexOf(this) >= 0,
67 compileFilter: function (patterns, default_) {
68 if (arguments.length < 2)
71 function siteFilter(uri)
72 let (match = array.nth(siteFilter.filters, function (f) f(uri), 0))
73 match ? match.result : default_;
75 return update(siteFilter, {
76 toString: function () this.filters.join(","),
78 toXML: function (modules) let (uri = modules && modules.buffer.uri)
79 template.map(this.filters,
80 function (f) <span highlight={uri && f(uri) ? "Filter" : ""}>{f}</span>,
83 filters: Option.parse.sitelist(patterns)
87 defaultFilter: Class.Memoize(function () this.compileFilter(["*"]))
90 var Contexts = Module("contexts", {
92 this.pluginModules = {};
95 cleanup: function () {
96 for each (let module in this.pluginModules)
97 util.trapErrors("unload", module);
99 this.pluginModules = {};
102 Local: function Local(dactyl, modules, window) ({
104 const contexts = this;
105 this.modules = modules;
107 Object.defineProperty(modules.plugins, "contexts", Const({}));
111 this.groupsProto = {};
115 this.builtin = this.addGroup("builtin", "Builtin items");
116 this.user = this.addGroup("user", "User-defined items", null, true);
117 this.builtinGroups = [this.builtin, this.user];
118 this.builtin.modifiable = false;
120 this.GroupFlag = Class("GroupFlag", CommandOption, {
121 init: function (name) {
124 this.type = ArgType("group", function (group) {
125 return isString(group) ? contexts.getGroup(group, name)
130 get toStringParams() [this.name],
132 names: ["-group", "-g"],
134 description: "Group to which to add",
136 get default() (contexts.context && contexts.context.group || contexts.user)[this.name],
138 completer: function (context) modules.completion.group(context)
141 memoize(modules, "userContext", function () contexts.Context(modules.io.getRCFile("~", true), contexts.user, [modules, true]));
142 memoize(modules, "_userContext", function () contexts.Context(modules.io.getRCFile("~", true), contexts.user, [modules.userContext]));
145 cleanup: function () {
146 for each (let hive in this.groupList.slice())
147 util.trapErrors("cleanup", hive, "shutdown");
150 destroy: function () {
151 for each (let hive in values(this.groupList.slice()))
152 util.trapErrors("destroy", hive, "shutdown");
154 for (let [name, plugin] in iter(this.modules.plugins.contexts))
155 if (plugin && "onUnload" in plugin && callable(plugin.onUnload))
156 util.trapErrors("onUnload", plugin);
160 "browser.locationChange": function (webProgress, request, uri) {
165 Group: Class("Group", Group, { modules: modules, get hiveMap() modules.contexts.hives }),
167 Hives: Class("Hives", Class.Property, {
168 init: function init(name, constructor) {
169 const { contexts } = modules;
176 get: function () array(contexts.groups[self.name])
179 this.Hive = constructor;
181 memoize(contexts.Group.prototype, name, function () {
182 let group = constructor(this);
183 this.hives.push(group);
188 memoize(contexts.hives, name,
189 function () Object.create(Object.create(contexts.hiveProto,
190 { _hive: { value: name } })));
192 memoize(contexts.groupsProto, name,
193 function () [group[name] for (group in values(this.groups)) if (Set.has(group, name))]);
196 get toStringParams() [this.name, this.Hive]
200 Context: function Context(file, group, args) {
201 const { contexts, io, newContext, plugins, userContext } = this.modules;
203 let isPlugin = array.nth(io.getRuntimeDirectories("plugins"),
204 function (dir) dir.contains(file, true),
206 let isRuntime = array.nth(io.getRuntimeDirectories(""),
207 function (dir) dir.contains(file, true),
210 let name = isPlugin ? file.getRelativeDescriptor(isPlugin).replace(File.PATH_SEP, "-")
212 let id = util.camelCase(name.replace(/\.[^.]*$/, ""));
214 let contextPath = file.path;
215 let self = Set.has(plugins, contextPath) && plugins.contexts[contextPath];
217 if (!self && isPlugin && false)
218 self = Set.has(plugins, id) && plugins[id];
221 if (Set.has(self, "onUnload"))
222 util.trapErrors("onUnload", self);
225 self = args && !isArray(args) ? args : newContext.apply(null, args || [userContext]);
229 PATH: Const(file.path),
231 CONTEXT: Const(self),
233 set isGlobalModule(val) {
239 unload: Const(function unload() {
240 if (plugins[this.NAME] === this || plugins[this.PATH] === this)
242 util.trapErrors("onUnload", this);
244 if (plugins[this.NAME] === this)
245 delete plugins[this.NAME];
247 if (plugins[this.PATH] === this)
248 delete plugins[this.PATH];
250 if (plugins.contexts[contextPath] === this)
251 delete plugins.contexts[contextPath];
253 if (!this.GROUP.builtin)
254 contexts.removeGroup(this.GROUP);
258 if (group !== this.user)
259 Class.replaceProperty(plugins, file.path, self);
261 // This belongs elsewhere
263 Object.defineProperty(plugins, self.NAME, {
266 get: function () self,
267 set: function (val) {
268 util.dactyl(val).reportError(FailedAssertion(_("plugin.notReplacingContext", self.NAME), 3, false), true);
273 let path = isRuntime ? file.getRelativeDescriptor(isRuntime) : file.path;
274 let name = isRuntime ? path.replace(/^(plugin|color)s([\\\/])/, "$1$2") : "script-" + path;
277 group = this.addGroup(commands.nameRegexp
278 .iterate(name.replace(/\.[^.]*$/, ""))
279 .join("-").replace(/--+/g, "-"),
280 _("context.scriptGroup", file.path),
283 Class.replaceProperty(self, "GROUP", group);
284 Class.replaceProperty(self, "group", group);
286 return plugins.contexts[contextPath] = self;
289 Script: function Script(file, group) {
290 return this.Context(file, group, [this.modules.userContext, true]);
293 Module: function Module(uri, isPlugin) {
294 const { io, plugins } = this.modules;
296 let canonical = uri.spec;
297 if (uri.scheme == "resource")
298 canonical = services["resource:"].resolveURI(uri);
300 if (uri instanceof Ci.nsIFileURL)
301 var file = File(uri.file);
303 let isPlugin = array.nth(io.getRuntimeDirectories("plugins"),
304 function (dir) dir.contains(file, true),
307 let name = isPlugin && file && file.getRelativeDescriptor(isPlugin)
308 .replace(File.PATH_SEP, "-");
309 let id = util.camelCase(name.replace(/\.[^.]*$/, ""));
311 let self = Set.has(this.pluginModules, canonical) && this.pluginModules[canonical];
314 self = Object.create(jsmodules);
319 PATH: Const(file && file.path),
321 CONTEXT: Const(self),
323 get isGlobalModule() true,
324 set isGlobalModule(val) {
325 util.assert(val, "Loading non-global module as global",
329 unload: Const(function unload() {
330 if (contexts.pluginModules[canonical] == this) {
332 util.trapErrors("onUnload", this);
334 delete contexts.pluginModules[canonical];
337 for each (let { plugins } in overlay.modules)
338 if (plugins[this.NAME] == this)
339 delete plugins[this.name];
343 JSMLoader.loadSubScript(uri.spec, self, File.defaultEncoding);
344 this.pluginModules[canonical] = self;
347 // This belongs elsewhere
349 Object.defineProperty(plugins, self.NAME, {
352 get: function () self,
353 set: function (val) {
354 util.dactyl(val).reportError(FailedAssertion(_("plugin.notReplacingContext", self.NAME), 3, false), true);
364 * Returns a frame object describing the currently executing
365 * command, if applicable, otherwise returns the passed frame.
367 * @param {nsIStackFrame} frame
369 getCaller: function getCaller(frame) {
370 if (this.context && this.context.file)
373 filename: this.context.file[0] == "[" ? this.context.file
374 : services.io.newFileURI(File(this.context.file)).spec,
375 lineNumber: this.context.line
380 groups: Class.Memoize(function () this.matchingGroups()),
382 allGroups: Class.Memoize(function () Object.create(this.groupsProto, {
383 groups: { value: this.initializedGroups() }
386 matchingGroups: function (uri) Object.create(this.groupsProto, {
387 groups: { value: this.activeGroups(uri) }
390 activeGroups: function (uri) {
391 if (uri instanceof Ci.nsIDOMDocument)
392 var [doc, uri] = [uri, uri.documentURIObject || util.newURI(uri.documentURI)];
395 var { uri, doc } = this.modules.buffer;
397 return this.initializedGroups().filter(function (g) {
398 let res = uri && g.filter(uri, doc);
400 g.lastDocument = res && doc;
405 flush: function flush() {
407 delete this.allGroups;
410 initializedGroups: function (hive)
411 let (need = hive ? [hive] : Object.keys(this.hives))
412 this.groupList.filter(function (group) need.some(Set.has(group))),
414 addGroup: function addGroup(name, description, filter, persist, replace) {
415 let group = this.getGroup(name);
420 group = this.Group(name, description, filter, persist);
421 this.groupList.unshift(group);
422 this.groupMap[name] = group;
423 this.hiveProto.__defineGetter__(name, function () group[this._hive]);
427 util.trapErrors("cleanup", group);
430 group.description = description;
432 group.filter = filter;
433 group.persist = persist;
440 removeGroup: function removeGroup(name) {
441 if (isObject(name)) {
442 if (this.groupList.indexOf(name) === -1)
447 let group = this.getGroup(name);
449 util.assert(!group || !group.builtin, _("group.cantRemoveBuiltin"));
453 this.groupList.splice(this.groupList.indexOf(group), 1);
454 util.trapErrors("destroy", group);
457 if (this.context && this.context.group === group)
458 this.context.group = null;
460 delete this.groupMap[name];
461 delete this.hiveProto[name];
466 getGroup: function getGroup(name, hive) {
467 if (name === "default")
468 var group = this.context && this.context.context && this.context.context.GROUP;
469 else if (Set.has(this.groupMap, name))
470 group = this.groupMap[name];
477 getDocs: function getDocs(context) {
479 if (isinstance(context, ["Sandbox"])) {
480 let info = "INFO" in context && Cu.evalInSandbox("this.INFO instanceof XML && INFO.toXMLString()", context);
481 return info && XML(info);
483 if (typeof context.INFO == "xml")
490 bindMacro: function (args, default_, params) {
491 const { dactyl, events, modules } = this.modules;
493 function Proxy(obj, key) Class.Property({
496 get: function Proxy_get() process(obj[key]),
497 set: function Proxy_set(val) obj[key] = val
500 let process = util.identity;
502 if (callable(params))
503 var makeParams = function makeParams(self, args)
504 let (obj = params.apply(self, args))
505 iter.toObject([k, Proxy(obj, k)] for (k in properties(obj)));
507 makeParams = function makeParams(self, args)
508 iter.toObject([name, process(args[i])]
509 for ([i, name] in Iterator(params)));
511 let rhs = args.literalArg;
512 let type = ["-builtin", "-ex", "-javascript", "-keys"].reduce(function (a, b) args[b] ? b : a, default_);
519 let silent = args["-silent"];
520 rhs = DOM.Event.canonicalKeys(rhs, true);
521 var action = function action() {
522 events.feedkeys(action.macro(makeParams(this, arguments)),
525 action.macro = util.compileMacro(rhs, true);
529 action = function action() modules.commands
530 .execute(action.macro, makeParams(this, arguments),
531 false, null, action.context);
532 action.macro = util.compileMacro(rhs, true);
533 action.context = this.context && update({}, this.context);
537 if (callable(params))
538 action = dactyl.userEval("(function action() { with (action.makeParams(this, arguments)) {" + args.literalArg + "} })");
540 action = dactyl.userFunc.apply(dactyl, params.concat(args.literalArg).array);
541 process = function (param) isObject(param) && param.valueOf ? param.valueOf() : param;
542 action.params = params;
543 action.makeParams = makeParams;
547 action.toString = function toString() (type === default_ ? "" : type + " ") + rhs;
552 withContext: function withContext(defaults, callback, self)
553 this.withSavedValues(["context"], function () {
554 this.context = defaults && update({}, defaults);
555 return callback.call(self, this.context);
558 Hive: Class("Hive", {
559 init: function init(group) {
563 cleanup: function cleanup() {},
564 destroy: function destroy() {},
566 get modifiable() this.group.modifiable,
568 get argsExtra() this.group.argsExtra,
569 get makeArgs() this.group.makeArgs,
570 get builtin() this.group.builtin,
572 get name() this.group.name,
573 set name(val) this.group.name = val,
575 get description() this.group.description,
576 set description(val) this.group.description = val,
578 get filter() this.group.filter,
579 set filter(val) this.group.filter = val,
581 get persist() this.group.persist,
582 set persist(val) this.group.persist = val,
584 prefix: Class.Memoize(function () this.name === "builtin" ? "" : this.name + ":"),
586 get toStringParams() [this.name]
589 commands: function initCommands(dactyl, modules, window) {
590 const { commands, contexts } = modules;
592 commands.add(["gr[oup]"],
593 "Create or select a group",
595 if (args.length > 0) {
596 var name = Option.dequote(args[0]);
597 util.assert(name !== "builtin", _("group.cantModifyBuiltin"));
598 util.assert(commands.validName.test(name), _("group.invalidName", name));
600 var group = contexts.getGroup(name);
603 var group = args.context && args.context.group;
605 return void modules.completion.listCompleter("group", "", null, null);
607 util.assert(group || name, _("group.noCurrent"));
609 let filter = Group.compileFilter(args["-locations"]);
610 if (!group || args.bang)
611 group = contexts.addGroup(name, args["-description"], filter, !args["-nopersist"], args.bang);
612 else if (!group.builtin) {
613 if (args.has("-locations"))
614 group.filter = filter;
615 if (args.has("-description"))
616 group.description = args["-description"];
617 if (args.has("-nopersist"))
618 group.persist = !args["-nopersist"];
621 if (!group.builtin && args.has("-args")) {
622 group.argsExtra = contexts.bindMacro({ literalArg: "return " + args["-args"] },
623 "-javascript", util.identity);
624 group.args = args["-args"];
628 args.context.group = group;
629 if (args.context.context) {
630 args.context.context.group = group;
632 let parent = args.context.context.GROUP;
633 if (parent && parent != group) {
634 group.parent = parent;
635 if (!~parent.children.indexOf(group))
636 parent.children.push(group);
641 util.assert(!group.builtin ||
642 !["-description", "-locations", "-nopersist"]
643 .some(Set.has(args.explicitOpts)),
644 _("group.cantModifyBuiltin"));
649 completer: function (context, args) {
650 if (args.length == 1)
651 modules.completion.group(context);
656 names: ["-args", "-a"],
657 description: "JavaScript Object which augments the arguments passed to commands, mappings, and autocommands",
658 type: CommandOption.STRING
661 names: ["-description", "-desc", "-d"],
662 description: "A description of this group",
663 default: ["User-defined group"],
664 type: CommandOption.STRING
667 names: ["-locations", "-locs", "-loc", "-l"],
668 description: ["The URLs for which this group should be active"],
670 type: CommandOption.LIST
673 names: ["-nopersist", "-n"],
674 description: "Do not save this group to an auto-generated RC file"
678 serialize: function () [
682 options: iter([v, typeof group[k] == "boolean" ? null : group[k]]
683 // FIXME: this map is expressed multiple times
684 for ([k, v] in Iterator({
686 description: "-description",
689 if (group[k])).toObject(),
690 arguments: [group.name],
693 for (group in values(contexts.initializedGroups()))
694 if (!group.builtin && group.persist)
695 ].concat([{ command: this.name, arguments: ["user"] }])
698 commands.add(["delg[roup]"],
701 util.assert(args.bang ^ !!args[0], _("error.argumentOrBang"));
704 contexts.groupList = contexts.groupList.filter(function (g) g.builtin);
706 util.assert(contexts.getGroup(args[0]), _("group.noSuch", args[0]));
707 contexts.removeGroup(args[0]);
713 completer: function (context, args) {
716 context.filters.push(function ({ item }) !item.builtin);
717 modules.completion.group(context);
721 commands.add(["fini[sh]"],
722 "Stop sourcing a script file",
724 util.assert(args.context, _("command.finish.illegal"));
725 args.context.finished = true;
729 function checkStack(cmd) {
730 util.assert(contexts.context && contexts.context.stack &&
731 contexts.context.stack[cmd] && contexts.context.stack[cmd].length,
732 _("command.conditional.illegal"));
736 return contexts.context.stack[cmd].pop();
738 function push(cmd, value) {
739 util.assert(contexts.context, _("command.conditional.illegal"));
740 if (arguments.length < 2)
741 value = contexts.context.noExecute;
742 contexts.context.stack = contexts.context.stack || {};
743 contexts.context.stack[cmd] = (contexts.context.stack[cmd] || []).concat([value]);
747 "Execute commands until the next :elseif, :else, or :endif only if the argument returns true",
748 function (args) { args.context.noExecute = !dactyl.userEval(args[0]); },
750 always: function (args) { push("if"); },
754 commands.add(["elsei[f]", "elif"],
755 "Execute commands until the next :elseif, :else, or :endif only if the argument returns true",
758 always: function (args) {
760 args.context.noExecute = args.context.stack.if.slice(-1)[0] ||
761 !args.context.noExecute || !dactyl.userEval(args[0]);
766 commands.add(["el[se]"],
767 "Execute commands until the next :endif only if the previous conditionals were not executed",
770 always: function (args) {
772 args.context.noExecute = args.context.stack.if.slice(-1)[0] ||
773 !args.context.noExecute;
777 commands.add(["en[dif]", "fi"],
778 "End a string of :if/:elseif/:else conditionals",
781 always: function (args) { args.context.noExecute = pop("if"); },
785 completion: function initCompletion(dactyl, modules, window) {
786 const { completion, contexts } = modules;
788 completion.group = function group(context, active) {
789 context.title = ["Group"];
790 let uri = modules.buffer.uri;
792 active: function (group) group.filter(uri),
794 description: function (g) <>{g.filter.toXML ? g.filter.toXML(modules) + <> </> : ""}{g.description || ""}</>
796 context.completions = (active === undefined ? contexts.groupList : contexts.initializedGroups(active))
799 iter({ Active: true, Inactive: false }).forEach(function ([name, active]) {
800 context.split(name, null, function (context) {
801 context.title[0] = name + " Groups";
802 context.filters.push(function ({ item }) !!item.filter(modules.buffer.uri) == active);
811 // catch(e){ if (!e.stack) e = Error(e); dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack); }
813 // vim: set fdm=marker sw=4 ts=4 et ft=javascript: