1 // Copyright (c) 2010-2013 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 defineModule("contexts", {
8 exports: ["Contexts", "Group", "contexts"],
9 require: ["services", "util"]
12 lazyRequire("commands", ["ArgType", "CommandOption", "commands"]);
13 lazyRequire("options", ["Option"]);
14 lazyRequire("overlay", ["overlay"]);
15 lazyRequire("storage", ["File"]);
16 lazyRequire("template", ["template"]);
18 var Const = function Const(val) Class.Property({ enumerable: true, value: val });
20 var Group = Class("Group", {
21 init: function init(name, description, filter, persist) {
23 this.description = description;
24 this.filter = filter || this.constructor.defaultFilter;
25 this.persist = persist || false;
30 get contexts() this.modules.contexts,
32 set lastDocument(val) { this._lastDocument = util.weakReference(val); },
33 get lastDocument() this._lastDocument && this._lastDocument.get(),
37 cleanup: function cleanup(reason) {
38 for (let hive in values(this.hives))
39 util.trapErrors("cleanup", hive);
42 for (let hive in keys(this.hiveMap))
45 if (reason != "shutdown")
46 this.children.splice(0).forEach(this.contexts.closure.removeGroup);
48 destroy: function destroy(reason) {
49 for (let hive in values(this.hives))
50 util.trapErrors("destroy", hive);
52 if (reason != "shutdown")
53 this.children.splice(0).forEach(this.contexts.closure.removeGroup);
56 argsExtra: function argsExtra() ({}),
58 makeArgs: function makeArgs(doc, context, args) {
59 let res = update({ doc: doc, context: context }, args);
60 return update(res, this.argsExtra(res), args);
63 get toStringParams() [this.name],
65 get builtin() this.modules.contexts.builtinGroups.indexOf(this) >= 0,
68 compileFilter: function (patterns, default_=false) {
69 function siteFilter(uri)
70 let (match = array.nth(siteFilter.filters, f => f(uri), 0))
71 match ? match.result : default_;
73 return update(siteFilter, {
74 toString: function () this.filters.join(","),
76 toJSONXML: function (modules) let (uri = modules && modules.buffer.uri)
77 template.map(this.filters,
78 f => ["span", { highlight: uri && f(uri) ? "Filter" : "" },
79 ("toJSONXML" in f ? f.toJSONXML()
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", () => contexts.Context(modules.io.getRCFile("~", true), contexts.user, [modules, true]));
142 memoize(modules, "_userContext", () => 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;
175 get: () => array(contexts.groups[this.name])
178 this.Hive = constructor;
180 memoize(contexts.Group.prototype, name, function () {
181 let group = constructor(this);
182 this.hives.push(group);
187 memoize(contexts.hives, name,
188 () => Object.create(Object.create(contexts.hiveProto,
189 { _hive: { value: name } })));
191 memoize(contexts.groupsProto, name,
192 function () [group[name] for (group in values(this.groups)) if (Set.has(group, name))]);
195 get toStringParams() [this.name, this.Hive]
199 Context: function Context(file, group, args) {
200 const { contexts, io, newContext, plugins, userContext } = this.modules;
202 let isPlugin = array.nth(io.getRuntimeDirectories("plugins"),
203 dir => dir.contains(file, true),
205 let isRuntime = array.nth(io.getRuntimeDirectories(""),
206 dir => dir.contains(file, true),
209 let name = isPlugin ? file.getRelativeDescriptor(isPlugin).replace(File.PATH_SEP, "-")
211 let id = util.camelCase(name.replace(/\.[^.]*$/, ""));
213 let contextPath = file.path;
214 let self = Set.has(plugins, contextPath) && plugins.contexts[contextPath];
216 if (!self && isPlugin && false)
217 self = Set.has(plugins, id) && plugins[id];
220 if (Set.has(self, "onUnload"))
221 util.trapErrors("onUnload", self);
224 let params = Array.slice(args || [userContext]);
225 params[2] = params[2] || File(file).URI.spec;
227 self = args && !isArray(args) ? args : newContext.apply(null, params);
231 PATH: Const(file.path),
233 CONTEXT: Const(self),
235 set isGlobalModule(val) {
241 unload: Const(function unload() {
242 if (plugins[this.NAME] === this || plugins[this.PATH] === this)
244 util.trapErrors("onUnload", this);
246 if (plugins[this.NAME] === this)
247 delete plugins[this.NAME];
249 if (plugins[this.PATH] === this)
250 delete plugins[this.PATH];
252 if (plugins.contexts[contextPath] === this)
253 delete plugins.contexts[contextPath];
255 if (!this.GROUP.builtin)
256 contexts.removeGroup(this.GROUP);
260 if (group !== this.user)
261 Class.replaceProperty(plugins, file.path, self);
263 // This belongs elsewhere
265 Object.defineProperty(plugins, self.NAME, {
268 get: function () self,
269 set: function (val) {
270 util.dactyl(val).reportError(FailedAssertion(_("plugin.notReplacingContext", self.NAME), 3, false), true);
275 let path = isRuntime ? file.getRelativeDescriptor(isRuntime) : file.path;
276 let name = isRuntime ? path.replace(/^(plugin|color)s([\\\/])/, "$1$2") : "script-" + path;
279 group = this.addGroup(commands.nameRegexp
280 .iterate(name.replace(/\.[^.]*$/, ""))
281 .join("-").replace(/--+/g, "-"),
282 _("context.scriptGroup", file.path),
285 Class.replaceProperty(self, "GROUP", group);
286 Class.replaceProperty(self, "group", group);
288 return plugins.contexts[contextPath] = self;
291 Script: function Script(file, group) {
292 return this.Context(file, group, [this.modules.userContext, true]);
295 Module: function Module(uri, isPlugin) {
296 const { io, plugins } = this.modules;
298 let canonical = uri.spec;
299 if (uri.scheme == "resource")
300 canonical = services["resource:"].resolveURI(uri);
302 if (uri instanceof Ci.nsIFileURL)
303 var file = File(uri.file);
305 let isPlugin = array.nth(io.getRuntimeDirectories("plugins"),
306 dir => dir.contains(file, true),
309 let name = isPlugin && file && file.getRelativeDescriptor(isPlugin)
310 .replace(File.PATH_SEP, "-");
311 let id = util.camelCase(name.replace(/\.[^.]*$/, ""));
313 let self = Set.has(this.pluginModules, canonical) && this.pluginModules[canonical];
316 self = Object.create(jsmodules);
321 PATH: Const(file && file.path),
323 CONTEXT: Const(self),
325 get isGlobalModule() true,
326 set isGlobalModule(val) {
327 util.assert(val, "Loading non-global module as global",
331 unload: Const(function unload() {
332 if (contexts.pluginModules[canonical] == this) {
334 util.trapErrors("onUnload", this);
336 delete contexts.pluginModules[canonical];
339 for each (let { plugins } in overlay.modules)
340 if (plugins[this.NAME] == this)
341 delete plugins[this.name];
345 JSMLoader.loadSubScript(uri.spec, self, File.defaultEncoding);
346 this.pluginModules[canonical] = self;
349 // This belongs elsewhere
351 Object.defineProperty(plugins, self.NAME, {
354 get: function () self,
355 set: function (val) {
356 util.dactyl(val).reportError(FailedAssertion(_("plugin.notReplacingContext", self.NAME), 3, false), true);
366 * Returns a frame object describing the currently executing
367 * command, if applicable, otherwise returns the passed frame.
369 * @param {nsIStackFrame} frame
371 getCaller: function getCaller(frame) {
372 if (this.context && this.context.file)
375 filename: this.context.file[0] == "[" ? this.context.file
376 : File(this.context.file).URI.spec,
377 lineNumber: this.context.line
382 groups: Class.Memoize(function () this.matchingGroups()),
384 allGroups: Class.Memoize(function () Object.create(this.groupsProto, {
385 groups: { value: this.initializedGroups() }
388 matchingGroups: function (uri) Object.create(this.groupsProto, {
389 groups: { value: this.activeGroups(uri) }
392 activeGroups: function (uri) {
393 if (uri instanceof Ci.nsIDOMDocument)
394 var [doc, uri] = [uri, uri.documentURIObject || util.newURI(uri.documentURI)];
397 var { uri, doc } = this.modules.buffer;
399 return this.initializedGroups().filter(function (g) {
400 let res = uri && g.filter(uri, doc);
402 g.lastDocument = res && doc;
407 flush: function flush() {
409 delete this.allGroups;
412 initializedGroups: function (hive)
413 let (need = hive ? [hive] : Object.keys(this.hives))
414 this.groupList.filter(group => need.some(Set.has(group))),
416 addGroup: function addGroup(name, description, filter, persist, replace) {
417 let group = this.getGroup(name);
422 group = this.Group(name, description, filter, persist);
423 this.groupList.unshift(group);
424 this.groupMap[name] = group;
425 this.hiveProto.__defineGetter__(name, function () group[this._hive]);
429 util.trapErrors("cleanup", group);
432 group.description = description;
434 group.filter = filter;
435 group.persist = persist;
442 removeGroup: function removeGroup(name) {
443 if (isObject(name)) {
444 if (this.groupList.indexOf(name) === -1)
449 let group = this.getGroup(name);
451 util.assert(!group || !group.builtin, _("group.cantRemoveBuiltin"));
455 this.groupList.splice(this.groupList.indexOf(group), 1);
456 util.trapErrors("destroy", group);
459 if (this.context && this.context.group === group)
460 this.context.group = null;
462 delete this.groupMap[name];
463 delete this.hiveProto[name];
468 getGroup: function getGroup(name, hive) {
469 if (name === "default")
470 var group = this.context && this.context.context && this.context.context.GROUP;
471 else if (Set.has(this.groupMap, name))
472 group = this.groupMap[name];
479 getDocs: function getDocs(context) {
481 if (isinstance(context, ["Sandbox"])) {
482 let info = "INFO" in context && Cu.evalInSandbox("this.INFO instanceof XML ? INFO.toXMLString() : this.INFO", context);
483 return /^</.test(info) ? XML(info) : info;
485 if (DOM.isJSONXML(context.INFO))
487 if (typeof context.INFO == "xml" && config.haveGecko(null, "14.*"))
494 bindMacro: function (args, default_, params) {
495 const { dactyl, events, modules } = this.modules;
497 function Proxy(obj, key) Class.Property({
500 get: function Proxy_get() process(obj[key]),
501 set: function Proxy_set(val) obj[key] = val
504 let process = util.identity;
506 if (callable(params))
507 var makeParams = function makeParams(self, args)
508 let (obj = params.apply(self, args))
509 iter.toObject([k, Proxy(obj, k)] for (k in properties(obj)));
511 makeParams = function makeParams(self, args)
512 iter.toObject([name, process(args[i])]
513 for ([i, name] in Iterator(params)));
515 let rhs = args.literalArg;
516 let type = ["-builtin", "-ex", "-javascript", "-keys"].reduce((a, b) => args[b] ? b : a, default_);
523 let silent = args["-silent"];
524 rhs = DOM.Event.canonicalKeys(rhs, true);
525 var action = function action() {
526 events.feedkeys(action.macro(makeParams(this, arguments)),
529 action.macro = util.compileMacro(rhs, true);
533 action = function action() modules.commands
534 .execute(action.macro, makeParams(this, arguments),
535 false, null, action.context);
536 action.macro = util.compileMacro(rhs, true);
537 action.context = this.context && update({}, this.context);
541 if (callable(params))
542 action = dactyl.userEval("(function action() { with (action.makeParams(this, arguments)) {" + args.literalArg + "} })");
544 action = dactyl.userFunc.apply(dactyl, params.concat(args.literalArg));
545 process = param => isObject(param) && param.valueOf ? param.valueOf() : param;
546 action.params = params;
547 action.makeParams = makeParams;
551 action.toString = function toString() (type === default_ ? "" : type + " ") + rhs;
556 withContext: function withContext(defaults, callback, self)
557 this.withSavedValues(["context"], function () {
558 this.context = defaults && update({}, defaults);
559 return callback.call(self, this.context);
562 Hive: Class("Hive", {
563 init: function init(group) {
567 cleanup: function cleanup() {},
568 destroy: function destroy() {},
570 get modifiable() this.group.modifiable,
572 get argsExtra() this.group.argsExtra,
573 get makeArgs() this.group.makeArgs,
574 get builtin() this.group.builtin,
576 get name() this.group.name,
577 set name(val) this.group.name = val,
579 get description() this.group.description,
580 set description(val) this.group.description = val,
582 get filter() this.group.filter,
583 set filter(val) this.group.filter = val,
585 get persist() this.group.persist,
586 set persist(val) this.group.persist = val,
588 prefix: Class.Memoize(function () this.name === "builtin" ? "" : this.name + ":"),
590 get toStringParams() [this.name]
593 commands: function initCommands(dactyl, modules, window) {
594 const { commands, contexts } = modules;
596 commands.add(["gr[oup]"],
597 "Create or select a group",
599 if (args.length > 0) {
600 var name = Option.dequote(args[0]);
601 util.assert(name !== "builtin", _("group.cantModifyBuiltin"));
602 util.assert(commands.validName.test(name), _("group.invalidName", name));
604 var group = contexts.getGroup(name);
607 var group = args.context && args.context.group;
609 return void modules.completion.listCompleter("group", "", null, null);
611 util.assert(group || name, _("group.noCurrent"));
613 let filter = Group.compileFilter(args["-locations"]);
614 if (!group || args.bang)
615 group = contexts.addGroup(name, args["-description"], filter, !args["-nopersist"], args.bang);
616 else if (!group.builtin) {
617 if (args.has("-locations"))
618 group.filter = filter;
619 if (args.has("-description"))
620 group.description = args["-description"];
621 if (args.has("-nopersist"))
622 group.persist = !args["-nopersist"];
625 if (!group.builtin && args.has("-args")) {
626 group.argsExtra = contexts.bindMacro({ literalArg: "return " + args["-args"] },
627 "-javascript", util.identity);
628 group.args = args["-args"];
632 args.context.group = group;
633 if (args.context.context) {
634 args.context.context.group = group;
636 let parent = args.context.context.GROUP;
637 if (parent && parent != group) {
638 group.parent = parent;
639 if (!~parent.children.indexOf(group))
640 parent.children.push(group);
645 util.assert(!group.builtin ||
646 !["-description", "-locations", "-nopersist"]
647 .some(Set.has(args.explicitOpts)),
648 _("group.cantModifyBuiltin"));
653 completer: function (context, args) {
654 if (args.length == 1)
655 modules.completion.group(context);
660 names: ["-args", "-a"],
661 description: "JavaScript Object which augments the arguments passed to commands, mappings, and autocommands",
662 type: CommandOption.STRING
665 names: ["-description", "-desc", "-d"],
666 description: "A description of this group",
667 default: "User-defined group",
668 type: CommandOption.STRING
671 names: ["-locations", "-locs", "-loc", "-l"],
672 description: "The URLs for which this group should be active",
674 type: CommandOption.LIST
677 names: ["-nopersist", "-n"],
678 description: "Do not save this group to an auto-generated RC file"
682 serialize: function () [
686 options: iter([v, typeof group[k] == "boolean" ? null : group[k]]
687 // FIXME: this map is expressed multiple times
688 for ([k, v] in Iterator({
690 description: "-description",
693 if (group[k])).toObject(),
694 arguments: [group.name],
697 for (group in values(contexts.initializedGroups()))
698 if (!group.builtin && group.persist)
699 ].concat([{ command: this.name, arguments: ["user"] }])
702 commands.add(["delg[roup]"],
705 util.assert(args.bang ^ !!args[0], _("error.argumentOrBang"));
708 contexts.groupList = contexts.groupList.filter(g => g.builtin);
710 util.assert(contexts.getGroup(args[0]), _("group.noSuch", args[0]));
711 contexts.removeGroup(args[0]);
717 completer: function (context, args) {
720 context.filters.push(({ item }) => !item.builtin);
721 modules.completion.group(context);
725 commands.add(["fini[sh]"],
726 "Stop sourcing a script file",
728 util.assert(args.context, _("command.finish.illegal"));
729 args.context.finished = true;
733 function checkStack(cmd) {
734 util.assert(contexts.context && contexts.context.stack &&
735 contexts.context.stack[cmd] && contexts.context.stack[cmd].length,
736 _("command.conditional.illegal"));
740 return contexts.context.stack[cmd].pop();
742 function push(cmd, value) {
743 util.assert(contexts.context, _("command.conditional.illegal"));
744 if (arguments.length < 2)
745 value = contexts.context.noExecute;
746 contexts.context.stack = contexts.context.stack || {};
747 contexts.context.stack[cmd] = (contexts.context.stack[cmd] || []).concat([value]);
751 "Execute commands until the next :elseif, :else, or :endif only if the argument returns true",
752 function (args) { args.context.noExecute = !dactyl.userEval(args[0]); },
754 always: function (args) { push("if"); },
758 commands.add(["elsei[f]", "elif"],
759 "Execute commands until the next :elseif, :else, or :endif only if the argument returns true",
762 always: function (args) {
764 args.context.noExecute = args.context.stack.if.slice(-1)[0] ||
765 !args.context.noExecute || !dactyl.userEval(args[0]);
770 commands.add(["el[se]"],
771 "Execute commands until the next :endif only if the previous conditionals were not executed",
774 always: function (args) {
776 args.context.noExecute = args.context.stack.if.slice(-1)[0] ||
777 !args.context.noExecute;
781 commands.add(["en[dif]", "fi"],
782 "End a string of :if/:elseif/:else conditionals",
785 always: function (args) { args.context.noExecute = pop("if"); },
789 completion: function initCompletion(dactyl, modules, window) {
790 const { completion, contexts } = modules;
792 completion.group = function group(context, active) {
793 context.title = ["Group"];
794 let uri = modules.buffer.uri;
796 active: group => group.filter(uri),
798 description: function (g) ["", g.filter.toJSONXML ? g.filter.toJSONXML(modules).concat("\u00a0") : "", g.description || ""]
800 context.completions = (active === undefined ? contexts.groupList : contexts.initializedGroups(active))
803 iter({ Active: true, Inactive: false }).forEach(function ([name, active]) {
804 context.split(name, null, function (context) {
805 context.title[0] = name + " Groups";
806 context.filters.push(({ item }) => !!item.filter(modules.buffer.uri) == active);
815 // catch(e){ if (!e.stack) e = Error(e); dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack); }
817 // vim: set fdm=marker sw=4 sts=4 ts=8 et ft=javascript: