1 // Copyright (c) 2010-2012 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) {
25 this.description = description;
26 this.filter = filter || this.constructor.defaultFilter;
27 this.persist = persist || false;
32 get contexts() this.modules.contexts,
34 set lastDocument(val) { this._lastDocument = util.weakReference(val); },
35 get lastDocument() this._lastDocument && this._lastDocument.get(),
39 cleanup: function cleanup(reason) {
40 for (let hive in values(this.hives))
41 util.trapErrors("cleanup", hive);
44 for (let hive in keys(this.hiveMap))
47 if (reason != "shutdown")
48 this.children.splice(0).forEach(this.contexts.closure.removeGroup);
50 destroy: function destroy(reason) {
51 for (let hive in values(this.hives))
52 util.trapErrors("destroy", hive);
54 if (reason != "shutdown")
55 this.children.splice(0).forEach(this.contexts.closure.removeGroup);
58 argsExtra: function argsExtra() ({}),
60 makeArgs: function makeArgs(doc, context, args) {
61 let res = update({ doc: doc, context: context }, args);
62 return update(res, this.argsExtra(res), args);
65 get toStringParams() [this.name],
67 get builtin() this.modules.contexts.builtinGroups.indexOf(this) >= 0,
70 compileFilter: function (patterns, default_) {
71 if (arguments.length < 2)
74 function siteFilter(uri)
75 let (match = array.nth(siteFilter.filters, function (f) f(uri), 0))
76 match ? match.result : default_;
78 return update(siteFilter, {
79 toString: function () this.filters.join(","),
81 toJSONXML: function (modules) let (uri = modules && modules.buffer.uri)
82 template.map(this.filters,
83 function (f) ["span", { highlight: uri && f(uri) ? "Filter" : "" },
84 "toJSONXML" in f ? f.toJSONXML() : String(f)],
87 filters: Option.parse.sitelist(patterns)
91 defaultFilter: Class.Memoize(function () this.compileFilter(["*"]))
94 var Contexts = Module("contexts", {
96 this.pluginModules = {};
99 cleanup: function () {
100 for each (let module in this.pluginModules)
101 util.trapErrors("unload", module);
103 this.pluginModules = {};
106 Local: function Local(dactyl, modules, window) ({
108 const contexts = this;
109 this.modules = modules;
111 Object.defineProperty(modules.plugins, "contexts", Const({}));
115 this.groupsProto = {};
119 this.builtin = this.addGroup("builtin", "Builtin items");
120 this.user = this.addGroup("user", "User-defined items", null, true);
121 this.builtinGroups = [this.builtin, this.user];
122 this.builtin.modifiable = false;
124 this.GroupFlag = Class("GroupFlag", CommandOption, {
125 init: function (name) {
128 this.type = ArgType("group", function (group) {
129 return isString(group) ? contexts.getGroup(group, name)
134 get toStringParams() [this.name],
136 names: ["-group", "-g"],
138 description: "Group to which to add",
140 get default() (contexts.context && contexts.context.group || contexts.user)[this.name],
142 completer: function (context) modules.completion.group(context)
145 memoize(modules, "userContext", function () contexts.Context(modules.io.getRCFile("~", true), contexts.user, [modules, true]));
146 memoize(modules, "_userContext", function () contexts.Context(modules.io.getRCFile("~", true), contexts.user, [modules.userContext]));
149 cleanup: function () {
150 for each (let hive in this.groupList.slice())
151 util.trapErrors("cleanup", hive, "shutdown");
154 destroy: function () {
155 for each (let hive in values(this.groupList.slice()))
156 util.trapErrors("destroy", hive, "shutdown");
158 for (let [name, plugin] in iter(this.modules.plugins.contexts))
159 if (plugin && "onUnload" in plugin && callable(plugin.onUnload))
160 util.trapErrors("onUnload", plugin);
164 "browser.locationChange": function (webProgress, request, uri) {
169 Group: Class("Group", Group, { modules: modules, get hiveMap() modules.contexts.hives }),
171 Hives: Class("Hives", Class.Property, {
172 init: function init(name, constructor) {
173 const { contexts } = modules;
180 get: function () array(contexts.groups[self.name])
183 this.Hive = constructor;
185 memoize(contexts.Group.prototype, name, function () {
186 let group = constructor(this);
187 this.hives.push(group);
192 memoize(contexts.hives, name,
193 function () Object.create(Object.create(contexts.hiveProto,
194 { _hive: { value: name } })));
196 memoize(contexts.groupsProto, name,
197 function () [group[name] for (group in values(this.groups)) if (Set.has(group, name))]);
200 get toStringParams() [this.name, this.Hive]
204 Context: function Context(file, group, args) {
205 const { contexts, io, newContext, plugins, userContext } = this.modules;
207 let isPlugin = array.nth(io.getRuntimeDirectories("plugins"),
208 function (dir) dir.contains(file, true),
210 let isRuntime = array.nth(io.getRuntimeDirectories(""),
211 function (dir) dir.contains(file, true),
214 let name = isPlugin ? file.getRelativeDescriptor(isPlugin).replace(File.PATH_SEP, "-")
216 let id = util.camelCase(name.replace(/\.[^.]*$/, ""));
218 let contextPath = file.path;
219 let self = Set.has(plugins, contextPath) && plugins.contexts[contextPath];
221 if (!self && isPlugin && false)
222 self = Set.has(plugins, id) && plugins[id];
225 if (Set.has(self, "onUnload"))
226 util.trapErrors("onUnload", self);
229 let params = Array.slice(args || [userContext]);
230 params[2] = params[2] || File(file).URI.spec;
232 self = args && !isArray(args) ? args : newContext.apply(null, params);
236 PATH: Const(file.path),
238 CONTEXT: Const(self),
240 set isGlobalModule(val) {
246 unload: Const(function unload() {
247 if (plugins[this.NAME] === this || plugins[this.PATH] === this)
249 util.trapErrors("onUnload", this);
251 if (plugins[this.NAME] === this)
252 delete plugins[this.NAME];
254 if (plugins[this.PATH] === this)
255 delete plugins[this.PATH];
257 if (plugins.contexts[contextPath] === this)
258 delete plugins.contexts[contextPath];
260 if (!this.GROUP.builtin)
261 contexts.removeGroup(this.GROUP);
265 if (group !== this.user)
266 Class.replaceProperty(plugins, file.path, self);
268 // This belongs elsewhere
270 Object.defineProperty(plugins, self.NAME, {
273 get: function () self,
274 set: function (val) {
275 util.dactyl(val).reportError(FailedAssertion(_("plugin.notReplacingContext", self.NAME), 3, false), true);
280 let path = isRuntime ? file.getRelativeDescriptor(isRuntime) : file.path;
281 let name = isRuntime ? path.replace(/^(plugin|color)s([\\\/])/, "$1$2") : "script-" + path;
284 group = this.addGroup(commands.nameRegexp
285 .iterate(name.replace(/\.[^.]*$/, ""))
286 .join("-").replace(/--+/g, "-"),
287 _("context.scriptGroup", file.path),
290 Class.replaceProperty(self, "GROUP", group);
291 Class.replaceProperty(self, "group", group);
293 return plugins.contexts[contextPath] = self;
296 Script: function Script(file, group) {
297 return this.Context(file, group, [this.modules.userContext, true]);
300 Module: function Module(uri, isPlugin) {
301 const { io, plugins } = this.modules;
303 let canonical = uri.spec;
304 if (uri.scheme == "resource")
305 canonical = services["resource:"].resolveURI(uri);
307 if (uri instanceof Ci.nsIFileURL)
308 var file = File(uri.file);
310 let isPlugin = array.nth(io.getRuntimeDirectories("plugins"),
311 function (dir) dir.contains(file, true),
314 let name = isPlugin && file && file.getRelativeDescriptor(isPlugin)
315 .replace(File.PATH_SEP, "-");
316 let id = util.camelCase(name.replace(/\.[^.]*$/, ""));
318 let self = Set.has(this.pluginModules, canonical) && this.pluginModules[canonical];
321 self = Object.create(jsmodules);
326 PATH: Const(file && file.path),
328 CONTEXT: Const(self),
330 get isGlobalModule() true,
331 set isGlobalModule(val) {
332 util.assert(val, "Loading non-global module as global",
336 unload: Const(function unload() {
337 if (contexts.pluginModules[canonical] == this) {
339 util.trapErrors("onUnload", this);
341 delete contexts.pluginModules[canonical];
344 for each (let { plugins } in overlay.modules)
345 if (plugins[this.NAME] == this)
346 delete plugins[this.name];
350 JSMLoader.loadSubScript(uri.spec, self, File.defaultEncoding);
351 this.pluginModules[canonical] = self;
354 // This belongs elsewhere
356 Object.defineProperty(plugins, self.NAME, {
359 get: function () self,
360 set: function (val) {
361 util.dactyl(val).reportError(FailedAssertion(_("plugin.notReplacingContext", self.NAME), 3, false), true);
371 * Returns a frame object describing the currently executing
372 * command, if applicable, otherwise returns the passed frame.
374 * @param {nsIStackFrame} frame
376 getCaller: function getCaller(frame) {
377 if (this.context && this.context.file)
380 filename: this.context.file[0] == "[" ? this.context.file
381 : File(this.context.file).URI.spec,
382 lineNumber: this.context.line
387 groups: Class.Memoize(function () this.matchingGroups()),
389 allGroups: Class.Memoize(function () Object.create(this.groupsProto, {
390 groups: { value: this.initializedGroups() }
393 matchingGroups: function (uri) Object.create(this.groupsProto, {
394 groups: { value: this.activeGroups(uri) }
397 activeGroups: function (uri) {
398 if (uri instanceof Ci.nsIDOMDocument)
399 var [doc, uri] = [uri, uri.documentURIObject || util.newURI(uri.documentURI)];
402 var { uri, doc } = this.modules.buffer;
404 return this.initializedGroups().filter(function (g) {
405 let res = uri && g.filter(uri, doc);
407 g.lastDocument = res && doc;
412 flush: function flush() {
414 delete this.allGroups;
417 initializedGroups: function (hive)
418 let (need = hive ? [hive] : Object.keys(this.hives))
419 this.groupList.filter(function (group) need.some(Set.has(group))),
421 addGroup: function addGroup(name, description, filter, persist, replace) {
422 let group = this.getGroup(name);
427 group = this.Group(name, description, filter, persist);
428 this.groupList.unshift(group);
429 this.groupMap[name] = group;
430 this.hiveProto.__defineGetter__(name, function () group[this._hive]);
434 util.trapErrors("cleanup", group);
437 group.description = description;
439 group.filter = filter;
440 group.persist = persist;
447 removeGroup: function removeGroup(name) {
448 if (isObject(name)) {
449 if (this.groupList.indexOf(name) === -1)
454 let group = this.getGroup(name);
456 util.assert(!group || !group.builtin, _("group.cantRemoveBuiltin"));
460 this.groupList.splice(this.groupList.indexOf(group), 1);
461 util.trapErrors("destroy", group);
464 if (this.context && this.context.group === group)
465 this.context.group = null;
467 delete this.groupMap[name];
468 delete this.hiveProto[name];
473 getGroup: function getGroup(name, hive) {
474 if (name === "default")
475 var group = this.context && this.context.context && this.context.context.GROUP;
476 else if (Set.has(this.groupMap, name))
477 group = this.groupMap[name];
484 getDocs: function getDocs(context) {
486 if (isinstance(context, ["Sandbox"])) {
487 let info = "INFO" in context && Cu.evalInSandbox("this.INFO instanceof XML ? INFO.toXMLString() : this.INFO", context);
488 return /^</.test(info) ? XML(info) : info;
490 if (DOM.isJSONXML(context.INFO))
492 if (typeof context.INFO == "xml" && config.haveGecko(null, "14.*"))
499 bindMacro: function (args, default_, params) {
500 const { dactyl, events, modules } = this.modules;
502 function Proxy(obj, key) Class.Property({
505 get: function Proxy_get() process(obj[key]),
506 set: function Proxy_set(val) obj[key] = val
509 let process = util.identity;
511 if (callable(params))
512 var makeParams = function makeParams(self, args)
513 let (obj = params.apply(self, args))
514 iter.toObject([k, Proxy(obj, k)] for (k in properties(obj)));
516 makeParams = function makeParams(self, args)
517 iter.toObject([name, process(args[i])]
518 for ([i, name] in Iterator(params)));
520 let rhs = args.literalArg;
521 let type = ["-builtin", "-ex", "-javascript", "-keys"].reduce(function (a, b) args[b] ? b : a, default_);
528 let silent = args["-silent"];
529 rhs = DOM.Event.canonicalKeys(rhs, true);
530 var action = function action() {
531 events.feedkeys(action.macro(makeParams(this, arguments)),
534 action.macro = util.compileMacro(rhs, true);
538 action = function action() modules.commands
539 .execute(action.macro, makeParams(this, arguments),
540 false, null, action.context);
541 action.macro = util.compileMacro(rhs, true);
542 action.context = this.context && update({}, this.context);
546 if (callable(params))
547 action = dactyl.userEval("(function action() { with (action.makeParams(this, arguments)) {" + args.literalArg + "} })");
549 action = dactyl.userFunc.apply(dactyl, params.concat(args.literalArg).array);
550 process = function (param) isObject(param) && param.valueOf ? param.valueOf() : param;
551 action.params = params;
552 action.makeParams = makeParams;
556 action.toString = function toString() (type === default_ ? "" : type + " ") + rhs;
561 withContext: function withContext(defaults, callback, self)
562 this.withSavedValues(["context"], function () {
563 this.context = defaults && update({}, defaults);
564 return callback.call(self, this.context);
567 Hive: Class("Hive", {
568 init: function init(group) {
572 cleanup: function cleanup() {},
573 destroy: function destroy() {},
575 get modifiable() this.group.modifiable,
577 get argsExtra() this.group.argsExtra,
578 get makeArgs() this.group.makeArgs,
579 get builtin() this.group.builtin,
581 get name() this.group.name,
582 set name(val) this.group.name = val,
584 get description() this.group.description,
585 set description(val) this.group.description = val,
587 get filter() this.group.filter,
588 set filter(val) this.group.filter = val,
590 get persist() this.group.persist,
591 set persist(val) this.group.persist = val,
593 prefix: Class.Memoize(function () this.name === "builtin" ? "" : this.name + ":"),
595 get toStringParams() [this.name]
598 commands: function initCommands(dactyl, modules, window) {
599 const { commands, contexts } = modules;
601 commands.add(["gr[oup]"],
602 "Create or select a group",
604 if (args.length > 0) {
605 var name = Option.dequote(args[0]);
606 util.assert(name !== "builtin", _("group.cantModifyBuiltin"));
607 util.assert(commands.validName.test(name), _("group.invalidName", name));
609 var group = contexts.getGroup(name);
612 var group = args.context && args.context.group;
614 return void modules.completion.listCompleter("group", "", null, null);
616 util.assert(group || name, _("group.noCurrent"));
618 let filter = Group.compileFilter(args["-locations"]);
619 if (!group || args.bang)
620 group = contexts.addGroup(name, args["-description"], filter, !args["-nopersist"], args.bang);
621 else if (!group.builtin) {
622 if (args.has("-locations"))
623 group.filter = filter;
624 if (args.has("-description"))
625 group.description = args["-description"];
626 if (args.has("-nopersist"))
627 group.persist = !args["-nopersist"];
630 if (!group.builtin && args.has("-args")) {
631 group.argsExtra = contexts.bindMacro({ literalArg: "return " + args["-args"] },
632 "-javascript", util.identity);
633 group.args = args["-args"];
637 args.context.group = group;
638 if (args.context.context) {
639 args.context.context.group = group;
641 let parent = args.context.context.GROUP;
642 if (parent && parent != group) {
643 group.parent = parent;
644 if (!~parent.children.indexOf(group))
645 parent.children.push(group);
650 util.assert(!group.builtin ||
651 !["-description", "-locations", "-nopersist"]
652 .some(Set.has(args.explicitOpts)),
653 _("group.cantModifyBuiltin"));
658 completer: function (context, args) {
659 if (args.length == 1)
660 modules.completion.group(context);
665 names: ["-args", "-a"],
666 description: "JavaScript Object which augments the arguments passed to commands, mappings, and autocommands",
667 type: CommandOption.STRING
670 names: ["-description", "-desc", "-d"],
671 description: "A description of this group",
672 default: "User-defined group",
673 type: CommandOption.STRING
676 names: ["-locations", "-locs", "-loc", "-l"],
677 description: "The URLs for which this group should be active",
679 type: CommandOption.LIST
682 names: ["-nopersist", "-n"],
683 description: "Do not save this group to an auto-generated RC file"
687 serialize: function () [
691 options: iter([v, typeof group[k] == "boolean" ? null : group[k]]
692 // FIXME: this map is expressed multiple times
693 for ([k, v] in Iterator({
695 description: "-description",
698 if (group[k])).toObject(),
699 arguments: [group.name],
702 for (group in values(contexts.initializedGroups()))
703 if (!group.builtin && group.persist)
704 ].concat([{ command: this.name, arguments: ["user"] }])
707 commands.add(["delg[roup]"],
710 util.assert(args.bang ^ !!args[0], _("error.argumentOrBang"));
713 contexts.groupList = contexts.groupList.filter(function (g) g.builtin);
715 util.assert(contexts.getGroup(args[0]), _("group.noSuch", args[0]));
716 contexts.removeGroup(args[0]);
722 completer: function (context, args) {
725 context.filters.push(function ({ item }) !item.builtin);
726 modules.completion.group(context);
730 commands.add(["fini[sh]"],
731 "Stop sourcing a script file",
733 util.assert(args.context, _("command.finish.illegal"));
734 args.context.finished = true;
738 function checkStack(cmd) {
739 util.assert(contexts.context && contexts.context.stack &&
740 contexts.context.stack[cmd] && contexts.context.stack[cmd].length,
741 _("command.conditional.illegal"));
745 return contexts.context.stack[cmd].pop();
747 function push(cmd, value) {
748 util.assert(contexts.context, _("command.conditional.illegal"));
749 if (arguments.length < 2)
750 value = contexts.context.noExecute;
751 contexts.context.stack = contexts.context.stack || {};
752 contexts.context.stack[cmd] = (contexts.context.stack[cmd] || []).concat([value]);
756 "Execute commands until the next :elseif, :else, or :endif only if the argument returns true",
757 function (args) { args.context.noExecute = !dactyl.userEval(args[0]); },
759 always: function (args) { push("if"); },
763 commands.add(["elsei[f]", "elif"],
764 "Execute commands until the next :elseif, :else, or :endif only if the argument returns true",
767 always: function (args) {
769 args.context.noExecute = args.context.stack.if.slice(-1)[0] ||
770 !args.context.noExecute || !dactyl.userEval(args[0]);
775 commands.add(["el[se]"],
776 "Execute commands until the next :endif only if the previous conditionals were not executed",
779 always: function (args) {
781 args.context.noExecute = args.context.stack.if.slice(-1)[0] ||
782 !args.context.noExecute;
786 commands.add(["en[dif]", "fi"],
787 "End a string of :if/:elseif/:else conditionals",
790 always: function (args) { args.context.noExecute = pop("if"); },
794 completion: function initCompletion(dactyl, modules, window) {
795 const { completion, contexts } = modules;
797 completion.group = function group(context, active) {
798 context.title = ["Group"];
799 let uri = modules.buffer.uri;
801 active: function (group) group.filter(uri),
803 description: function (g) ["", g.filter.toJSONXML ? g.filter.toJSONXML(modules).concat("\u00a0") : "", g.description || ""]
805 context.completions = (active === undefined ? contexts.groupList : contexts.initializedGroups(active))
808 iter({ Active: true, Inactive: false }).forEach(function ([name, active]) {
809 context.split(name, null, function (context) {
810 context.title[0] = name + " Groups";
811 context.filters.push(function ({ item }) !!item.filter(modules.buffer.uri) == active);
820 // catch(e){ if (!e.stack) e = Error(e); dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack); }
822 // vim: set fdm=marker sw=4 ts=4 et ft=javascript: